qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
198,240
|
<p>I'm looking to use Java to parse an ongoing stream of event drive XML generated by a remote device. Here's a simplified sample of two events:</p>
<pre><code><?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
<?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
</code></pre>
<p>It seems like SAX is more suited to this than DOM because it is an ongoing stream, though I'm not as familiar with Sax. Don't yell at me for the structure of the XML - I know it already and can't change it. </p>
<p>And yes the device DOES send the xml directive before every event. My first problem is that the second xml processing instruction is croaking the SAX parser. </p>
<p>Can anyone suggest a way to get around that?</p>
<hr>
<p>The code I'm using so far which is croaking on the second xml processing instruction is:</p>
<pre><code>public class TestMe extends HandlerBase {
public void startDocument () throws SAXException
{
System.out.println("got startDocument");
}
public void endDocument () throws SAXException
{
System.out.println("got endDocument");
}
public void startElement (String name, AttributeList attrs) throws SAXException
{
System.out.println("got startElement");
}
public void endElement (String name) throws SAXException
{
System.out.println("got endElement");
}
public void characters (char buf [], int offset, int len) throws SAXException
{
System.out.println("found characters");
}
public void processingInstruction (String target, String data) throws SAXException
{
System.out.println("got processingInstruction");
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
// using a file as test input for now
saxParser.parse( new File("devmodule.xml"), new TestMe() );
} catch (Throwable err) {
err.printStackTrace ();
}
}
}
</code></pre>
|
[
{
"answer_id": 199102,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\"?>"
},
{
"answer_id": 199143,
"author": "simon",
"author_id": 6040,
"author_profile": "https://Stackoverflow.com/users/6040",
"pm_score": 0,
"selected": false,
"text": "catch(SAXException SaxErr){\n System.out.println(\"ignore this error\");\n }\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27524/"
] |
198,244
|
<p>I have a checkstyle suppression filter setup (e.g. ignore magic numbers in unit test code).</p>
<p>The suppression xml file resides in the same folder as the checkstyle xml file. However, where this file actually is varies:
on my windows dev box it is in d:\dev\shared\checkstyle\config
on the Linux CI server it will be in /root/repo/shared/checkstyle/config
on another developers box it could be anywhere (they check out their svn repo to).</p>
<p>The only "consistent" thing is that the suppression file is always in the same folder as the checkstyle xml file.
I cannot work out how to ensure that this file is always consistently picked up. Also I don't know why checkstyle does not support embedded suppression within the checkstyle xml file.</p>
<p>any help?</p>
|
[
{
"answer_id": 199291,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 5,
"selected": true,
"text": "SuppressionFilter checkstyle-suppressions-file <module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${checkstyle-suppressions-file}\"/>\n</module>\n template-checkstyle.properties checkstyle-suppressions-file=@SCM_DIR@/checkstyle_suppressions.xml\n checkstyle.properties <copy file=\"${scm.dir}/template-checkstyle.properties\" tofile=\"${scm.dir}/checkstyle.properties\">\n <filterset>\n <filter token=\"SCM_DIR\" value=\"${scm.dir.unix}\"/>\n </filterset>\n</copy>\n scm.dir.unix scm.dir.unix file SuppressionFilter C:\\foo\\bar\\baz C:foobarbaz scm.dir pathconvert <pathconvert targetos=\"unix\" property=\"scm.dir.unix\">\n <path location=\"${scm.dir}\"/>\n</pathconvert>\n checkstyle <checkstyle config=\"${scm.dir}/checkstyle_checks.xml\"\n properties=\"${scm.dir}/checkstyle.properties\">\n <!-- details elided -->\n</checkstyle>\n checkstyle checkstyle.properties"
},
{
"answer_id": 945071,
"author": "gibbss",
"author_id": 116621,
"author_profile": "https://Stackoverflow.com/users/116621",
"pm_score": 2,
"selected": false,
"text": "build.xml ant.file <project name=\"common\" ... >\n <dirname property=\"thisdir\" file=\"${ant.file.common}\"/>\n checkstyle.suppressions.file=${thisdir}/qclib/checkstyle-suppressions.xml\n thisdir"
},
{
"answer_id": 8020122,
"author": "Jörg",
"author_id": 745640,
"author_profile": "https://Stackoverflow.com/users/745640",
"pm_score": 2,
"selected": false,
"text": "<module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${config_dir}/my_suppressions.xml\"/>\n</module>\n config_dir ---> ${config_loc}\n"
},
{
"answer_id": 15010596,
"author": "Robert Hutto",
"author_id": 2096840,
"author_profile": "https://Stackoverflow.com/users/2096840",
"pm_score": 3,
"selected": false,
"text": "<module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${samedir}/suppressions.xml\"/>\n</module>\n"
},
{
"answer_id": 15226808,
"author": "Sebastian vom Meer",
"author_id": 579849,
"author_profile": "https://Stackoverflow.com/users/579849",
"pm_score": 1,
"selected": false,
"text": "<module name=\"SuppressionFilter\">\n <property name=\"file\" value=\"${samedir}/suppressions.xml\"/>\n</module>\n <checkstyle config=\"${checkstyle.config}/checkstyle-checks.xml\">\n <!-- ... -->\n <property key=\"samedir\" value=\"${checkstyle.config}\"/>\n</checkstyle>\n"
},
{
"answer_id": 51795099,
"author": "Jérémie DERUETTE",
"author_id": 8029150,
"author_profile": "https://Stackoverflow.com/users/8029150",
"pm_score": 0,
"selected": false,
"text": "<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-checkstyle-plugin</artifactId>\n <version>3.0.0</version>\n <configuration>\n <configLocation>${project.basedir}/quality/checkstyle/dap_checkstyle_checks.xml</configLocation>\n <propertyExpansion>basedir=${project.basedir}</propertyExpansion>\n </configuration>\n <reportSets>\n <reportSet>\n <reports>\n <report>checkstyle</report>\n </reports>\n </reportSet>\n </reportSets>\n</plugin>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27522/"
] |
198,247
|
<p>Where I'm at the developers have been updated to Excel 2007, but most of the users haven't. I'm building a spreadsheet template (*.xlt) for a user that's gonna need some vba code included, and I'm wondering what issues I'm likely to run into building this in 2007 instead of 2003? I don't have access to a machine with Excel 2003 for testing, and I'm worried this particular project is headed for disaster.</p>
|
[
{
"answer_id": 2221331,
"author": "Chris Spicer",
"author_id": 210566,
"author_profile": "https://Stackoverflow.com/users/210566",
"pm_score": 2,
"selected": false,
"text": "#If USINGRIBBON Then\n Public Sub CallFromRibbon(control As IRibbonControl)\n#Else\n Public Sub CallFromRibbon()\n#End If\n ' Code here\n End Sub\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
198,248
|
<p>I’m using the gcc in MinGW that comes with Strawberry Perl, on Windows XP. I’d like to have <a href="http://www.gnu.org/software/ddd/" rel="nofollow noreferrer">ddd</a> (the Data Display Debugger) as well but apparently on Windows the simplest way to get ddd is by running Cygwin. So what's the bare minimum of Cygwin I can install to get ddd up and running? I'd prefer if I could run ddd natively on Win32 but that doesn't seem to be an option. </p>
|
[
{
"answer_id": 198335,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 0,
"selected": false,
"text": "xorg-x11-base"
},
{
"answer_id": 8272440,
"author": "Keith Thompson",
"author_id": 827263,
"author_profile": "https://Stackoverflow.com/users/827263",
"pm_score": 1,
"selected": false,
"text": "setup.exe ddd"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25093/"
] |
198,266
|
<p>Can anyone provide and example of downloading a PDF file using Watin? I tried the SaveAsDialogHandler but I couldn't figure it out. Perhaps a MemoryStream could be used?</p>
<p>Thanks,</p>
<p>--jb</p>
|
[
{
"answer_id": 201464,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);\nfileDownloadHandler.WaitUntilDownloadCompleted(200);\n"
},
{
"answer_id": 201470,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "FileDownloadHandler fileDownloadHandler = new FileDownloadHandler(file.FullName);\nusing (new UseDialogOnce(ie.DialogWatcher, fileDownloadHandler))\n{\n ie.Button(\"exportPdfButtonId\").ClickNoWait();\n\n fileDownloadHandler.WaitUntilFileDownloadDialogIsHandled(30);\n fileDownloadHandler.WaitUntilDownloadCompleted(200);\n}\n"
},
{
"answer_id": 291671,
"author": "Matt Honeycutt",
"author_id": 32353,
"author_profile": "https://Stackoverflow.com/users/32353",
"pm_score": 1,
"selected": false,
"text": " string file = Path.Combine(Directory.GetCurrentDirectory(), \"test.pdf\");\n\n using (IE ie = new IE())\n {\n FileDownloadHandler handler = new FileDownloadHandler(file);\n\n using (new UseDialogOnce(ie.DialogWatcher, handler))\n {\n try\n {\n ie.GoToNoWait(\"http://www.tug.org/texshowcase/cheat.pdf\");\n\n //WatiN seems to hang when IE loads a PDF, so let it timeout...\n ie.WaitForComplete(5);\n }\n catch (Exception)\n {\n //Ok.\n }\n\n handler.WaitUntilFileDownloadDialogIsHandled(30);\n handler.WaitUntilDownloadCompleted(30);\n }\n\n }\n\n Assert.That(File.Exists(file));\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,272
|
<p>Is it possible to read damaged media (cd, hdd, dvd,...) even if windows explorer bombs out?</p>
<p>What I mean to ask is, whether there is a set of APIs or something that can access the disk at a very low level (below explorer?) and read whatever can be retrieved even if it is only partial, especially if you can still see the file is there from explorer, but can't do anything with it because it is damaged somehow (scratch on cd, etc)?</p>
|
[
{
"answer_id": 36512022,
"author": "ryenus",
"author_id": 537554,
"author_profile": "https://Stackoverflow.com/users/537554",
"pm_score": 1,
"selected": false,
"text": "ddrescue ddrescue [options] infile outfile [mapfile]\n mapfile"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,279
|
<p>I am a complete beginner trying to develop for FCKeditor so please bear with me here. I have been tasked with developing a custom plugin that will allow users to browse a specific set of images that the user uploads. Essentially the user first attaches images, then uses the FCKeditor to insert those images.</p>
<p>So I have my plugin directory:</p>
<ul>
<li>lang </li>
<li>fckplugin.js </li>
<li>img.png (for the toolbar button)</li>
</ul>
<p>I am looking for some help on strategy for the custom file browser (lets call it mybrowser.asp).</p>
<p>1) Should mybrowser.asp be in the plugin directory? It is dynamic and only applies to one specific area of the site.</p>
<p>2) How should I pass the querystring to mybrowser.asp?</p>
<p>3) Any other recommendations for developing FCKeditor plugins? Any sample plugins that might be helpful to me? </p>
<p>EDIT: The querystring passed to the plugin page will be the exact same as the one on the host page. (This is a very specific plugin that will only be used in one place)</p>
|
[
{
"answer_id": 198311,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 2,
"selected": true,
"text": "// Register the related command. \n// RegisterCommand takes the following arguments: CommandName, DialogCommand \n// FCKDialogCommand takes the following arguments: CommandName, \n// Dialog Title, Path to HTML file, Width, Height\n\nFCKCommands.RegisterCommand( \n 'MyBrowser', \n new FCKDialogCommand( \n 'My Browser', \n 'Select An Image',\n FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp',\n 500,\n 250) \n);\n\n// Create the toolbar button. \n// FCKToolbarButton takes the following arguments: CommandName, Button Caption \n\nvar button = new FCKToolbarButton( 'MyBrowser', 'Select An Image' ) ; \nbutton.IconPath = FCKPlugins.Items['MyBrowser'].Path + 'img.png' ; \nFCKToolbarItems.RegisterItem( 'MyBrowser', button ) ; \n 'Select An Image',\n FCKPlugins.Items['MyBrowser'].Path + 'mybrowser.asp' + window.top.location.search,\n 500, \n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/285/"
] |
198,285
|
<p>I'm using the following code, using the <a href="http://www.sharpziplib.com/" rel="noreferrer">SharpZipLib</a> library, to add files to a .zip file, but each file is being stored with its full path. I need to only store the file, in the 'root' of the .zip file.</p>
<pre><code>string[] files = Directory.GetFiles(folderPath);
using (ZipFile zipFile = ZipFile.Create(zipFilePath))
{
zipFile.BeginUpdate();
foreach (string file in files)
{
zipFile.Add(file);
}
zipFile.CommitUpdate();
}
</code></pre>
<p>I can't find anything about an option for this in the supplied documentation. As this is a very popular library, I hope someone reading this may know something.</p>
|
[
{
"answer_id": 198301,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 4,
"selected": false,
"text": "string[] files = Directory.GetFiles(folderPath);\nusing (ZipFile zipFile = ZipFile.Create(zipFilePath))\n{\n zipFile.BeginUpdate();\n foreach (string file in files)\n {\n zipFile.Add(file, System.IO.Path.GetFileName(file));\n }\n zipFile.CommitUpdate();\n}\n"
},
{
"answer_id": 198302,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "Directory.GetFiles() zipFile.Add() public void Add(string fileName, string entryName) \nParameters:\n fileName(String) The name of the file to add.\n entryName (String) The name to use for the ZipEntry on the Zip file created.\n string[] files = Directory.GetFiles(folderPath);\nusing (ZipFile zipFile = ZipFile.Create(zipFilePath))\n{\n zipFile.BeginUpdate();\n foreach (string file in files)\n {\n zipFile.Add(file, Path.GetFileName(file));\n }\n zipFile.CommitUpdate();\n}\n"
},
{
"answer_id": 200895,
"author": "ProfK",
"author_id": 8741,
"author_profile": "https://Stackoverflow.com/users/8741",
"pm_score": 6,
"selected": true,
"text": "NameTransform ZipFile ZipNameTransform TrimPrefix public static void ZipFolderContents(string folderPath, string zipFilePath)\n{\n string[] files = Directory.GetFiles(folderPath);\n using (ZipFile zipFile = ZipFile.Create(zipFilePath))\n {\n zipFile.NameTransform = new ZipNameTransform(folderPath);\n foreach (string file in files)\n {\n zipFile.BeginUpdate();\n zipFile.Add(file);\n zipFile.CommitUpdate();\n }\n }\n}\n INameTransform"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
198,295
|
<p>I'm setting the cookie expiration using the following code:</p>
<hr>
<pre><code>// remove existing cookies.
request.Cookies.Clear();
response.Cookies.Clear();
// ... serialize and encrypt my data ...
// now set the cookie.
HttpCookie cookie = new HttpCookie(AuthCookieName, encrypted);
cookie.Expires = DateTime.Now.Add(TimeSpan.FromHours(CookieTimeOutHours));
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
// redirect to different page
</code></pre>
<hr>
<p>When I read the cookie timeout in the other page I'm getting 1/1/0001 12:00 AM. If someone can help me figure out the problem, I'll appreciate it. I'm using ASP.NET 3.5</p>
<p>ok. after reading the links from Gulzar, it appears that I cannot check cookie.Expires on the HttpRequest at all? Because the links seem to suggest that cookie.Expires is always set to DateTime.MinValue because the server can never know the actual time on the client machine? So this means I have to store the time inside the cookie myself and check it? Is my understanding correct?</p>
<p>thanks
Shankar</p>
|
[
{
"answer_id": 31889776,
"author": "Jeff Nicholson",
"author_id": 1815399,
"author_profile": "https://Stackoverflow.com/users/1815399",
"pm_score": 2,
"selected": false,
"text": " public static void Configuration(IAppBuilder app)\n {\n\n app.UseCookieAuthentication(new CookieAuthenticationOptions\n {\n AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,\n LoginPath = new PathString(string.Format(\"~/Login.aspx\"),\n Provider = new CookieAuthenticationProvider\n {\n OnValidateIdentity = SetExpiryClaim \n }\n });\n\n app.MapSignalR();\n }\n\n\n private static Task SetExpiryClaim(CookieValidateIdentityContext context)\n {\n var contextExpireUtc = context.Properties.ExpiresUtc;\n\n var claimTypeName = \"contextExpireUtc\";\n var identity = context.Identity;\n\n Claim contextExpiryClaim;\n\n if (identity.HasClaim(c => c.Type == claimTypeName))\n {\n contextExpiryClaim = identity.FindFirst(claimTypeName);\n identity.RemoveClaim(contextExpiryClaim);\n }\n contextExpiryClaim = new Claim(claimTypeName, contextExpireUtc.ToString());\n context.Identity.AddClaim(contextExpiryClaim);\n\n return Task.FromResult(true);\n }\n ClaimsPrincipal principle = Thread.CurrentPrincipal as ClaimsPrincipal;\n DateTime contextExpiry = principle.Claims.First(p => p.Type == \"contextExpireUtc\").Value.AsDateTime();\n"
},
{
"answer_id": 64606447,
"author": "Ali Kleit",
"author_id": 7964217,
"author_profile": "https://Stackoverflow.com/users/7964217",
"pm_score": 0,
"selected": false,
"text": "name value GET /sample_page.html HTTP/2.0\nHost: www.example.org\nCookie: yummy_cookie=choco; tasty_cookie=strawberry\n null"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20818/"
] |
198,312
|
<p>I'm learning how to make a firefox extension.
I have created a xul and overlay file that makes a sidebar in my browser. I'm trying to put buttons in my sidebar that load different pages within the main browser window. I'm not sure how to access the main browser window and load a new url within it. I have here a simple button and script to show you what I have so far. Any light on this subject would be greatly appreciated! </p>
<pre><code><script type="application/x-javascript">
function loadURL(url) {
// I know this part is wrong. How do I load url into main browser??
window.content.open(url)
}
</script>
<button
id="identifier"
class="dialog"
label="Yahoo"
image="images/image.jpg"
oncommand="loadURL("http://www.yahoo.com);"/>
</code></pre>
|
[
{
"answer_id": 3382347,
"author": "esafwan",
"author_id": 363661,
"author_profile": "https://Stackoverflow.com/users/363661",
"pm_score": 0,
"selected": false,
"text": "document.getElementById('1').loadURI('http://tridz.com')\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27538/"
] |
198,320
|
<p>As far as I can understand, when I new up a <em>Linq to SQL class</em>, it is the equivalent of new'ing up a <em>SqlConnection object</em>.</p>
<p>Suppose I have an object with two methods: <code>Delete()</code> and <code>SubmitChanges()</code>. Would it be wise of me to new up the <em>Linq to SQL class</em> in each of the methods, or would a private variable holding the <em>Linq to SQL class</em> - new'ed up by the constructor - be the way to go?</p>
<p>What I'm trying to avoid is a time-out.</p>
<p><strong>UPDATE:</strong></p>
<pre><code>namespace Madtastic
{
public class Comment
{
private Boolean _isDirty = false;
private Int32 _id = 0;
private Int32 _recipeID = 0;
private String _value = "";
private Madtastic.User _user = null;
public Int32 ID
{
get
{
return this._id;
}
}
public String Value
{
get
{
return this._value;
}
set
{
this._isDirty = true;
this._value = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public Comment()
{
}
public Comment(Int32 commentID)
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment != null)
{
this._id = comment.CommentsID;
this._recipeID = comment.RecipesID;
this._value = comment.CommentsValue;
this._user = new User(comment.UsersID);
}
mdc.Dispose();
}
public void SubmitChanges()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null && this._isDirty)
{
comment.CommentsValue = this._value;
}
else
{
Madtastic.Entities.Comment c = new Madtastic.Entities.Comment();
c.RecipesID = this._recipeID;
c.UsersID = this._user.ID;
c.CommentsValue = this._value;
mdc.Comments.InsertOnSubmit(c);
}
mdc.SubmitChanges();
mdc.Dispose();
}
public void Delete()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null)
{
mdc.Comments.DeleteOnSubmit(comment);
mdc.SubmitChanges();
this._isDirty = false;
this._id = 0;
this._recipeID = 0;
this._value = "";
this._user = null;
}
mdc.Dispose();
}
}
}
</code></pre>
<p><strong>REFACTORED CODE (according to Grank's spec):</strong></p>
<pre><code>namespace Madtastic
{
public sealed class CommentNew : IDisposable
{
private Madtastic.DataContext _mdc;
private Madtastic.Entities.Comment _comment;
private Madtastic.User _user;
public Int32 ID
{
get
{
return this._comment.CommentsID;
}
}
public String Value
{
get
{
return this._comment.CommentsValue;
}
set
{
this._comment.CommentsValue = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public void Comment(Int32 commentID)
{
this._mdc = new Madtastic.DataContext();
this._comment = (from c in _mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (this._comment == null)
{
this._comment = new Madtastic.Entities.Comment();
this._mdc.Comments.InsertOnSubmit(this._comment);
}
else
{
this._user = new Madtastic.User(this._comment.User.UsersID);
}
}
public void SubmitChanges()
{
this._mdc.SubmitChanges();
}
public void Delete()
{
this._mdc.Comments.DeleteOnSubmit(this._comment);
this.SubmitChanges();
}
void IDisposable.Dispose()
{
this._mdc.Dispose();
}
}
}
</code></pre>
|
[
{
"answer_id": 199159,
"author": "Grank",
"author_id": 12975,
"author_profile": "https://Stackoverflow.com/users/12975",
"pm_score": 3,
"selected": true,
"text": "namespace Madtastic\n{\n public class Comment\n {\n private Madtastic.DataContext mdc;\n private Madtastic.Entities.Comment comment;\n\n public Int32 ID\n {\n get\n {\n return comment.CommentsID;\n }\n }\n\n public Madtastic.User Owner\n {\n get\n {\n return comment.User;\n }\n }\n\n public Comment(Int32 commentID)\n { \n mdc = new Madtastic.DataContext();\n\n comment = (from c in mdc.Comments\n where c.CommentsID == commentID\n select c).FirstOrDefault();\n\n if (comment == null)\n {\n comment = new Madtastic.Entities.Comment();\n mdc.Comments.InsertOnSubmit(comment);\n }\n\n }\n\n public void SubmitChanges()\n {\n\n mdc.SubmitChanges();\n\n }\n\n\n public void Delete()\n {\n mdc.Comments.DeleteOnSubmit(comment);\n SubmitChanges();\n }\n }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
198,322
|
<p>Let's say I'm working on a little batch-processing console app in VB.Net. I want to be able to structure the app like this:</p>
<pre class="lang-vb prettyprint-override"><code>Sub WorkerMethod()
'Do some work
Trace.WriteLine("Work progress")
'Do more work
Trace.WriteLine("Another progress update")
'...
End Sub
Sub Main()
'Do any setup, like confirm the user wants to continue or whatever
WorkerMethod()
End Sub
</code></pre>
<p>Note that I'm using <code>Trace</code> rather than <code>Console</code> for my output. This is because the worker method may be called from elsewhere, or even live in a different assembly, and I want to be able to attach different trace listeners to it. So how can I connect the console to the trace? </p>
<p>I can already do it by defining a simple class (shown below) and adding an instance to the Trace's listeners collection, but I'm wondering if there's a more accepted or built in way to accomplish this:</p>
<pre class="lang-vb prettyprint-override"><code>Public Class ConsoleTrace
Inherits Diagnostics.TraceListener
Public Overloads Overrides Sub Write(ByVal message As String)
Console.Write(message)
End Sub
Public Overloads Overrides Sub WriteLine(ByVal message As String)
Console.WriteLine(message)
End Sub
End Class
</code></pre>
|
[
{
"answer_id": 198326,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 8,
"selected": true,
"text": "<?xml version=\"1.0\"?>\n<configuration>\n <system.diagnostics>\n <trace autoflush=\"true\">\n <listeners>\n <add name=\"logListener\" type=\"System.Diagnostics.TextWriterTraceListener\" initializeData=\"cat.log\" />\n <add name=\"consoleListener\" type=\"System.Diagnostics.ConsoleTraceListener\"/>\n </listeners>\n </trace>\n </system.diagnostics>\n</configuration>\n"
},
{
"answer_id": 863832,
"author": "Scott Marlowe",
"author_id": 1683,
"author_profile": "https://Stackoverflow.com/users/1683",
"pm_score": 4,
"selected": false,
"text": "Stream outResultsFile = File.Create (\"output.txt\");\nvar textListener = new TextWriterTraceListener (outResultsFile);\nTrace.Listeners.Add (textListener);\n"
},
{
"answer_id": 1614253,
"author": "Scott P",
"author_id": 33848,
"author_profile": "https://Stackoverflow.com/users/33848",
"pm_score": 6,
"selected": false,
"text": "Trace.Listeners.Add(new ConsoleTraceListener());\n ConsoleTraceListener listener = new ConsoleTraceListener();\nTrace.Listeners.Add(listener);\n\nTrace.WriteLine(\"Howdy\");\n\nTrace.Listeners.Remove(listener);\n\nTrace.Close();\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
198,343
|
<p>We're working with a fixed transaction log size on our databases, and I'd like to put together an application to monitor the log sizes so we can see when things are getting too tight and we need to grow the fixed trn log. </p>
<p>Is there any TSQL command that I can run which will tell me the current size of the transaction log, and the fixed limit of the transaction log?</p>
|
[
{
"answer_id": 198363,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 4,
"selected": false,
"text": "DBCC SQLPERF ( LOGSPACE )\n"
},
{
"answer_id": 198427,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": false,
"text": "SELECT\n (size * 8)/1024.0 AS size_in_mb,\n CASE\n WHEN max_size = -1 THEN 9999999 -- Unlimited growth, so handle this how you want\n ELSE (max_size * 8)/1024.0\n END AS max_size_in_mb\nFROM\n MyDB.sys.database_files\nWHERE\n data_space_id = 0 -- Log file\n"
},
{
"answer_id": 7085251,
"author": "Myles Yamada",
"author_id": 897547,
"author_profile": "https://Stackoverflow.com/users/897547",
"pm_score": 6,
"selected": true,
"text": "SELECT (size * 8.0)/1024.0 AS size_in_mb\n , CASE\n WHEN max_size = -1 \n THEN 9999999 -- Unlimited growth, so handle this how you want\n ELSE (max_size * 8.0)/1024.0 END AS max_size_in_mb\n FROM YOURDBNAMEHERE.sys.database_files\n WHERE data_space_id = 0 \n"
},
{
"answer_id": 9309286,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 4,
"selected": false,
"text": "SELECT\n RTRIM(instance_name) [database], \n cntr_value log_size_kb\nFROM \n sys.dm_os_performance_counters \nWHERE \n object_name = 'SQLServer:Databases'\n AND counter_name = 'Log File(s) Used Size (KB)'\n AND instance_name <> '_Total'\n"
},
{
"answer_id": 42283692,
"author": "James",
"author_id": 622140,
"author_profile": "https://Stackoverflow.com/users/622140",
"pm_score": 2,
"selected": false,
"text": "FILEPROPERTY select [Name], physical_name [Path], CAST(size AS BIGINT)*8192 [TotalBytes], CAST(FILEPROPERTY(name,'SpaceUsed') AS BIGINT)*8192 [UsedBytes], (case when max_size<0 then -1 else CAST(max_size AS BIGINT)*8192 end) [MaxBytes]\nfrom sys.database_files\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21973/"
] |
198,346
|
<p>I've found a few samples online but I'd like to get feedback from people who use PHP daily as to potential security or performance considerations and their solutions.</p>
<p>Note that I am only interested in uploading a single file at a time.</p>
<p>Ideally no browser plugin would be required (Flash/Java), although it would be interesting to know the benefits of using a plugin.</p>
<p>I would like to know both the best HTML form code and PHP processing code.</p>
|
[
{
"answer_id": 198459,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 6,
"selected": true,
"text": "<form enctype=\"multipart/form-data\" action=\"action.php\" method=\"POST\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"1000000\" />\n <input name=\"userfile\" type=\"file\" />\n <input type=\"submit\" value=\"Go\" />\n</form>\n action.php MAX_FILE_SIZE file file <?php\n$uploaddir = \"/www/uploads/\";\n$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);\n\necho '<pre>';\nif (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {\n echo \"Success.\\n\";\n} else {\n echo \"Failure.\\n\";\n}\n\necho 'Here is some more debugging info:';\nprint_r($_FILES);\nprint \"</pre>\";\n?>\n $_FILES php.ini php.ini max_execution_time = 30 upload_max_filesize = 2M memory_limit upload_tmp_dir fileinfo mime_content_type // FILEINFO_MIME set to return MIME types, will return string of info otherwise\n$fileinfo = new finfo(FILEINFO_MIME);\n$file = $fileinfo->file($_FILE['filename']);\n\n$allowed_types = array('image/jpeg', 'image/png');\nif(!in_array($file, $allowed_types))\n{\n die('Files of type' . $file . ' are not allowed to be uploaded.');\n}\n// Continue\n //For those who are using PHP 5.3, the code varies.\n$fileinfo = new finfo(FILEINFO_MIME_TYPE);\n$file = $fileinfo->file($_FILE['filename']['tmp_name']);\n$allowed_types = array('image/jpeg', 'image/png');\nif(!in_array($file, $allowed_types))\n{\n die('Files of type' . $file . ' are not allowed to be uploaded.');\n}\n// Continue\n"
},
{
"answer_id": 199899,
"author": "cole",
"author_id": 910,
"author_profile": "https://Stackoverflow.com/users/910",
"pm_score": 2,
"selected": false,
"text": "Options -Indexes\nOptions -ExecCGI\nAddHandler cgi-script .php .php3 .php4 .phtml .pl .py .jsp .asp .htm .shtml .sh .cgi \n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
] |
198,357
|
<p>A lot of programming languages and frameworks do/allow/require something that I can't seem to find the name for, even though there probably is one in computer science. What they basically do is bind to a variable/object/class/function by name. </p>
<p><a href="http://www.adobe.com/products/flex/" rel="noreferrer">Flex</a> example ("selectAll()"):</p>
<pre><code><mx:Button click="selectAll()" label="Select All"/>
</code></pre>
<p><a href="http://mate.asfusion.com/" rel="noreferrer">Mate</a> example ("price"):</p>
<pre><code><Injectors target="{QuotePanel}">
<PropertyInjector targetKey="price" source="{QuoteManager}" sourceKey="currentPrice" />
</Injectors>
</code></pre>
<p>Java example ("Foo"):</p>
<pre><code>Class.forName("Foo")
</code></pre>
<p>There are many other examples. You get the idea. What troubles me is that there is virtually no way to verify this at compile-time, and not much the IDE can do to help in terms of code completion, navigation, and refactoring. But that's besides the point.</p>
<p>My question is, what is this called? <strong><em>I don't think it's one of these: <a href="http://en.wikipedia.org/wiki/Dynamic_binding" rel="noreferrer">dynamic binding</a>, <a href="http://en.wikipedia.org/wiki/Name_binding" rel="noreferrer">name binding</a>, <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)" rel="noreferrer">reflection</a></em></strong></p>
<p><strong>Update</strong>: No, this is not a quiz, sorry if it sounds like one. It's simply a matter of "name that song" for programming.</p>
<p><strong>Update</strong>: Answers that helped:</p>
<ul>
<li>From Tim Lesher: It's called "late binding", "dynamic binding", or "runtime binding". <em>The fact that it binds by a string is just an implementation detail</em>...</li>
<li>From Konrad Rudolph: ...<em>it's simply input for an interpreter</em>.</li>
</ul>
<p><strong>Update</strong>: As people have correctly pointed out, some of the examples are late binding, some are reflection, some are runtime-evaluation (interpretation), etc. However, I conclude there probably is no name that describes them all. It's just a bunch of examples that do have something in common, but not enough to give it a name. I liked the "everything is a string" answer, but even though it's funny, it doesn't fully do it justice either.</p>
|
[
{
"answer_id": 198364,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "Class.forName"
},
{
"answer_id": 198436,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "click eval"
},
{
"answer_id": 216438,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 2,
"selected": false,
"text": "<mx:Button click=\"selectAll()\" label=\"Select All\"/>\n selectAll() -keep-generated-actionscript _button1 = new Button();\n_button1.label = \"Select All\";\n_button1.addEventListener(\"click\", function( event : Event ) : void {\n selectAll();\n});\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
] |
198,360
|
<p>I would like to host a silverlight control in winforms via a winforms browser, but for it to work I need some way for the forms to talk to the silverlight, and also the other way around. Would it be possible to somehow have the two interact with each other using JavaScript as a middleman? I.e., have the form speak to the browser's javascript, and have that speak to the silverlight control? Is there a better way? Or even a way at all? (other than compiling the code as silverlight and wpf)</p>
|
[
{
"answer_id": 208920,
"author": "wahrhaft",
"author_id": 17986,
"author_profile": "https://Stackoverflow.com/users/17986",
"pm_score": 5,
"selected": true,
"text": "webBrowser.AllowNavigation = false;\nwebBrowser.AllowWebBrowserDrop = false;\nwebBrowser.IsWebBrowserContextMenuEnabled = false;\nwebBrowser.WebBrowserShortcutsEnabled = false;\n [ComVisible(true)]\npublic partial class Form1 : Form\n{\n ......\n webBrowser.ObjectForScripting = this;\n ......\n public void CallMeInForm(string something)\n {\n MessageBox.Show(\"Silverlight said: \" + something);\n }\n}\n using System.Windows.Browser;\n......\nScriptObject myForm = (ScriptObject)HtmlPage.Window.GetProperty(\"external\");\nmyForm.Invoke(\"CallMeInForm\", \"testing 1 2 3\");\n HtmlPage.RegisterScriptableObject(\"Page\", this);\n......\n[ScriptableMember]\npublic void CallMeInSilverlight(string message)\n{\n HtmlPage.Window.Alert(\"The form said: \" + message);\n}\n id=\"silverlightControl\" <object> document.getElementById('silverlightControl').Content.Page.CallMeInSilverlight(\"testing 1 2 3\");\n Page RegisterScriptableObject() <script type=\"text/javascript\">\n function CallMe(message) {\n var control = document.getElementById('silverlightControl');\n control.Content.Page.CallMeInSilverlight(message);\n }\n</script>\n CallMe() public void CallToSilverlight()\n{\n webBrowser.InvokeScript(\"CallMe\", new object[] { \"testing 1 2 3\" });\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
198,365
|
<p>in Config.groovy I see this:</p>
<pre><code>// set per-environment serverURL stem for creating absolute links
environments {
production {
grails.serverURL = "http://www.changeme.com"
}
}
</code></pre>
<p>what is the correct way to access that at runtime?</p>
|
[
{
"answer_id": 198466,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 4,
"selected": false,
"text": "import org.codehaus.groovy.grails.commons.ConfigurationHolder\nprintln ConfigurationHolder.config.grails.serverURL\n grailsApplication.config.grails.serverURL\n"
},
{
"answer_id": 198541,
"author": "Robert Fischer",
"author_id": 27561,
"author_profile": "https://Stackoverflow.com/users/27561",
"pm_score": 5,
"selected": false,
"text": "import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH\nprintln CH.config.grails.serverURL\n"
},
{
"answer_id": 10597881,
"author": "khylo",
"author_id": 249672,
"author_profile": "https://Stackoverflow.com/users/249672",
"pm_score": 7,
"selected": true,
"text": "grailsApplication.config.grails.serverURL\n class MyController{\n def grailsApplication\n def myAction() {\n grailsApplication.config.grails.serverURL\n }\n"
},
{
"answer_id": 24789570,
"author": "jstricker",
"author_id": 1475872,
"author_profile": "https://Stackoverflow.com/users/1475872",
"pm_score": 3,
"selected": false,
"text": "grails.utils.Holders import grails.util.Holders\n\nclass Foo {\n def bar() {\n println(Holders.config.grails.serverURL)\n }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
198,409
|
<p>Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?</p>
|
[
{
"answer_id": 198702,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 7,
"selected": true,
"text": "QueryPerformanceCounter CTimer .StartCounter .TimeElapsed Option Explicit\n\nPrivate Type LARGE_INTEGER\n lowpart As Long\n highpart As Long\nEnd Type\n\nPrivate Declare Function QueryPerformanceCounter Lib \"kernel32\" (lpPerformanceCount As LARGE_INTEGER) As Long\nPrivate Declare Function QueryPerformanceFrequency Lib \"kernel32\" (lpFrequency As LARGE_INTEGER) As Long\n\nPrivate m_CounterStart As LARGE_INTEGER\nPrivate m_CounterEnd As LARGE_INTEGER\nPrivate m_crFrequency As Double\n\nPrivate Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256#\n\nPrivate Function LI2Double(LI As LARGE_INTEGER) As Double\nDim Low As Double\n Low = LI.lowpart\n If Low < 0 Then\n Low = Low + TWO_32\n End If\n LI2Double = LI.highpart * TWO_32 + Low\nEnd Function\n\nPrivate Sub Class_Initialize()\nDim PerfFrequency As LARGE_INTEGER\n QueryPerformanceFrequency PerfFrequency\n m_crFrequency = LI2Double(PerfFrequency)\nEnd Sub\n\nPublic Sub StartCounter()\n QueryPerformanceCounter m_CounterStart\nEnd Sub\n\nProperty Get TimeElapsed() As Double\nDim crStart As Double\nDim crStop As Double\n QueryPerformanceCounter m_CounterEnd\n crStart = LI2Double(m_CounterStart)\n crStop = LI2Double(m_CounterEnd)\n TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency\nEnd Property\n"
},
{
"answer_id": 199480,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 6,
"selected": false,
"text": "Dim t as single\nt = Timer\n'code\nMsgBox Timer - t\n"
},
{
"answer_id": 6820028,
"author": "Kodak",
"author_id": 197559,
"author_profile": "https://Stackoverflow.com/users/197559",
"pm_score": 5,
"selected": false,
"text": "Public Declare Function GetTickCount Lib \"kernel32.dll\" () As Long\nSub testTimer()\nDim t As Long\nt = GetTickCount\n\nFor i = 1 To 1000000\na = a + 1\nNext\n\nMsgBox GetTickCount - t, , \"Milliseconds\"\nEnd Sub\n"
},
{
"answer_id": 58006854,
"author": "Gajendra Santosh",
"author_id": 9561828,
"author_profile": "https://Stackoverflow.com/users/9561828",
"pm_score": 3,
"selected": false,
"text": "Sub Macro1()\n Dim StartTime As Double\n StartTime = Timer\n\n ''''''''''''''''''''\n 'Your Code'\n ''''''''''''''''''''\n MsgBox \"RunTime : \" & Format((Timer - StartTime) / 86400, \"hh:mm:ss\")\nEnd Sub\n"
},
{
"answer_id": 61219046,
"author": "SendETHToThisAddress",
"author_id": 5835002,
"author_profile": "https://Stackoverflow.com/users/5835002",
"pm_score": 1,
"selected": false,
"text": "Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime) / 1000000, \"#,##0.00\") & \" seconds\") 'end timer\n Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime), \"#,##0.00\") & \" milliseconds\") 'end timer\n Dim startTime As Single 'start timer\nMsgBox (\"run time: \" & Format((Timer - startTime) * 1000, \"#,##0.00\") & \" milliseconds\") 'end timer\n"
},
{
"answer_id": 68406681,
"author": "jonadv",
"author_id": 6544310,
"author_profile": "https://Stackoverflow.com/users/6544310",
"pm_score": 2,
"selected": false,
"text": "Sub TimerBenchmark()\n\nDim bm As New cBenchmark\n\n'Some code here\nbm.TrackByName \"Some code\"\n\nEnd Sub\n IDnr Name Count Sum of tics Percentage Time sum\n0 Some code 1 163 100,00% 16 us\n TOTAL 1 163 100,00% 16 us\n\nTotal time recorded: 16 us\n Sub TimerBenchmark()\n\nDim bm As New cBenchmark\n\nbm.Wait 0.0001 'Simulation of some code\nbm.TrackByName \"Some code\"\n\nbm.Wait 0.04 'Simulation of some (time consuming) code here\nbm.TrackByName \"Bottleneck code\"\n\n\nbm.Wait 0.00004 'Simulation of some code, with the same tag as above\nbm.TrackByName \"Some code\"\n\nEnd Sub\n IDnr Name Count Sum of tics Percentage Time sum\n0 Some code 2 21.374 5,07% 2,14 ms\n1 Bottleneck code 1 400.395 94,93% 40 ms\n TOTAL 3 421.769 100,00% 42 ms\n\nTotal time recorded: 42 ms\n"
},
{
"answer_id": 71786637,
"author": "Daekar",
"author_id": 11964259,
"author_profile": "https://Stackoverflow.com/users/11964259",
"pm_score": 1,
"selected": false,
"text": "Option Explicit\n\n'This class allows you to easily see how long your code takes to run by encapsulating the Timer function, which returns the time since midnight in seconds.\n'Instantiate the class to start the clock and use the StopTimer method to stop it and output to the Immediate window. It will accept an optional argument to label the timer.\n'If you want to use it multiple times in the same program, make sure to terminate it before creating another timer.\n\n'EXAMPLE:\n'Sub ExampleSub()\n'Dim t As cTimer 'Declare t as a member of the cTimer class\n'Set t = New cTimer 'Create a new cTimer class object called \"t\" and set the start time\n'...\n'...\n'...\n'some code\n'...\n'...\n'...\n't.StopTimer 'Set the stop time and output elapsed time to the Immediate window. This will output \"Timed process took X.XXXXX seconds\"\n'Set t = Nothing 'Destroy the existing cTimer object called \"t\"\n'Set t = New cTimer 'Create a new cTimer class object called \"t\" and set the start time again.\n'...\n'...\n'...\n'some code\n'...\n'...\n'...\n't.StopTimer (\"Second section\") 'Set the stop time once more and output elapsed time to the Immediate window. The text output will read \"Second section: X.XXXX seconds\" for this line.\n'End Sub\n\n\nPrivate pStartTime As Single\nPrivate pEndTime As Single\n\nPrivate Sub Class_Initialize()\npStartTime = Timer\nEnd Sub\n\nPublic Sub StopTimer(Optional SectionName As String)\npEndTime = Timer\nIf Not SectionName = \"\" Then 'If user defines the optional SectionName string\n Debug.Print SectionName & \": \" & (pEndTime - pStartTime) & \" seconds\"\nElse\n Debug.Print \"Timed process took \" & (pEndTime - pStartTime) & \" seconds\"\nEnd If\nEnd Sub\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13295/"
] |
198,419
|
<p>I'm getting XML like this:</p>
<p><code><Items>
<Row attr1="val"></Row>
<Row attr1="val2"></Row>
</Items></code></p>
<p>This is valid XML, as you know, but another library I'm using is busted and it will only accept XML in this format: </p>
<p><code><Items>
<Row attr1="val"/>
<Row attr1="val2"/>
</Items>
</code></p>
<p>I'm already reading the XML into XmlDocuments, manipulating them, and rewriting them using an XmlWriter(), what's the easiest (and most efficient) way for me to "collapse" these empty tags?</p>
|
[
{
"answer_id": 198579,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "XmlElement items = xmlDoc.SelectNodes(\"items\");\nXmlElement row = xmlDoc.CreateElement(\"row\");\nitems[0].appendChild(row);\n"
},
{
"answer_id": 198765,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 0,
"selected": false,
"text": " public class BetterXmlTextWriter : XmlTextWriter\n {\n public BetterXmlTextWriter(TextWriter w)\n : base(w)\n {\n }\n\n public override void WriteFullEndElement()\n {\n base.WriteEndElement();\n }\n }\n"
},
{
"answer_id": 198906,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "XmlWriter xw = XmlWriter.Create(Console.Out);\nxw.WriteStartElement(\"foo\");\nxw.WriteAttributeString(\"bar\", null, \"baz\");\nxw.WriteEndElement();\nxw.Flush();\nxw.Close();\n <foo bar='baz' />"
},
{
"answer_id": 38748211,
"author": "rory.ap",
"author_id": 2704659,
"author_profile": "https://Stackoverflow.com/users/2704659",
"pm_score": 0,
"selected": false,
"text": "private static void FormatEmptyNodes(XmlNode rootNode)\n{\n foreach (XmlNode childNode in rootNode.ChildNodes)\n {\n FormatEmptyNodes(childNode);\n\n if(childNode is XmlElement)\n {\n XmlElement element = (XmlElement) childNode;\n if (string.IsNullOrEmpty(element.InnerText)) element.IsEmpty = true;\n }\n }\n}\n var doc = new XmlDocument();\ndoc.Load(inputFilePath);\nFormatEmptyNodes(doc);\ndoc.Save(outputFilePath);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12979/"
] |
198,431
|
<p>Is there a standard idiom for comparing version numbers? I can't just use a straight String compareTo because I don't know yet what the maximum number of point releases there will be. I need to compare the versions and have the following hold true:</p>
<pre><code>1.0 < 1.1
1.0.1 < 1.1
1.9 < 1.10
</code></pre>
|
[
{
"answer_id": 836665,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 6,
"selected": false,
"text": "import java.util.regex.Pattern;\n\npublic class Main {\n public static void main(String... args) {\n compare(\"1.0\", \"1.1\");\n compare(\"1.0.1\", \"1.1\");\n compare(\"1.9\", \"1.10\");\n compare(\"1.a\", \"1.9\");\n }\n\n private static void compare(String v1, String v2) {\n String s1 = normalisedVersion(v1);\n String s2 = normalisedVersion(v2);\n int cmp = s1.compareTo(s2);\n String cmpStr = cmp < 0 ? \"<\" : cmp > 0 ? \">\" : \"==\";\n System.out.printf(\"'%s' %s '%s'%n\", v1, cmpStr, v2);\n }\n\n public static String normalisedVersion(String version) {\n return normalisedVersion(version, \".\", 4);\n }\n\n public static String normalisedVersion(String version, String sep, int maxWidth) {\n String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);\n StringBuilder sb = new StringBuilder();\n for (String s : split) {\n sb.append(String.format(\"%\" + maxWidth + 's', s));\n }\n return sb.toString();\n }\n}\n '1.0' < '1.1'\n'1.0.1' < '1.1'\n'1.9' < '1.10'\n'1.a' > '1.9'\n"
},
{
"answer_id": 2031954,
"author": "Cenk Alti",
"author_id": 242451,
"author_profile": "https://Stackoverflow.com/users/242451",
"pm_score": 2,
"selected": false,
"text": "public int compare(String v1, String v2) {\n v1 = v1.replaceAll(\"\\\\s\", \"\");\n v2 = v2.replaceAll(\"\\\\s\", \"\");\n String[] a1 = v1.split(\"\\\\.\");\n String[] a2 = v2.split(\"\\\\.\");\n List<String> l1 = Arrays.asList(a1);\n List<String> l2 = Arrays.asList(a2);\n\n\n int i=0;\n while(true){\n Double d1 = null;\n Double d2 = null;\n\n try{\n d1 = Double.parseDouble(l1.get(i));\n }catch(IndexOutOfBoundsException e){\n }\n\n try{\n d2 = Double.parseDouble(l2.get(i));\n }catch(IndexOutOfBoundsException e){\n }\n\n if (d1 != null && d2 != null) {\n if (d1.doubleValue() > d2.doubleValue()) {\n return 1;\n } else if (d1.doubleValue() < d2.doubleValue()) {\n return -1;\n }\n } else if (d2 == null && d1 != null) {\n if (d1.doubleValue() > 0) {\n return 1;\n }\n } else if (d1 == null && d2 != null) {\n if (d2.doubleValue() > 0) {\n return -1;\n }\n } else {\n break;\n }\n i++;\n }\n return 0;\n }\n"
},
{
"answer_id": 6640972,
"author": "Alex Dean",
"author_id": 255627,
"author_profile": "https://Stackoverflow.com/users/255627",
"pm_score": 7,
"selected": false,
"text": "import org.apache.maven.artifact.versioning.DefaultArtifactVersion;\n\nDefaultArtifactVersion minVersion = new DefaultArtifactVersion(\"1.0.1\");\nDefaultArtifactVersion maxVersion = new DefaultArtifactVersion(\"1.10\");\n\nDefaultArtifactVersion version = new DefaultArtifactVersion(\"1.11\");\n\nif (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {\n System.out.println(\"Sorry, your version is unsupported\");\n}\n <dependency>\n<groupId>org.apache.maven</groupId>\n<artifactId>maven-artifact</artifactId>\n<version>3.0.3</version>\n</dependency>\n"
},
{
"answer_id": 10034633,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 5,
"selected": false,
"text": "// VersionComparator.java\nimport java.util.Comparator;\n\npublic class VersionComparator implements Comparator {\n\n public boolean equals(Object o1, Object o2) {\n return compare(o1, o2) == 0;\n }\n\n public int compare(Object o1, Object o2) {\n String version1 = (String) o1;\n String version2 = (String) o2;\n\n VersionTokenizer tokenizer1 = new VersionTokenizer(version1);\n VersionTokenizer tokenizer2 = new VersionTokenizer(version2);\n\n int number1 = 0, number2 = 0;\n String suffix1 = \"\", suffix2 = \"\";\n\n while (tokenizer1.MoveNext()) {\n if (!tokenizer2.MoveNext()) {\n do {\n number1 = tokenizer1.getNumber();\n suffix1 = tokenizer1.getSuffix();\n if (number1 != 0 || suffix1.length() != 0) {\n // Version one is longer than number two, and non-zero\n return 1;\n }\n }\n while (tokenizer1.MoveNext());\n\n // Version one is longer than version two, but zero\n return 0;\n }\n\n number1 = tokenizer1.getNumber();\n suffix1 = tokenizer1.getSuffix();\n number2 = tokenizer2.getNumber();\n suffix2 = tokenizer2.getSuffix();\n\n if (number1 < number2) {\n // Number one is less than number two\n return -1;\n }\n if (number1 > number2) {\n // Number one is greater than number two\n return 1;\n }\n\n boolean empty1 = suffix1.length() == 0;\n boolean empty2 = suffix2.length() == 0;\n\n if (empty1 && empty2) continue; // No suffixes\n if (empty1) return 1; // First suffix is empty (1.2 > 1.2b)\n if (empty2) return -1; // Second suffix is empty (1.2a < 1.2)\n\n // Lexical comparison of suffixes\n int result = suffix1.compareTo(suffix2);\n if (result != 0) return result;\n\n }\n if (tokenizer2.MoveNext()) {\n do {\n number2 = tokenizer2.getNumber();\n suffix2 = tokenizer2.getSuffix();\n if (number2 != 0 || suffix2.length() != 0) {\n // Version one is longer than version two, and non-zero\n return -1;\n }\n }\n while (tokenizer2.MoveNext());\n\n // Version two is longer than version one, but zero\n return 0;\n }\n return 0;\n }\n}\n\n// VersionTokenizer.java\npublic class VersionTokenizer {\n private final String _versionString;\n private final int _length;\n\n private int _position;\n private int _number;\n private String _suffix;\n private boolean _hasValue;\n\n public int getNumber() {\n return _number;\n }\n\n public String getSuffix() {\n return _suffix;\n }\n\n public boolean hasValue() {\n return _hasValue;\n }\n\n public VersionTokenizer(String versionString) {\n if (versionString == null)\n throw new IllegalArgumentException(\"versionString is null\");\n\n _versionString = versionString;\n _length = versionString.length();\n }\n\n public boolean MoveNext() {\n _number = 0;\n _suffix = \"\";\n _hasValue = false;\n\n // No more characters\n if (_position >= _length)\n return false;\n\n _hasValue = true;\n\n while (_position < _length) {\n char c = _versionString.charAt(_position);\n if (c < '0' || c > '9') break;\n _number = _number * 10 + (c - '0');\n _position++;\n }\n\n int suffixStart = _position;\n\n while (_position < _length) {\n char c = _versionString.charAt(_position);\n if (c == '.') break;\n _position++;\n }\n\n _suffix = _versionString.substring(suffixStart, _position);\n\n if (_position < _length) _position++;\n\n return true;\n }\n}\n public class Main\n{\n private static VersionComparator cmp;\n\n public static void main (String[] args)\n {\n cmp = new VersionComparator();\n Test(new String[]{\"1.1.2\", \"1.2\", \"1.2.0\", \"1.2.1\", \"1.12\"});\n Test(new String[]{\"1.3\", \"1.3a\", \"1.3b\", \"1.3-SNAPSHOT\"});\n }\n\n private static void Test(String[] versions) {\n for (int i = 0; i < versions.length; i++) {\n for (int j = i; j < versions.length; j++) {\n Test(versions[i], versions[j]);\n }\n }\n }\n\n private static void Test(String v1, String v2) {\n int result = cmp.compare(v1, v2);\n String op = \"==\";\n if (result < 0) op = \"<\";\n if (result > 0) op = \">\";\n System.out.printf(\"%s %s %s\\n\", v1, op, v2);\n }\n}\n 1.1.2 == 1.1.2 ---> same length and value\n1.1.2 < 1.2 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.2.0 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.2.1 ---> first number (1) less than second number (2) => -1\n1.1.2 < 1.12 ---> first number (1) less than second number (12) => -1\n1.2 == 1.2 ---> same length and value\n1.2 == 1.2.0 ---> first shorter than second, but zero\n1.2 < 1.2.1 ---> first shorter than second, and non-zero\n1.2 < 1.12 ---> first number (2) less than second number (12) => -1\n1.2.0 == 1.2.0 ---> same length and value\n1.2.0 < 1.2.1 ---> first number (0) less than second number (1) => -1\n1.2.0 < 1.12 ---> first number (2) less than second number (12) => -1\n1.2.1 == 1.2.1 ---> same length and value\n1.2.1 < 1.12 ---> first number (2) less than second number (12) => -1\n1.12 == 1.12 ---> same length and value\n\n1.3 == 1.3 ---> same length and value\n1.3 > 1.3a ---> first suffix ('') is empty, but not second ('a') => 1\n1.3 > 1.3b ---> first suffix ('') is empty, but not second ('b') => 1\n1.3 > 1.3-SNAPSHOT ---> first suffix ('') is empty, but not second ('-SNAPSHOT') => 1\n1.3a == 1.3a ---> same length and value\n1.3a < 1.3b ---> first suffix ('a') compared to second suffix ('b') => -1\n1.3a < 1.3-SNAPSHOT ---> first suffix ('a') compared to second suffix ('-SNAPSHOT') => -1\n1.3b == 1.3b ---> same length and value\n1.3b < 1.3-SNAPSHOT ---> first suffix ('b') compared to second suffix ('-SNAPSHOT') => -1\n1.3-SNAPSHOT == 1.3-SNAPSHOT ---> same length and value\n"
},
{
"answer_id": 11024200,
"author": "alex",
"author_id": 1445568,
"author_profile": "https://Stackoverflow.com/users/1445568",
"pm_score": 8,
"selected": false,
"text": "public class Version implements Comparable<Version> {\n\n private String version;\n\n public final String get() {\n return this.version;\n }\n\n public Version(String version) {\n if(version == null)\n throw new IllegalArgumentException(\"Version can not be null\");\n if(!version.matches(\"[0-9]+(\\\\.[0-9]+)*\"))\n throw new IllegalArgumentException(\"Invalid version format\");\n this.version = version;\n }\n\n @Override public int compareTo(Version that) {\n if(that == null)\n return 1;\n String[] thisParts = this.get().split(\"\\\\.\");\n String[] thatParts = that.get().split(\"\\\\.\");\n int length = Math.max(thisParts.length, thatParts.length);\n for(int i = 0; i < length; i++) {\n int thisPart = i < thisParts.length ?\n Integer.parseInt(thisParts[i]) : 0;\n int thatPart = i < thatParts.length ?\n Integer.parseInt(thatParts[i]) : 0;\n if(thisPart < thatPart)\n return -1;\n if(thisPart > thatPart)\n return 1;\n }\n return 0;\n }\n\n @Override public boolean equals(Object that) {\n if(this == that)\n return true;\n if(that == null)\n return false;\n if(this.getClass() != that.getClass())\n return false;\n return this.compareTo((Version) that) == 0;\n }\n\n}\n Version a = new Version(\"1.1\");\nVersion b = new Version(\"1.1.1\");\na.compareTo(b) // return -1 (a<b)\na.equals(b) // return false\n\nVersion a = new Version(\"2.0\");\nVersion b = new Version(\"1.9.9\");\na.compareTo(b) // return 1 (a>b)\na.equals(b) // return false\n\nVersion a = new Version(\"1.0\");\nVersion b = new Version(\"1\");\na.compareTo(b) // return 0 (a=b)\na.equals(b) // return true\n\nVersion a = new Version(\"1\");\nVersion b = null;\na.compareTo(b) // return 1 (a>b)\na.equals(b) // return false\n\nList<Version> versions = new ArrayList<Version>();\nversions.add(new Version(\"2\"));\nversions.add(new Version(\"1.0.5\"));\nversions.add(new Version(\"1.01.0\"));\nversions.add(new Version(\"1.00.1\"));\nCollections.min(versions).get() // return min version\nCollections.max(versions).get() // return max version\n\n// WARNING\nVersion a = new Version(\"2.06\");\nVersion b = new Version(\"2.060\");\na.equals(b) // return false\n"
},
{
"answer_id": 27109234,
"author": "sfrizvi6",
"author_id": 4288292,
"author_profile": "https://Stackoverflow.com/users/4288292",
"pm_score": -1,
"selected": false,
"text": "public class VersionComparator {\n\n /* loop through both version strings\n * then loop through the inner string to computer the val of the int\n * for each integer read, do num*10+<integer read>\n * and stop when stumbling upon '.'\n * When '.' is encountered...\n * see if '.' is encountered for both strings\n * if it is then compare num1 and num2 \n * if num1 == num2... iterate over p1++, p2++\n * else return (num1 > num2) ? 1 : -1\n * If both the string end then compare(num1, num2) return 0, 1, -1\n * else loop through the longer string and \n * verify if it only has trailing zeros\n * If it only has trailing zeros then return 0\n * else it is greater than the other string\n */\n public static int compareVersions(String v1, String v2) {\n int num1 = 0;\n int num2 = 0;\n int p1 = 0;\n int p2 = 0;\n\n while (p1 < v1.length() && p2 < v2.length()) {\n num1 = Integer.parseInt(v1.charAt(p1) + \"\");\n num2 = Integer.parseInt(v2.charAt(p2) + \"\");\n p1++;\n p2++;\n\n while (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) != '.' && v2.charAt(p2) != '.') {\n if (p1 < v1.length()) num1 = num1 * 10 + Integer.parseInt(v1.charAt(p1) + \"\");\n if (p2 < v2.length()) num2 = num2 * 10 + Integer.parseInt(v2.charAt(p2) + \"\");\n p1++;\n p2++;\n }\n\n if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.' && v2.charAt(p2) == '.') {\n if ((num1 ^ num2) == 0) {\n p1++;\n p2++;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n else if (p1 < v1.length() && p2 < v2.length() && v1.charAt(p1) == '.') return -1;\n else if (p1 < v1.length() && p2 < v2.length() && v2.charAt(p2) == '.') return 1;\n }\n\n if (p1 == v1.length() && p2 == v2.length()) {\n if ((num1 ^ num2) == 0) return 0;\n else return (num1 > num2) ? 1 : -1;\n }\n else if (p1 == v1.length()) {\n if ((num1 ^ num2) == 0) {\n while (p2 < v2.length()) {\n if (v2.charAt(p2) != '.' && v2.charAt(p2) != '0') return -1;\n p2++;\n }\n return 0;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n else {\n if ((num1 ^ num2) == 0) {\n while (p1 < v1.length()) {\n if (v1.charAt(p1) != '.' && v1.charAt(p1) != '0') return 1;\n p1++;\n }\n return 0;\n }\n else return (num1 > num2) ? 1 : -1;\n }\n }\n\n public static void main(String[] args) {\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"11.21.1.0.0.1.0\", \"11.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.23.0.0.0.1.0\") ^ -1);\n System.out.println(compareVersions(\"11.2\", \"11.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"1.21.1.0.0.1.0\", \"2.23\") ^ -1);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"11.23.0.0.0.0.0\", \"11.23\") ^ 0);\n System.out.println(compareVersions(\"11.23\", \"11.21.1.0.0.1.0\") ^ 1);\n System.out.println(compareVersions(\"1.5.1.3\", \"1.5.1.3.0\") ^ 0);\n System.out.println(compareVersions(\"1.5.1.4\", \"1.5.1.3.0\") ^ 1);\n System.out.println(compareVersions(\"1.2.1.3\", \"1.5.1.3.0\") ^ -1);\n System.out.println(compareVersions(\"1.2.1.3\", \"1.22.1.3.0\") ^ -1);\n System.out.println(compareVersions(\"1.222.1.3\", \"1.22.1.3.0\") ^ 1);\n }\n}\n"
},
{
"answer_id": 27891752,
"author": "Algorithmatic",
"author_id": 1122229,
"author_profile": "https://Stackoverflow.com/users/1122229",
"pm_score": 4,
"selected": false,
"text": "public static int compareVersions(String version1, String version2){\n\n String[] levels1 = version1.split(\"\\\\.\");\n String[] levels2 = version2.split(\"\\\\.\");\n\n int length = Math.max(levels1.length, levels2.length);\n for (int i = 0; i < length; i++){\n Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;\n Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;\n int compare = v1.compareTo(v2);\n if (compare != 0){\n return compare;\n }\n }\n\n return 0;\n}\n"
},
{
"answer_id": 31103694,
"author": "ballzak",
"author_id": 445360,
"author_profile": "https://Stackoverflow.com/users/445360",
"pm_score": -1,
"selected": false,
"text": "public static final Comparator<CharSequence> VERSION_ORDER = new Comparator<CharSequence>() {\n\n @Override\n public int compare (CharSequence lhs, CharSequence rhs) {\n int ll = lhs.length(), rl = rhs.length(), lv = 0, rv = 0, li = 0, ri = 0;\n char c;\n do {\n lv = rv = 0;\n while (--ll >= 0) {\n c = lhs.charAt(li++);\n if (c < '0' || c > '9')\n break;\n lv = lv*10 + c - '0';\n }\n while (--rl >= 0) {\n c = rhs.charAt(ri++);\n if (c < '0' || c > '9')\n break;\n rv = rv*10 + c - '0';\n }\n } while (lv == rv && (ll >= 0 || rl >= 0));\n return lv - rv;\n }\n\n};\n \"0.1\" - \"1.0\" = -1\n\"1.0\" - \"1.0\" = 0\n\"1.0\" - \"1.0.0\" = 0\n\"10\" - \"1.0\" = 9\n\"3.7.6\" - \"3.7.11\" = -5\n\"foobar\" - \"1.0\" = -1\n"
},
{
"answer_id": 36431997,
"author": "gorums",
"author_id": 1327403,
"author_profile": "https://Stackoverflow.com/users/1327403",
"pm_score": -1,
"selected": false,
"text": "public static boolean apply(String cmpDeviceVersion, String reqDeviceVersion)\n{\n Boolean equal = !cmpDeviceVersion.contains(\">\") && !cmpDeviceVersion.contains(\">=\") &&\n !cmpDeviceVersion.contains(\"<\") && !cmpDeviceVersion.contains(\"<=\") &&\n !cmpDeviceVersion.contains(\"~>\");\n\n Boolean between = cmpDeviceVersion.contains(\"~>\");\n Boolean higher = cmpDeviceVersion.contains(\">\") && !cmpDeviceVersion.contains(\">=\") && !cmpDeviceVersion.contains(\"~>\");\n Boolean higherOrEqual = cmpDeviceVersion.contains(\">=\");\n\n Boolean less = cmpDeviceVersion.contains(\"<\") && !cmpDeviceVersion.contains(\"<=\");\n Boolean lessOrEqual = cmpDeviceVersion.contains(\"<=\");\n\n cmpDeviceVersion = cmpDeviceVersion.replaceAll(\"[<>=~]\", \"\");\n cmpDeviceVersion = cmpDeviceVersion.trim();\n\n String[] version = cmpDeviceVersion.split(\"\\\\.\");\n String[] reqVersion = reqDeviceVersion.split(\"\\\\.\");\n\n if(equal)\n {\n return isEqual(version, reqVersion);\n }\n else if(between)\n {\n return isBetween(version, reqVersion);\n }\n else if(higher)\n {\n return isHigher(version, reqVersion);\n }\n else if(higherOrEqual)\n {\n return isEqual(version, reqVersion) || isHigher(version, reqVersion);\n }\n else if(less)\n {\n return isLess(version, reqVersion);\n }\n else if(lessOrEqual)\n {\n return isEqual(version, reqVersion) || isLess(version, reqVersion);\n }\n\n return false;\n}\n\nprivate static boolean isEqual(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strVersion.equals(strReqVersion);\n}\n\nprivate static boolean isHigher(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strReqVersion.compareTo(strVersion) > 0;\n}\n\nprivate static boolean isLess(String[] version, String[] reqVersion)\n{\n String strVersion = StringUtils.join(version);\n String strReqVersion = StringUtils.join(reqVersion);\n if(version.length > reqVersion.length)\n {\n Integer diff = version.length - reqVersion.length;\n strReqVersion += StringUtils.repeat(\".0\", diff);\n }\n else if(reqVersion.length > version.length)\n {\n Integer diff = reqVersion.length - version.length;\n strVersion += StringUtils.repeat(\".0\", diff);\n }\n\n return strReqVersion.compareTo(strVersion) < 0;\n}\n\nprivate static boolean isBetween(String[] version, String[] reqVersion)\n{\n return (isEqual(version, reqVersion) || isHigher(version, reqVersion)) &&\n isLess(getNextVersion(version), reqVersion);\n}\n\nprivate static String[] getNextVersion(String[] version)\n{\n String[] nextVersion = new String[version.length];\n for(int i = version.length - 1; i >= 0 ; i--)\n {\n if(i == version.length - 1)\n {\n nextVersion[i] = \"0\";\n }\n else if((i == version.length - 2) && NumberUtils.isNumber(version[i]))\n {\n nextVersion[i] = String.valueOf(NumberUtils.toInt(version[i]) + 1);\n }\n else\n {\n nextVersion[i] = version[i];\n }\n }\n return nextVersion;\n}\n"
},
{
"answer_id": 37593558,
"author": "Igor Maznitsa",
"author_id": 1802697,
"author_profile": "https://Stackoverflow.com/users/1802697",
"pm_score": 1,
"selected": false,
"text": "!=ide-1.1.1,>idea-1.3.4-SNAPSHOT;<1.2.3"
},
{
"answer_id": 40089814,
"author": "Alex",
"author_id": 288568,
"author_profile": "https://Stackoverflow.com/users/288568",
"pm_score": 5,
"selected": false,
"text": "Semver sem = new Semver(\"1.2.3\");\nsem.isGreaterThan(\"1.2.2\"); // true\n"
},
{
"answer_id": 41530729,
"author": "Abhinav Puri",
"author_id": 4370675,
"author_profile": "https://Stackoverflow.com/users/4370675",
"pm_score": -1,
"selected": false,
"text": " /**\n * Normalize string array, \n * Appends zeros if string from the array\n * has length smaller than the maxLen.\n **/\n private String normalize(String[] split, int maxLen){\n StringBuilder sb = new StringBuilder(\"\");\n for(String s : split) {\n for(int i = 0; i<maxLen-s.length(); i++) sb.append('0');\n sb.append(s);\n }\n return sb.toString();\n }\n\n /**\n * Removes trailing zeros of the form '.00.0...00'\n * (and does not remove zeros from, say, '4.1.100')\n **/\n public String removeTrailingZeros(String s){\n int i = s.length()-1;\n int k = s.length()-1;\n while(i >= 0 && (s.charAt(i) == '.' || s.charAt(i) == '0')){\n if(s.charAt(i) == '.') k = i-1;\n i--; \n } \n return s.substring(0,k+1);\n }\n\n /**\n * Compares two versions(works for alphabets too),\n * Returns 1 if v1 > v2, returns 0 if v1 == v2,\n * and returns -1 if v1 < v2.\n **/\n public int compareVersion(String v1, String v2) {\n\n // Uncomment below two lines if for you, say, 4.1.0 is equal to 4.1\n // v1 = removeTrailingZeros(v1);\n // v2 = removeTrailingZeros(v2);\n\n String[] splitv1 = v1.split(\"\\\\.\");\n String[] splitv2 = v2.split(\"\\\\.\");\n int maxLen = 0;\n for(String str : splitv1) maxLen = Math.max(maxLen, str.length());\n for(String str : splitv2) maxLen = Math.max(maxLen, str.length());\n int cmp = normalize(splitv1, maxLen).compareTo(normalize(splitv2, maxLen));\n return cmp > 0 ? 1 : (cmp < 0 ? -1 : 0);\n }\n"
},
{
"answer_id": 42311661,
"author": "Arpan Sharma",
"author_id": 5954472,
"author_profile": "https://Stackoverflow.com/users/5954472",
"pm_score": 0,
"selected": false,
"text": " public static boolean checkVersionUpdate(String olderVerison, String newVersion) {\n if (olderVerison.length() == 0 || newVersion.length() == 0) {\n return false;\n }\n List<String> newVerList = Arrays.asList(newVersion.split(\"\\\\.\"));\n List<String> oldVerList = Arrays.asList(olderVerison.split(\"\\\\.\"));\n\n int diff = newVerList.size() - oldVerList.size();\n List<String> newList = new ArrayList<>();\n if (diff > 0) {\n newList.addAll(oldVerList);\n for (int i = 0; i < diff; i++) {\n newList.add(\"0\");\n }\n return examineArray(newList, newVerList, diff);\n } else if (diff < 0) {\n newList.addAll(newVerList);\n for (int i = 0; i < -diff; i++) {\n newList.add(\"0\");\n }\n return examineArray(oldVerList, newList, diff);\n } else {\n return examineArray(oldVerList, newVerList, diff);\n }\n\n }\n\n public static boolean examineArray(List<String> oldList, List<String> newList, int diff) {\n boolean newVersionGreater = false;\n for (int i = 0; i < oldList.size(); i++) {\n if (Integer.parseInt(newList.get(i)) > Integer.parseInt(oldList.get(i))) {\n newVersionGreater = true;\n break;\n } else if (Integer.parseInt(newList.get(i)) < Integer.parseInt(oldList.get(i))) {\n newVersionGreater = false;\n break;\n } else {\n newVersionGreater = diff > 0;\n }\n }\n\n return newVersionGreater;\n }\n"
},
{
"answer_id": 50181582,
"author": "Stan Towianski",
"author_id": 2366973,
"author_profile": "https://Stackoverflow.com/users/2366973",
"pm_score": 2,
"selected": false,
"text": "/** \n * written by: Stan Towianski - May 2018 \n * notes: I make assumption each of 3 version sections a.b.c is not longer then 4 digits: aaaa.bbbb.cccc-MODWORD1(-)modnum2\n * 5.10.13-release-1 becomes 0000500100013.501 6.0-snapshot becomes 0000600000000.100\n * MODWORD1 = -xyz/NotMatching, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing return: .0, .1, .2, .3, .4, .5\n * modnum2 = up to 2 digit/chars second version\n * */\npublic class VersionCk {\n\n private static boolean isVersionHigher( String baseVersion, String testVersion )\n {\n System.out.println( \"versionToComparable( baseVersion ) =\" + versionToComparable( baseVersion ) );\n System.out.println( \"versionToComparable( testVersion ) =\" + versionToComparable( testVersion ) + \" is this higher ?\" );\n return versionToComparable( testVersion ).compareTo( versionToComparable( baseVersion ) ) > 0;\n }\n\n //---- not worrying about += for something so small\n private static String versionToComparable( String version )\n {\n// System.out.println(\"version - \" + version);\n String versionNum = version;\n int at = version.indexOf( '-' );\n if ( at >= 0 )\n versionNum = version.substring( 0, at );\n\n String[] numAr = versionNum.split( \"\\\\.\" );\n String versionFormatted = \"0\";\n for ( String tmp : numAr )\n {\n versionFormatted += String.format( \"%4s\", tmp ).replace(' ', '0');\n }\n while ( versionFormatted.length() < 12 ) // pad out to aaaa.bbbb.cccc\n {\n versionFormatted += \"0000\";\n }\n// System.out.println( \"converted min version =\" + versionFormatted + \"= : \" + versionNum );\n return versionFormatted + getVersionModifier( version, at );\n }\n\n //---- use order low to high: -xyz, -SNAPSHOT, -ALPHA, -BETA, -RC, -RELEASE/nothing returns: 0, 1, 2, 3, 4, 5\n private static String getVersionModifier( String version, int at )\n {\n// System.out.println(\"version - \" + version );\n String[] wordModsAr = { \"-SNAPSHOT\", \"-ALPHA\", \"-BETA\", \"-RC\", \"-RELEASE\" }; \n\n if ( at < 0 )\n return \".\" + wordModsAr.length + \"00\"; // make nothing = RELEASE level\n\n int i = 1;\n for ( String word : wordModsAr )\n {\n if ( ( at = version.toUpperCase().indexOf( word ) ) > 0 )\n return \".\" + i + getSecondVersionModifier( version.substring( at + word.length() ) );\n i++;\n }\n\n return \".000\";\n }\n\n //---- add 2 chars for any number after first modifier. -rc2 or -rc-2 returns 02\n private static String getSecondVersionModifier( String version )\n {\n System.out.println( \"second modifier =\" + version + \"=\" );\n Matcher m = Pattern.compile(\"(.*?)(\\\\d+).*\").matcher( version );\n// if ( m.matches() )\n// System.out.println( \"match ? =\" + m.matches() + \"= m.group(1) =\" + m.group(1) + \"= m.group(2) =\" + m.group(2) + \"= m.group(3) =\" + (m.groupCount() >= 3 ? m.group(3) : \"x\") );\n// else\n// System.out.println( \"No match\" );\n return m.matches() ? String.format( \"%2s\", m.group(2) ).replace(' ', '0') : \"00\";\n }\n\n public static void main(String[] args) \n {\n checkVersion( \"3.10.0\", \"3.4.0\");\n checkVersion( \"5.4.2\", \"5.4.1\");\n checkVersion( \"5.4.4\", \"5.4.5\");\n checkVersion( \"5.4.9\", \"5.4.12\");\n checkVersion( \"5.9.222\", \"5.10.12\");\n checkVersion( \"5.10.12\", \"5.10.12\");\n checkVersion( \"5.10.13\", \"5.10.14\");\n checkVersion( \"6.7.0\", \"6.8\");\n checkVersion( \"6.7\", \"2.7.0\");\n checkVersion( \"6\", \"6.3.1\");\n checkVersion( \"4\", \"4.0.0\");\n checkVersion( \"6.3.0\", \"6\");\n checkVersion( \"5.10.12-Alpha\", \"5.10.12-beTA\");\n checkVersion( \"5.10.13-release\", \"5.10.14-beta\");\n checkVersion( \"6.7.0\", \"6.8-snapshot\");\n checkVersion( \"6.7.1\", \"6.7.0-release\");\n checkVersion( \"6-snapshot\", \"6.0.0-beta\");\n checkVersion( \"6.0-snapshot\", \"6.0.0-whatthe\");\n checkVersion( \"5.10.12-Alpha-1\", \"5.10.12-alpha-2\");\n checkVersion( \"5.10.13-release-1\", \"5.10.13-release2\");\n checkVersion( \"10-rc42\", \"10.0.0-rc53\");\n }\n\n private static void checkVersion(String baseVersion, String testVersion) \n {\n System.out.println( \"baseVersion - \" + baseVersion );\n System.out.println( \"testVersion - \" + testVersion );\n System.out.println( \"isVersionHigher = \" + isVersionHigher( baseVersion, testVersion ) );\n System.out.println( \"---------------\");\n }\n\n }\n ---------------\nbaseVersion - 6.7\ntestVersion - 2.7.0\nversionToComparable( baseVersion ) =0000600070000.500\nversionToComparable( testVersion ) =0000200070000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 6\ntestVersion - 6.3.1\nversionToComparable( baseVersion ) =0000600000000.500\nversionToComparable( testVersion ) =0000600030001.500 is this higher ?\nisVersionHigher = true\n---------------\nbaseVersion - 4\ntestVersion - 4.0.0\nversionToComparable( baseVersion ) =0000400000000.500\nversionToComparable( testVersion ) =0000400000000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 6.3.0\ntestVersion - 6\nversionToComparable( baseVersion ) =0000600030000.500\nversionToComparable( testVersion ) =0000600000000.500 is this higher ?\nisVersionHigher = false\n---------------\nbaseVersion - 5.10.12-Alpha\ntestVersion - 5.10.12-beTA\nsecond modifier ==\nversionToComparable( baseVersion ) =0000500100012.200\nsecond modifier ==\nversionToComparable( testVersion ) =0000500100012.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 5.10.13-release\ntestVersion - 5.10.14-beta\nsecond modifier ==\nversionToComparable( baseVersion ) =0000500100013.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000500100014.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.7.0\ntestVersion - 6.8-snapshot\nversionToComparable( baseVersion ) =0000600070000.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000600080000.100 is this higher ?\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.7.1\ntestVersion - 6.7.0-release\nversionToComparable( baseVersion ) =0000600070001.500\nsecond modifier ==\nversionToComparable( testVersion ) =0000600070000.500 is this higher ?\nsecond modifier ==\nisVersionHigher = false\n---------------\nbaseVersion - 6-snapshot\ntestVersion - 6.0.0-beta\nsecond modifier ==\nversionToComparable( baseVersion ) =0000600000000.100\nsecond modifier ==\nversionToComparable( testVersion ) =0000600000000.300 is this higher ?\nsecond modifier ==\nsecond modifier ==\nisVersionHigher = true\n---------------\nbaseVersion - 6.0-snapshot\ntestVersion - 6.0.0-whatthe\nsecond modifier ==\nversionToComparable( baseVersion ) =0000600000000.100\nversionToComparable( testVersion ) =0000600000000.000 is this higher ?\nsecond modifier ==\nisVersionHigher = false\n---------------\nbaseVersion - 5.10.12-Alpha-1\ntestVersion - 5.10.12-alpha-2\nsecond modifier =-1=\nversionToComparable( baseVersion ) =0000500100012.201\nsecond modifier =-2=\nversionToComparable( testVersion ) =0000500100012.202 is this higher ?\nsecond modifier =-2=\nsecond modifier =-1=\nisVersionHigher = true\n---------------\nbaseVersion - 5.10.13-release-1\ntestVersion - 5.10.13-release2\nsecond modifier =-1=\nversionToComparable( baseVersion ) =0000500100013.501\nsecond modifier =2=\nversionToComparable( testVersion ) =0000500100013.502 is this higher ?\nsecond modifier =2=\nsecond modifier =-1=\nisVersionHigher = true\n---------------\nbaseVersion - 10-rc42\ntestVersion - 10.0.0-rc53\nsecond modifier =42=\nversionToComparable( baseVersion ) =0001000000000.442\nsecond modifier =53=\nversionToComparable( testVersion ) =0001000000000.453 is this higher ?\nsecond modifier =53=\nsecond modifier =42=\nisVersionHigher = true\n---------------\n"
},
{
"answer_id": 53944480,
"author": "Maciej Dzikowicki",
"author_id": 3249355,
"author_profile": "https://Stackoverflow.com/users/3249355",
"pm_score": 3,
"selected": false,
"text": "com.fasterxml.jackson.core.Version import com.fasterxml.jackson.core.Version;\nimport org.junit.Test;\n\nimport static org.junit.Assert.assertTrue;\n\npublic class VersionTest {\n\n @Test\n public void shouldCompareVersion() {\n Version version1 = new Version(1, 11, 1, null, null, null);\n Version version2 = new Version(1, 12, 1, null, null, null);\n assertTrue(version1.compareTo(version2) < 0);\n }\n}\n"
},
{
"answer_id": 55023200,
"author": "Michael Gantman",
"author_id": 5802417,
"author_profile": "https://Stackoverflow.com/users/5802417",
"pm_score": 2,
"selected": false,
"text": "TextUtils.comapreVersions(...)"
},
{
"answer_id": 55141303,
"author": "ban",
"author_id": 4269728,
"author_profile": "https://Stackoverflow.com/users/4269728",
"pm_score": 1,
"selected": false,
"text": "public int CompareVersions(String version1, String version2)\n{\n String[] string1Vals = version1.split(\"\\\\.\");\n String[] string2Vals = version2.split(\"\\\\.\");\n\n int length = Math.max(string1Vals.length, string2Vals.length);\n\n for (int i = 0; i < length; i++)\n {\n Integer v1 = (i < string1Vals.length)?Integer.parseInt(string1Vals[i]):0;\n Integer v2 = (i < string2Vals.length)?Integer.parseInt(string2Vals[i]):0;\n\n //Making sure Version1 bigger than version2\n if (v1 > v2)\n {\n return 1;\n }\n //Making sure Version1 smaller than version2\n else if(v1 < v2)\n {\n return -1;\n }\n }\n\n //Both are equal\n return 0;\n}\n"
},
{
"answer_id": 57338571,
"author": "G00fY",
"author_id": 3660290,
"author_profile": "https://Stackoverflow.com/users/3660290",
"pm_score": 1,
"selected": false,
"text": " public int compareVersions(String versionA, String versionB) {\n String[] versionTokensA = versionA.split(\"\\\\.\");\n String[] versionTokensB = versionB.split(\"\\\\.\");\n List<Integer> versionNumbersA = new ArrayList<>();\n List<Integer> versionNumbersB = new ArrayList<>();\n\n for (String versionToken : versionTokensA) {\n versionNumbersA.add(Integer.parseInt(versionToken));\n }\n for (String versionToken : versionTokensB) {\n versionNumbersB.add(Integer.parseInt(versionToken));\n }\n\n final int versionASize = versionNumbersA.size();\n final int versionBSize = versionNumbersB.size();\n int maxSize = Math.max(versionASize, versionBSize);\n\n for (int i = 0; i < maxSize; i++) {\n if ((i < versionASize ? versionNumbersA.get(i) : 0) > (i < versionBSize ? versionNumbersB.get(i) : 0)) {\n return 1;\n } else if ((i < versionASize ? versionNumbersA.get(i) : 0) < (i < versionBSize ? versionNumbersB.get(i) : 0)) {\n return -1;\n }\n }\n return 0;\n }\n"
},
{
"answer_id": 57900552,
"author": "Saurav Sahu",
"author_id": 1465553,
"author_profile": "https://Stackoverflow.com/users/1465553",
"pm_score": 0,
"selected": false,
"text": "public int compareVersion(String A, String B) {\n List<String> strList1 = Arrays.stream(A.split(\"\\\\.\"))\n .map(s -> s.replaceAll(\"^0+(?!$)\", \"\"))\n .collect(Collectors.toList());\n List<String> strList2 = Arrays.stream(B.split(\"\\\\.\"))\n .map(s -> s.replaceAll(\"^0+(?!$)\", \"\"))\n .collect(Collectors.toList());\n int len1 = strList1.size();\n int len2 = strList2.size();\n int i = 0;\n while(i < len1 && i < len2){\n if (strList1.get(i).length() > strList2.get(i).length()) return 1;\n if (strList1.get(i).length() < strList2.get(i).length()) return -1;\n int result = new Long(strList1.get(i)).compareTo(new Long(strList2.get(i)));\n if (result != 0) return result;\n i++;\n }\n while (i < len1){\n if (!strList1.get(i++).equals(\"0\")) return 1;\n }\n while (i < len2){\n if (!strList2.get(i++).equals(\"0\")) return -1;\n }\n return 0;\n}\n"
},
{
"answer_id": 58876745,
"author": "felixh",
"author_id": 3415235,
"author_profile": "https://Stackoverflow.com/users/3415235",
"pm_score": 1,
"selected": false,
"text": "import java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nclass Main {\n static double parseVersion(String v) {\n if (v.isEmpty()) {\n return 0;\n }\n Pattern p = Pattern.compile(\"^(\\\\D*)(\\\\d*)(\\\\D*)$\");\n Matcher m = p.matcher(v);\n m.find();\n if (m.group(2).isEmpty()) {\n // v1.0.0.[preview]\n return -1;\n }\n double i = Integer.parseInt(m.group(2));\n if (!m.group(3).isEmpty()) {\n // v1.0.[0b]\n i -= 0.1;\n }\n return i;\n }\n\n public static int versionCompare(String str1, String str2) {\n String[] v1 = str1.split(\"\\\\.\");\n String[] v2 = str2.split(\"\\\\.\");\n int i = 0;\n for (; i < v1.length && i < v2.length; i++) {\n double iv1 = parseVersion(v1[i]);\n double iv2 = parseVersion(v2[i]);\n\n if (iv1 != iv2) {\n return iv1 - iv2 < 0 ? -1 : 1;\n }\n }\n if (i < v1.length) {\n // \"1.0.1\", \"1.0\"\n double iv1 = parseVersion(v1[i]);\n return iv1 < 0 ? -1 : (int) Math.ceil(iv1);\n }\n if (i < v2.length) {\n double iv2 = parseVersion(v2[i]);\n return -iv2 < 0 ? -1 : (int) Math.ceil(iv2);\n }\n return 0;\n }\n\n\n public static void main(String[] args) {\n System.out.println(\"versionCompare(v1.0.0, 1.0.0)\");\n System.out.println(versionCompare(\"v1.0.0\", \"1.0.0\")); // 0\n\n System.out.println(\"versionCompare(v1.0.0b, 1.0.0)\");\n System.out.println(versionCompare(\"v1.0.0b\", \"1.0.0\")); // -1\n\n System.out.println(\"versionCompare(v1.0.0.preview, 1.0.0)\");\n System.out.println(versionCompare(\"v1.0.0.preview\", \"1.0.0\")); // -1\n\n System.out.println(\"versionCompare(v1.0, 1.0.0)\");\n System.out.println(versionCompare(\"v1.0\", \"1.0.0\")); // 0\n\n System.out.println(\"versionCompare(ver1.0, 1.0.1)\");\n System.out.println(versionCompare(\"ver1.0\", \"1.0.1\")); // -1\n }\n}\n"
},
{
"answer_id": 59214235,
"author": "BharathRao",
"author_id": 8331006,
"author_profile": "https://Stackoverflow.com/users/8331006",
"pm_score": 0,
"selected": false,
"text": "import java.util.List;\nimport java.util.ArrayList;\nimport java.util.Arrays;\npublic class Main\n{\n static String firebaseVersion = \"2.1.3\"; // or 2.1\n static String appVersion = \"2.1.4\";\n static List<String> firebaseVersionArray;\n static List<String> appVersionArray;\n static boolean isNeedToShowAlert = false;\n public static void main (String[]args)\n {\n System.out.println (\"Hello World\");\n firebaseVersionArray = new ArrayList<String>(Arrays.asList(firebaseVersion.split (\"\\\\.\")));\n appVersionArray = new ArrayList<String>(Arrays.asList(appVersion.split (\"\\\\.\")));\n if(appVersionArray.size() < firebaseVersionArray.size()) {\n appVersionArray.add(\"0\");\n }\n if(firebaseVersionArray.size() < appVersionArray.size()) {\n firebaseVersionArray.add(\"0\");\n }\n isNeedToShowAlert = needToShowAlert(); //Returns false\n System.out.println (isNeedToShowAlert);\n\n }\n static boolean needToShowAlert() {\n boolean result = false;\n for(int i = 0 ; i < appVersionArray.size() ; i++) {\n if (Integer.parseInt(appVersionArray.get(i)) == Integer.parseInt(firebaseVersionArray.get(i))) {\n continue;\n } else if (Integer.parseInt(appVersionArray.get(i)) > Integer.parseInt(firebaseVersionArray.get(i))){\n result = false;\n break;\n } else if (Integer.parseInt(appVersionArray.get(i)) < Integer.parseInt(firebaseVersionArray.get(i))) {\n result = true;\n break; \n }\n }\n return result;\n }\n}\n"
},
{
"answer_id": 59906510,
"author": "Lakshmi Narayana Galla",
"author_id": 7269334,
"author_profile": "https://Stackoverflow.com/users/7269334",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n\n String version1 = \"1.0\";\n String version2 = \"1.0.0\";\n String[] version1_splits = version1.split(\"\\\\.\");\n String[] version2_splits = version2.split(\"\\\\.\");\n int length = version1_splits.length >= version2_splits.length ? version1_splits.length : version2_splits.length;\n int i=0;\n for(;i<length;i++){\n int version1_int = getValue(version1_splits,i);\n int version2_int = getValue(version2_splits,i);\n if(version1_int > version2_int){\n System.out.println(\"version1 > version2\");\n break;\n }\n else if(version1_int < version2_int){\n System.out.println(\"version2 > version1\");\n break;\n }\n else{\n if(i == length-1)\n System.out.println(\"version1 = version2\");\n }\n }\n}\n\nprivate static int getValue(String[] version1_splits, int i) {\n int temp;\n try{\n temp = Integer.valueOf(version1_splits[i]);\n }\n catch(IndexOutOfBoundsException e){\n temp=0;\n }\n\n return temp;\n}\n"
},
{
"answer_id": 61420225,
"author": "Marcello Câmara",
"author_id": 11157397,
"author_profile": "https://Stackoverflow.com/users/11157397",
"pm_score": 2,
"selected": false,
"text": "userVersion.split(\"\\\\.\")\n isUpdateAvailable(userVersion.split(\"\\\\.\"), latestVersionSplit.split(\"\\\\.\"));\n /**\n * Compare two versions\n *\n * @param userVersionSplit - User string array with major, minor and patch version from user (exemple: {\"5\", \"2\", \"70\"})\n * @param latestVersionSplit - Latest string array with major, minor and patch version from api (example: {\"5\", \"2\", \"71\"})\n * @return true if user version is smaller than latest version\n */\npublic static boolean isUpdateAvailable(String[] userVersionSplit, String[] latestVersionSplit) {\n\n try {\n int majorUserVersion = Integer.parseInt(userVersionSplit[0]);\n int minorUserVersion = Integer.parseInt(userVersionSplit[1]);\n int patchUserVersion = Integer.parseInt(userVersionSplit[2]);\n\n int majorLatestVersion = Integer.parseInt(latestVersionSplit[0]);\n int minorLatestVersion = Integer.parseInt(latestVersionSplit[1]);\n int patchLatestVersion = Integer.parseInt(latestVersionSplit[2]);\n\n if (majorUserVersion <= majorLatestVersion) {\n if (majorUserVersion < majorLatestVersion) {\n return true;\n } else {\n if (minorUserVersion <= minorLatestVersion) {\n if (minorUserVersion < minorLatestVersion) {\n return true;\n } else {\n return patchUserVersion < patchLatestVersion;\n }\n }\n }\n }\n } catch (Exception ignored) {\n // Will be throw only if the versions pattern is different from \"x.x.x\" format\n // Will return false at the end\n }\n\n return false;\n}\n"
},
{
"answer_id": 61795721,
"author": "Serg Burlaka",
"author_id": 6352712,
"author_profile": "https://Stackoverflow.com/users/6352712",
"pm_score": 2,
"selected": false,
"text": "class Version(inputVersion: String) : Comparable<Version> {\n\n var version: String\n private set\n\n override fun compareTo(other: Version) =\n (split() to other.split()).let {(thisParts, thatParts)->\n val length = max(thisParts.size, thatParts.size)\n for (i in 0 until length) {\n val thisPart = if (i < thisParts.size) thisParts[i].toInt() else 0\n val thatPart = if (i < thatParts.size) thatParts[i].toInt() else 0\n if (thisPart < thatPart) return -1\n if (thisPart > thatPart) return 1\n }\n 0\n }\n\n init {\n require(inputVersion.matches(\"[0-9]+(\\\\.[0-9]+)*\".toRegex())) { \"Invalid version format\" }\n version = inputVersion\n }\n }\n\n fun Version.split() = version.split(\".\").toTypedArray()\n Version(\"1.2.4\").compareTo(Version(\"0.0.5\")) //return 1\n"
},
{
"answer_id": 62532745,
"author": "Alessandro Scarozza",
"author_id": 2642478,
"author_profile": "https://Stackoverflow.com/users/2642478",
"pm_score": 1,
"selected": false,
"text": "class Version(private val value: String) : Comparable<Version> {\n private val splitted by lazy { value.split(\"-\").first().split(\".\").map { it.toIntOrNull() ?: 0 } }\n\n override fun compareTo(other: Version): Int {\n for (i in 0 until maxOf(splitted.size, other.splitted.size)) {\n val compare = splitted.getOrElse(i) { 0 }.compareTo(other.splitted.getOrElse(i) { 0 })\n if (compare != 0)\n return compare\n }\n return 0\n }\n}\n System.err.println(Version(\"1.0\").compareTo( Version(\"1.0\")))\n System.err.println(Version(\"1.0\") < Version(\"1.1\"))\n System.err.println(Version(\"1.10\") > Version(\"1.9\"))\n System.err.println(Version(\"1.10.1\") > Version(\"1.10\"))\n System.err.println(Version(\"0.0.1\") < Version(\"1\"))\n"
},
{
"answer_id": 64374606,
"author": "Artyom Deynega",
"author_id": 2787260,
"author_profile": "https://Stackoverflow.com/users/2787260",
"pm_score": 1,
"selected": false,
"text": "class Version private constructor(private val versionString: String) : Comparable<Version> {\n\n private val major: Int by lazy { versionString.split(\".\")[0].toInt() }\n\n private val minor: Int by lazy { versionString.split(\".\")[1].toInt() }\n\n private val patch: Int by lazy {\n val splitArray = versionString.split(\".\")\n\n if (splitArray.size == 3)\n splitArray[2].toInt()\n else\n 0\n }\n\n override fun compareTo(other: Version): Int {\n return when {\n major > other.major -> 1\n major < other.major -> -1\n minor > other.minor -> 1\n minor < other.minor -> -1\n patch > other.patch -> 1\n patch < other.patch -> -1\n else -> 0\n }\n }\n\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is Version) return false\n return compareTo(other) == 0\n }\n\n override fun hashCode(): Int {\n return major * minor * patch\n }\n\n companion object {\n private fun doesContainsVersion(string: String): Boolean {\n val versionArray = string.split(\".\")\n\n return versionArray.size in 2..3\n && versionArray[0].toIntOrNull() != null\n && versionArray[1].toIntOrNull() != null\n && (versionArray.size == 2 || versionArray[2].toIntOrNull() != null)\n }\n\n fun from(string: String): Version? {\n return if (doesContainsVersion(string)) {\n Version(string)\n } else {\n null\n }\n }\n }\n}\n val version1 = Version.from(\"3.2\")\nval version2 = Version.from(\"3.2.1\")\nversion1 <= version2\n\n"
},
{
"answer_id": 65077344,
"author": "Olivier Grégoire",
"author_id": 180719,
"author_profile": "https://Stackoverflow.com/users/180719",
"pm_score": 6,
"selected": false,
"text": "Version import java.util.*;\nimport java.lang.module.ModuleDescriptor.Version;\nclass Main {\n public static void main(String[] args) {\n var versions = Arrays.asList(\n \"1.0.2\",\n \"1.0.0-beta.2\",\n \"1.0.0\",\n \"1.0.0-beta\",\n \"1.0.0-alpha.12\",\n \"1.0.0-beta.11\",\n \"1.0.1\",\n \"1.0.11\",\n \"1.0.0-rc.1\",\n \"1.0.0-alpha.1\",\n \"1.1.0\",\n \"1.0.0-alpha.beta\",\n \"1.11.0\",\n \"1.0.0-alpha.12.ab-c\",\n \"0.0.1\",\n \"1.2.1\",\n \"1.0.0-alpha\",\n \"1.0.0.1\", // Also works with a number of sections different than 3\n \"1.0.0.2\",\n \"2\",\n \"10\",\n \"1.0.0.10\"\n );\n versions.stream()\n .map(Version::parse)\n .sorted()\n .forEach(System.out::println);\n }\n}\n 0.0.1\n1.0.0-alpha\n1.0.0-alpha.1\n1.0.0-alpha.12\n1.0.0-alpha.12.ab-c\n1.0.0-alpha.beta\n1.0.0-beta\n1.0.0-beta.2\n1.0.0-beta.11\n1.0.0-rc.1\n1.0.0\n1.0.0.1\n1.0.0.2\n1.0.0.10\n1.0.1\n1.0.2\n1.0.11\n1.1.0\n1.2.1\n1.11.0\n2\n10\n"
},
{
"answer_id": 71320022,
"author": "legendmohe",
"author_id": 1349479,
"author_profile": "https://Stackoverflow.com/users/1349479",
"pm_score": 0,
"selected": false,
"text": "@kotlin.jvm.Throws(InvalidParameterException::class)\nfun String.versionCompare(remoteVersion: String?): Int {\n val remote = remoteVersion?.splitToSequence(\".\")?.toList() ?: return 1\n val local = this.splitToSequence(\".\").toList()\n\n if(local.filter { it.toIntOrNull() != null }.size != local.size) throw InvalidParameterException(\"version invalid: $this\")\n if(remote.filter { it.toIntOrNull() != null }.size != remote.size) throw InvalidParameterException(\"version invalid: $remoteVersion\")\n\n val totalRange = 0 until kotlin.math.max(local.size, remote.size)\n for (i in totalRange) {\n if (i < remote.size && i < local.size) {\n val result = local[i].compareTo(remote[i])\n if (result != 0) return result\n } else (\n return local.size.compareTo(remote.size)\n )\n }\n return 0\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
198,438
|
<p>Is there an efficient way of detecting if a jpeg file is corrupted? </p>
<p>Background info:<br>
solutions needs to work from within a php script<br>
the jpeg files are on disk<br>
manual checking is no option (user uploaded data) </p>
<p>I know that <code>imagecreatefromjpeg(string $filename);</code> can do it. But it is quite slow at doing so.</p>
<p>Does anybody know a faster/more efficient solutions?</p>
|
[
{
"answer_id": 1622536,
"author": "fireweasel",
"author_id": 26258,
"author_profile": "https://Stackoverflow.com/users/26258",
"pm_score": 3,
"selected": false,
"text": "\nfunction jpeg_file_is_complete($path) {\n if (!is_resource($file = fopen($path, 'rb'))) {\n return FALSE;\n }\n // check for the existence of the EOI segment header at the end of the file\n if (0 !== fseek($file, -2, SEEK_END) || \"\\xFF\\xD9\" !== fread($file, 2)) {\n fclose($file);\n return FALSE;\n }\n fclose($file);\n return TRUE;\n}\n\nfunction jpeg_file_is_corrupted($path) {\n return !jpeg_file_is_complete($path);\n}\n"
},
{
"answer_id": 2761021,
"author": "Travis",
"author_id": 252828,
"author_profile": "https://Stackoverflow.com/users/252828",
"pm_score": 3,
"selected": false,
"text": "jpeg_file_is_complete imagecreatefromjpeg() jpeginfo imagecreatefromjpeg microtime()"
},
{
"answer_id": 22722570,
"author": "T-prod",
"author_id": 2842670,
"author_profile": "https://Stackoverflow.com/users/2842670",
"pm_score": -1,
"selected": false,
"text": "if(!getimagesize($image_url)) echo 'Image is corrupt or not readable';\n"
},
{
"answer_id": 34292239,
"author": "deasq.io",
"author_id": 5682596,
"author_profile": "https://Stackoverflow.com/users/5682596",
"pm_score": 0,
"selected": false,
"text": "<?php\n$img = $_GET['img'];\n$str_exec = 'jpeginfo -c /chroot/home/www/html/media/'.$img;\n$result = exec($str_exec);\nif(strpos($result, 'ERROR'))\n{\n echo 'ERROR';\n}\nelse\n{\n echo 'OK';\n}\n?>\n"
},
{
"answer_id": 43900746,
"author": "Tom",
"author_id": 1404447,
"author_profile": "https://Stackoverflow.com/users/1404447",
"pm_score": 0,
"selected": false,
"text": "jpeginfo.exe cygwin1.dll jpeginfo --help jpeginfo Warning: unknown JFIF revision number 2.01 1280 x 720 24bit JFIF N 122550 [WARNING] 1328 x 2048 24bit JFIF N 1310080 Premature end of JPEG file [WARNING]"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22674/"
] |
198,448
|
<p>I'm planning on doing my next project in c# rather than c++ (using SlimDX).</p>
<p>All of directX uses floats, however System.Math uses doubles. This means constantly converting between floats and doubles.</p>
<p>So ideally I'd like to write all the code using floats, since I'm not getting any added precision converting to floats from doubles all the time anyways...</p>
<p>However Ive been unable to find a set of maths functions for .net that uses floats. I could of course write my own library in c#, but id rather use an existing library which has been optimised etc...</p>
|
[
{
"answer_id": 60558935,
"author": "picolino",
"author_id": 9262535,
"author_profile": "https://Stackoverflow.com/users/9262535",
"pm_score": 1,
"selected": false,
"text": "MathF MathF"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] |
198,460
|
<p>How do I generate a random number between <code>0</code> and <code>n</code>?</p>
|
[
{
"answer_id": 198469,
"author": "Mark A. Nicolosi",
"author_id": 1103052,
"author_profile": "https://Stackoverflow.com/users/1103052",
"pm_score": 5,
"selected": false,
"text": "rand(n + 1)\n"
},
{
"answer_id": 198470,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 11,
"selected": true,
"text": "rand(range) 1 + rand(6) 2 + rand(6) + rand(6) rand Random 10.times.map{ 20 + Random.rand(11) } \n#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]\n Random.new.rand(20..30) Random.new Random.new rand max Range Random Range Random.new.rand(20..30) 20 + Random.rand(11) Random.rand(int) 20..30"
},
{
"answer_id": 2773866,
"author": "Marc-André Lafortune",
"author_id": 8279,
"author_profile": "https://Stackoverflow.com/users/8279",
"pm_score": 9,
"selected": false,
"text": "rand(42-10) + 10 10 42 rand(10...42) # => 13\n backports Random r = Random.new\nr.rand(10...42) # => 22\nr.bytes(3) # => \"rnd\"\n Random Random.rand(10...42) # => same as rand(10...42)\n Random.new rand Random.rand Random.new MyApp::Random = Random.new Random.new rand Random.rand Random"
},
{
"answer_id": 10714301,
"author": "Rimian",
"author_id": 63810,
"author_profile": "https://Stackoverflow.com/users/63810",
"pm_score": 4,
"selected": false,
"text": "n = 3\n(0..n).to_a.sample\n"
},
{
"answer_id": 11578224,
"author": "Thomas Fankhauser",
"author_id": 408557,
"author_profile": "https://Stackoverflow.com/users/408557",
"pm_score": 6,
"selected": false,
"text": "SecureRandom ActiveSupport require 'securerandom'\n\np SecureRandom.random_number(100) #=> 15\np SecureRandom.random_number(100) #=> 88\n\np SecureRandom.random_number #=> 0.596506046187744\np SecureRandom.random_number #=> 0.350621695741409\n\np SecureRandom.hex #=> \"eb693ec8252cd630102fd0d0fb7c3485\"\n"
},
{
"answer_id": 13408086,
"author": "Josh",
"author_id": 1193216,
"author_profile": "https://Stackoverflow.com/users/1193216",
"pm_score": 3,
"selected": false,
"text": "rand(6) #=> gives a random number between 0 and 6 inclusively \nrand(1..6) #=> gives a random number between 1 and 6 inclusively\n"
},
{
"answer_id": 13847818,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "rand rand integer range rand(9) # this generates a number between 0 to 8\nrand(0 .. 9) # this generates a number between 0 to 9\nrand(1 .. 50) # this generates a number between 1 to 50\n#rand(m .. n) # m is the start of the number range, n is the end of number range\n"
},
{
"answer_id": 20764761,
"author": "Sam",
"author_id": 1776255,
"author_profile": "https://Stackoverflow.com/users/1776255",
"pm_score": 2,
"selected": false,
"text": "puts (rand() * 10).to_i\n puts rand(10)\n puts rand(10..15)\n srand(5)\n puts (0..10).map{rand(0..10)}\n"
},
{
"answer_id": 28115646,
"author": "LuckyElf",
"author_id": 4479264,
"author_profile": "https://Stackoverflow.com/users/4479264",
"pm_score": 1,
"selected": false,
"text": "array#shuffle array = (1..10).to_a\narray.shuffle.first\n"
},
{
"answer_id": 28614573,
"author": "sqrcompass",
"author_id": 3128333,
"author_profile": "https://Stackoverflow.com/users/3128333",
"pm_score": 4,
"selected": false,
"text": "rand(0..n)\n"
},
{
"answer_id": 32161641,
"author": "Scott",
"author_id": 3335551,
"author_profile": "https://Stackoverflow.com/users/3335551",
"pm_score": 3,
"selected": false,
"text": "x = rand(1..5)\n"
},
{
"answer_id": 35942168,
"author": "amarradi",
"author_id": 1200840,
"author_profile": "https://Stackoverflow.com/users/1200840",
"pm_score": 2,
"selected": false,
"text": "https://github.com/rubyworks/facets\nclass String\n\n # Create a random String of given length, using given character set\n #\n # Character set is an Array which can contain Ranges, Arrays, Characters\n #\n # Examples\n #\n # String.random\n # => \"D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3\"\n #\n # String.random(10)\n # => \"t8BIna341S\"\n #\n # String.random(10, ['a'..'z'])\n # => \"nstpvixfri\"\n #\n # String.random(10, ['0'..'9'] )\n # => \"0982541042\"\n #\n # String.random(10, ['0'..'9','A'..'F'] )\n # => \"3EBF48AD3D\"\n #\n # BASE64_CHAR_SET = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\", '_', '-']\n # String.random(10, BASE64_CHAR_SET)\n # => \"xM_1t3qcNn\"\n #\n # SPECIAL_CHARS = [\"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"(\", \")\", \"-\", \"_\", \"=\", \"+\", \"|\", \"/\", \"?\", \".\", \",\", \";\", \":\", \"~\", \"`\", \"[\", \"]\", \"{\", \"}\", \"<\", \">\"]\n # BASE91_CHAR_SET = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\", SPECIAL_CHARS]\n # String.random(10, BASE91_CHAR_SET)\n # => \"S(Z]z,J{v;\"\n #\n # CREDIT: Tilo Sloboda\n #\n # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba\n #\n # TODO: Move to random.rb in standard library?\n\n def self.random(len=32, character_set = [\"A\"..\"Z\", \"a\"..\"z\", \"0\"..\"9\"])\n chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten\n Array.new(len){ chars.sample }.join\n end\n\nend\n"
},
{
"answer_id": 35942797,
"author": "Juan Dela Cruz",
"author_id": 4423225,
"author_profile": "https://Stackoverflow.com/users/4423225",
"pm_score": 2,
"selected": false,
"text": "num = Random.new\nnum.rand(1..n)\n"
},
{
"answer_id": 41675944,
"author": "techdreams",
"author_id": 2936491,
"author_profile": "https://Stackoverflow.com/users/2936491",
"pm_score": 4,
"selected": false,
"text": "random_number random_number random_number any_number = SecureRandom.random_number(100) \n"
},
{
"answer_id": 42270685,
"author": "Vaisakh VM",
"author_id": 1905008,
"author_profile": "https://Stackoverflow.com/users/1905008",
"pm_score": 2,
"selected": false,
"text": "def random \n (1..10).to_a.sample.to_s\nend\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103052/"
] |
198,462
|
<p>When comparing an HTTP GET to an HTTP POST, what are the differences from a security perspective? Is one of the choices inherently more secure than the other? If so, why?</p>
<p>I realize that POST doesn't expose information on the URL, but is there any real value in that or is it just security through obscurity? Is there ever a reason that I should prefer POST when security is a concern?</p>
<p><strong>Edit:</strong><br>
Over HTTPS, POST data is encoded, but could URLs be sniffed by a 3rd party? Additionally, I am dealing with JSP; when using JSP or a similar framework, would it be fair to say the best practice is to avoid placing sensitive data in the POST or GET altogether and using server side code to handle sensitive information instead?</p>
|
[
{
"answer_id": 198487,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 5,
"selected": false,
"text": "POST GET POST POST GET GET POST SSL HTTPS"
},
{
"answer_id": 4725795,
"author": "Incognito",
"author_id": 257493,
"author_profile": "https://Stackoverflow.com/users/257493",
"pm_score": 8,
"selected": false,
"text": "<html>\n<body>\n<form action=\"http://example.com\" method=\"get\">\n User: <input type=\"text\" name=\"username\" /><br/>\n Password: <input type=\"password\" name=\"password\" /><br/>\n <input type=\"hidden\" name=\"extra\" value=\"lolcatz\" />\n <input type=\"submit\"/>\n</form>\n</body>\n</html>\n GET /?username=swordfish&password=hunter2&extra=lolcatz HTTP/1.1\n Host: example.com\n Connection: keep-alive\n Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/ [...truncated]\n User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) [...truncated]\n Accept-Encoding: gzip,deflate,sdch\n Accept-Language: en-US,en;q=0.8\n Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n POST / HTTP/1.1\n Host: example.com\n Connection: keep-alive\n Content-Length: 49\n Cache-Control: max-age=0\n Origin: null\n Content-Type: application/x-www-form-urlencoded\n Accept: application/xml,application/xhtml+xml,text/ [...truncated]\n User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; [...truncated]\n Accept-Encoding: gzip,deflate,sdch\n Accept-Language: en-US,en;q=0.8\n Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3\n\n username=swordfish&password=hunter2&extra=lolcatz\n q5XQP%RWCd2u#o/T9oiOyR2_YO?yo/3#tR_G7 2_RO8w?FoaObi)\noXpB_y?oO4q?`2o?O4G5D12Aovo?C@?/P/oOEQC5v?vai /%0Odo\nQVw#6eoGXBF_o?/u0_F!_1a0A?Q b%TFyS@Or1SR/O/o/_@5o&_o\n9q1/?q$7yOAXOD5sc$H`BECo1w/`4?)f!%geOOF/!/#Of_f&AEI#\nyvv/wu_b5?/o d9O?VOVOFHwRO/pO/OSv_/8/9o6b0FGOH61O?ti\n/i7b?!_o8u%RS/Doai%/Be/d4$0sv_%YD2_/EOAO/C?vv/%X!T?R\n_o_2yoBP)orw7H_yQsXOhoVUo49itare#cA?/c)I7R?YCsg ??c'\n(_!(0u)o4eIis/S8Oo8_BDueC?1uUO%ooOI_o8WaoO/ x?B?oO@&\nPw?os9Od!c?/$3bWWeIrd_?( `P_C?7_g5O(ob(go?&/ooRxR'u/\nT/yO3dS&??hIOB/?/OI?$oH2_?c_?OsD//0/_s%r\n rV/O8ow1pc`?058/8OS_Qy/$7oSsU'qoo#vCbOO`vt?yFo_?EYif)\n43`I/WOP_8oH0%3OqP_h/cBO&24?'?o_4`scooPSOVWYSV?H?pV!i\n?78cU!_b5h'/b2coWD?/43Tu?153pI/9?R8!_Od\"(//O_a#t8x?__\nbb3D?05Dh/PrS6_/&5p@V f $)/xvxfgO'q@y&e&S0rB3D/Y_/fO?\n_'woRbOV?_!yxSOdwo1G1?8d_p?4fo81VS3sAOvO/Db/br)f4fOxt\n_Qs3EO/?2O/TOo_8p82FOt/hO?X_P3o\"OVQO_?Ww_dr\"'DxHwo//P\noEfGtt/_o)5RgoGqui&AXEq/oXv&//?%/6_?/x_OTgOEE%v (u(?/\nt7DX1O8oD?fVObiooi'8)so?o??`o\"FyVOByY_ Supo? /'i?Oi\"4\ntr'9/o_7too7q?c2Pv\n"
},
{
"answer_id": 8601786,
"author": "Halil Özgür",
"author_id": 372654,
"author_profile": "https://Stackoverflow.com/users/372654",
"pm_score": 3,
"selected": false,
"text": "http://www.example.com/api?apikey=abcdef123456&action=deleteCategory&id=1\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20774/"
] |
198,465
|
<p>Is there any way to access the file object used by a CSV writer/reader object after it has been instantiated? I openned up the csv module, and it appears it's contest are builtin. I also tried setting the file object as a property but I get the following error:</p>
<pre><code>AttributeError: '_csv.writer' object has no attribute 'fileobj'
</code></pre>
|
[
{
"answer_id": 198553,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": true,
"text": "csv.writer w = csv.writer(fileobj, dialect, ...)\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
] |
198,478
|
<p>What are the key differences between Microsoft's SQL Server 2005 and SQL Server 2008? </p>
<p>Are there any compelling reasons for upgrading (any edition, as I have a customer with multiple editions)? Or is there a website with either a chart or bullet point comparison of the two servers?</p>
<p>Also, is there anything noteworthy in the <a href="http://en.wikipedia.org/wiki/SQL_Server_Express" rel="noreferrer">Express</a> editions of either version?</p>
|
[
{
"answer_id": 4538108,
"author": "vipin",
"author_id": 554888,
"author_profile": "https://Stackoverflow.com/users/554888",
"pm_score": 2,
"selected": false,
"text": "* DATE: As you can imagine, the DATE data type only stores a date in the format of YYYY-MM-DD. It has a range of 0001-01-01 through 9999-12-32, which should be adequate for most business and scientific applications. The accuracy is 1 day, and it only takes 3 bytes to store the date.\n* TIME: TIME is stored in the format: hh:mm:ss.nnnnnnn, with a range of 00:00:00.0000000 through 23:59:59:9999999 and is accurate to 100 nanoseconds. Storage depends on the precision and scale selected, and runs from 3 to 5 bytes.\n* DATETIME2: DATETIME2 is very similar to the older DATETIME data type, but has a greater range and precision. The format is YYYY-MM-DD hh:mm:ss:nnnnnnnm with a range of 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999, and an accuracy of 100 nanoseconds. Storage depends on the precision and scale selected, and runs from 6 to 8 bytes.\n* DATETIMEOFFSET: DATETIMEOFFSET is similar to DATETIME2, but includes additional information to track the time zone. The format is YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+|-]hh:mm with a range of 0001-01-01 00:00:00.0000000 through 0001-01-01 00:00:00.0000000 through 9999-12-31 23:59:59.9999999 (in UTC), and an accuracy of 100 nanoseconds. Storage depends on the precision and scale selected, and runs from 8 to 10 bytes.\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
198,493
|
<p>I'm developing a system that needs to execute Intersystems Cache Terminal Scripts.</p>
<p>When I run a routine inside the regular Caché terminal or a telnet terminal, Cache executes the routine until the end with no problems. But when I try to run the same routine, but this time calling the routine within a Caché terminal Script, Caché disconnects the session after a while. There is no mention at all in the documentation of a "timeout" setting or anything realted to the "" messages i'm getting.</p>
<p>The script is run just like this:</p>
<pre><code>Cterm.exe /console=cn_iptcp:192.168.2.13[23] c:\test.s
</code></pre>
<p>1) Does anybody know what may be causing Interystems Caché to disconnected the session in the middle of the run (the session isn't idle either. It regularly outputs status messages to the console)?</p>
<p>2) Any ideas of how to solve it?</p>
<p>Thanks,</p>
<p>Luís Fernando</p>
|
[
{
"answer_id": 302330,
"author": "Luis Soeiro",
"author_id": 24165,
"author_profile": "https://Stackoverflow.com/users/24165",
"pm_score": 2,
"selected": false,
"text": " waitfor \"Operation finished\"\nterminate\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24165/"
] |
198,496
|
<p>What’s the difference between the <code>System.Array.CopyTo()</code> and <code>System.Array.Clone()</code>?</p>
|
[
{
"answer_id": 198500,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "1- CopyTo require to have a destination array when Clone return a new array.\n2- CopyTo let you specify an index (if required) to the destination array.\n"
},
{
"answer_id": 198512,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "CopyTo CopyTo"
},
{
"answer_id": 198602,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "Clone() CopyTo()"
},
{
"answer_id": 1690062,
"author": "GenZiy",
"author_id": 201889,
"author_profile": "https://Stackoverflow.com/users/201889",
"pm_score": 3,
"selected": false,
"text": "object[] myarray = new object[] { \"one\", 2, \"three\", 4, \"really big number\", 2324573984927361 };\n\n//create shallow copy by CopyTo\n//You have to instantiate your new array first\nobject[] myarray2 = new object[myarray.Length];\n//but then you can specify how many members of original array you would like to copy \nmyarray.CopyTo(myarray2, 0);\n\n//create shallow copy by Clone\nobject[] myarray1;\n//here you don't need to instantiate array, \n//but all elements of the original array will be copied\nmyarray1 = myarray.Clone() as object[];\n\n//if not sure that we create a shalow copy lets test it\nmyarray[0] = 0;\nConsole.WriteLine(myarray[0]);// print 0\nConsole.WriteLine(myarray1[0]);//print \"one\"\nConsole.WriteLine(myarray2[0]);//print \"one\"\n"
},
{
"answer_id": 2123176,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "Clone() CopyTo()"
},
{
"answer_id": 5295876,
"author": "SFD",
"author_id": 642684,
"author_profile": "https://Stackoverflow.com/users/642684",
"pm_score": 2,
"selected": false,
"text": "public class Test\n{\npublic string s;\n}\n\n// Write Main() method and within it call test()\n\nprivate void test()\n{\nTest[] array = new Test[1];\narray[0] = new Test();\narray[0].s = \"ORIGINAL\";\n\nTest[] copy = new Test[1];\narray.CopyTo(copy, 0);\n\n// Next line displays \"ORIGINAL\"\nMessageBox.Show(\"array[0].s = \" + array[0].s);\ncopy[0].s = \"CHANGED\";\n\n// Next line displays \"CHANGED\", showing that\n// changing the copy also changes the original.\nMessageBox.Show(\"array[0].s = \" + array[0].s);\n}\n"
},
{
"answer_id": 9508230,
"author": "Mohammad Ahmed",
"author_id": 1098528,
"author_profile": "https://Stackoverflow.com/users/1098528",
"pm_score": 0,
"selected": false,
"text": "Clone() CopyTo()"
},
{
"answer_id": 12141764,
"author": "João Angelo",
"author_id": 204699,
"author_profile": "https://Stackoverflow.com/users/204699",
"pm_score": 5,
"selected": false,
"text": "System.Array.Clone CopyTo Object.MemberwiseClone System.Array.CopyTo Clone Array.Copy int[] object[] object[] int int[] int[] long[] Stream[] MemoryStream[] MemoryStream ICloneable ICollection Clone CopyTo Array.Copy Array.ConstrainedCopy"
},
{
"answer_id": 20470263,
"author": "inbaly",
"author_id": 2924987,
"author_profile": "https://Stackoverflow.com/users/2924987",
"pm_score": -1,
"selected": false,
"text": "public void test()\n{\n StringBuilder[] sArrOr = new StringBuilder[1];\n sArrOr[0] = new StringBuilder();\n sArrOr[0].Append(\"hello\");\n StringBuilder[] sArrClone = (StringBuilder[])sArrOr.Clone();\n StringBuilder[] sArrCopyTo = new StringBuilder[1];\n sArrOr.CopyTo(sArrCopyTo,0);\n sArrOr[0].Append(\" world\");\n\n Console.WriteLine(sArrOr[0] + \" \" + sArrClone[0] + \" \" + sArrCopyTo[0]);\n //Outputs: hello world hello world hello world\n\n //Same result in int[] as using String[]\n int[] iArrOr = new int[2];\n iArrOr[0] = 0;\n iArrOr[1] = 1;\n int[] iArrCopyTo = new int[2];\n iArrOr.CopyTo(iArrCopyTo,0);\n int[] iArrClone = (int[])iArrOr.Clone();\n iArrOr[0]++;\n Console.WriteLine(iArrOr[0] + \" \" + iArrClone[0] + \" \" + iArrCopyTo[0]);\n // Output: 1 0 0\n}\n"
},
{
"answer_id": 43382728,
"author": "Nikhil Redij",
"author_id": 7802556,
"author_profile": "https://Stackoverflow.com/users/7802556",
"pm_score": 0,
"selected": false,
"text": "public class TestClass1\n{\n public string a = \"test1\";\n}\n\npublic static void ArrayCopyClone()\n{\n TestClass1 tc1 = new TestClass1();\n TestClass1 tc2 = new TestClass1();\n\n TestClass1[] arrtest1 = { tc1, tc2 };\n TestClass1[] arrtest2 = new TestClass1[arrtest1.Length];\n TestClass1[] arrtest3 = new TestClass1[arrtest1.Length];\n\n arrtest1.CopyTo(arrtest2, 0);\n arrtest3 = arrtest1.Clone() as TestClass1[];\n\n Console.WriteLine(arrtest1[0].a);\n Console.WriteLine(arrtest2[0].a);\n Console.WriteLine(arrtest3[0].a);\n\n arrtest1[0].a = \"new\";\n\n Console.WriteLine(arrtest1[0].a);\n Console.WriteLine(arrtest2[0].a);\n Console.WriteLine(arrtest3[0].a);\n}\n\n/* Output is \ntest1\ntest1\ntest1\nnew\nnew\nnew */\n"
},
{
"answer_id": 63319470,
"author": "Umasankar Siva",
"author_id": 14072525,
"author_profile": "https://Stackoverflow.com/users/14072525",
"pm_score": 1,
"selected": false,
"text": "Array.Clone() int int[] numbers = new int[] { -11, 12, -42, 0, 1, 90, 68, 6, -9 }; \n\nSortByAscending(numbers); // Sort the array in ascending order by clone the numbers array to local new array.\nSortByDescending(numbers); // Same as Ascending order Clone\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
198,526
|
<p>How do I determine if the currency symbol is supposed to be on the left or right of a number using CFLocale / CFNumberFormatter in a Mac Carbon project?</p>
<p>I need to interface with a spreadsheet application which requires me to pass a number, currency symbol, currency symbol location and padding instead of a CStringRef created with CFNumberFormatter.</p>
<pre><code>CFLocaleRef currentLocale = CFLocaleCopyCurrent();
CFTypeRef currencySymbol = CFLocaleGetValue (currentLocale, kCFLocaleCurrencySymbol);
</code></pre>
<p>provides me with the currency symbol as a string. But I'm lost on how to determine the position of the currency symbol...</p>
|
[
{
"answer_id": 200245,
"author": "Hans Martin Kern",
"author_id": 27559,
"author_profile": "https://Stackoverflow.com/users/27559",
"pm_score": 2,
"selected": false,
"text": " CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(kCFAllocatorDefault, CFLocaleCopyCurrent(), kCFNumberFormatterCurrencyStyle);\n double someNumber = 0;\n CFStringRef asString = CFNumberFormatterCreateStringWithValue(kCFAllocatorDefault, numberFormatter, kCFNumberDoubleType, &someNumber);\n"
},
{
"answer_id": 237653,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 0,
"selected": false,
"text": "CFNumberFormatterGetFormat ¤ \\u00A4"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27559/"
] |
198,532
|
<p>In <code>.NET</code> (at least in the 2008 version, and maybe in 2005 as well), changing the <code>BackColor</code> property of a <code>DateTimePicker</code> has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?</p>
<p><strong><em>Edit:</em></strong> I was talking about Windows forms, not ASP.</p>
|
[
{
"answer_id": 199278,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 5,
"selected": true,
"text": "BackColor DateTimePicker DateTimePicker BackColor WndProc BackColor myDTPicker.Invalidate() const int WM_ERASEBKGND = 0x14;\nprotected override void WndProc(ref System.Windows.Forms.Message m)\n{\n if(m.Msg == WM_ERASEBKGND)\n {\n using(var g = Graphics.FromHdc(m.WParam))\n {\n using(var b = new SolidBrush(_backColor))\n {\n g.FillRectangle(b, ClientRectangle);\n }\n }\n return;\n }\n\n base.WndProc(ref m);\n}\n"
},
{
"answer_id": 1202804,
"author": "Gustavo",
"author_id": 2015,
"author_profile": "https://Stackoverflow.com/users/2015",
"pm_score": 3,
"selected": false,
"text": "DateTimePicker BackColor DateTimePicker BackColor"
},
{
"answer_id": 46486746,
"author": "Carlos Borau",
"author_id": 4676223,
"author_profile": "https://Stackoverflow.com/users/4676223",
"pm_score": 3,
"selected": false,
"text": "MyDateTimePicker Public Class MyDateTimePicker \n Inherits System.Windows.Forms.DateTimePicker\n Private _disabled_back_color As Color\n Private _image As Image\n Private _text_color As Color = Color.Black\n\n Public Sub New()\n MyBase.New()\n Me.SetStyle(ControlStyles.UserPaint, True)\n _disabled_back_color = Color.FromKnownColor(KnownColor.Control)\n End Sub\n\n ''' <summary>\n ''' Gets or sets the background color of the control\n ''' </summary>\n <Browsable(True)>\n Public Overrides Property BackColor() As Color\n Get\n Return MyBase.BackColor\n End Get\n Set\n MyBase.BackColor = Value\n End Set\n End Property\n\n ''' <summary>\n ''' Gets or sets the background color of the control when disabled\n ''' </summary>\n <Category(\"Appearance\"), Description(\"The background color of the component when disabled\")>\n <Browsable(True)>\n Public Property BackDisabledColor() As Color\n Get\n Return _disabled_back_color\n End Get\n Set\n _disabled_back_color = Value\n End Set\n End Property\n\n ''' <summary>\n ''' Gets or sets the Image next to the dropdownbutton\n ''' </summary>\n <Category(\"Appearance\"),\n Description(\"Get or Set the small Image next to the dropdownbutton\")>\n Public Property Image() As Image\n Get\n Return _image\n End Get\n Set(ByVal Value As Image)\n _image = Value\n Invalidate()\n End Set\n End Property\n\n ''' <summary>\n ''' Gets or sets the text color when calendar is not visible\n ''' </summary>\n <Category(\"Appearance\")>\n Public Property TextColor As Color\n Get\n Return _text_color\n End Get\n Set(value As Color)\n _text_color = value\n End Set\n End Property\n\n\n Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)\n Dim g As Graphics = Me.CreateGraphics()\n g.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit\n\n 'Dropdownbutton rectangle\n Dim ddb_rect As New Rectangle(ClientRectangle.Width - 17, 0, 17, ClientRectangle.Height)\n 'Background brush\n Dim bb As Brush\n\n Dim visual_state As ComboBoxState\n\n 'When enabled the brush is set to Backcolor, \n 'otherwise to color stored in _disabled_back_Color\n If Me.Enabled Then\n bb = New SolidBrush(Me.BackColor)\n visual_state = ComboBoxState.Normal\n Else\n bb = New SolidBrush(Me._disabled_back_color)\n visual_state = ComboBoxState.Disabled\n End If\n\n 'Filling the background\n g.FillRectangle(bb, 0, 0, ClientRectangle.Width, ClientRectangle.Height)\n\n 'Drawing the datetime text\n g.DrawString(Me.Text, Me.Font, New SolidBrush(TextColor), 5, 2)\n\n 'Drawing icon\n If Not _image Is Nothing Then\n Dim im_rect As New Rectangle(ClientRectangle.Width - 40, 4, ClientRectangle.Height - 8, ClientRectangle.Height - 8)\n g.DrawImage(_image, im_rect)\n End If\n\n 'Drawing the dropdownbutton using ComboBoxRenderer\n ComboBoxRenderer.DrawDropDownButton(g, ddb_rect, visual_state)\n\n g.Dispose()\n bb.Dispose()\n End Sub\nEnd Class\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27302/"
] |
198,535
|
<p>I have small page which has label, DropDownList and a submit button.</p>
<pre><code><div>
<asp:label id="Message" runat="server"/>
<br />
Which city do you wish to look at on hotels for?<br /><br />
<asp:dropdownlist id="Dropdownlist1" runat="server" EnableViewState="true">
</asp:dropdownlist>
<br /><br /><br /><br />
<input type="Submit" />
</div>
</code></pre>
<p>On form load I am inserting items into the DropDownList and on the button click I am displaying the count of the items in the DropDownList. Here's the code for that.</p>
<code>
if (Page.IsPostBack)
{
Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString();
}
else
{
Message.Text = "You have selected " + Dropdownlist1.Items.Count.ToString();
Dropdownlist1.Items.Add("Madrid");
Dropdownlist1.Items.Add("Chennai");
Dropdownlist1.Items.Add("New York");
}
</code>
<p>Here's the funny part. If I run it directly from the IDE, its working perfectly fine. I get the count as 0 the first time and 3 when I press submit button. I need to run this small code on an existing virtual directory. If I run the same aspx page within that virtual directory, I get count 0 for the for the first time it loads. When I click submit, I get count as 0 and I don't see any items in the DropDownList, it is getting cleared. I have set ViewState to true so that I remember what was inserted.</p>
<p>I am not sure what difference is there when I run it from IDE and when I run it from another virtual directory. I am fairly new to Asp.Net so I have exhuasted all my options here so to find out how a DropDownList works. Is there a config I am missing here ?.</p>
<p>BTW just FYI, I am facing the same issue when I put the DropDownList in a Wizard Control. When run from IDE it is working fine but when I run from the virtual directory its not getting the selected value neither is it remembering the items in the DropDownList.</p>
<blockquote>
<p>According to your code the list only gets populated when it is not a PostBack. Therefore when you click the button the list will be empty.If you dynamically populate the list, the items are not remembered. You must added in each Page_load. The view state will only remember which item was selected.</p>
</blockquote>
<p>How it does then remember the items when the page is executed directly from the IDE and not remember when I run from a virtual directory. Is there a view state that I might need to set to get it working. The cache setting also did not do much luck. I enabled Trace info, funny thing again :|, tracing is happening when executed directly from the IDE and not from the virual directory. Question again, the child directory's <code>web.config</code> should override the parent <code>web.config</code> right?</p>
|
[
{
"answer_id": 198547,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 0,
"selected": false,
"text": "Response.Cache.SetCacheability(HttpCacheability.NoCache)\n"
},
{
"answer_id": 13134015,
"author": "Siddhesh Bondre",
"author_id": 1784773,
"author_profile": "https://Stackoverflow.com/users/1784773",
"pm_score": 2,
"selected": false,
"text": " protected void Page_Load(object sender, EventArgs e)\n{\n if(!IsPostBack)\n FillApplicationDropDown();\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2245/"
] |
198,543
|
<p>I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (<kbd>Alt</kbd> + <kbd>Down</kbd>) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick event. Unfortunately, there doesn't seem to be a method in the control that raises the ButtonClick event, so...</p>
<p>How do I raise the event from an external function via reflection?</p>
|
[
{
"answer_id": 198584,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": " public event EventHandler<EventArgs> MyEventToBeFired;\n\n public void FireEvent(Guid instanceId, string handler)\n {\n\n // Note: this is being fired from a method with in the same\n // class that defined the event (that is, \"this\").\n\n EventArgs e = new EventArgs(instanceId);\n\n MulticastDelegate eventDelagate =\n (MulticastDelegate)this.GetType().GetField(handler,\n System.Reflection.BindingFlags.Instance |\n System.Reflection.BindingFlags.NonPublic).GetValue(this);\n\n Delegate[] delegates = eventDelagate.GetInvocationList();\n\n foreach (Delegate dlg in delegates)\n {\n dlg.Method.Invoke(dlg.Target, new object[] { this, e });\n }\n }\n\n FireEvent(new Guid(), \"MyEventToBeFired\");\n"
},
{
"answer_id": 198593,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "AddHandler RemoveHandler EventHandlerList ButtonEdit OnClick EventInfo.GetRaiseMethod"
},
{
"answer_id": 201444,
"author": "Josh Kodroff",
"author_id": 549,
"author_profile": "https://Stackoverflow.com/users/549",
"pm_score": 3,
"selected": false,
"text": "buttonEdit1.Properties.Buttons[0].Shortcut = new DevExpress.Utils.KeyShortcut(Keys.Alt | Keys.Down);\n"
},
{
"answer_id": 585846,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "PerformClick() OnEnter OnExit"
},
{
"answer_id": 586156,
"author": "Wiebe Cnossen",
"author_id": 70868,
"author_profile": "https://Stackoverflow.com/users/70868",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Reflection;\nstatic class Program {\n private class Sub {\n public event EventHandler<EventArgs> SomethingHappening;\n }\n internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs\n {\n var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);\n if (eventDelegate != null)\n {\n foreach (var handler in eventDelegate.GetInvocationList())\n {\n handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });\n }\n }\n }\n public static void Main()\n {\n var p = new Sub();\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n p.SomethingHappening += (o, e) => Console.WriteLine(\"Foo!\");\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n p.SomethingHappening += (o, e) => Console.WriteLine(\"Bar!\");\n p.Raise(\"SomethingHappening\", EventArgs.Empty);\n Console.ReadLine();\n }\n}\n"
},
{
"answer_id": 3312601,
"author": "The Chris",
"author_id": 399525,
"author_profile": "https://Stackoverflow.com/users/399525",
"pm_score": 3,
"selected": false,
"text": "this.RaisePropertyChanged(() => MyProperty);\n using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Globalization;\n\nnamespace Infrastructure\n{\n /// <summary>\n /// Adds a RaisePropertyChanged method to objects implementing INotifyPropertyChanged.\n /// </summary>\n public static class NotifyPropertyChangeExtension\n {\n #region private fields\n\n private static readonly Dictionary<string, PropertyChangedEventArgs> eventArgCache = new Dictionary<string, PropertyChangedEventArgs>();\n private static readonly object syncLock = new object();\n\n #endregion\n\n #region the Extension's\n\n /// <summary>\n /// Verifies the name of the property for the specified instance.\n /// </summary>\n /// <param name=\"bindableObject\">The bindable object.</param>\n /// <param name=\"propertyName\">Name of the property.</param>\n [Conditional(\"DEBUG\")]\n public static void VerifyPropertyName(this INotifyPropertyChanged bindableObject, string propertyName)\n {\n bool propertyExists = TypeDescriptor.GetProperties(bindableObject).Find(propertyName, false) != null;\n if (!propertyExists)\n throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,\n \"{0} is not a public property of {1}\", propertyName, bindableObject.GetType().FullName));\n }\n\n /// <summary>\n /// Gets the property name from expression.\n /// </summary>\n /// <param name=\"notifyObject\">The notify object.</param>\n /// <param name=\"propertyExpression\">The property expression.</param>\n /// <returns>a string containing the name of the property.</returns>\n public static string GetPropertyNameFromExpression<T>(this INotifyPropertyChanged notifyObject, Expression<Func<T>> propertyExpression)\n {\n return GetPropertyNameFromExpression(propertyExpression);\n }\n\n /// <summary>\n /// Raises a property changed event.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"bindableObject\">The bindable object.</param>\n /// <param name=\"propertyExpression\">The property expression.</param>\n public static void RaisePropertyChanged<T>(this INotifyPropertyChanged bindableObject, Expression<Func<T>> propertyExpression)\n {\n RaisePropertyChanged(bindableObject, GetPropertyNameFromExpression(propertyExpression));\n }\n\n #endregion\n\n /// <summary>\n /// Raises the property changed on the specified bindable Object.\n /// </summary>\n /// <param name=\"bindableObject\">The bindable object.</param>\n /// <param name=\"propertyName\">Name of the property.</param>\n private static void RaisePropertyChanged(INotifyPropertyChanged bindableObject, string propertyName)\n {\n bindableObject.VerifyPropertyName(propertyName);\n RaiseInternalPropertyChangedEvent(bindableObject, GetPropertyChangedEventArgs(propertyName));\n }\n\n /// <summary>\n /// Raises the internal property changed event.\n /// </summary>\n /// <param name=\"bindableObject\">The bindable object.</param>\n /// <param name=\"eventArgs\">The <see cref=\"System.ComponentModel.PropertyChangedEventArgs\"/> instance containing the event data.</param>\n private static void RaiseInternalPropertyChangedEvent(INotifyPropertyChanged bindableObject, PropertyChangedEventArgs eventArgs)\n {\n // get the internal eventDelegate\n var bindableObjectType = bindableObject.GetType();\n\n // search the base type, which contains the PropertyChanged event field.\n FieldInfo propChangedFieldInfo = null;\n while (bindableObjectType != null)\n {\n propChangedFieldInfo = bindableObjectType.GetField(\"PropertyChanged\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (propChangedFieldInfo != null)\n break;\n\n bindableObjectType = bindableObjectType.BaseType;\n }\n if (propChangedFieldInfo == null)\n return;\n\n // get prop changed event field value\n var fieldValue = propChangedFieldInfo.GetValue(bindableObject);\n if (fieldValue == null)\n return;\n\n MulticastDelegate eventDelegate = fieldValue as MulticastDelegate;\n if (eventDelegate == null)\n return;\n\n // get invocation list\n Delegate[] delegates = eventDelegate.GetInvocationList();\n\n // invoke each delegate\n foreach (Delegate propertyChangedDelegate in delegates)\n propertyChangedDelegate.Method.Invoke(propertyChangedDelegate.Target, new object[] { bindableObject, eventArgs });\n }\n\n /// <summary>\n /// Gets the property name from an expression.\n /// </summary>\n /// <param name=\"propertyExpression\">The property expression.</param>\n /// <returns>The property name as string.</returns>\n private static string GetPropertyNameFromExpression<T>(Expression<Func<T>> propertyExpression)\n {\n var lambda = (LambdaExpression)propertyExpression;\n\n MemberExpression memberExpression;\n\n if (lambda.Body is UnaryExpression)\n {\n var unaryExpression = (UnaryExpression)lambda.Body;\n memberExpression = (MemberExpression)unaryExpression.Operand;\n }\n else memberExpression = (MemberExpression)lambda.Body;\n\n return memberExpression.Member.Name;\n }\n\n /// <summary>\n /// Returns an instance of PropertyChangedEventArgs for the specified property name.\n /// </summary>\n /// <param name=\"propertyName\">\n /// The name of the property to create event args for.\n /// </param>\n private static PropertyChangedEventArgs GetPropertyChangedEventArgs(string propertyName)\n {\n PropertyChangedEventArgs args;\n\n lock (NotifyPropertyChangeExtension.syncLock)\n {\n if (!eventArgCache.TryGetValue(propertyName, out args))\n eventArgCache.Add(propertyName, args = new PropertyChangedEventArgs(propertyName));\n }\n\n return args;\n }\n }\n}\n"
},
{
"answer_id": 37498170,
"author": "bitbonk",
"author_id": 4227,
"author_profile": "https://Stackoverflow.com/users/4227",
"pm_score": 3,
"selected": false,
"text": "private void RaiseEventViaReflection(object source, string eventName)\n{\n ((Delegate)source\n .GetType()\n .GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic)\n .GetValue(source))\n .DynamicInvoke(source, EventArgs.Empty);\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
198,551
|
<p>I am interacting with an Oracle DB using SQL over an ODBC connection. Is there an SQL command I can use to get the MAC address of the server, or something that uniquely identifies the server hardware or software installation. This is so I can be sure (or at least fairly sure) that I'm talking to the same database all the time.</p>
|
[
{
"answer_id": 198569,
"author": "Node",
"author_id": 7190,
"author_profile": "https://Stackoverflow.com/users/7190",
"pm_score": 0,
"selected": false,
"text": "SELECT * FROM v$instance;\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12889/"
] |
198,552
|
<p>I have a row of data that I need to modify in a database, using a stored procedure. But in order to call that stored procedure, I need to know the name of the each column. How do I determine the name of the columns? (Hardcoding is not an option as we are talking a LOT of columns whose names may change).</p>
<p>EDIT: given the accepted answer, it looks like eviljack wanted the header text of the column and not the name of the bound field</p>
|
[
{
"answer_id": 2056245,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " foreach (TableCell objCell in e.Row.Cells)\n {\n if (objCell is DataControlFieldHeaderCell)\n {\n string HEADERTEXT = objCell.Text;\n\n }\n }\n"
},
{
"answer_id": 3015312,
"author": "ChrisS",
"author_id": 363547,
"author_profile": "https://Stackoverflow.com/users/363547",
"pm_score": 0,
"selected": false,
"text": "''' <summary>\n''' Requires that the 'AccessibleHeaderText' property is set on the column in the aspx\n''' </summary>\nPrivate Function GetCellByName(ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs, ByVal colName As String) As System.Web.UI.WebControls.TableCell\n\n Dim result As TableCell = Nothing\n\n If e.Row.RowType = DataControlRowType.DataRow Then\n Dim grid As GridView = e.Row.NamingContainer\n Dim index As Integer = 0\n\n For i As Integer = 0 To grid.Columns.Count - 1\n If String.Compare(grid.Columns(i).AccessibleHeaderText, colName, True) = 0 Then\n index = i\n Exit For\n End If\n Next\n\n If index <= e.Row.Cells.Count Then\n result = e.Row.Cells(index)\n End If\n End If\n\n Return result\n\nEnd Function\n"
},
{
"answer_id": 17277367,
"author": "Hiren",
"author_id": 2051920,
"author_profile": "https://Stackoverflow.com/users/2051920",
"pm_score": 0,
"selected": false,
"text": "List<string> ColName = new List<string>();\nforeach(DataColumn c in gridview.Columns)\n{\n ColName.Add(c);\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] |
198,561
|
<p>I know this won't be a popular question, because a lot of web designers want to assume that their craft is difficult and valuable.</p>
<p><strong>IT IS</strong>. But I do not believe that it is difficult because HTML and CSS are difficult to master, I believe its difficult because being a good creative designer is difficult. Please resist the urge to reflexively disagree with me because I consider the language simple.</p>
<p>I suck as a designer, thankfully its not my job. However I can take a photo shopped comp and create a pure HTML/CSS web page from it with ease.</p>
<p>It is my personal believe that <strong>anyone</strong> can become an effective HTML/CSS guru in a week or two's study. There just isn't that much complexity (and this is someone with years of experience talking).</p>
<p>Crossbrowser coding is not as hard as people make it sound. I develop in Firefox, and tweak for IE, and I'm done, a good CSS reset handles 99% of the issues.</p>
<p>Do you disagree with this? Is HTML and CSS impossible to learn well in a week?</p>
<p>EDIT: This has to do with my heavily downvoted answer here: <a href="https://stackoverflow.com/questions/198337/testing-htmlcssjavascript-skills-when-hiring#198344">Testing HTML/CSS/Javascript skills when hiring</a></p>
|
[
{
"answer_id": 198603,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<font>"
},
{
"answer_id": 198751,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 0,
"selected": false,
"text": "#header h1 { font-size: 2em; }\n<div id=\"header\">\n <h1>Title</h1>\n<div>\n .title { font-size: 2em; }\n<div id=\"header\">\n <h1 class=\"title\">Title</h1>\n<div>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
198,564
|
<p>I have apache web server installed as frontend and I have j2ee SAP Netweaver Application Server installed in Intranet server. How can I configure apache to forward requests and response to/from j2ee app server.
for example, external apache server's ip is 9.20.1.1:80.
internal sap server's address is 192.168.0.1/sap/bc/gui/sap/its/webgui?sap_client=200
I want access to my sap app server for example 9.20.1.1/sapserver/sap/bc/gui/sap/its/webgui?sap_client=200</p>
|
[
{
"answer_id": 198611,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 1,
"selected": false,
"text": " ProxyRequests Off\n <Location \"/sapserver\">\n ProxyPass http://192.168.0.1\n ProxyPassReverse http://192.168.0.1\n </Location>\n"
},
{
"answer_id": 198630,
"author": "jrwren",
"author_id": 16998,
"author_profile": "https://Stackoverflow.com/users/16998",
"pm_score": 2,
"selected": false,
"text": " ProxyPassReverse /sap/ \n"
},
{
"answer_id": 202111,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 3,
"selected": true,
"text": "mod_proxy_balancer <Proxy balancer://myclustername>\n # cluster member 1\n BalancerMember http://192.168.0.1:3000 \n BalancerMember http://192.168.0.1:3001\n\n # cluster member 2, the fastest machine so double the load\n BalancerMember http://192.168.0.11:3000 loadfactor=2\n BalancerMember http://192.168.0.11:3001 loadfactor=2\n\n # cluster member 3\n BalancerMember http://192.168.0.12:3000\n BalancerMember http://192.168.0.12:3001\n\n # cluster member 4\n BalancerMember http://192.168.0.13:3000\n BalancerMember http://192.168.0.13:3001\n</Proxy>\n\n<VirtualHost *:80>\n ServerAdmin info@meinprof.de\n ServerName www.meinprof.de\n ServerAlias meinprof.de\n ProxyPass / balancer://meinprofcluster/\n ProxyPassReverse / balancer://meinprofcluster/\n ErrorLog /var/log/www/www.meinprof.de/apache_error_log\n CustomLog /var/log/www/www.meinprof.de/apache_access_log combined\n</VirtualHost>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27563/"
] |
198,568
|
<p>What is the simplest way to programmatically export Excel data to Matlab?</p>
|
[
{
"answer_id": 35903356,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "csvread() writetable()"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26276/"
] |
198,577
|
<p>Is there any real practical difference between "java -server" and "java -client"? </p>
<p>All I can find on Sun's site is a vague </p>
<blockquote>
<p>"-server starts slower but should run faster". </p>
</blockquote>
<p>What are the real differences? (Using JDK 1.6.0_07 currently.)</p>
|
[
{
"answer_id": 198651,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 10,
"selected": true,
"text": "-client java -client\n -client -server"
},
{
"answer_id": 3775811,
"author": "prule",
"author_id": 20242,
"author_profile": "https://Stackoverflow.com/users/20242",
"pm_score": 5,
"selected": false,
"text": "prstat -Z"
},
{
"answer_id": 12003938,
"author": "Mark Booth",
"author_id": 42473,
"author_profile": "https://Stackoverflow.com/users/42473",
"pm_score": 7,
"selected": false,
"text": "-client -server $ java -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'\nuintx AdaptivePermSizeWeight = 20 {product}\nuintx ErgoHeapSizeLimit = 0 {product}\nuintx InitialHeapSize := 66328448 {product}\nuintx LargePageHeapSizeThreshold = 134217728 {product}\nuintx MaxHeapSize := 1063256064 {product}\nuintx MaxPermSize = 67108864 {pd product}\nuintx PermSize = 16777216 {pd product}\njava version \"1.6.0_24\"\n -server -client $ java -client -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'\nuintx AdaptivePermSizeWeight = 20 {product}\nuintx ErgoHeapSizeLimit = 0 {product}\nuintx InitialHeapSize := 16777216 {product}\nuintx LargePageHeapSizeThreshold = 134217728 {product}\nuintx MaxHeapSize := 268435456 {product}\nuintx MaxPermSize = 67108864 {pd product}\nuintx PermSize = 12582912 {pd product}\njava version \"1.6.0_24\"\n -server java jvm jvisualvm JAVA_OPTS"
},
{
"answer_id": 15471505,
"author": "pharsicle",
"author_id": 181506,
"author_profile": "https://Stackoverflow.com/users/181506",
"pm_score": 5,
"selected": false,
"text": "-client -server"
},
{
"answer_id": 29192128,
"author": "Nuwan Arambage",
"author_id": 572675,
"author_profile": "https://Stackoverflow.com/users/572675",
"pm_score": 1,
"selected": false,
"text": "initial heap size of 1/64 of physical memory up to 1Gbyte\nmaximum heap size of ¼ of physical memory up to 1Gbyte\n"
},
{
"answer_id": 31877125,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 5,
"selected": false,
"text": "package com.blogspot.sdoulger;\n\npublic class LoopTest {\n public LoopTest() {\n super();\n }\n\n public static void main(String[] args) {\n long start = System.currentTimeMillis();\n spendTime();\n long end = System.currentTimeMillis();\n System.out.println(\"Time spent: \"+ (end-start));\n\n LoopTest loopTest = new LoopTest();\n }\n\n private static void spendTime() {\n for (int i =500000000;i>0;i--) {\n }\n }\n}\n"
},
{
"answer_id": 35913837,
"author": "Adam",
"author_id": 1385174,
"author_profile": "https://Stackoverflow.com/users/1385174",
"pm_score": 4,
"selected": false,
"text": "-server volatile boolean asleep;\n...\nwhile (!asleep)\n countSomeSheep();\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
198,580
|
<p>What are optimal settings for Recycling of Application Pools in IIS7 in a shared environment?</p>
<p><img src="https://i.stack.imgur.com/RNQo8.png" alt="enter image description here"></p>
|
[
{
"answer_id": 201812,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 6,
"selected": true,
"text": "retail=\"true\" <deployment> <system.web>\n <!--\n <deployment\n retail = \"false\" [true|false]\n />\n -->\n <deployment retail=\"true\" />\n</system.web>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
] |
198,606
|
<p>I typically use URL rewriting to pass content IDs to my website, so this</p>
<pre><code> Foo.1.aspx
</code></pre>
<p>rewrites to</p>
<pre><code> Foo.aspx?id=1
</code></pre>
<p>For a specific application I need to pass in multiple IDs to a single page, so I've rewritten things to accept this:</p>
<pre><code> Foo.1,2,3,4,5.aspx
</code></pre>
<p>This works fine in Cassini (the built-in ad hoc web server for Visual Studio) but gives me "Internet Explorer cannot display the webpage" when I try it on a live server running IIS. Is this an IIS limitation? Should I just use dashes or underscores instead of commas?</p>
|
[
{
"answer_id": 198617,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "Foo.aspx?id=1;id=2;id=3;id=4;id=5\n"
},
{
"answer_id": 198850,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": false,
"text": "mod_rewrite Foo.aspx Foo.N,N reserved = \";\" | \"/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" |\n \"$\" | \",\"\n"
},
{
"answer_id": 198891,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": "Foo.1-2-3-4-5.aspx\n"
},
{
"answer_id": 199079,
"author": "Luke",
"author_id": 21406,
"author_profile": "https://Stackoverflow.com/users/21406",
"pm_score": 1,
"selected": false,
"text": "index.aspx?c=Foo/1/2/3/4\n"
},
{
"answer_id": 199286,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 6,
"selected": true,
"text": "~/page.aspx?id=1,2,3,4 ~/page/1-2-3-4.aspx ~/products/view.aspx?id=1\n~/products/category.aspx?type=beverage\n ~/products/view/1\n~/products/category/beverage\n"
},
{
"answer_id": 1948967,
"author": "Gordon",
"author_id": 237156,
"author_profile": "https://Stackoverflow.com/users/237156",
"pm_score": 4,
"selected": false,
"text": "%2c"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
198,623
|
<p>I haven't really done any Windows scripting at all, so I am at a loss on how to pull this one off. Anyway, basically what we want to do is have a script that will take an argument on which IIS AppPool to recycle. I have done some research on Google and haven't had much success on getting things to work.</p>
<p>Here is what I am trying now:</p>
<pre><code>$appPoolName = $args[0]
$appPool = get-wmiobject -namespace "root\MicrosoftIISv2" -class "IIsApplicationPools" Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"}
$appPool.Recycle()
</code></pre>
<p>and the error I get:</p>
<pre><code>Get-WmiObject : A parameter cannot be found that matches parameter name '$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"'.
</code></pre>
<p>Anyway, it would be nice if I also knew how to debug things like this. I already fixed one bug with the original script by doing gwmi -namespace "root\MicrosoftIISv2" -list. Any other tips like that one would be great.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: Here is some more info</p>
<pre><code>$appPool = gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools" | Get-Member
. TypeName: System.Management.ManagementObject#root\MicrosoftIISv2\IIsApplicationPools
Name MemberType Definition
---- ---------- ----------
Caption Property System.String Caption {get;set;}
Description Property System.String Description {get;set;}
InstallDate Property System.String InstallDate {get;set;}
Name Property System.String Name {get;set;}
Status Property System.String Status {get;set;}
__CLASS Property System.String __CLASS {get;set;}
__DERIVATION Property System.String[] __DERIVATION {get;set;}
__DYNASTY Property System.String __DYNASTY {get;set;}
__GENUS Property System.Int32 __GENUS {get;set;}
__NAMESPACE Property System.String __NAMESPACE {get;set;}
__PATH Property System.String __PATH {get;set;}
__PROPERTY_COUNT Property System.Int32 __PROPERTY_COUNT {get;set;}
__RELPATH Property System.String __RELPATH {get;set;}
__SERVER Property System.String __SERVER {get;set;}
__SUPERCLASS Property System.String __SUPERCLASS {get;set;}
ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime();
ConvertToDateTime ScriptMethod System.Object ConvertToDateTime();
Delete ScriptMethod System.Object Delete();
GetType ScriptMethod System.Object GetType();
Put ScriptMethod System.Object Put();
gwmi -namespace "root\MicrosoftIISv2" -class "IISApplicationPools"
__GENUS : 2
__CLASS : IIsApplicationPools
__SUPERCLASS : CIM_LogicalElement
__DYNASTY : CIM_ManagedSystemElement
__RELPATH : IIsApplicationPools.Name="W3SVC/AppPools"
__PROPERTY_COUNT : 5
__DERIVATION : {CIM_LogicalElement, CIM_ManagedSystemElement}
__SERVER : IRON
__NAMESPACE : root\MicrosoftIISv2
__PATH : \\IRON\root\MicrosoftIISv2:IIsApplicationPools.Name="W3SVC/A
ppPools"
Caption :
Description :
InstallDate :
Name : W3SVC/AppPools
Status :
</code></pre>
|
[
{
"answer_id": 198760,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 4,
"selected": false,
"text": "$appPoolName = $args[0]\n$appPool = get-wmiobject -namespace \"root\\MicrosoftIISv2\" -class \"IIsApplicationPool\" | Where-Object {$_.Name -eq \"W3SVC/APPPOOLS/$appPoolName\"}\n$appPool.Recycle()\n"
},
{
"answer_id": 198948,
"author": "EdgeVB",
"author_id": 24863,
"author_profile": "https://Stackoverflow.com/users/24863",
"pm_score": 2,
"selected": false,
"text": "$appPoolName = $args[0]\n$appPool = get-wmiobject -namespace \"root\\MicrosoftIISv2\" -class \"IIsApplicationPools\" -filter 'name=\"W3SVC/APPPOOLS/$appPoolName\"'\n"
},
{
"answer_id": 5824109,
"author": "Jason",
"author_id": 136584,
"author_profile": "https://Stackoverflow.com/users/136584",
"pm_score": 3,
"selected": false,
"text": "function Get-IisAppPools {\n\n Get-WmiObject -Namespace \"root\\MicrosoftIISv2\" -Class \"IIsApplicationPool\" -Filter 'name like \"W3SVC/APPPOOLS/%\"' \n | ForEach-Object { $_.Name.ToString().SubString(15) } \n\n}\n\nfunction Recycle-IisAppPool([string]$appPoolName) { \n\n Invoke-WmiMethod -Name Recycle -Namespace \"root\\MicrosoftIISv2\" -Path \"IIsApplicationPool.Name='W3SVC/APPPOOLS/$appPoolName'\" \n\n}\n Recycle-IisAppPool DefaultAppPool\nGet-IisAppPools | ? { $_ -match \"v4.0$\" } | % { Recycle-IisAppPool $_ }\n"
},
{
"answer_id": 6600509,
"author": "Thomas S. Trias",
"author_id": 189048,
"author_profile": "https://Stackoverflow.com/users/189048",
"pm_score": 1,
"selected": false,
"text": "(Get-WmiObject -Query \"SELECT * FROM IIsApplicationPool WHERE Name = 'W3SVC/AppPools/$appPoolName'\" -Namespace 'root\\MicrosoftIISv2').Recycle()\n"
},
{
"answer_id": 36120804,
"author": "user4317867",
"author_id": 4317867,
"author_profile": "https://Stackoverflow.com/users/4317867",
"pm_score": 0,
"selected": false,
"text": "-namespace root\\webadministration -class ApplicationPool | where ( gwmi -comp WebServer01 -namespace root\\webadministration -class ApplicationPool\n\n#Recycle app pool by name.\n(gwmi -comp WebServer01 -namespace root\\webadministration -class ApplicationPool | `\nwhere {$_.Name -eq 'YourAppPool'}).recycle()\n (gwmi -comp WebSserver01 -namespace root\\webadministration -class ApplicationPool | where {$_.Name -eq 'YourAppPool'}).recycle()\n"
},
{
"answer_id": 52865969,
"author": "mvanle",
"author_id": 1213722,
"author_profile": "https://Stackoverflow.com/users/1213722",
"pm_score": 2,
"selected": false,
"text": "$pool = Get-IISAppPool -Name <name>\n\n$pool.recycle()\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
198,625
|
<p>Does anyone know if it is possible to reliably determine (programattically C/C++...) whether or not a firewall or IP filtering software is installed on a Windows PC? I need to detect whether a certain server IP is being blocked in my client software by the host OS.</p>
<p>I don't need to worry about external hardware firewals in this situation as I have full control of this. It is only software firewalls that I am concerned with. My hope was that I could iterate the windows network stack or NDIS interfaces and determine this</p>
|
[
{
"answer_id": 200260,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 3,
"selected": true,
"text": "Private Sub DumpFirewallInfo()\n\nDim oLocator As WbemScripting.SWbemLocator\nDim oService As WbemScripting.SWbemServicesEx\nDim oFirewalls As WbemScripting.SWbemObjectSet\nDim oFirewall As WbemScripting.SWbemObjectEx\nDim oFwMgr As Variant\n \n \n Set oFwMgr = CreateObject(\"HNetCfg.FwMgr\")\n \n Debug.Print \"Checking the Windows Firewall...\"\n Debug.Print \"Windows Firewal Enabled: \" & oFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled\n Debug.Print \"\"\n \n Set oFwMgr = Nothing\n \n \n Debug.Print \"Checking for other installed firewalls...\"\n \n Set oLocator = New WbemScripting.SWbemLocator\n Set oService = oLocator.ConnectServer(\".\", \"root\\SecurityCenter\")\n oService.Security_.ImpersonationLevel = 3\n\n Set oFirewalls = oService.ExecQuery(\"SELECT * FROM FirewallProduct\") ' This could also be \"AntivirusProduct\"\n \n For Each oFirewall In oFirewalls\n Debug.Print \"Company: \" & vbTab & oFirewall.CompanyName\n Debug.Print \"Firewall Name: \" & vbTab & oFirewall.DisplayName\n Debug.Print \"Enabled: \" & vbTab & Format$(oFirewall.Enabled)\n Debug.Print \"Version: \" & vbTab & oFirewall.versionNumber\n Debug.Print \"\"\n Next oFirewall\n \n Set oFirewall = Nothing\n Set oFirewalls = Nothing\n Set oService = Nothing\n Set oLocator = Nothing\n\nEnd Sub\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10446/"
] |
198,634
|
<p>I have a table which contains 3 nvarchar(255) columns and a combination of these 3 columns must be unique. Normally I would create a Unique constraint, but in this case, I am hitting the 900 byte limit. Since I have to support SQL Server 2000, I can not use Include columns to get around this situation.</p>
|
[
{
"answer_id": 198737,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE dbo.Test_Unique_Limit (\n string_1 NVARCHAR(255) NOT NULL,\n string_2 NVARCHAR(255) NOT NULL,\n string_3 NVARCHAR(255) NOT NULL )\nGO\nCREATE VIEW dbo.Test_Unique_Limit_View\nWITH SCHEMABINDING\nAS\n SELECT string_1, string_2, string_3, CHECKSUM(string_1, string_2, string_3) AS CHKSUM\n FROM dbo.Test_Unique_Limit\nGO\nCREATE UNIQUE CLUSTERED INDEX Test_Unique_Limit_IDX ON dbo.Test_Unique_Limit_View (CHKSUM)\nGO\n"
},
{
"answer_id": 198847,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION [dbo].[fn_count_rows_for_ids]\n(\n @id1 nvarchar(255),\n @id2 nvarchar(255),\n @id3 nvarchar(255)\n)\nRETURNS int\nAS\nBEGIN\n DECLARE @count int\n\n SELECT @count = count(*) FROM tbl_test WHERE (string_1 = @id1 AND string_2 = @id2 AND string_3 = @id3)\n\n RETURN @count\n\nEND\n\nCREATE TABLE [dbo].[tbl_test](\n [string_1] [nvarchar](255) NOT NULL,\n [string_2] [nvarchar](255) NOT NULL,\n [string_3] [nvarchar](255) NOT NULL\n) ON [PRIMARY]\n\nALTER TABLE [dbo].[tbl_test] WITH CHECK ADD CONSTRAINT [CK_tbl_test] CHECK (([dbo].[fn_count_rows_for_ids]([string_1],[string_2],[string_3])<=(1)))\n\nALTER TABLE [dbo].[tbl_test] CHECK CONSTRAINT [CK_tbl_test]\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4441/"
] |
198,650
|
<p>In asp.net, you can retrieve MULTIPLE datatables from a single call to the database. Can you do the same thing in php?</p>
<p>Example:</p>
<pre><code>$sql ="select * from t1; select * from t2;";
$result = SomeQueryFunc($sql);
print_r($result[0]); // dump results for t1
print_r($result[1]); // dump results for t2
</code></pre>
<p>Can you do something like this?</p>
|
[
{
"answer_id": 198686,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "PDOStatement::nextRowset()"
},
{
"answer_id": 8111427,
"author": "genesis",
"author_id": 764846,
"author_profile": "https://Stackoverflow.com/users/764846",
"pm_score": 0,
"selected": false,
"text": "function SomeQueryFunc($queries) {\n $queries = explode(';', $queries);\n $return = array();\n foreach($queries as $index => $query) {\n $result = mysql_query($query);\n $return[$index] = array();\n while($row = mysql_fetch_assoc($result)) {\n foreach($row as $column => $value) {\n $return[$index][$column] = $value;\n }\n }\n }\n return $return;\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27305/"
] |
198,656
|
<p>I creating a control for WPF, and I have a question for you WPF gurus out there.</p>
<p>I want my control to be able to expand to fit a resizable window. </p>
<p>In my control, I have a list box that I want to expand with the window. I also have other controls around the list box (buttons, text, etc).</p>
<p>I want to be able to set a minimum size on my control, but I want the window to be able to be sized smaller by creating scroll bars for viewing the control. </p>
<p>This creates nested scroll areas: One for the list box and a ScrollViewer wrapping the whole control. </p>
<p>Now, if the list box is set to auto size, it will never have a scroll bar because it is always drawn full size within the ScrollViewer. </p>
<p>I only want the control to scroll if the content can't get any smaller, otherwise I don't want to scroll the control; instead I want to scroll the list box inside the control.</p>
<p>How can I alter the default behavior of the ScrollViewer class? I tried inheriting from the ScrollViewer class and overriding the MeasureOverride and ArrangeOverride classes, but I couldn't figure out how to measure and arrange the child properly. It appears that the arrange has to affect the ScrollContentPresenter somehow, not the actual content child.</p>
<p>Any help/suggestions would be much appreciated.</p>
|
[
{
"answer_id": 198688,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n > \n <ScrollViewer HorizontalScrollBarVisibility=\"Auto\" \n VerticalScrollBarVisibility=\"Auto\">\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n </Grid.ColumnDefinitions>\n <ListBox Grid.Row=\"0\" Grid.RowSpan=\"3\" Grid.Column=\"0\" MinWidth=\"200\"/>\n <Button Grid.Row=\"0\" Grid.Column=\"1\" Content=\"Button1\"/>\n <Button Grid.Row=\"1\" Grid.Column=\"1\" Content=\"Button2\"/>\n <Button Grid.Row=\"2\" Grid.Column=\"1\" Content=\"Button3\"/>\n </Grid>\n </ScrollViewer>\n</Window>\n"
},
{
"answer_id": 218587,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "Control ScrollViewer ListBox ScrollViewer ListBox ScrollViewer ScrollViewer MeasureOverride() availableSize availableSize Visual VisualChildrenCount GetVisualChild(int)"
},
{
"answer_id": 1571972,
"author": "Daniel",
"author_id": 141502,
"author_profile": "https://Stackoverflow.com/users/141502",
"pm_score": 4,
"selected": false,
"text": "public class RestrictDesiredSize : Decorator\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n if (lastArrangeSize != arrangeSize) {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <local:RestrictDesiredSize MinWidth=\"200\" MinHeight=\"200\">\n <ListBox />\n</local>\n"
},
{
"answer_id": 9988974,
"author": "Heiner",
"author_id": 495910,
"author_profile": "https://Stackoverflow.com/users/495910",
"pm_score": 2,
"selected": false,
"text": "KeepWidth KeepHeight MeasureOverride protected override Size MeasureOverride(Size constraint)\n{\n var innerWidth = Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = KeepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = KeepHeight ? Child.DesiredSize.Height : 0;\n return new Size(outerWidth, outerHeight);\n}\n"
},
{
"answer_id": 44592501,
"author": "Dmitry",
"author_id": 5475902,
"author_profile": "https://Stackoverflow.com/users/5475902",
"pm_score": 0,
"selected": false,
"text": " public class ScrollExt: ScrollViewer\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n public ScrollExt()\n {\n\n }\n protected override Size MeasureOverride(Size constraint)\n {\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n if (lastArrangeSize != arrangeSize)\n {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <ScrollViewer HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\">\n <Grid >\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <TextBlock Background=\"Beige\" Width=\"600\" Text=\"Example\"/>\n <Grid Grid.Column=\"1\" x:Name=\"grid\">\n <Grid Grid.Column=\"1\" Margin=\"25\" Background=\"Green\">\n <local:ScrollExt HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\">\n <Grid Width=\"10000\" Margin=\"25\" Background=\"Red\" />\n </local:ScrollExt>\n </Grid>\n </Grid>\n </Grid>\n </ScrollViewer>\n"
},
{
"answer_id": 53011021,
"author": "Glaucus",
"author_id": 1011688,
"author_profile": "https://Stackoverflow.com/users/1011688",
"pm_score": 0,
"selected": false,
"text": "public class RestrictDesiredSizeDecorator : Decorator\n{\n public static readonly DependencyProperty KeepWidth;\n public static readonly DependencyProperty KeepHeight;\n\n #region Dependency property setters and getters\n public static void SetKeepWidth(UIElement element, bool value)\n {\n element.SetValue(KeepWidth, value);\n }\n\n public static bool GetKeepWidth(UIElement element)\n {\n return (bool)element.GetValue(KeepWidth);\n }\n\n public static void SetKeepHeight(UIElement element, bool value)\n {\n element.SetValue(KeepHeight, value);\n }\n\n public static bool GetKeepHeight(UIElement element)\n {\n return (bool)element.GetValue(KeepHeight);\n }\n #endregion\n\n private Size _lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n static RestrictDesiredSizeDecorator()\n {\n KeepWidth = DependencyProperty.RegisterAttached(\n nameof(KeepWidth),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n\n KeepHeight = DependencyProperty.RegisterAttached(\n nameof(KeepHeight),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n\n var keepWidth = GetValue(KeepWidth) as bool? ?? false;\n var keepHeight = GetValue(KeepHeight) as bool? ?? false;\n\n var innerWidth = keepWidth ? constraint.Width : Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = keepHeight ? constraint.Height : Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = keepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = keepHeight ? Child.DesiredSize.Height : 0;\n\n return new Size(outerWidth, outerHeight);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n\n if (_lastArrangeSize != arrangeSize)\n {\n _lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <ScrollViewer>\n <StackPanel Orientation=\"Vertical\">\n <Whatever />\n\n <decorators:RestrictDesiredSizeDecorator MinWidth=\"100\" KeepHeight=\"True\">\n <TextBox\n Text=\"{Binding Comment, UpdateSourceTrigger=PropertyChanged}\"\n Height=\"Auto\"\n MaxHeight=\"360\"\n VerticalScrollBarVisibility=\"Auto\"\n HorizontalScrollBarVisibility=\"Auto\"\n AcceptsReturn=\"True\"\n AcceptsTab=\"True\"\n TextWrapping=\"WrapWithOverflow\"\n />\n </decorators:RestrictDesiredSizeDecorator>\n\n <Whatever />\n </StackPanel>\n</ScrollViewer\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,668
|
<p>I have a situation where I need to be able to load assemblies in the GAC based on their partial names. In order to do this I have added the following to my app.config file:</p>
<pre><code><runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<qualifyAssembly partialName="MyAssembly"
fullName= "MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef"/>
</assemblyBinding>
</runtime>
</code></pre>
<p>This works exactly the way I want it to. However, if I place the same element in my machine.config file, it seems to be ignored, and I get FileNotFoundExceptions when trying to load MyAssembly.</p>
<p>The following is the assembly binding log when the element is in my app.config, and the bind succeeds:</p>
<pre>LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Partial reference qualified from config file. New reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef.
LOG: Post-policy reference: MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef
LOG: Found assembly by looking in the GAC.
LOG: Binding succeeds. Returns assembly from C:\WINDOWS\assembly\GAC_MSIL\MyAssembly\1.0.0.0__b20f4683c1030dbd\MyAssembly.dll.
LOG: Assembly is loaded in default load context.</pre>
<p>Contrast that with the log when my configuration is in machine.config, and the bind fails:</p>
<pre>LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Documents and Settings\jon_scheiding\My Documents\Source\Testing\Test Projects 1\Cmd\bin\Debug\Testers.Cmd.vshost.exe.config
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.DLL.
LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.DLL.
LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly.EXE.
LOG: Attempting download of new URL file:///C:/Documents and Settings/jon_scheiding/My Documents/Source/Testing/Test Projects 1/Cmd/bin/Debug/MyAssembly/MyAssembly.EXE.
LOG: All probing URLs attempted and failed.</pre>
<p>The problem seems to be the fourth line, "Policy not being applied to reference at this time." However, I can find very little documentation on what this message means, or how to address it.</p>
<p>How can I get the framework to recognize my <runtime> element?</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 198688,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 0,
"selected": false,
"text": "<Window\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n > \n <ScrollViewer HorizontalScrollBarVisibility=\"Auto\" \n VerticalScrollBarVisibility=\"Auto\">\n <Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n <RowDefinition Height=\"Auto\"/>\n </Grid.RowDefinitions>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\"/>\n <ColumnDefinition Width=\"Auto\"/>\n </Grid.ColumnDefinitions>\n <ListBox Grid.Row=\"0\" Grid.RowSpan=\"3\" Grid.Column=\"0\" MinWidth=\"200\"/>\n <Button Grid.Row=\"0\" Grid.Column=\"1\" Content=\"Button1\"/>\n <Button Grid.Row=\"1\" Grid.Column=\"1\" Content=\"Button2\"/>\n <Button Grid.Row=\"2\" Grid.Column=\"1\" Content=\"Button3\"/>\n </Grid>\n </ScrollViewer>\n</Window>\n"
},
{
"answer_id": 218587,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "Control ScrollViewer ListBox ScrollViewer ListBox ScrollViewer ScrollViewer MeasureOverride() availableSize availableSize Visual VisualChildrenCount GetVisualChild(int)"
},
{
"answer_id": 1571972,
"author": "Daniel",
"author_id": 141502,
"author_profile": "https://Stackoverflow.com/users/141502",
"pm_score": 4,
"selected": false,
"text": "public class RestrictDesiredSize : Decorator\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n if (lastArrangeSize != arrangeSize) {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <local:RestrictDesiredSize MinWidth=\"200\" MinHeight=\"200\">\n <ListBox />\n</local>\n"
},
{
"answer_id": 9988974,
"author": "Heiner",
"author_id": 495910,
"author_profile": "https://Stackoverflow.com/users/495910",
"pm_score": 2,
"selected": false,
"text": "KeepWidth KeepHeight MeasureOverride protected override Size MeasureOverride(Size constraint)\n{\n var innerWidth = Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = KeepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = KeepHeight ? Child.DesiredSize.Height : 0;\n return new Size(outerWidth, outerHeight);\n}\n"
},
{
"answer_id": 44592501,
"author": "Dmitry",
"author_id": 5475902,
"author_profile": "https://Stackoverflow.com/users/5475902",
"pm_score": 0,
"selected": false,
"text": " public class ScrollExt: ScrollViewer\n{\n Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n public ScrollExt()\n {\n\n }\n protected override Size MeasureOverride(Size constraint)\n {\n base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),\n Math.Min(lastArrangeSize.Height, constraint.Height)));\n return new Size(0, 0);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n if (lastArrangeSize != arrangeSize)\n {\n lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <ScrollViewer HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\">\n <Grid >\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n </Grid.ColumnDefinitions>\n <TextBlock Background=\"Beige\" Width=\"600\" Text=\"Example\"/>\n <Grid Grid.Column=\"1\" x:Name=\"grid\">\n <Grid Grid.Column=\"1\" Margin=\"25\" Background=\"Green\">\n <local:ScrollExt HorizontalScrollBarVisibility=\"Auto\" VerticalScrollBarVisibility=\"Auto\">\n <Grid Width=\"10000\" Margin=\"25\" Background=\"Red\" />\n </local:ScrollExt>\n </Grid>\n </Grid>\n </Grid>\n </ScrollViewer>\n"
},
{
"answer_id": 53011021,
"author": "Glaucus",
"author_id": 1011688,
"author_profile": "https://Stackoverflow.com/users/1011688",
"pm_score": 0,
"selected": false,
"text": "public class RestrictDesiredSizeDecorator : Decorator\n{\n public static readonly DependencyProperty KeepWidth;\n public static readonly DependencyProperty KeepHeight;\n\n #region Dependency property setters and getters\n public static void SetKeepWidth(UIElement element, bool value)\n {\n element.SetValue(KeepWidth, value);\n }\n\n public static bool GetKeepWidth(UIElement element)\n {\n return (bool)element.GetValue(KeepWidth);\n }\n\n public static void SetKeepHeight(UIElement element, bool value)\n {\n element.SetValue(KeepHeight, value);\n }\n\n public static bool GetKeepHeight(UIElement element)\n {\n return (bool)element.GetValue(KeepHeight);\n }\n #endregion\n\n private Size _lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);\n\n static RestrictDesiredSizeDecorator()\n {\n KeepWidth = DependencyProperty.RegisterAttached(\n nameof(KeepWidth),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n\n KeepHeight = DependencyProperty.RegisterAttached(\n nameof(KeepHeight),\n typeof(bool),\n typeof(RestrictDesiredSizeDecorator));\n }\n\n protected override Size MeasureOverride(Size constraint)\n {\n Debug.WriteLine(\"Measure: \" + constraint);\n\n var keepWidth = GetValue(KeepWidth) as bool? ?? false;\n var keepHeight = GetValue(KeepHeight) as bool? ?? false;\n\n var innerWidth = keepWidth ? constraint.Width : Math.Min(this._lastArrangeSize.Width, constraint.Width);\n var innerHeight = keepHeight ? constraint.Height : Math.Min(this._lastArrangeSize.Height, constraint.Height);\n base.MeasureOverride(new Size(innerWidth, innerHeight));\n\n var outerWidth = keepWidth ? Child.DesiredSize.Width : 0;\n var outerHeight = keepHeight ? Child.DesiredSize.Height : 0;\n\n return new Size(outerWidth, outerHeight);\n }\n\n protected override Size ArrangeOverride(Size arrangeSize)\n {\n Debug.WriteLine(\"Arrange: \" + arrangeSize);\n\n if (_lastArrangeSize != arrangeSize)\n {\n _lastArrangeSize = arrangeSize;\n base.MeasureOverride(arrangeSize);\n }\n\n return base.ArrangeOverride(arrangeSize);\n }\n}\n <ScrollViewer>\n <StackPanel Orientation=\"Vertical\">\n <Whatever />\n\n <decorators:RestrictDesiredSizeDecorator MinWidth=\"100\" KeepHeight=\"True\">\n <TextBox\n Text=\"{Binding Comment, UpdateSourceTrigger=PropertyChanged}\"\n Height=\"Auto\"\n MaxHeight=\"360\"\n VerticalScrollBarVisibility=\"Auto\"\n HorizontalScrollBarVisibility=\"Auto\"\n AcceptsReturn=\"True\"\n AcceptsTab=\"True\"\n TextWrapping=\"WrapWithOverflow\"\n />\n </decorators:RestrictDesiredSizeDecorator>\n\n <Whatever />\n </StackPanel>\n</ScrollViewer\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27578/"
] |
198,670
|
<p>Thanks for reading. I'm a bit new to jQuery, and am trying to make a script I can include in all my websites to solve a problem that always drives me crazy...</p>
<p>The problem:
Select boxes with long options get cut off in Internet Explorer. For example, these select boxes:
<a href="http://discoverfire.com/test/select.php" rel="noreferrer">http://discoverfire.com/test/select.php</a></p>
<p>In Firefox they are fine, but in IE, the options are cut off to the width of the select when they drop down.</p>
<p>The solution:
What I am looking to do, is create a script that I can include in any page that will do the following:</p>
<ol>
<li><p>Loop through all the selects on the page.</p></li>
<li><p>For each select:
A. Loop through its options.
B. Find the width of the longest option.
C. Bind a function to expand the select to that width on focus (or maybe click...).
D. Bind a function to shrink to it's original width on blur.</p></li>
</ol>
<p>I've managed to do most of step #2 for one select box.</p>
<p>I found that getting the options width was a problem (especially in IE), so I looped through and copied the text of each option to a span, measured the span width, and used the longest one as the width the select will be expanded to. Perhaps somebody has a better idea.</p>
<p>Here is the code</p>
<pre><code><script type='text/javascript'>
$(function() {
/*
This function will:
1. Create a data store for the select called ResizeToWidth.
2. Populate it with the width of the longest option, as approximated by span width.
The data store can then be used
*/
// Make a temporary span to hold the text of the options.
$('body').append("<span id='CurrentOptWidth'></span>");
$("#TheSelect option").each(function(i){
// If this is the first time through, zero out ResizeToWidth (or it will end up NaN).
if ( isNaN( $(this).parent().data('ResizeToWidth') ) ) {
$(this).parent().data( 'OriginalWidth', $(this).parent().width() );
$(this).parent().data('ResizeToWidth', 0);
$('CurrentOptWidth').css('font-family', $(this).css('font-family') );
$('CurrentOptWidth').css('font-size', $(this).css('font-size') );
$('CurrentOptWidth').css('font-weight', $(this).css('font-weight') );
}
// Put the text of the current option into the span.
$('#CurrentOptWidth').text( $(this).text() );
// Set ResizeToWidth to the longer of a) the current opt width, or b) itself.
//So it will hold the width of the longest option when we are done
ResizeToWidth = Math.max( $('#CurrentOptWidth').width() , $(this).parent().data('ResizeToWidth') );
// Update parent ResizeToWidth data.
$(this).parent().data('ResizeToWidth', ResizeToWidth)
});
// Remove the temporary span.
$('#CurrentOptWidth').remove();
$('#TheSelect').focus(function(){
$(this).width( $(this).data('ResizeToWidth') );
});
$('#TheSelect').blur(function(){
$(this).width( $(this).data('OriginalWidth') );
});
alert( $('#TheSelect').data('OriginalWidth') );
alert( $('#TheSelect').data('ResizeToWidth') );
});
</script>
</code></pre>
<p>and the select:</p>
<pre><code><select id='TheSelect' style='width:50px;'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
<option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option>
<option value='5'>Five</option>
<option value='6'>Six</option>
<option value='7'>Seven...</option>
</select>
</code></pre>
<p>Hopefully this will run for you if you want to run it, or you can see it in action here: <a href="http://discoverfire.com/test/select.php" rel="noreferrer">http://discoverfire.com/test/select.php</a>.</p>
<p>What I need help with:
This needs a bit of polish, but seems to work ok if you specify the select box.</p>
<p>However, I don't seem to be able to figure out how to apply it to all select boxes on the page with a loop. So far, I have this:</p>
<pre><code>$('select').each(
function(i, select){
// Get the options for the select here... can I use select.each...?
}
);
</code></pre>
<p>Also, is there a better way to get the length of the longest option for each select? The span is close, but not very exact. The problem is that IE returns zero for the option widths of the actual selects.</p>
<p>Any ideas are very welcome, both for the questions asked, and any other improvements to my code.</p>
<p>Thanks!!</p>
|
[
{
"answer_id": 198901,
"author": "msmithstubbs",
"author_id": 27606,
"author_profile": "https://Stackoverflow.com/users/27606",
"pm_score": 5,
"selected": true,
"text": "$('select').each(function(){\n\n $('option', this).each(function() {\n // your normalizing script here\n\n })\n\n});\n"
},
{
"answer_id": 198950,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 3,
"selected": false,
"text": "function resize(selectId, size){\n var objSelect = document.getElementById(selectId);\n var maxlength = 0;\n if(objSelect){\n if(size){\n objSelect.style.width = size;\n } else {\n for (var i=0; i< objSelect.options.length; i++){\n if (objSelect[i].text.length > maxlength){\n maxlength = objSelect[i].text.length;\n }\n }\n objSelect.style.width = maxlength * 9;\n }\n } \n}\n\n$(document).ready(function(){\n $(\"select\").focus(function(){\n resize($(this).attr(\"id\"));\n });\n $(\"select\").blur(function(){\n resize($(this).attr(\"id\"), 40);\n });\n});\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27580/"
] |
198,679
|
<p>Given an <code>InputStream</code> called <code>in</code> which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a <code>byte</code> array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error:</p>
<pre><code>java.io.IOException: stream length not specified
</code></pre>
<p>I managed to get it to work by writing the wav to a temporary file, then reading it back in, as shown below:</p>
<pre><code>AudioInputStream source = AudioSystem.getAudioInputStream(new BufferedInputStream(in, 1024));
AudioInputStream pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source);
AudioInputStream ulaw = AudioSystem.getAudioInputStream(AudioFormat.Encoding.ULAW, pcm);
File tempFile = File.createTempFile("wav", "tmp");
AudioSystem.write(ulaw, AudioFileFormat.Type.WAVE, tempFile);
// The fileToByteArray() method reads the file
// into a byte array; omitted for brevity
byte[] bytes = fileToByteArray(tempFile);
tempFile.delete();
return bytes;
</code></pre>
<p>This is obviously less desirable. Is there a better way?</p>
|
[
{
"answer_id": 6505115,
"author": "Gábor Dikán",
"author_id": 818978,
"author_profile": "https://Stackoverflow.com/users/818978",
"pm_score": -1,
"selected": false,
"text": "File f = new File(exportFileName+\".tmp\");\nFile f2 = new File(exportFileName);\nlong l = f.length();\nFileInputStream fi = new FileInputStream(f);\nAudioInputStream ai = new AudioInputStream(fi,mainFormat,l/4);\nAudioSystem.write(ai, Type.WAVE, f2);\nfi.close();\nf.delete();\n"
},
{
"answer_id": 28844417,
"author": "HolloW",
"author_id": 752900,
"author_profile": "https://Stackoverflow.com/users/752900",
"pm_score": 2,
"selected": false,
"text": "public void UploadFiles(String fileName, byte[] bFile)\n{\n String uploadedFileLocation = \"c:\\\\\";\n\n AudioInputStream source;\n AudioInputStream pcm;\n InputStream b_in = new ByteArrayInputStream(bFile);\n source = AudioSystem.getAudioInputStream(new BufferedInputStream(b_in));\n pcm = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED, source);\n File newFile = new File(uploadedFileLocation + fileName);\n AudioSystem.write(pcm, Type.WAVE, newFile);\n\n source.close();\n pcm.close();\n}\n"
},
{
"answer_id": 39232513,
"author": "Kanaris007",
"author_id": 5685534,
"author_profile": "https://Stackoverflow.com/users/5685534",
"pm_score": -1,
"selected": false,
"text": "public void run() { \n try { \n writer = new NewWaveWriter(44100); \n\n byte[]buffer = new byte[256]; \n int res = 0; \n while((res = m_audioInputStream.read(buffer)) > 0) { \n writer.write(buffer, 0, res); \n } \n } catch (IOException e) { \n System.out.println(\"Error: \" + e.getMessage()); \n } \n} \n\npublic byte[]getResult() throws IOException { \n return writer.getByteBuffer(); \n} \n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4287/"
] |
198,691
|
<p>I'm working on a solution that contains multiple projects targeting Windows Mobile 5 and standard Windows applications.</p>
<p>Lately when opening up a form in designer the common UI controls (textbox, button, label, etc etc...) have vanished leaving only the controls defined within the project.</p>
<p>Resetting the toolbox has no effect. A google search suggested deleting the toolbox temp files in the <code>Local Settings\Application Data\Microsoft\VisualStudio\9.0</code>, however this was only successful in bringing back the default controls for Windows Mobile 5. The WinForms controls are still mysteriously missing.</p>
<p>Also, if I right-click and <em>Select All</em> on the toolbox, all of the WinForms controls do in fact come up, however they're all grayed out.</p>
<p>Has anyone else experienced this?</p>
|
[
{
"answer_id": 199273,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 1,
"selected": false,
"text": "[ToolboxBitmap(typeof(MyControl), \"MyControlBitmap\")]\n"
},
{
"answer_id": 868765,
"author": "Simon H.",
"author_id": 72807,
"author_profile": "https://Stackoverflow.com/users/72807",
"pm_score": 2,
"selected": false,
"text": "<VisualStudioProject\n ProjectType=\"Visual C++\"\n Version=\"9,00\"\n Name=\"COLLADA Import\"\n ProjectGUID=\"{0DEEF9B6-1929-44E3-92EC-13712839FB63}\"\n RootNamespace=\"COLLADAImport\"\n Keyword=\"ManagedCProj\"\n TargetFrameworkVersion=\"0\"\n >\n"
},
{
"answer_id": 10598825,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 1,
"selected": false,
"text": "devenv /setup /resetuserdata /selfreg /resetskippkgs\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,692
|
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob?
(I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
|
[
{
"answer_id": 199393,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 1,
"selected": false,
"text": "shelve"
},
{
"answer_id": 200143,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 2,
"selected": false,
"text": "query = u'''insert into testtable VALUES(?)'''\nb = sqlite3.Binary(binarydata)\ncur.execute(query,(b,))\ncon.commit()\n"
},
{
"answer_id": 436677,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 3,
"selected": false,
"text": "# register the \"loader\" to get the data back out.\nsqlite3.register_converter(\"pickle\", cPickle.loads) \n p_string = p.dumps( dict(a=1,b=[1,2,3])) \nconn.execute(''' \n create table snapshot( \n id INTEGER PRIMARY KEY AUTOINCREMENT, \n mydata pickle); \n''') \n\nconn.execute(''' \n insert into snapshot values \n (null, ?)''', (p_string,))\n''')\n"
},
{
"answer_id": 2340858,
"author": "Benoît Vidis",
"author_id": 138305,
"author_profile": "https://Stackoverflow.com/users/138305",
"pm_score": 6,
"selected": false,
"text": "pdata = cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL)\ncurr.execute(\"insert into table (data) values (:data)\", sqlite3.Binary(pdata))\n curr.execute(\"select data from table limit 1\")\nfor row in curr:\n data = cPickle.loads(str(row['data']))\n"
},
{
"answer_id": 15384886,
"author": "pervlad",
"author_id": 2165211,
"author_profile": "https://Stackoverflow.com/users/2165211",
"pm_score": 1,
"selected": false,
"text": "import sqlite3\nimport pickle\n\ndef adapt_tuple(tuple):\n return pickle.dumps(tuple) \n\nsqlite3.register_adapter(tuple, adapt_tuple) #cannot use pickle.dumps directly because of inadequate argument signature \nsqlite3.register_converter(\"tuple\", pickle.loads)\n\ndef collate_tuple(string1, string2):\n return cmp(pickle.loads(string1), pickle.loads(string2))\n\n#########################\n# 1) Using declared types\ncon = sqlite3.connect(\":memory:\", detect_types=sqlite3.PARSE_DECLTYPES)\n\ncon.create_collation(\"cmptuple\", collate_tuple)\n\ncur = con.cursor()\ncur.execute(\"create table test(p tuple unique collate cmptuple) \")\ncur.execute(\"create index tuple_collated_index on test(p collate cmptuple)\")\n\ncur.execute(\"select name, type from sqlite_master\") # where type = 'table'\")\nprint(cur.fetchall())\n\np = (1,2,3)\np1 = (1,2)\n\ncur.execute(\"insert into test(p) values (?)\", (p,))\ncur.execute(\"insert into test(p) values (?)\", (p1,))\ncur.execute(\"insert into test(p) values (?)\", ((10, 1),))\ncur.execute(\"insert into test(p) values (?)\", (tuple((9, 33)) ,))\ncur.execute(\"insert into test(p) values (?)\", (((9, 5), 33) ,))\n\ntry:\n cur.execute(\"insert into test(p) values (?)\", (tuple((9, 33)) ,))\nexcept Exception as e:\n print e\n\ncur.execute(\"select p from test order by p\")\nprint \"\\nwith declared types and default collate on column:\"\nfor raw in cur:\n print raw\n\ncur.execute(\"select p from test order by p collate cmptuple\")\nprint \"\\nwith declared types collate:\"\nfor raw in cur:\n print raw\n\ncon.create_function('pycmp', 2, cmp)\n\nprint \"\\nselect grater than using cmp function:\"\ncur.execute(\"select p from test where pycmp(p,?) >= 0\", ((10, ),) )\nfor raw in cur:\n print raw\n\ncur.execute(\"explain query plan select p from test where p > ?\", ((3,)))\nfor raw in cur:\n print raw \n\nprint \"\\nselect grater than using collate:\"\ncur.execute(\"select p from test where p > ?\", ((10,),) )\nfor raw in cur:\n print raw \n\ncur.execute(\"explain query plan select p from test where p > ?\", ((3,)))\nfor raw in cur:\n print raw\n\ncur.close()\ncon.close()\n"
},
{
"answer_id": 57580626,
"author": "jbplasma",
"author_id": 9886516,
"author_profile": "https://Stackoverflow.com/users/9886516",
"pm_score": 1,
"selected": false,
"text": "from sqlalchemy import PickleType, Integer\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import create_engine\nimport pickle\n\nBase= declarative_base()\n\nclass User(Base):\n __tablename__= 'Users'\n\n id= Column(Integer, primary_key= True)\n user_login_data_array= Column(PickleType)\n\nlogin_information= {'User1':{'Times': np.arange(0,20),\n 'IP': ['123.901.12.189','123.441.49.391']}}\n\nengine= create_engine('sqlite:///memory:',echo= False) \n\nBase.metadata.create_all(engine)\nSession_maker= sessionmaker(bind=engine)\nSession= Session_maker()\n\n# The pickling here is very intuitive! Just need to have \n# defined the column \"user_login_data_array\" to take pickletype data.\n\npickled_login_data_array= pickle.dumps(login_information)\nuser_object_to_add= User(user_login_data_array= pickled_login_data_array)\n\nSession.add(user_object_to_add)\nSession.commit()\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
198,705
|
<p>In my <a href="http://www.codeplex.com/MEF" rel="nofollow noreferrer">MEF</a> usage, I have a bunch of imports that I want to make available in many other parts of my code. Something like:</p>
<pre><code>[Export (typeof (IBarProvider))]
class MyBarFactory : IBarPovider
{
[Import]
public IFoo1Service IFoo1Service { get; set; }
[Import]
public IFoo2Service IFoo2Service { get; set; }
[Import]
public IFoo3Service IFoo3Service { get; set; }
[Import]
public IFoo4Service IFoo4Service { get; set; }
[Import]
public IFoo5Service IFoo5Service { get; set; }
public IBar CreateBar()
{
return new BarImplementation(/* want to pass the imported services here */);
}
}
class BarImplementation : IBar
{
readonly zib zib;
public BarImplementation(/* ... */)
{
this.zib = new Zib(/* pass services here, too */);
}
}
</code></pre>
<p>I could pass each imported service as an individual parameter, but it's a lot of boring code. There's gotta be something better. Any ideas?</p>
|
[
{
"answer_id": 198708,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "partial class BarImplementation\n{\n public IRequiredServices\n {\n\n public IFoo1Service IFoo1Service { get; set; }\n public IFoo2Service IFoo2Service { get; set; } \n public IFoo3Service IFoo3Service { get; set; } \n public IFoo4Service IFoo4Service { get; set; } \n public IFoo5Service IFoo5Service { get; set; }\n }\n}\n MyBarFactory BarImplementation : BarImplementation.IRequiredServices Zib Zib"
},
{
"answer_id": 198715,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "IImports"
},
{
"answer_id": 207547,
"author": "Wes Haggard",
"author_id": 12784,
"author_profile": "https://Stackoverflow.com/users/12784",
"pm_score": 1,
"selected": false,
"text": "class BarImplementation : IBar\n{\n [ImportingConstructor]\n public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
198,707
|
<p>As a workaround for a problem, I think I have to handle KeyDown events to get the printable character the user actually typed.</p>
<p>KeyDown supplies me with a KeyEventArgs object with the properities KeyCode, KeyData, KeyValue, Modifiers, Alt, Shift, Control.</p>
<p>My first attempt was just to consider the KeyCode to be the ascii code, but KeyCode on my keyboard is 46, a period ("."), so I end up printing a period when the user types the delete key. So, I know my logic is inadequate.</p>
<p>(For those who are curious, the problem is that I have my own combobox in a DataGridView's control collection and somehow SOME characters I type don't produce the KeyPress and TextChanged ComboBox events. These letters include Q, $, %....</p>
<p>This code will reproduce the problem. Generate a Form App and replace the ctor with this code. Run it, and try typing the letter Q into the two comboxes.</p>
<pre><code>public partial class Form1 : Form
{
ComboBox cmbInGrid;
ComboBox cmbNotInGrid;
DataGridView grid;
public Form1()
{
InitializeComponent();
grid = new DataGridView();
cmbInGrid = new ComboBox();
cmbNotInGrid = new ComboBox();
cmbInGrid.Items.Add("a");
cmbInGrid.Items.Add("b");
cmbNotInGrid.Items.Add("c");
cmbNotInGrid.Items.Add("d");
this.Controls.Add(cmbNotInGrid);
this.Controls.Add(grid);
grid.Location = new Point(0, 100);
this.grid.Controls.Add(cmbInGrid);
}
</code></pre>
|
[
{
"answer_id": 198804,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 0,
"selected": false,
"text": "KeysConverter converter = new KeysConverter();\nstring key = converter.ConvertTo(e.KeyCode, typeof(string));\n"
},
{
"answer_id": 201137,
"author": "Jon Schneider",
"author_id": 12484,
"author_profile": "https://Stackoverflow.com/users/12484",
"pm_score": 0,
"selected": false,
"text": "DataGridView DataGridView DataGridView"
},
{
"answer_id": 1801116,
"author": "Pedery",
"author_id": 118211,
"author_profile": "https://Stackoverflow.com/users/118211",
"pm_score": 2,
"selected": false,
"text": "protected override bool IsInputKey(Keys keyData) {\n // This snippet informs .Net that arrow keys should be processed in the panel (which is strangely not standard).\n\n switch (keyData & Keys.KeyCode) {\n case Keys.Left:\n return true;\n case Keys.Right:\n return true;\n case Keys.Up:\n return true;\n case Keys.Down:\n return true;\n }\n return base.IsInputKey(keyData);\n\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
198,716
|
<p>I need to pivot one column (Numbers column).
example need this data:</p>
<pre><code>a 1
a 2
b 3
b 4
c 5
d 6
d 7
d 8
d 9
e 10
e 11
e 12
e 13
e 14
</code></pre>
<p>Look like this</p>
<pre><code>a 1 2
b 3 4
c 5
d 6 7 8 9
e 10 11 12 13 14
</code></pre>
<p>any help would be greatly appreciated...</p>
|
[
{
"answer_id": 198920,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "WITH CTE(CTEstring, CTEids, CTElast_id)\nAS\n(\n SELECT string, CAST(id AS VARCHAR(1000)), id\n FROM dbo.Test_Pivot TP1\n WHERE NOT EXISTS (SELECT * FROM dbo.Test_Pivot TP2 WHERE TP2.string = TP1.string AND TP2.id < TP1.id)\n UNION ALL\n SELECT CTEstring, CAST(CTEids + ' ' + CAST(TP.id AS VARCHAR) AS VARCHAR(1000)), TP.id\n FROM dbo.Test_Pivot TP\n INNER JOIN CTE ON\n CTE.CTEstring = TP.string\n WHERE\n TP.id > CTE.CTElast_id AND\n NOT EXISTS (SELECT * FROM dbo.Test_Pivot WHERE string = CTE.CTEstring AND id > CTE.CTElast_id AND id < TP.id)\n)\nSELECT\n t1.CTEstring, t1.CTEids\nFROM CTE t1\nINNER JOIN (SELECT CTEstring, MAX(LEN(CTEids)) AS max_len_ids FROM CTE GROUP BY CTEstring) SQ ON SQ.CTEstring = t1.CTEstring AND SQ.max_len_ids = LEN(t1.CTEids)\nORDER BY CTEstring\nGO\n"
},
{
"answer_id": 199041,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "select distinct Letter from MyTable\n select Number from MyTable where Letter=:letter\n"
},
{
"answer_id": 199763,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 4,
"selected": false,
"text": "ROW_NUMBER() PIVOT CREATE TABLE [dbo].[stackoverflow_198716](\n [code] [varchar](1) NOT NULL,\n [number] [int] NOT NULL\n) ON [PRIMARY]\n\nDECLARE @sql AS varchar(max)\nDECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique\nDECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique\n\nSELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'\n ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']'\nFROM (\n SELECT DISTINCT PIVOT_CODE\n FROM (\n SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE\n FROM stackoverflow_198716\n ) AS rows\n) AS PIVOT_CODES\n\nSET @sql = '\n;WITH p AS (\n SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE\n FROM stackoverflow_198716\n)\nSELECT code, ' + @select_list + '\nFROM p\nPIVOT (\n MIN(number)\n FOR PIVOT_CODE IN (\n ' + @pivot_list + '\n )\n) AS pvt\n'\n\nPRINT @sql\n\nEXEC (@sql)\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27585/"
] |
198,717
|
<p>Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another. </p>
<p>I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate? </p>
<p>Thank you. </p>
|
[
{
"answer_id": 198817,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 2,
"selected": false,
"text": "<asp:Image ... />\n"
},
{
"answer_id": 199212,
"author": "Alfred B. Thordarson",
"author_id": 3379,
"author_profile": "https://Stackoverflow.com/users/3379",
"pm_score": 1,
"selected": true,
"text": " <asp:SiteMapPath ID=\"SiteMapPath1\" Runat=\"server\" OnItemDataBound=\"Item_Bound\">\n <PathSeparatorTemplate>\n <asp:Image ID=\"SepImage\" runat=\"server\" ImageUrl=\"/images\"/>\n </PathSeparatorTemplate>\n </asp:SiteMapPath>\n private string lastItemKey = \"\";\n public void Item_Bound(Object sender, SiteMapNodeItemEventArgs e)\n {\n if (e.Item.ItemType == SiteMapNodeItemType.PathSeparator)\n {\n string imageUrl = ((Image) e.Item.Controls[1]).ImageUrl;\n imageUrl += lastItemKey + \".png\";\n ((Image) e.Item.Controls[1]).ImageUrl = imageUrl;\n }\n else\n {\n lastItemKey = e.Item.SiteMapNode.Key;\n }\n }\n /images Key SiteMapNode"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
198,720
|
<p>Is there a ColdFusion analog for the deployment descriptor/web.xml file found in a J2EE web container? I know CF is running on top of JRun and that I could just tweak the JRun dd, but what about an application-specific configuration file? Is there something like this that I'm not aware of or do you just have to roll your own?</p>
|
[
{
"answer_id": 13518556,
"author": "James A Mohler",
"author_id": 1845869,
"author_profile": "https://Stackoverflow.com/users/1845869",
"pm_score": 2,
"selected": false,
"text": "application.cfc application.cfm fusebox.xml circuit.xml application.cfc"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2376109/"
] |
198,721
|
<p>I have a set of Word documents which I want to publish using a PHP tool I've written. I copy and paste the Word documents into a text box and then save them into MySQL using the PHP program. The problem I Have arises from all the non-standard characters that Word documents have, like curly quotes and ellipses ("..."). What I do at the moment is manually search and replace these kinds of things (and also foreign symbols such as e-acute) with either plain text or HTML entities (&eacute ; etc) Is there a function in PHP I can call that will take the output of a Word document and convert everything that should be entities into entities, and other symbols that don't display properly in Firefox into symbols that do display.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 198757,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "$str = mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8')\n"
},
{
"answer_id": 6561145,
"author": "tylerl",
"author_id": 86060,
"author_profile": "https://Stackoverflow.com/users/86060",
"pm_score": 0,
"selected": false,
"text": "$translation=array(\n // reference from http://www.cs.tut.fi/~jkorpela/www/windows-chars.html\n \"\\x82\" => \"‚\",\n \"\\x83\" => \"ƒ\",\n \"\\x84\" => \"„\",\n \"\\x85\" => \"…\",\n \"\\x86\" => \"†\",\n \"\\x87\" => \"‡\",\n \"\\x88\" => \"ˆ\",\n \"\\x89\" => \"‰\",\n \"\\x8a\" => \"Š\",\n \"\\x8b\" => \"‹\",\n \"\\x8c\" => \"Œ\",\n \"\\x91\" => \"‘\",\n \"\\x92\" => \"’\",\n \"\\x93\" => \"“\",\n \"\\x94\" => \"”\",\n \"\\x95\" => \"•\",\n \"\\x96\" => \"–\",\n \"\\x97\" => \"—\",\n \"\\x98\" => \"˜\",\n \"\\x99\" => \"™\",\n \"\\x9a\" => \"š\",\n \"\\x9b\" => \"›\",\n \"\\x9c\" => \"œ\",\n \"\\x9f\" => \"Ÿ\",\n); \nreturn str_replace(array_keys($translation),array_values($translation),$input);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
198,726
|
<p>I'm responsible for several (rather small) programs, which share a lot of code via different libraries. I'm wondering what the best repository layout is to develop the different prorgrams (and libraries), and keep the libraries in sync across all the programs.</p>
<p>For the sake of argument let's say there are two programs with two libraries:</p>
<ul>
<li>Program1
<ul>
<li>Library1</li>
<li>Library2</li>
</ul></li>
<li>Program2
<ul>
<li>Library1</li>
<li>Library2</li>
</ul></li>
</ul>
<p>Naturally, bug fixes and enhancements for the libraries should (eventually) merge to all programs. Since the libraries are being worked on while working on the different programs, using <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.externals.html" rel="noreferrer">externals definitions</a> seems out of the question.</p>
<p>So I thought to treat my libraries at all but one place as <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.vendorbr.html" rel="noreferrer">vendor branches</a> but I'm not sure what the best layout for this would be.</p>
<p>I was thinking something along the lines of:</p>
<ul>
<li>Libraries
<ul>
<li>Library1 (ancestor)</li>
<li>Library2 (ancestor)</li>
</ul></li>
<li>Program1
<ul>
<li>Program1 code</li>
<li>Library1 (vendor branch)</li>
<li>Library2 (vendor branch)</li>
</ul></li>
<li>...</li>
</ul>
<p>Then say when developing Program1 some changes are made for Library2, I merge them back to the Libraries part of the repository, and merge them from there to all other programs when desired. </p>
<p>Merging to the other programs can't always happen immediately, the people working on Program2 could be close to a release and rather finish that first, create a tag, and only then update all libraries.</p>
<p>I'm a bit concerned this will result in many merges and a bit of a maintenance headache after a while but I don't really see a much better solution.</p>
<p>Then again, this seems a rather common use case to me, so I thought I'd just ask the stackoverflow community, what's the best repository layout to achieve this?</p>
|
[
{
"answer_id": 198800,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 4,
"selected": true,
"text": "svnadmin create /path/library1\nsvnadmin create /path/library2\n...\n svnadmin create /path/program1\nsvnadmin create /path/program2\n...\n cd /path/program1\nsvn propset svn:externals \"library1 svnpath://wherever/library1/trunk/\" .\nsvn propset svn:externals \"library2 svnpath://wherever2/library2/trunk/\" .\n ... make a change in /path/program1/library1 ... \ncd /path/program1\nsvn commit -m \"some change\"\n cd /path/program1/library1\nsvn commit -m \"change to library code\"\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5822/"
] |
198,743
|
<p>After many years of using make, I've just started using jam (actually ftjam) for my projects. </p>
<p>In my project workspaces, I have two directories:</p>
<ul>
<li><code>src</code> where I build executables and libraries</li>
<li><code>test</code> where my test programs are</li>
</ul>
<p>I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to).</p>
<p>Any suggestion on how to do it? </p>
|
[
{
"answer_id": 201788,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 2,
"selected": false,
"text": "jmk jam if [ \"$JMKROOT\" = \"\" ] ; then\n JMKROOT=`pwd`\n export JMKROOT\nfi\ncd $JMKROOT\njam $*\n jmk.bat @echo off\nif \"%JMKROOT%\" EQU \"\" set JMKROOT=%CD%\n\nset OLDCD=%CD%\ncd %JMKROOT%\njam %1 %2 %3 %4 %5 %6 %7 %8 %9\n\ncd %OLDCD%\n"
},
{
"answer_id": 18434928,
"author": "wjk",
"author_id": 2059100,
"author_profile": "https://Stackoverflow.com/users/2059100",
"pm_score": 0,
"selected": false,
"text": "bin lib SubDir TOP ; $(TOP) SubInclude TOP bin llvm-tblgen SubInclude TOP lib Support bin/llvm-tblgen lib/Support bin/llvm-tblgen SubDir TOP bin llvm-tblgen ; lib/Support SubDir TOP lib Support ; SubDir TOP $(TOP)/lib/Support/libLLVMSupport.a libLLVMSupport.a bin/llvm-tblgen"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16827/"
] |
198,744
|
<p>Yeah, its a bit on this side of pointless, but I was wondering... I've got all these codebehind files cluttering my MVC app. The only reason why I need these files, as far as I can tell, is to tell ASP.NET that my page extends from ViewPage rather than Page. </p>
<p>I've tried a couple different Page directives changes, but nothing I've found will allow me to identify the base class for the page AND let me delete the codebehind files.</p>
<p>Is there a way to do it?</p>
<p><strong>UPDATE</strong>: I'm trying to inherit from a strongly-typed ViewPage! Seems like its possible to inherit from a regular ViewPage...</p>
|
[
{
"answer_id": 198797,
"author": "Chris Sutton",
"author_id": 3289,
"author_profile": "https://Stackoverflow.com/users/3289",
"pm_score": 3,
"selected": true,
"text": "<%@ Page Title=\"Title\" Inherits=\"System.Web.Mvc.ViewPage\" Language=\"C#\" MasterPageFile=\"~/Views/Layouts/Site.Master\" %>\n <%@ Page Inherits=\"System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" %>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,754
|
<p>When using the unmanaged API for the .NET framework to profile a .NET process in-process, is it possible to look up the IL instruction pointer that correlates to the native instruction pointer provided to the StackSnapshotCallback function?</p>
<p>As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump. The <em>Managed Stack Explorer</em> does this by querying <code>ISymUnmanagedMethod::GetSequencePoints</code>. This is great, but the sequence points are associated to offsets, and I have so far assumed these are offsets from the beginning of the method ( in intermediate language ).</p>
<p>In a follow-up comment to his blog post <a href="https://web.archive.org/web/20190114032244/https://blogs.msdn.microsoft.com/davbr/2005/10/06/profiler-stack-walking-basics-and-beyond" rel="nofollow noreferrer">Profiler stack walking: Basics and beyond</a>, David Broman indicates that this mapping can be achieved using <code>ICorDebugCode::GetILToNativeMapping</code>. However, this is not ideal as getting this interface requires attaching to my process from another, debugger process.</p>
<p>I would like to avoid that step because I would like to continue to be able to run my application from within the visual studio debugger while I am taking these snapshots. It makes it easier to click on the line number in the output window and go to the code in question.</p>
<p>The functionality is possible.... you can spit out a line-numbered stack trace at will inside of managed code, the only question, is it accessible. Also, I don't want to use the <code>System::Diagnostics::StackTrace</code> or <code>System::Environment::StackTrace</code> functionality because, for performance reasons, I need to delay the actual dump of the stack.... so saving the cost for resolution of method names and code location for later is desirable... along with the ability to intermix native and managed frames.</p>
|
[
{
"answer_id": 214123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Console.WriteLine(\"StackTrace: '{0}'\", Environment.StackTrace);\n"
},
{
"answer_id": 255795,
"author": "Steven",
"author_id": 27577,
"author_profile": "https://Stackoverflow.com/users/27577",
"pm_score": 4,
"selected": true,
"text": "ICorProfilerInfo2::DoStackSnapshot DoStackSnapshot FunctionID ICorProfilerInfo2::GetCodeInfo2 ULONG32 pcIL(0xffffffff);\nHRESULT hr(E_FAIL);\nCOR_PRF_CODE_INFO* codeInfo(NULL);\nCOR_DEBUG_IL_TO_NATIVE_MAP* map(NULL);\nULONG32 cItem(0);\n\nUINT_PTR nativePCOffset(0xffffffff);\nif (SUCCEEDED(hr = pInfo->GetCodeInfo2(functioId, 0, &cItem, NULL)) &&\n (NULL != (codeInfo = new COR_PRF_CODE_INFO[cItem])))\n{\n if (SUCCEEDED(hr = pInfo->GetCodeInfo2(functionId, cItem, &cItem, codeInfo)))\n {\n COR_PRF_CODE_INFO *pCur(codeInfo), *pEnd(codeInfo + cItem);\n nativePCOffset = 0;\n for (; pCur < pEnd; pCur++)\n {\n // 'ip' is the UINT_PTR passed to the StackSnapshotCallback as named in\n // the docs I am looking at \n if ((ip >= pCur->startAddress) && (ip < (pCur->startAddress + pCur->size)))\n {\n nativePCOffset += (instructionPtr - pCur->startAddress);\n break;\n }\n else\n {\n nativePCOffset += pCur->size;\n }\n\n }\n }\n delete[] codeInfo; codeInfo = NULL;\n}\n ICorProfilerInfo2::GetILToNativeMapping if ((nativePCOffset != -1) &&\n SUCCEEDED(hr = pInfo->GetILToNativeMapping(functionId, 0, &cItem, NULL)) &&\n (NULL != (map = new COR_DEBUG_IL_TO_NATIVE_MAP[cItem])))\n{\n if (SUCCEEDED(pInfo->GetILToNativeMapping(functionId, cItem, &cItem, map)))\n {\n COR_DEBUG_IL_TO_NATIVE_MAP* mapCurrent = map + (cItem - 1);\n for (;mapCurrent >= map; mapCurrent--)\n {\n if ((mapCurrent->nativeStartOffset <= nativePCOffset) && \n (mapCurrent->nativeEndOffset > nativePCOffset))\n {\n pcIL = mapCurrent->ilOffset;\n break;\n }\n }\n }\n delete[] map; map = NULL;\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27577/"
] |
198,772
|
<p>I know there are tools to get text files to resource files for Visual Studio. But I want to get the text from my resource files to a text file so they can be translated. Or is there a better way to do this? </p>
|
[
{
"answer_id": 17493871,
"author": "fireydude",
"author_id": 869290,
"author_profile": "https://Stackoverflow.com/users/869290",
"pm_score": 2,
"selected": false,
"text": "public class Export\n{\n public string Run()\n {\n var resources = new StringBuilder();\n\n var assembly = Assembly.GetExecutingAssembly();\n var types = from t in assembly.GetTypes()\n where t != typeof(Export)\n select t;\n foreach (Type t in types)\n {\n resources.AppendLine(t.Name);\n resources.AppendLine(\"Key, Value\");\n var props = from p in t.GetProperties()\n where !p.CanWrite && p.Name != \"ResourceManager\"\n select p;\n foreach (PropertyInfo p in props)\n {\n resources.AppendFormat(\"\\\"{0}\\\",\\\"{1}\\\"\\n\", p.Name, p.GetValue(null));\n }\n\n resources.AppendLine();\n }\n return resources.ToString();\n }\n}\n var hack = new Languages.Export();\nvar resourcesSummary = hack.Run();\nvar cultureName = System.Threading.Thread.CurrentThread.CurrentCulture.Name;\nusing (TextWriter file = File.CreateText(@\"C:\\resources.\" + cultureName + \".csv\"))\n{\n file.Write(resourcesSummary);\n}\n"
},
{
"answer_id": 34124762,
"author": "ajbeaven",
"author_id": 161735,
"author_profile": "https://Stackoverflow.com/users/161735",
"pm_score": 1,
"selected": false,
"text": "<div id=\"content\">\n <h2>[[[Welcome to my web app!]]]</h2>\n <h3><span>[[[Amazing slogan here]]]</span></h3>\n <p>[[[Ad copy that would make Hiten Shah fall off his chair!]]]</p>\n <span class=\"button\" title=\"[[[Click to see plans and pricing]]]\">\n <a href=\"@Url.Action(\"Plans\", \"Home\", new { area = \"\" })\">\n <strong>[[[SEE PLANS & PRICING]]]</strong>\n <span>[[[Free unicorn with all plans!]]]</span>\n </a>\n </span>\n</div>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7024/"
] |
198,777
|
<p>I'm trying to configure Windows Powershell to work with Visual Studio. Nothing fancy, just get things set so I can cl & nmake. I think all I need to do is edit the path setting(but I don't know how to set that in WPSH).</p>
|
[
{
"answer_id": 199529,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 3,
"selected": true,
"text": "function Get-Batchfile($file) \n{\n $theCmd = \"`\"$file`\" & set\" \n cmd /c $theCmd | Foreach-Object {\n $thePath, $theValue = $_.split('=')\n Set-Item -path env:$thePath -value $theValue\n }\n}\n\n\nGet-Batchfile(\"C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\")\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26227/"
] |
198,781
|
<p>Easy question this time.</p>
<p>I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^<em>x</em>]" where <em>x</em> is the character that you don't want to appear, but that doesn't seem to be working.</p>
<p>For example,</p>
<pre><code>Regex.IsMatch("103","[^0]")
</code></pre>
<p>and</p>
<pre><code>Regex.IsMatch("103&","[^&]")
</code></pre>
<p>both return true (I would expect false).</p>
<p>I started using <code>"[^&]"</code> and thought maybe the & needed to be escaped as \&, but it didn't seem to make a difference.</p>
<p>Ideas? I assume it's something small.</p>
<p>Also, I'm using .NET, so keep that in mind.</p>
<p>Edit1:</p>
<p>I found <a href="https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring">this</a>, but it doesn't seem to answer the issue I'm having.</p>
<p>Edit2:</p>
<p>I wanted to respond to <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198793">Kevin</a> and <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198796">Joel</a>'s suggestions. These suggestions would indeed be faster, but they don't accomplish the flexibility I need in this case, so if you found this question through search, definitely look to see if their answers will fit your needs. In my case, the regular expression is getting passed in to a DataTable validation method that loops through each row and verifies that the contents of that row in a specific column matches the RegEx that is getting passed in. Since I'll be reusing this method for several other DataTables that are being validated, I wanted to:</p>
<ol>
<li>Use Regex to enable the widest range of validations, and</li>
<li>Always look for a positive match (i.e. instead of using !Regex.IsMatch(cell, regexvariable), I wanted to rely on always being able to use Regex.IsMatch(cell, regexvariable) since the majority of DataTables invoking this method will be using the positive match instead of the negative.</li>
</ol>
<p>Hopefully that helps.</p>
|
[
{
"answer_id": 198790,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 7,
"selected": true,
"text": "Regex.IsMatch(\"103\",\"^[^0]*$\")\n"
},
{
"answer_id": 198796,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "[^x] Not Regex.IsMatch(\"103\", \"0\")\n\nNot Regex.IsMatch(\"103&\", \"&\")\n"
},
{
"answer_id": 2503334,
"author": "Brett",
"author_id": 300284,
"author_profile": "https://Stackoverflow.com/users/300284",
"pm_score": 2,
"selected": false,
"text": "^((?!0).)*$"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
198,803
|
<p>What is the best practice for storing keys, and or passwords for a website. These keys are for various 3rd party web services. Is it best to have them in the Web.config file, or in the database, or encrypted somehow? </p>
|
[
{
"answer_id": 198816,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 2,
"selected": false,
"text": "<configSections>\n <section \n name=\"sampleSection\" \n type=\"System.Configuration.SingleTagSectionHandler\" \n />\n</configSections>\n\n<MySecrets\n FavoriteMusic=\"Disco\" \n FavoriteLanguage=\"COBOL\" \n DreamJob=\"Dancing in the opening ceremonies of the Olympics\" \n/>\n aspnet_regiis -pef MySecrets .\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13855/"
] |
198,825
|
<p>Let's say you've inherited a C# codebase that uses one class with 200 static methods to provide core functionality (such as database lookups). Of the many nightmares in that class, there's copious use of Hungarian notation (the bad kind).</p>
<p>Would you refactor the variable names to remove the Hungarian notation, or would you leave them alone?</p>
<p>If you chose to change all the variables to remove Hungarian notation, what would be your method?</p>
|
[
{
"answer_id": 1797887,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\"\" Hungarian notation conversion helpers\n\"\" get rid of str prefixes and fix caps e.g. strName -> name\nmap ,bs /\\Wstr[A-Z]^Ml3x~\nmap ,bi /\\Wint[A-Z]^Ml3x~\n\"\" little more complex to clean up m_p type class variables\nmap ,bm /\\Wm_p\\?[A-Z]^M:.s/\\(\\W\\)m_p\\?/\\1_/^M/\\W_[A-Z]^Mll~\nmap ,bp /\\Wp[A-Z]^Mlx~\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
198,831
|
<p>I'm building an app in Ruby on Rails, and I'm including 3 of my models (and their migration scripts) to show what I'm trying to do, and what isn't working. Here's the rundown: I have users in my application that belong to teams, and each team can have multiple coaches. I want to be able to pull a list of the coaches that are applicable to a user. </p>
<p>For instance, User A could belong to teams T1 and T2. Teams T1 and T2 could have four different coaches each, and one coach in common. I'd like to be able to pull the list of coaches by simply saying: </p>
<pre><code>u = User.find(1)
coaches = u.coaches
</code></pre>
<p>Here are my migration scripts, and the associations in my models. Am I doing something incorrectly in my design? Are my associations correct?</p>
<pre><code>class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :login, :string, :default => nil
t.column :firstname, :string, :default => nil
t.column :lastname, :string, :default => nil
t.column :password, :string, :default => nil
t.column :security_token, :string, :default => nil
t.column :token_expires, :datetime, :default => nil
t.column :legacy_password, :string, :default => nil
end
end
def self.down
drop_table :users
end
end
class CreateTeams < ActiveRecord::Migration
def self.up
create_table :teams do |t|
t.column :name, :string
end
end
def self.down
drop_table :teams
end
end
class TeamsUsers < ActiveRecord::Migration
def self.up
create_table :teams_users, :id => false do |t|
t.column :team_id, :integer
t.column :user_id, :integer
t.column :joined_date, :datetime
end
end
def self.down
drop_table :teams_users
end
end
</code></pre>
<p>Here are the models (not the entire file):</p>
<pre><code>class User < ActiveRecord::Base
has_and_belongs_to_many :teams
has_many :coaches, :through => :teams
class Team < ActiveRecord::Base
has_many :coaches
has_and_belongs_to_many :users
class Coach < ActiveRecord::Base
belongs_to :teams
end
</code></pre>
<p>This is what happens when I try to pull the coaches:</p>
<pre><code>u = User.find(1)
=> #<User id: 1, firstname: "Dan", lastname: "Wolchonok">
>> u.coaches
ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT `coaches`.* FROM `coaches` INNER JOIN teams ON coaches.team_id = teams.id WHERE ((`teams`.user_id = 1))
</code></pre>
<p>Here's the error in sql:</p>
<p>Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT <code>coaches</code>.* FROM <code>coaches</code> INNER JOIN teams ON coaches.team_id = teams.id WHERE ((<code>teams</code>.user_id = 1)) </p>
<p>Am I missing something in my :through clause? Is my design totally off? Can someone point me in the right direction?</p>
|
[
{
"answer_id": 198971,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "has_many :coaches, :finder_sql => 'SELECT * from coaches, teams_users WHERE \n coaches.team_id=teams_users.team_id \n AND teams_users.user_id=#{id}'\n"
},
{
"answer_id": 199064,
"author": "Steropes",
"author_id": 21872,
"author_profile": "https://Stackoverflow.com/users/21872",
"pm_score": 3,
"selected": true,
"text": " def coaches\n self.teams.collect do |team|\n team.coaches\n end.flatten.uniq\n end\n"
},
{
"answer_id": 199109,
"author": "Roy Pardee",
"author_id": 64731,
"author_profile": "https://Stackoverflow.com/users/64731",
"pm_score": 1,
"selected": false,
"text": "def coaches\n ret = []\n teams.each do |t|\n t.coaches.each do |c|\n ret << c\n end\n end\n ret.uniq\nend\n"
},
{
"answer_id": 199830,
"author": "Dan Wolchonok",
"author_id": 168,
"author_profile": "https://Stackoverflow.com/users/168",
"pm_score": 0,
"selected": false,
"text": " def coaches\n self.teams.collect do |team|\n team.coaches\n end.flatten.uniq\n end\n\n def canCoach(coachee)\n u = User.find(coachee)\n\n coaches = u.coaches\n c = []\n coaches.collect do |coach|\n c.push(coach.user_id)\n end\n\n return c.include?(self.id)\n end\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168/"
] |
198,849
|
<p>I've just performed a new installation of the very latest (Fall, 2008) version of Fedora 9 Linux and am perplexed that it never set the default route properly and that even traveling the labyrinthine ways of this OS, there's no obvious way.</p>
<p>Of course, it's clear that one can do it on a one-off basis like this:</p>
<pre><code> route add default gw gw1 metric 0 eth0
</code></pre>
<p>or like this:</p>
<pre><code> ip route add to default via 192.168.2.1 protocol static
</code></pre>
<p>However, neither of these survives reboot. In reading through /etc/rc.d/init.d/network, it attempts to find data from a file in /etc/sysconfig/static-routes, but that file never existed. So, I tried to create it and populate it with data. The trouble with that is that the script places a dash (minus sign) in an odd spot that I'm not sure how to deal with.</p>
<p>Of course, one can just edit /etc/rc.d/init.d/network, but that would be non-standard. As it is, my only other recourse seems to be editing rc.local, but that doesn't come early enough in the boot sequence to be there for things like, for example, the network time daemon.</p>
<p>I've done my homework - I've read all the man pages, info entries, tried apropos, and I've even done a fair bit of web searching, all to no avail - my next step, sans answer here, will be to sign up to the Fedora mailing lists and ask there! Or, give up and edit the scripts.</p>
<p>So, how is one supposed to do this?</p>
|
[
{
"answer_id": 198899,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "gnome-network-preferences"
},
{
"answer_id": 198969,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": true,
"text": "NETWORKING=yes\nNETWORKING_IPV6=no\nHOSTNAME=flyboys\nNISDOMAIN=ekcineon\n DEVICE=eth0\nONBOOT=yes\nHWADDR=00:1d:09:31:3a:cc\nNETMASK=255.255.255.0\nIPADDR=150.102.65.30\nGATEWAY=150.102.65.252\nTYPE=Ethernet\n"
},
{
"answer_id": 26589470,
"author": "Dex",
"author_id": 1463474,
"author_profile": "https://Stackoverflow.com/users/1463474",
"pm_score": 0,
"selected": false,
"text": "host: 172.30.xxx.xxx via 172.30.xxx.xxx\nnetwork: 172.30.xxx.xxx/xx via 172.30.xxx.xxx\nDefault gateway: 0.0.0.0 via xxx.xxx.xxx.xxx</li>\n"
},
{
"answer_id": 39559978,
"author": "user6845878",
"author_id": 6845878,
"author_profile": "https://Stackoverflow.com/users/6845878",
"pm_score": 2,
"selected": false,
"text": "/etc/sysconfig/network-scripts/route-ethXX"
},
{
"answer_id": 67841807,
"author": "Luc",
"author_id": 9520099,
"author_profile": "https://Stackoverflow.com/users/9520099",
"pm_score": 1,
"selected": false,
"text": "\n# nmcli con show\nNAME UUID TYPE DEVICE\nSystem eth0 xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ethernet eth0\nens33 xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ethernet --\n\n# nmcli con edit \"System eth0\"\n\nnmcli> goto ipv4\nYou may edit the following properties: method, dns, dns-search, dns-options, dns-priority, addresses, gateway, routes, route-metric, route-table, routing-rules, ignore-auto-routes, ignore-auto-dns, dhcp-client-id, dhcp-timeout, dhcp-send-hostname, dhcp-hostname, dhcp-fqdn, never-default, may-fail, dad-timeout\nnmcli ipv4>\n\nnmcli ipv4> print\n['ipv4' setting values]\nipv4.method: manual\nipv4.dns: --\nipv4.dns-search: --\nipv4.dns-options: --\nipv4.dns-priority: 0\nipv4.addresses: 10.10.10.1/26\nipv4.gateway: 10.10.10.129\nipv4.routes: --\nipv4.route-metric: -1\nipv4.route-table: 0 (unspec)\nipv4.routing-rules: --\nipv4.ignore-auto-routes: no\nipv4.ignore-auto-dns: no\nipv4.dhcp-client-id: --\nipv4.dhcp-timeout: 0 (default)\nipv4.dhcp-send-hostname: yes\nipv4.dhcp-hostname: --\nipv4.dhcp-fqdn: --\nipv4.never-default: no\nipv4.may-fail: yes\nipv4.dad-timeout: -1 (default)\nnmcli ipv4>\n\n\nnmcli ipv4> set routes 192.168.122.0/24 10.10.10.1\n\nnmcli ipv4> verify\nVerify setting 'ipv4': OK\nnmcli ipv4> save\nnmcli ipv4> quit\n\n#nmcli con up \"System eth0\"\n ADDRESS0=192.0.2.0\nNETMASK0=255.255.255.0\nGATEWAY0=198.51.100.1\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26976/"
] |
198,852
|
<p>I am using Visual Studio 2005 to make an install. The application has a dependency on a DLL that was built with MFC 7.1 (from Visual Studio 2003).</p>
<p>Are there merge modules for MFC 7.1 or other redistributables like there are for MFC 8? Where could they be found?</p>
|
[
{
"answer_id": 200047,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 0,
"selected": false,
"text": "%ProgramFiles%\\Microsoft Visual Studio .NET 2003\\redist"
},
{
"answer_id": 209093,
"author": "djeidot",
"author_id": 4880,
"author_profile": "https://Stackoverflow.com/users/4880",
"pm_score": 3,
"selected": true,
"text": "%ProgramFiles%\\Common Files\\Merge Modules. vc_user_crt71_rtl_x86_---.msm vc_user_mfc71_rtl_x86_---.msm vc_user_stl71_rtl_x86_---.msm vc_user_mfc71_loc_rtl_x86_---.msm"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4066/"
] |
198,868
|
<p>a while back I ran across a situation where we needed to display message-boxes to the user for notifications but we could not use MessageBox.Show because it blocks the GUI thread (so nothing on the screen gets updated while the dialog is active). Any suggestions on an alternative?</p>
<p>[I coded an alternative at the time but I don't like it. I'll post it as an answer if nothing better appears though]</p>
<p>EDIT: the dialog must float on top of the main window; i don't care if it appears in the taskbar or not. More than one dialog may be active at once in certain circumstances.</p>
<p>ADDENDUM: my solution was a base form that provided OK and CANCEL buttons to emit Completed and Cancelled events; OK called a virtual ValidateData for subclass override. The calling form used properties to avoid recreating the form each time (the form was just hidden instead of closed) and kept a dictionary of active forms to prevent the same form from being activated more than once. This looks like a modal form, supports multiple pop-up forms at once, but does not tie up the main GUI thread.</p>
|
[
{
"answer_id": 198938,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": -1,
"selected": false,
"text": "ThreadPool.QueueUserWorkItem( (state) =>\n {\n MessageBox.Show(\"Your message\");\n });\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
] |
198,873
|
<p>What are the minimum OS requirements for each of the .Net frameworks? E.g. for which version is it impossible to run each OS on:</p>
<ul>
<li>Windows 95</li>
<li>Windows 98</li>
<li>Windows 98SE</li>
<li>Windows ME</li>
<li>Windows NT 3.x</li>
<li>Windows NT 4</li>
<li>Windows 2000</li>
</ul>
<p>I believe all .Net frameworks are compatible w/ XP, Vista, Windows Server 2003, and Windows Server 2008 (please correct me on that if wrong).</p>
|
[
{
"answer_id": 198886,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 2,
"selected": false,
"text": "Windows NT\nWindows Server 2003 (Itanium-based)\n Microsoft Windows 2003 Server Service Pack 1 (SP1)\nWindows XP SP2\nWindows Vista *\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
198,892
|
<p>I have an img tag in my webapp that uses the onload handler to resize the image:</p>
<pre><code><img onLoad="SizeImage(this);" src="foo" >
</code></pre>
<p>This works fine in Firefox 3, but fails in IE7 because the image object being passed to the <code>SizeImage()</code> function has a width and height of 0 for some reason -- maybe IE calls the function before it finishes loading?. In researching this, I have discovered that other people have had this same problem with IE. I have also discovered that this isn't valid HTML 4. This is our doctype, so I don't know if it's valid or not:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
<p>Is there a reasonable solution for resizing an image as it is loaded, preferably one that is standards-compliant? The image is being used for the user to upload a photo of themselves, which can be nearly any size, and we want to display it at a maximum of 150x150. If your solution is to resize the image server-side on upload, I know that is the correct solution, but I am forbidden from implementing it :( It must be done client side, and it must be done on display.</p>
<p>Thanks.</p>
<p><strong>Edit</strong>: Due to the structure of our app, it is impractical (bordering on impossible) to run this script in the document's onload. I can only reasonably edit the image tag and the code near it (for instance I could add a <code><script></code> right below it). Also, we already have Prototype and EXT JS libraries... management would prefer to not have to add another (some answers have suggested jQuery). If this can be solved using those frameworks, that would be great.</p>
<p><strong>Edit 2</strong>: Unfortunately, we must support Firefox 3, IE 6 and IE 7. It is desirable to support all Webkit-based browsers as well, but as our site doesn't currently support them, we can tolerate solutions that only work in the Big 3.</p>
|
[
{
"answer_id": 198903,
"author": "Steve Paulo",
"author_id": 9414,
"author_profile": "https://Stackoverflow.com/users/9414",
"pm_score": 4,
"selected": true,
"text": "document.onload(runFunction);"
},
{
"answer_id": 198908,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "$(document).load(function(){\n // applies to all images, could be replaced \n //by img.resize to resize all images with class=\"resize\"\n $('img').each(function(){\n // sizing code here\n });\n});\n"
},
{
"answer_id": 198934,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "yourImageSelector {\n max-width: 150px;\n max-height: 150px;\n}\n"
},
{
"answer_id": 360563,
"author": "Jeremy Wadhams",
"author_id": 8995,
"author_profile": "https://Stackoverflow.com/users/8995",
"pm_score": 2,
"selected": false,
"text": "<img src=\"mypicture.jpg?keepfresh=12345\" />\n document.body.appendChild(newPicture);\nif(newPicture.complete){\n doStuff.apply(newPicture);\n}else{\n YAHOO.util.Event.addListener(newPicture, \"load\", doStuff);\n}\n"
},
{
"answer_id": 821729,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": false,
"text": "window.onload <script type=\"text/javascript\">\nfunction addOnloadHandler(func) {\n if (window.onload) {\n var windowOnload = window.onload;\n window.onload = function(evt) {\n windowOnload(evt);\n func(evt);\n }\n } else {\n window.onload = function(evt) {\n func(evt);\n }\n }\n}\n\n// attach a handler to window.onload as you normally might\nwindow.onload = function() { alert('Watch'); };\n\n// demonstrate that you can now attach as many other handlers\n// to the onload event as you want\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('window.onload'); });\naddOnloadHandler(function() { alert('runs'); });\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('many'); });\naddOnloadHandler(function() { alert('handlers'); });\naddOnloadHandler(function() { alert('as'); });\naddOnloadHandler(function() { alert('you'); });\naddOnloadHandler(function() { alert('want.'); });\n</script>\n addOnloadHandler() attachEvent attachEvent evt onload"
},
{
"answer_id": 1580858,
"author": "Maksym Klymyshyn",
"author_id": 186734,
"author_profile": "https://Stackoverflow.com/users/186734",
"pm_score": 2,
"selected": false,
"text": "var onload = function(){ /** your awesome onload method **/ };\nvar img = new Image();\nimg.src = 'test.png';\n\n// IE 7 workarond\nif($.browser.version.substr(0,1) == 7){\n function testImg(){\n if(img.complete != null && img.complete == true){ \n onload();\n return;\n }\n setTimeout(testImg, 1000);\n }\n setTimeout(testImg, 1000);\n}else{\n img.onload = onload\n}\n"
},
{
"answer_id": 11029706,
"author": "Sebastien",
"author_id": 809953,
"author_profile": "https://Stackoverflow.com/users/809953",
"pm_score": 0,
"selected": false,
"text": "var img = new Image();\nimg.src = '/output/preview_image.jpg' + '?' + Math.random();\nimg.onload = function() {\n alert('pass')\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10861/"
] |
198,910
|
<p>I wrote a small WPF app where I like to prepend text into a RichTextBox, so that the newest stuff is on top. I wrote this, and it works: </p>
<pre><code> /// <summary>
/// Prepends the text to the rich textbox
/// </summary>
/// <param name="textoutput">The text representing the character information.</param>
private void PrependSimpleText(string textoutput)
{
Run run = new Run(textoutput);
Paragraph paragraph = new Paragraph(run);
if (this.RichTextBoxOutput.Document.Blocks.Count == 0)
{
this.RichTextBoxOutput.Document.Blocks.Add(paragraph);
}
else
{
this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph);
}
}
</code></pre>
<p>Now I would like to make a new version of that function which can add small images as well. I'm at a loss though - is it possible to add images? </p>
|
[
{
"answer_id": 200185,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 5,
"selected": true,
"text": "BitmapImage bi = new BitmapImage(new Uri(@\"C:\\SimpleImage.jpg\"));\nImage image = new Image();\nimage.Source = bi;\nInlineUIContainer container = new InlineUIContainer(image); \nParagraph paragraph = new Paragraph(container); \nRichTextBoxOutput.Document.Blocks.Add(paragraph);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5948/"
] |
198,928
|
<p>Brief:</p>
<pre><code>convert ( -size 585x128 gradient: ) NewImage.png
</code></pre>
<p>How do I change the above ImageMagick command so it takes the width and height from an existing image? I need it to remain a one line command.</p>
<hr>
<p>Details:</p>
<p>I'm trying to programatically create an image reflection using ImageMagick. The effect I am looking for is similar to what you would see when looking at an object on the edge of a pool of water. There is a pretty good thread on what I am trying to do <a href="http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=11585" rel="nofollow noreferrer">here</a> but the solution isn't exactly what I am looking for. Since I will be calling ImageMagick from a C#.Net application I want to use one call without any temp files and return the image through stdout. So far I have this...</p>
<pre><code>convert OriginalImage.png ( OriginalImage.png -flip -blur 3x5 \
-crop 100%%x30%%+0+0 -negate -evaluate multiply 0.3 \
-negate ( -size 585x128 gradient: ) +matte -compose copy_opacity -composite )
-append NewImage.png
</code></pre>
<p>This works ok but doesn't give me the exact fade I am looking for. Instead of a nice solid fade from top to bottom it is giving me a fade from top left to bottom right. I added the (-negate -evaluate multiply 0.3 -negate) section in to lighten it up a bit more since I wasn't getting the fade I wanted. I also don't want to have to hard code in the size of the image when creating the gradient ( -size 585x128 gradient: ) I'm also going to want to keep the original image's transparency if possible.</p>
<p>To go to stdout I plan on replacing "NewImage.png" with "-"</p>
|
[
{
"answer_id": 205401,
"author": "korro",
"author_id": 22650,
"author_profile": "https://Stackoverflow.com/users/22650",
"pm_score": 1,
"selected": false,
"text": "command = String.Format(\"convert bar %1x%2\",img.Width,img.Height)\n"
},
{
"answer_id": 2701367,
"author": "hacketiwack",
"author_id": 324533,
"author_profile": "https://Stackoverflow.com/users/324533",
"pm_score": -1,
"selected": false,
"text": "#!/bin/sh\n\ngamma=$1\nsource=$2\ndestination=$3\nsize=`identify -format \"%wx%h\" $source`\n\nconvert $source \\\n \\( -size $size xc:none \\\n \\( \\( -flip $source -crop $size+0+0 \\) \\\n -size $size gradient: -gamma $gamma \\\n -compose copy_opacity -composite \\) \\\n -compose blend -composite \\) \\\n -append $destination\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
198,931
|
<p>How can I find out if SP1 has been installed on a server which has .NET 3.5?</p>
|
[
{
"answer_id": 198959,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 7,
"selected": false,
"text": "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v3.5\\ Version SP const string name = @\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v3.5\";\nRegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);\nvar version = subKey.GetValue(\"Version\").ToString();\nvar servicePack = subKey.GetValue(\"SP\").ToString();\n"
},
{
"answer_id": 198998,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "string uninstallKey = @\"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\";\nusing (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey))\n{\n return rk.GetSubKeyNames().Contains(\"Microsoft .NET Framework 3.5 SP1\");\n}\n"
},
{
"answer_id": 2748208,
"author": "Matt",
"author_id": 179310,
"author_profile": "https://Stackoverflow.com/users/179310",
"pm_score": 4,
"selected": false,
"text": "string path = System.Environment.SystemDirectory;\npath = path.Substring( 0, path.LastIndexOf('\\\\') );\npath = Path.Combine( path, \"Microsoft.NET\" );\n// C:\\WINDOWS\\Microsoft.NET\\\n\nstring[] versions = new string[]{\n \"Framework\\\\v1.0.3705\",\n \"Framework64\\\\v1.0.3705\",\n \"Framework\\\\v1.1.4322\",\n \"Framework64\\\\v1.1.4322\",\n \"Framework\\\\v2.0.50727\",\n \"Framework64\\\\v2.0.50727\",\n \"Framework\\\\v3.0\",\n \"Framework64\\\\v3.0\",\n \"Framework\\\\v3.5\",\n \"Framework64\\\\v3.5\",\n \"Framework\\\\v3.5\\\\Microsoft .NET Framework 3.5 SP1\",\n \"Framework64\\\\v3.5\\\\Microsoft .NET Framework 3.5 SP1\",\n \"Framework\\\\v4.0\",\n \"Framework64\\\\v4.0\"\n};\n\nforeach( string version in versions )\n{\n string versionPath = Path.Combine( path, version );\n\n DirectoryInfo dir = new DirectoryInfo( versionPath );\n if( dir.Exists )\n {\n Response.Output.Write( \"{0}<br/>\", version );\n }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
198,936
|
<p>What is the right way to populate the model for the index page in a grails app? There is no IndexController by default, is there some other mechanism for getting lists of this and that into the model?</p>
|
[
{
"answer_id": 204537,
"author": "Ed.T",
"author_id": 3014,
"author_profile": "https://Stackoverflow.com/users/3014",
"pm_score": 6,
"selected": true,
"text": "class UrlMappings {\n static mappings = {\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n \"500\"(view:'/error')\n \"/\"\n {\n controller = \"quote\"\n }\n }\n}\n class QuoteController {\n\n def index = {\n ...\n }\n}\n def index = {\n redirect(action: random)\n}\n class QuoteController {\n\n def quoteService\n\n def index = {\n redirect(action: random)\n }\n\n def random = {\n def randomQuote = quoteService.getRandomQuote()\n [ quote : randomQuote ]\n }\n}\n"
},
{
"answer_id": 1085014,
"author": "William Pietri",
"author_id": 123248,
"author_profile": "https://Stackoverflow.com/users/123248",
"pm_score": 4,
"selected": false,
"text": "UrlMappings.groovy \"/\"(controller: 'home', action: 'index')\n class HomeController {\n\n def index = {\n def quotes = = latest(Quote.list(), 5)\n [\"quotes\": quotes, \"totalQuotes\": Quote.count()]\n }\n\n}\n views/home index.gsp index.gsp"
},
{
"answer_id": 4884485,
"author": "alk",
"author_id": 601267,
"author_profile": "https://Stackoverflow.com/users/601267",
"pm_score": 0,
"selected": false,
"text": "\"/index.gsp\"(uri:\"/\") class UrlMappings {\n\n static mappings = {\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n\n \"/\"(view:\"/index\")\n \"500\"(view:'/error')\n\n \"/index.gsp\"(uri:\"/\")\n }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
198,945
|
<p>How can you get a <strong>raw</strong> socket in Perl, and then what's the best way to built a packet for use with it?</p>
|
[
{
"answer_id": 199031,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 3,
"selected": true,
"text": "use Net::RawIP;\n$a = new Net::RawIP;\n$a->set({ip => {saddr => 'my.target.lan',daddr => 'my.target.lan'},\n tcp => {source => 139,dest => 139,psh => 1, syn => 1}});\n$a->send;\n\n$a->ethnew(\"eth0\");\n$a->ethset(source => 'my.target.lan',dest =>'my.target.lan'); \n$a->ethsend;\n\n$p = $a->pcapinit(\"eth0\",\"dst port 21\",1500,30);\n$f = dump_open($p,\"/my/home/log\");\nloop $p,10,\\&dump,$f;\n"
},
{
"answer_id": 199194,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "use Socket;\n\nsocket my $socket, PF_INET, SOCK_RAW, 0 or die \"Couldn't create raw socket: $!\";\n\nsend $socket, $message, $flags, $to or die \"Couldn't send packet: $!\";\n\nmy $from = recv $socket, $message, $length, $flags or die \"Couldn't receive from socket: $!\";\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
198,952
|
<p>I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus:</p>
<pre>
create user $blah identified by $password;
grant resource, connect, create view to $blah;
</pre>
<p>I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice.</p>
<p>Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.</p>
|
[
{
"answer_id": 198962,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "SELECT 'GRANT ALL ON '||table_name||' TO BOB;'\nFROM ALL_TABLES\nWHERE OWNER = 'ALICE';\n PROCEDURE GRANT_TABLES\n IS\n BEGIN\n\n FOR tab IN (SELECT table_name\n FROM all_tables\n WHERE owner = this_user) LOOP\n EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user';\n END LOOP;\n END;\n"
},
{
"answer_id": 2789143,
"author": "arnep",
"author_id": 217711,
"author_profile": "https://Stackoverflow.com/users/217711",
"pm_score": 3,
"selected": false,
"text": "BEGIN\n\n FOR x IN (SELECT owner||'.'||table_name ownertab\n FROM all_tables\n WHERE owner IN ('A', 'B', 'C', 'D'))\n LOOP\n EXECUTE IMMEDIATE 'GRANT SELECT ON '||x.ownertab||' TO other_user';\n END LOOP;\nEND;\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25915/"
] |
198,970
|
<p>I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?</p>
|
[
{
"answer_id": 198980,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 5,
"selected": true,
"text": "// In global scope\nint x, y;\nconst struct {int *px, *py; } s = {&x, &y};\n"
},
{
"answer_id": 198983,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 3,
"selected": false,
"text": "const struct mytype foo = {&var1, &var2};\n"
},
{
"answer_id": 3684193,
"author": "ylzhang",
"author_id": 416860,
"author_profile": "https://Stackoverflow.com/users/416860",
"pm_score": 0,
"selected": false,
"text": "struct struct Foo\n{\n const int a;\n int b;\n};\n struct malloc struct Foo foo = { 10, 20 };\nchar *ptr = (char*)malloc(sizeof(struct Foo));\nmemcpy(ptr, &foo, sizeof(foo));\nstruct Foo *pfoo = (struct Foo*)ptr;\n struct Foo"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26551/"
] |
198,974
|
<p>I have a validation control that has the following expression:</p>
<pre><code>(?=(.*\\d.*){2,})(?=(.*\\w.*){2,})(?=(.*\\W.*){1,}).{8,}
</code></pre>
<p>That's a password with at least <strong>2 digits</strong>, <strong>2 alpha characters</strong>, <strong>1 non-alphanumeric</strong> and <strong>8 character minimum</strong>. Unfortunately this doesn't seem to be cross-browser compliant.</p>
<p>This validation works perfectly in Firefox, but it does not in Internet Explorer.</p>
<p><strong><em>A combination of each of your answers results in:</em></strong></p>
<pre><code>var format = "^(?=.{" + minLength + ",})" +
(minAlpha > 0 ? "(?=(.*[A-Za-z].*){" + minAlpha + ",})" : "") +
(minNum > 0 ? "(?=(.*[0-9].*){" + minNum + ",})" : "") +
(minNonAlpha > 0 ? "(?=(.*\\W.*){" + minNonAlpha + ",})" : "") + ".*$";
EX: "^(?=.{x,})(?=(.*[A-Za-z].*){y,})(?=(.*[0-9].*){z,})(?=(.*\W.*){a,}).*$"
</code></pre>
<p>The important piece is having the (?.{x,}) for the length <strong>first</strong>.</p>
|
[
{
"answer_id": 199085,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 5,
"selected": true,
"text": "(?=(.*\\W.*){0,}) (?!.*\\W) (?=\\w*$) \\W \\w{8,} .{8,} \\w \\d [^\\W\\d] [A-Za-z] /^(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})\\w{8,}$/\n \\w [A-Za-z0-9_] \\d [0-9] \\s [ \\t\\n\\r\\f\\v] var re = new RegExp(\"^(?=(?:.*?\\\\d){2})(?=(?:.*?[A-Za-z]){2})\\\\w{8,}$\");\nif (re.test(password)) { /* ok */ }\n ^^;; /^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{3,}/.test(\"password123\") // matches\n/^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{4,}/.test(\"password123\") // does not match\n/^(?=.*[a-z].*[a-z]).{4,}/.test(\"password123\") // matches\n (?= ) /^(?=.{8,}$)(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\W){1})/\nnew RegExp(\"^(?=.{8,}$)(?=(?:.*?\\\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\\\W){1})\")\n (?=.{8,}$)"
},
{
"answer_id": 199090,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": 1,
"selected": false,
"text": "^(?=.*\\d{2})(?=.*[a-zA-Z]{2}).{8,}$\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19753/"
] |
198,975
|
<p>I am tring to get the <a href="http://www.herrodius.com/blog/85" rel="nofollow noreferrer">ASDoc Ant task</a> to work:</p>
<pre><code><target name="asdoc" depends="compile">
<mkdir dir="${dist_asdocs}"/>
<asdoc
docSources="${srcdir}"
output="${dist_asdocs}"
executable="${FLEX_HOME}/bin/asdoc.exe" />
</target>
</code></pre>
<p>When I run it I get errors from ASDoc like "Error: Type was not found or was not a compile-time constant: XXX". When I run ASDoc manually I do: "asdoc -source-path src -doc-sources src". If I omit the -source-path value I get the same errors... so how am I supposed to get the Ant task to work?</p>
|
[
{
"answer_id": 199586,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 2,
"selected": false,
"text": "<exec executable=\"${FLEX_HOME}/bin/asdoc\" dir=\"${basedir}\">\n <arg value=\"-source-path\"/>\n <arg path=\"${basedir}/src\"/>\n\n <arg value=\"-doc-sources\"/>\n <arg path=\"${basedir}/src\"/>\n\n <arg value=\"-output\"/>\n <arg path=\"${DOC_DIR}\"/>\n\n <arg value=\"-main-title\"/>\n <arg path=\"${ant.project.name} Documentation\"/>\n\n <arg line=\"-library-path+=${basedir}/libs\"/>\n</exec>\n src src"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
198,979
|
<p>I'm using Visual Studio 2008 Team System with SP1, and I've noticed an annoying tendency for the IDE to hang for several (10-15) seconds whenever I stop debugging an application. At first I thought this only happened with WPF apps, but I've observed the behavior in Windows Forms apps and ASP.NET sites as well. I've made a series of changes to the Options based on <a href="https://stackoverflow.com/questions/8440/visual-studio-optimizations">this previous post</a> and done exhaustive Google/MSDN searches, but still haven't found a way to stop this. </p>
<p>Anyone have any ideas?</p>
<hr>
<p>@<a href="https://stackoverflow.com/users/25731/korona">korona</a> - Nope, that didn't fix it. Thanks for your suggestion, though.</p>
<p>More research in ProcMon shows this interesting tidbit, not sure if it is related:</p>
<pre><code>8:45:46.6790857 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12
8:45:46.6793569 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile C:\WINXP\Microsoft.NET\Framework\v2.0.50727\CONFIG\enterprisesec.config.cch FAST IO DISALLOWED Offset: 508, Length: 12
</code></pre>
<p>This repeats several times, like hundreds of times, then it switches to a different path:</p>
<pre><code>8:45:46.7470314 AM WindowsFormsApplication1.vshost.exe 7684 FASTIO_CHECK_IF_POSSIBLE D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Operation: Read, Offset: 48, Length: 12
8:45:46.7472187 AM WindowsFormsApplication1.vshost.exe 7684 ReadFile D:\documents and settings\myusername\Application Data\Microsoft\CLR Security Config\v2.0.50727.42\security.config.cch FAST IO DISALLOWED Offset: 508, Length: 12
</code></pre>
<p>And repeats again many more times, with slight changes in the offset each iteration. Maybe unrelated, but....</p>
|
[
{
"answer_id": 199062,
"author": "AJ.",
"author_id": 27457,
"author_profile": "https://Stackoverflow.com/users/27457",
"pm_score": 0,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n MessageBox.Show(\"I am saying hello.\");\n}\n"
},
{
"answer_id": 201259,
"author": "AJ.",
"author_id": 27457,
"author_profile": "https://Stackoverflow.com/users/27457",
"pm_score": 0,
"selected": false,
"text": "8:45:31.0221244 AM devenv.exe 7096 QueryNameInformationFile D:\\Working\\WindowsFormsApplication1\\WindowsFormsApplication1\\bin\\Debug\\WindowsFormsApplication1.vshost.exe BUFFER OVERFLOW Name: \\W\n8:45:31.0227991 AM devenv.exe 7096 CreateFile D:\\Working\\WindowsFormsApplication1\\WindowsFormsApplication1\\bin\\Debug\\WindowsFormsApplication1.vshost.exe.Manifest NAME NOT FOUND Desired Access: Generic Read/Execute, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Attributes: n/a, ShareMode: Read, AllocationSize: n/a\n8:45:46.7647624 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7647792 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7649139 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.7649264 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{141243A4-76E6-4FC3-A114-EAE02389304E} NAME NOT FOUND Desired Access: Read\n8:45:46.9834610 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Microsoft\\VisualStudio\\9.0\\UseMRUDocOrdering NAME NOT FOUND Length: 144\n8:45:46.9835087 AM devenv.exe 7096 RegQueryValue HKLM\\SOFTWARE\\Microsoft\\VisualStudio\\9.0\\UseMRUDocOrdering NAME NOT FOUND Length: 144\n8:45:46.9865681 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Read\n8:45:46.9865881 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Read\n8:45:46.9866155 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9866285 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveLeft NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9869661 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Read\n8:45:46.9869813 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Read\n8:45:46.9870055 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9870177 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveRight NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9872667 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Read\n8:45:46.9872818 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Read\n8:45:46.9873078 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9873207 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveUp NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9875683 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Read\n8:45:46.9875873 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Read\n8:45:46.9876141 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9876276 AM devenv.exe 7096 RegOpenKey HKCR\\ReSharper.ReSharper_MoveDown NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9912375 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n8:45:46.9912529 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n8:45:46.9914799 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9915751 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9916485 AM devenv.exe 7096 RegEnumValue HKCU\\Software\\Microsoft\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NO MORE ENTRIES Index: 1, Length: 220\n8:45:46.9916921 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\AppMgmt\\{B72DC9F7-717F-48A3-A281-F5187E018006} NAME NOT FOUND Length: 144\n8:45:46.9917220 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9918086 AM devenv.exe 7096 RegOpenKey HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\Managed\\S-1-5-21-2966119792-2635991036-4117835597-414090\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NAME NOT FOUND Desired Access: Read\n8:45:46.9918661 AM devenv.exe 7096 RegEnumValue HKCU\\Software\\Microsoft\\Installer\\Features\\7F9CD27BF7173A842A185F81E7100860 NO MORE ENTRIES Index: 1, Length: 220\n8:45:46.9919019 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919204 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919447 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandler32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919595 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandler32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919825 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandlerX86 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9919969 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\InprocHandlerX86 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920191 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920322 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920543 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9920677 AM devenv.exe 7096 RegOpenKey HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\LocalServer NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9921310 AM devenv.exe 7096 RegQueryValue HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\AppID NAME NOT FOUND Length: 144\n8:45:46.9921387 AM devenv.exe 7096 RegQueryValue HKCR\\CLSID\\{00020424-0000-0000-C000-000000000046}\\AppID NAME NOT FOUND Length: 144\n8:45:46.9921910 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Query Value\n8:45:46.9922398 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9922774 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\ProxyStubClsid32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9923306 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\Forward NAME NOT FOUND Desired Access: Query Value\n8:45:46.9923447 AM devenv.exe 7096 RegOpenKey HKCR\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\Forward NAME NOT FOUND Desired Access: Query Value\n8:45:46.9923676 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924159 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924549 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9924925 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9925301 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\Interface\\{A6FAF38C-284B-48B3-B871-84B9A66010E9}\\TypeLib NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9925761 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9926243 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9926490 AM devenv.exe 7096 RegEnumKey HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A} NO MORE ENTRIES Index: 1, Length: 288\n8:45:46.9926676 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9927153 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9927525 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928018 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928530 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9928710 AM devenv.exe 7096 RegQueryValue HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32\\(Default) BUFFER OVERFLOW Length: 144\n8:45:46.9928986 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32 NAME NOT FOUND Desired Access: Maximum Allowed\n8:45:46.9929159 AM devenv.exe 7096 RegQueryValue HKCR\\TypeLib\\{95FF4B0C-E6EC-470C-82AC-EB0471714C5A}\\1.0\\0\\win32\\(Default) BUFFER OVERFLOW Length: 144\n8:45:46.9936201 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 224, Length: 4\n8:45:46.9936267 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 224, Length: 4\n8:45:46.9938304 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 228, Length: 20\n8:45:46.9938360 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 228, Length: 20\n8:45:46.9939826 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 472, Length: 40\n8:45:46.9939877 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 472, Length: 40\n8:45:46.9941335 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 512, Length: 40\n8:45:46.9941384 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 512, Length: 40\n8:45:46.9943155 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 552, Length: 40\n8:45:46.9943207 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 552, Length: 40\n8:45:46.9944710 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,072, Length: 16\n8:45:46.9944762 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,072, Length: 16\n8:45:46.9947328 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,088, Length: 8\n8:45:46.9947380 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,088, Length: 8\n8:45:46.9948846 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,232, Length: 2\n8:45:46.9948895 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,232, Length: 2\n8:45:46.9954480 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,234, Length: 14\n8:45:46.9954536 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,234, Length: 14\n8:45:46.9956052 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,104, Length: 16\n8:45:46.9956103 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,104, Length: 16\n8:45:46.9957616 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,120, Length: 8\n8:45:46.9957666 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,120, Length: 8\n8:45:46.9959108 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,152, Length: 16\n8:45:46.9959158 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,152, Length: 16\n8:45:46.9961043 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,168, Length: 8\n8:45:46.9961095 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,168, Length: 8\n8:45:46.9962559 AM devenv.exe 7096 ReadFile C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Offset: 3,200, Length: 16\n8:45:46.9962612 AM devenv.exe 7096 FASTIO_CHECK_IF_POSSIBLE C:\\Program Files\\Common Files\\Microsoft Shared\\MSENV\\vsprojhostproc.olb FAST IO DISALLOWED Operation: Read, Offset: 3,200, Length: 16\n8:45:47.0162060 AM devenv.exe 7096 RegOpenKey HKCU\\Software\\Classes\\CLSID\\{00020424-0000-0000-C000-000000000046}\\TreatAs NAME NOT FOUND Desired Access: Query Value\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27457/"
] |
198,984
|
<p>I have a solution with multiple projects and we need to do some serious global replacements.</p>
<p>Is there a way to do a wildcard replacement where some values remain in after the replace?</p>
<p>So, for instance if I want every <strong>HttpContext.Current.Session[“whatevervalue”]</strong> to become <strong>HttpContext.Current.Session[“whatevervalue”].ToString()</strong> the string value being passed in will be respected? I don’t want to replace “whatevervalue” I just want to append a .ToString() where the pattern matches. </p>
<p>Is this possible in Visual Studio?</p>
|
[
{
"answer_id": 199002,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 5,
"selected": true,
"text": "HttpContext\\.Current\\.Session\\[\"{.@}\"\\]\n HttpContext.Current.Session[\"\\1\"].ToString()\n"
},
{
"answer_id": 199010,
"author": "Amanda Mitchell",
"author_id": 26628,
"author_profile": "https://Stackoverflow.com/users/26628",
"pm_score": 2,
"selected": false,
"text": "HttpContext\\.Current\\.Session\\[{(\"([^\"]|\\\")*\")}\\]\n HttpContext.Current.Session[\\1].ToString()\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2213/"
] |
198,991
|
<p>I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C.
Just so I don't reinvent the wheel suboptimally.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 228970,
"author": "Nazgob",
"author_id": 3579,
"author_profile": "https://Stackoverflow.com/users/3579",
"pm_score": 1,
"selected": false,
"text": "#include <D3DX9Math.h>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/198991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8683/"
] |
199,014
|
<p>I have a proxy object generated by Visual Studio (client side) named ServerClient. I am attempting to set ClientCredentials.UserName.UserName/Password before opening up a new connection using this code:</p>
<pre><code>InstanceContext context = new InstanceContext(this);
m_client = new ServerClient(context);
m_client.ClientCredentials.UserName.UserName = "Sample";
</code></pre>
<p>As soon as the code hits the UserName line it fails with an "Object is read-only" error. I know this can happen if the connection is already open or faulted, but at this point I haven't called context.Open() yet. </p>
<p>I have configured the Bindings (which uses netTcpBinding) to use Message as it's security mode, and MessageClientCredentialType is set to UserName.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 201190,
"author": "Paul Mrozowski",
"author_id": 3656,
"author_profile": "https://Stackoverflow.com/users/3656",
"pm_score": 4,
"selected": true,
"text": "base.ClientCredentials.UserName.UserName = \"Sample\";\n"
},
{
"answer_id": 800233,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "UserName FooServiceClient client = new FooServiceClient(\"BasicHttpBinding_IFooService\");\n client.ClientCredentials.UserName.UserName = \"user\";\n client.ClientCredentials.UserName.Password = \"password\";\n"
},
{
"answer_id": 1058577,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "using SysSvcmod = System.ServiceModel.Description;\n\nSysSvcmod.ClientCredentials clientCredentials = new SysSvcmod.ClientCredentials();\nclientCredentials.UserName.UserName = \"user_name\";\nclientCredentials.UserName.Password = \"pass_word\";\n\nm_client.ChannelFactory.Endpoint.Behaviors.RemoveAt(1);\nm_client.ChannelFactory.Endpoint.Behaviors.Add(clientCredentials);\n"
},
{
"answer_id": 19564548,
"author": "Fabienne Bonzon",
"author_id": 2915490,
"author_profile": "https://Stackoverflow.com/users/2915490",
"pm_score": 2,
"selected": false,
"text": "// Remove the ClientCredentials behavior.\nclient.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();\n\n// Add a custom client credentials instance to the behaviors collection.\nclient.ChannelFactory.Endpoint.Behaviors.Add(new MyClientCredentials());\n"
},
{
"answer_id": 28292014,
"author": "savitha",
"author_id": 4522761,
"author_profile": "https://Stackoverflow.com/users/4522761",
"pm_score": 2,
"selected": false,
"text": "ProductClient Manager = new ProductClient(); \nManager.ClientCredentials.UserName.UserName = txtUserName.Text;\nManager.ClientCredentials.UserName.Password = txtPassword.Text;\n"
},
{
"answer_id": 52768005,
"author": "Atul",
"author_id": 8449956,
"author_profile": "https://Stackoverflow.com/users/8449956",
"pm_score": 2,
"selected": false,
"text": " public static T CreateClient<T>(string url) where T : class\n {\n EndpointAddress endPoint = new EndpointAddress(url);\n CustomBinding binding = CreateCustomBinding();\n\n T client = (T)Activator.CreateInstance(typeof(T), new object[] { binding, endPoint });\n SetClientCredentials(client);\n\n return client;\n }\n\n public static void SetClientCredentials(dynamic obj)\n {\n obj.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();\n obj.ChannelFactory.Endpoint.Behaviors.Add(new CustomCredentials());\n\n obj.ClientCredentials.UserName.UserName = \"UserId\";\n obj.ClientCredentials.UserName.Password = \"Password\";\n }\n"
},
{
"answer_id": 58555093,
"author": "Davit Mikuchadze",
"author_id": 7611527,
"author_profile": "https://Stackoverflow.com/users/7611527",
"pm_score": 0,
"selected": false,
"text": " if (client.ClientCredentials.ClientCertificate.Certificate == null || string.IsNullOrEmpty(client.ClientCredentials.ClientCertificate.Certificate.Thumbprint))\n {\n client.ClientCredentials.ClientCertificate.SetCertificate(\n StoreLocation.LocalMachine,\n StoreName.My,\n X509FindType.FindByThumbprint, ConfigurationManager.AppSettings.Get(\"CertificateThumbprint\"));\n }\n"
},
{
"answer_id": 71669519,
"author": "jcs",
"author_id": 2526059,
"author_profile": "https://Stackoverflow.com/users/2526059",
"pm_score": 0,
"selected": false,
"text": "Type endpointBehaviorType = serviceClient.ClientCredentials.GetType();\nserviceClient.Endpoint.EndpointBehaviors.Remove(endpointBehaviorType);\n\nClientCredentials clientCredentials = new ClientCredentials();\nclientCredentials.UserName.UserName = userName;\nclientCredentials.UserName.Password = password;\n\nserviceClient.Endpoint.EndpointBehaviors.Add(clientCredentials);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3656/"
] |
199,016
|
<p>I'm trying to use opengl in C#. I have following code which fails with error 2000 ERROR_INVALID_PIXEL_FORMAT<br>
First definitions:</p>
<pre><code>[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[StructLayout(LayoutKind.Sequential)]
public struct PIXELFORMATDESCRIPTOR
{
public void Init()
{
nSize = (ushort) Marshal.SizeOf(typeof (PIXELFORMATDESCRIPTOR));
nVersion = 1;
dwFlags = PFD_FLAGS.PFD_DRAW_TO_WINDOW | PFD_FLAGS.PFD_SUPPORT_OPENGL | PFD_FLAGS.PFD_DOUBLEBUFFER | PFD_FLAGS.PFD_SUPPORT_COMPOSITION;
iPixelType = PFD_PIXEL_TYPE.PFD_TYPE_RGBA;
cColorBits = 24;
cRedBits = cRedShift = cGreenBits = cGreenShift = cBlueBits = cBlueShift = 0;
cAlphaBits = cAlphaShift = 0;
cAccumBits = cAccumRedBits = cAccumGreenBits = cAccumBlueBits = cAccumAlphaBits = 0;
cDepthBits = 32;
cStencilBits = cAuxBuffers = 0;
iLayerType = PFD_LAYER_TYPES.PFD_MAIN_PLANE;
bReserved = 0;
dwLayerMask = dwVisibleMask = dwDamageMask = 0;
}
ushort nSize;
ushort nVersion;
PFD_FLAGS dwFlags;
PFD_PIXEL_TYPE iPixelType;
byte cColorBits;
byte cRedBits;
byte cRedShift;
byte cGreenBits;
byte cGreenShift;
byte cBlueBits;
byte cBlueShift;
byte cAlphaBits;
byte cAlphaShift;
byte cAccumBits;
byte cAccumRedBits;
byte cAccumGreenBits;
byte cAccumBlueBits;
byte cAccumAlphaBits;
byte cDepthBits;
byte cStencilBits;
byte cAuxBuffers;
PFD_LAYER_TYPES iLayerType;
byte bReserved;
uint dwLayerMask;
uint dwVisibleMask;
uint dwDamageMask;
}
[Flags]
public enum PFD_FLAGS : uint
{
PFD_DOUBLEBUFFER = 0x00000001,
PFD_STEREO = 0x00000002,
PFD_DRAW_TO_WINDOW = 0x00000004,
PFD_DRAW_TO_BITMAP = 0x00000008,
PFD_SUPPORT_GDI = 0x00000010,
PFD_SUPPORT_OPENGL = 0x00000020,
PFD_GENERIC_FORMAT = 0x00000040,
PFD_NEED_PALETTE = 0x00000080,
PFD_NEED_SYSTEM_PALETTE = 0x00000100,
PFD_SWAP_EXCHANGE = 0x00000200,
PFD_SWAP_COPY = 0x00000400,
PFD_SWAP_LAYER_BUFFERS = 0x00000800,
PFD_GENERIC_ACCELERATED = 0x00001000,
PFD_SUPPORT_DIRECTDRAW = 0x00002000,
PFD_DIRECT3D_ACCELERATED = 0x00004000,
PFD_SUPPORT_COMPOSITION = 0x00008000,
PFD_DEPTH_DONTCARE = 0x20000000,
PFD_DOUBLEBUFFER_DONTCARE = 0x40000000,
PFD_STEREO_DONTCARE = 0x80000000
}
public enum PFD_LAYER_TYPES : byte
{
PFD_MAIN_PLANE = 0,
PFD_OVERLAY_PLANE = 1,
PFD_UNDERLAY_PLANE = 255
}
public enum PFD_PIXEL_TYPE : byte
{
PFD_TYPE_RGBA = 0,
PFD_TYPE_COLORINDEX = 1
}
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int ChoosePixelFormat(IntPtr hdc, [In] ref PIXELFORMATDESCRIPTOR ppfd);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern bool SetPixelFormat(IntPtr hdc, int iPixelFormat, ref PIXELFORMATDESCRIPTOR ppfd);
[DllImport("opengl32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr wglCreateContext(IntPtr hDC);
</code></pre>
<p>And now the code that fails:</p>
<pre><code>IntPtr dc = Win.GetDC(hwnd);
var pixelformatdescriptor = new GL.PIXELFORMATDESCRIPTOR();
pixelformatdescriptor.Init();
var pixelFormat = GL.ChoosePixelFormat(dc, ref pixelformatdescriptor);
if(!GL.SetPixelFormat(dc, pixelFormat, ref pixelformatdescriptor))
throw new Win32Exception(Marshal.GetLastWin32Error());
IntPtr hglrc;
if((hglrc = GL.wglCreateContext(dc)) == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error()); //<----- here I have exception
</code></pre>
<p>the same code in managed C++ is working</p>
<pre><code>HDC dc = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pf;
pf.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pf.nVersion = 1;
pf.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER | PFD_SUPPORT_COMPOSITION;
pf.cColorBits = 24;
pf.cRedBits = pf.cRedShift = pf.cGreenBits = pf.cGreenShift = pf.cBlueBits = pf.cBlueShift = 0;
pf.cAlphaBits = pf.cAlphaShift = 0;
pf.cAccumBits = pf.cAccumRedBits = pf.cAccumGreenBits = pf.cAccumBlueBits = pf.cAccumAlphaBits = 0;
pf.cDepthBits = 32;
pf.cStencilBits = pf.cAuxBuffers = 0;
pf.iLayerType = PFD_MAIN_PLANE;
pf.bReserved = 0;
pf.dwLayerMask = pf.dwVisibleMask = pf.dwDamageMask = 0;
int ipf = ChoosePixelFormat(dc, &pf);
SetPixelFormat(dc, ipf, &pf);
HGLRC hglrc = wglCreateContext(dc);
</code></pre>
<p>I've tried it on VIsta 64-bit with ATI graphic card and on Windows XP 32-bit with Nvidia with the same result in both cases.<br>
Also I want to mention that I don't want to use any already written framework for it.<br>
<br>
Can anyone show me where is the bug in C# code that is causing the exception?<br>
<br></p>
|
[
{
"answer_id": 205675,
"author": "Brian",
"author_id": 17356,
"author_profile": "https://Stackoverflow.com/users/17356",
"pm_score": 0,
"selected": false,
"text": "[StructLayout(LayoutKind.Sequential, Pack=1)]\n"
},
{
"answer_id": 206933,
"author": "SeeR",
"author_id": 22569,
"author_profile": "https://Stackoverflow.com/users/22569",
"pm_score": 5,
"selected": true,
"text": "public static bool SetPixelFormat(IntPtr deviceContext, int pixelFormat, ref PIXELFORMATDESCRIPTOR pixelFormatDescriptor) {\n Kernel.LoadLibrary(\"opengl32.dll\");\n return _SetPixelFormat(deviceContext, pixelFormat, ref pixelFormatDescriptor);\n }\n [DllImport(\"opengl32.dll\", EntryPoint = \"glGetString\", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]\nstatic extern IntPtr _glGetString(StringName name);\npublic static string glGetString(StringName name)\n{\n return Marshal.PtrToStringAnsi(_glGetString(name));\n}\npublic enum StringName : uint\n{\n GL_VENDOR = 0x1F00,\n GL_RENDERER = 0x1F01,\n GL_VERSION = 0x1F02,\n GL_EXTENSIONS = 0x1F03\n}\n GL.glGetString(0);\n"
},
{
"answer_id": 11994774,
"author": "Yuriy",
"author_id": 878178,
"author_profile": "https://Stackoverflow.com/users/878178",
"pm_score": 0,
"selected": false,
"text": "if (SetPixelFormat(DC, iPixelformat, ref pfd) == false)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\nRC = wglCreateContext(DC);\nif (RC == HGLRC.Zero)\n{ \n if (SetPixelFormat(DC, iPixelformat, ref pfd) == false)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n RC = wglCreateContext(DC);\n if (RC == HGLRC.Zero)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22569/"
] |
199,017
|
<p>I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.</p>
<p>Main purpose is to filter out XSS and similar nasties that may be entered via web forms. Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has an HTML view.</p>
<p>I'm considering using <a href="http://htmlpurifier.org" rel="noreferrer">HTML Purifier</a>, or rolling my own by using an HTML DOM parser to go through a process like HTML(dirty)->DOM(dirty)->filter->DOM(clean)->HTML(clean).</p>
<p>Can you describe successes with these or any easier strategies that are also effective? Any pitfalls to watch out for?</p>
|
[
{
"answer_id": 199072,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<img src=\"http://www.mysite.com/logout\" />\n <a href=\"javascript:alert('xss hole');\">click</a>\n"
},
{
"answer_id": 199123,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": true,
"text": "javascript: java	script: http://spoof.com:xxx@evil.com //evil.com"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27304/"
] |
199,035
|
<p>Has anyone used <a href="http://pear.php.net/package/Spreadsheet_Excel_Writer/" rel="nofollow noreferrer">Pear: Spreadsheet_Excel_Writer</a>?</p>
<p>The <a href="http://pear.php.net/manual/en/package.fileformats.spreadsheet-excel-writer.intro-format.php" rel="nofollow noreferrer">Formatting Tutorial</a> lists a script similar to what I'm working with: (trimmed down)</p>
<pre><code><?php
require_once 'Spreadsheet/Excel/Writer.php';
$workbook = new Spreadsheet_Excel_Writer();
$worksheet =& $workbook->addWorksheet();
$worksheet->write(0, 0, "Quarterly Profits for Dotcom.Com");
$workbook->send('test.xls');
$workbook->close();
?>
</code></pre>
<p>What I think I understand so far about it...<br>
<code>$workbook->send('test.xls');</code> sets the headers up for Excel file transfer. Now, no errors seem to come up, but the file downloaded is entirely empty (even in a hex editor).</p>
<p>So...<br>
Where (in what class/method) is the <code>$workbook</code> binary supposed to be written? Or, am I misunderstanding it all?</p>
<p><strong>Note</strong>: I honestly don't know what version of Spreadsheet_Excel_Writer is being used; the sources don't include such useful information.<br>
I can tell you the copyright is <strong><em>2002-2003</em></strong>; so, anywhere from version 0.1 to 0.6.</p>
<p>[<strong>Edit</strong>] Sorry, thought I'd mentioned this somewhere.. This is someone else's script that I've been assigned to fix.</p>
|
[
{
"answer_id": 199166,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 3,
"selected": true,
"text": "<?php\nrequire_once 'Spreadsheet/Excel/Writer.php';\n$workbook = new Spreadsheet_Excel_Writer('test.xls');\n$worksheet =& $workbook->addWorksheet('My first worksheet');\nif (PEAR::isError($worksheet)) {\n die($worksheet->getMessage());\n}\n$workbook->close();\n?>\n send() PEAR::isError()"
},
{
"answer_id": 1323890,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$workbook = new Spreadsheet_Excel_Writer(); // <-- leave parantheses empty\n$workbook->send($DownloadFileName);\n// Your fancy spreadsheet generating code\n$workbook->close();\n $workbook = new Spreadsheet_Excel_Writer($SaveFileName);\n// Your fancy spreadsheet generating code\n$workbook->close();\n"
},
{
"answer_id": 1574633,
"author": "Mávil",
"author_id": 190844,
"author_profile": "https://Stackoverflow.com/users/190844",
"pm_score": 0,
"selected": false,
"text": "$worksheet =& $workbook->addWorksheet(); require_once 'Spreadsheet/Excel/Writer.php';\n\n//Create a workbook\n$workbook = new Spreadsheet_Excel_Writer(); //() must be empty or your downloaded file will be corrupt.\n\n// Create a worksheet \n$worksheet =& $workbook->addWorksheet('test'); <-- You forgot to name your worksheet in your code, yours is \"addWorksheet()\"\n\n// The actual data \n$worksheet->write(0, 0, 'Name'); \n$worksheet->write(0, 1, 'Age'); \n$worksheet->write(1, 0, 'John Smith'); \n$worksheet->write(1, 1, 30);\n$worksheet->write(2, 0, 'Johann Schmidt');\n$worksheet->write(2, 1, 31); $worksheet->write(3, 0, 'Juan Herrera');\n$worksheet->write(3, 1, 32);\n\n// send HTTP headers \n$workbook->send('prueba.xls');\n\n// Let's send the file\n$workbook->close();\n"
},
{
"answer_id": 4743114,
"author": "John R. Tipton",
"author_id": 582396,
"author_profile": "https://Stackoverflow.com/users/582396",
"pm_score": 1,
"selected": false,
"text": "$tmpDocument = '/path/to/tmp/file.xls';\n$workbook = new Spreadsheet_Excel_Writer($tmpDocument); \n $workbook->close();\n$workbook->send('Report.xls');\nreadfile($tmpDocument);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15031/"
] |
199,044
|
<p>My rails app is in a svn repository, but several of the plugins are installed through git and later added to the svn repo. How can I update these plugins? I can't seem to get script/plugin update to do anything. I'd really like to update activemerchant to get rid of the Inflector warnings.</p>
|
[
{
"answer_id": 200349,
"author": "Greg Borenstein",
"author_id": 10419,
"author_profile": "https://Stackoverflow.com/users/10419",
"pm_score": 0,
"selected": false,
"text": "\ngit pull\n script/install plugin"
},
{
"answer_id": 215380,
"author": "Matt",
"author_id": 29228,
"author_profile": "https://Stackoverflow.com/users/29228",
"pm_score": 2,
"selected": false,
"text": "script/plugin install --force script/plugin install --force git://github.com/dchelimsky/rspec.git\n"
},
{
"answer_id": 241000,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": ".git"
},
{
"answer_id": 2420012,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 2,
"selected": false,
"text": "script/plugin git clone git://github.com/foo/bar.git ~/foobar\nmv ~/foobar/.git rails_app/vendor/plugins/foobar/.git\nrm -rf ~/foobar\ncd rails_app/vendor/plugins\ngit reset --hard\n .git"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2884/"
] |
199,045
|
<p>I'm looking for a library that has functionality similar to Perl's <a href="http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS" rel="noreferrer">WWW::Mechanize</a>, but for PHP. Basically, it should allow me to submit HTTP GET and POST requests with a simple syntax, and then parse the resulting page and return in a simple format all forms and their fields, along with all links on the page.</p>
<p>I know about CURL, but it's a little too barebones, and the syntax is pretty ugly (tons of <code>curl_foo($curl_handle, ...)</code> statements</p>
<p><strong>Clarification:</strong></p>
<p>I want something more high-level than the answers so far. For example, in Perl, you could do something like:</p>
<pre><code># navigate to the main page
$mech->get( 'http://www.somesite.com/' );
# follow a link that contains the text 'download this'
$mech->follow_link( text_regex => qr/download this/i );
# submit a POST form, to log into the site
$mech->submit_form(
with_fields => {
username => 'mungo',
password => 'lost-and-alone',
}
);
# save the results as a file
$mech->save_content('somefile.zip');
</code></pre>
<p>To do the same thing using HTTP_Client or wget or CURL would be a lot of work, I'd have to manually parse the pages to find the links, find the form URL, extract all the hidden fields, and so on. The reason I'm asking for a PHP solution is that I have no experience with Perl, and I could probably build what I need with a lot of work, but it would be much quicker if I could do the above in PHP.</p>
|
[
{
"answer_id": 199054,
"author": "moo",
"author_id": 23107,
"author_profile": "https://Stackoverflow.com/users/23107",
"pm_score": 1,
"selected": false,
"text": "class curl {\n private $resource;\n\n public function __construct($url) {\n $this->resource = curl_init($url);\n }\n\n public function __call($function, array $params) {\n array_unshift($params, $this->resource);\n return call_user_func_array(\"curl_$function\", $params);\n }\n}\n"
},
{
"answer_id": 199387,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 1,
"selected": false,
"text": "/**\n * CURLHandler handles simple HTTP GETs and POSTs via Curl \n * \n * @package Pork\n * @author SchizoDuckie\n * @copyright SchizoDuckie 2008\n * @version 1.0\n * @access public\n */\nclass CURLHandler\n{\n\n /**\n * CURLHandler::Get()\n * \n * Executes a standard GET request via Curl.\n * Static function, so that you can use: CurlHandler::Get('http://www.google.com');\n * \n * @param string $url url to get\n * @return string HTML output\n */\n public static function Get($url)\n {\n return self::doRequest('GET', $url);\n }\n\n /**\n * CURLHandler::Post()\n * \n * Executes a standard POST request via Curl.\n * Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=>'StackOverFlow'));\n * If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ ! \n * @param string $url url to post data to\n * @param Array $vars Array with key=>value pairs to post.\n * @return string HTML output\n */\n public static function Post($url, $vars, $auth = false) \n {\n return self::doRequest('POST', $url, $vars, $auth);\n }\n\n /**\n * CURLHandler::doRequest()\n * This is what actually does the request\n * <pre>\n * - Create Curl handle with curl_init\n * - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER\n * - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS)\n * - Call curl_exec on the interface\n * - Close the connection\n * - Return the result or throw an exception.\n * </pre>\n * @param mixed $method Request Method (Get/ Post)\n * @param mixed $url URI to get or post to\n * @param mixed $vars Array of variables (only mandatory in POST requests)\n * @return string HTML output\n */\n public static function doRequest($method, $url, $vars=array(), $auth = false)\n {\n $curlInterface = curl_init();\n\n curl_setopt_array ($curlInterface, array( \n CURLOPT_URL => $url,\n CURLOPT_RETURNTRANSFER => 1,\n CURLOPT_FOLLOWLOCATION =>1,\n CURLOPT_HEADER => 0));\n if (strtoupper($method) == 'POST')\n {\n curl_setopt_array($curlInterface, array(\n CURLOPT_POST => 1,\n CURLOPT_POSTFIELDS => http_build_query($vars))\n ); \n }\n if($auth !== false)\n {\n curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . \":\" . $auth['password']);\n }\n $result = curl_exec ($curlInterface);\n curl_close ($curlInterface);\n\n if($result === NULL)\n {\n throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . \" - \" . curl_error($curlInterface));\n }\n else\n {\n return($result);\n }\n }\n\n}\n\n?>\n"
},
{
"answer_id": 5169099,
"author": "method",
"author_id": 40883,
"author_profile": "https://Stackoverflow.com/users/40883",
"pm_score": 1,
"selected": false,
"text": "# This is the sugar for importing the library within CakePHP \nApp::import('Core', 'HttpSocket');\n$HttpSocket = new HttpSocket();\n\n$result = $HttpSocket->post($login_url,\narray(\n \"username\" => \"username\",\n \"password\" => \"password\"\n)\n);\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
] |
199,059
|
<p>I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".</p>
<p>My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?</p>
|
[
{
"answer_id": 199075,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": ">>> re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", \"WordWordWord\")\n'Word Word Word'\n"
},
{
"answer_id": 199094,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 3,
"selected": false,
"text": "re.sub('([A-Z])', r' \\1', str)\n"
},
{
"answer_id": 199120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": ">>> re.sub(r\"(\\w)([A-Z])\", r\"\\1 \\2\", \"WordWordWWWWWWWord\")\n'Word Word WW WW WW Word'\n >>> re.sub(r\"(?<=\\w)([A-Z])\", r\" \\1\", \"WordWordWWWWWWWord\")\n'Word Word W W W W W W Word'\n"
},
{
"answer_id": 199126,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 4,
"selected": false,
"text": "re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\\1 ', text)\n \"SimpleHTTPServer\" => [\"Simple\", \"HTTP\", \"Server\"]\n"
},
{
"answer_id": 199215,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": false,
"text": ">>> re.sub(r\"\\B([A-Z])\", r\" \\1\", \"DoIThinkThisIsABetterAnswer?\")\n"
},
{
"answer_id": 200122,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 1,
"selected": false,
"text": "text = 'WordWordWord'\nnew_text = ''\n\nfor i, letter in enumerate(text):\n if i and letter.isupper():\n new_text += ' '\n\n new_text += letter\n"
},
{
"answer_id": 200456,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 0,
"selected": false,
"text": "def splitCaps(s):\n result = []\n for ch, next in window(s+\" \", 2):\n result.append(ch)\n if next.isupper() and not ch.isspace():\n result.append(' ')\n return ''.join(result)\n import collections, itertools\n\ndef window(it, winsize, step=1):\n it=iter(it) # Ensure we have an iterator\n l=collections.deque(itertools.islice(it, winsize))\n while 1: # Continue till StopIteration gets raised.\n yield tuple(l)\n for i in range(step):\n l.append(it.next())\n l.popleft()\n"
},
{
"answer_id": 45778633,
"author": "Yaroslav Surzhikov",
"author_id": 8489834,
"author_profile": "https://Stackoverflow.com/users/8489834",
"pm_score": 3,
"selected": false,
"text": "''.join(' ' + char if char.isupper() else char.strip() for char in text).strip()\n"
},
{
"answer_id": 46760056,
"author": "David Underhill",
"author_id": 164602,
"author_profile": "https://Stackoverflow.com/users/164602",
"pm_score": 2,
"selected": false,
"text": "re_outer = re.compile(r'([^A-Z ])([A-Z])')\nre_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')\nre_outer.sub(r'\\1 \\2', re_inner.sub(r' \\1\\2', 'DaveIsAFKRightNow!Cool'))\n 'Dave Is AFK Right Now! Cool'"
},
{
"answer_id": 67114560,
"author": "Srini",
"author_id": 1939379,
"author_profile": "https://Stackoverflow.com/users/1939379",
"pm_score": 0,
"selected": false,
"text": "re.sub() st = 'ThisIsTextStringToSplitWithSpace'\nprint(''.join([' '+ s if s.isupper() else s for s in st]).lstrip())\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
199,065
|
<p>I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it.</p>
<p>Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like:</p>
<pre><code>var jsArray = new {key: 'test test', value: 'value value'},
new {key: 'test 2', value: 'value 2'};
</code></pre>
<p>and accessed like:</p>
<pre><code>value = jsArray[key]
</code></pre>
<p>Can someone remind me?</p>
|
[
{
"answer_id": 199083,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": true,
"text": "var a = {'a':0, 'b':1, 'c':2};\n\nvar b = new Array();\nb['a'] = 0;\nb['b'] = 1;\nb['c'] = 2;\n\nvar c = new Object();\nc.a = 0;\nc.b = 1;\nc.c = 2;\n"
},
{
"answer_id": 199093,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 2,
"selected": false,
"text": "var myFancyDictionary = {\n key: 'value',\n anotherKey: 'anotherValue',\n youGet: 'the idea'\n}\n"
},
{
"answer_id": 199114,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": -1,
"selected": false,
"text": "if( typeof( rp ) == \"undefined\" ) rp = {};\n\nrp.clientState = new function()\n{\n this.items = new Object();\n this.length = 0;\n\n this.set = function( key, value )\n {\n if ( ! this.keyExists( key ) )\n {\n this.length++;\n }\n this.items[ key ] = value; \n }\n\n this.get = function( key )\n {\n if ( this.keyExists( key ) )\n {\n return this.items[ key ];\n } \n }\n\n this.keyExists = function( key )\n {\n return typeof( this.items[ key ] ) != \"undefined\"; \n }\n\n this.remove = function( key )\n {\n if ( this.keyExists( key ) )\n {\n delete this.items[ key ];\n this.length--; \n return true;\n }\n return false;\n }\n\n this.removeAll = function()\n {\n this.items = null;\n this.items = new Object();\n this.length = 0;\n }\n}\n // Add a value pair.\nrp.clientState.set( key, value );\n\n// Fetch a value.\nvar x = rp.clientState.Get( key );\n\n// Check to see if a key exists.\nif ( rp.clientState.keyExists( key ) \n{\n // Do something.\n}\n\n// Remove a key.\nrp.clientState.remove( key );\n\n// Remove all keys.\nrp.clientState.removeAll();\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
199,068
|
<p>Is it possible to play video from data that has been embedded in a swf at compile time (with the <code>[Embed]</code> metatag)?</p>
<p>The "Import Video->Embed" feature provided by Flash CS3 etc. is not acceptable because it has many severe limitations (including sound synchronization issues, a maximum number of frames, and other caveats)</p>
<p>I'm interested in being able to bundle flv video data in a swf (along with other assets), which will be played by an AIR application.</p>
<p>I don't think it can be done. Anyone disagree?</p>
|
[
{
"answer_id": 2519192,
"author": "aaaidan",
"author_id": 26331,
"author_profile": "https://Stackoverflow.com/users/26331",
"pm_score": 0,
"selected": false,
"text": "Embed [Embed(\n source=\"local_data_file.flv\",\n mimeType=\"application/octet-stream\") ]\nprivate static var __FlvClass123:Class;\nprotected static var flvData:ByteArray = new __FlvClass123();\n"
},
{
"answer_id": 9887078,
"author": "Thom",
"author_id": 24618,
"author_profile": "https://Stackoverflow.com/users/24618",
"pm_score": 4,
"selected": true,
"text": "NetStream.appendBytes() ByteArray public class Main extends MovieClip\n{\n [Embed(source=\"sample.flv\", mimeType=\"application/octet-stream\")]\n private var SampleVideo:Class;\n\n public function Main():void \n {\n var video:Video = new Video(320, 240);\n addChild(video);\n\n var netConnection:NetConnection = new NetConnection();\n netConnection.connect(null);\n var netStream:NetStream = new NetStream(netConnection);\n netStream.client = {};\n video.attachNetStream(netStream);\n\n var byteArray:ByteArray = new SampleVideo();\n netStream.play(null);\n netStream.appendBytes(byteArray);\n }\n}\n"
},
{
"answer_id": 50616790,
"author": "George Hummet",
"author_id": 9469669,
"author_profile": "https://Stackoverflow.com/users/9469669",
"pm_score": 0,
"selected": false,
"text": "public function loadSWF(){\n\n var _assetLdr:Loader;\n_assetLdr = new Loader();\n_assetLdr.load(new URLRequest(\"1.swf\"));\n_assetLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, this.handleComplete);\naddChild(_assetLdr); \n}\n\n\npublic function handleComplete(event:Event):void {\n\n trace(\"complete\");\n var loaderInfo:LoaderInfo=event.target as LoaderInfo;\n var content:MovieClip = loaderInfo.loader.content as MovieClip;\n addChild(content);\n\n}\n library.swf"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26331/"
] |
199,080
|
<p>A similar question was asked <a href="https://stackoverflow.com/questions/198931/how-do-i-tell-if-net-35-sp1-is-installed">here</a>, but it was specific to .NET 3.5. Specifically, I'm looking for the following:</p>
<ol>
<li>What is the correct way to determine which .NET Framework versions and service packs are installed?</li>
<li>Is there a list of registry keys that can be used?</li>
<li>Are there any dependencies between Framework versions?</li>
</ol>
|
[
{
"answer_id": 199121,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP Install=1 MSI=1"
},
{
"answer_id": 199783,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 10,
"selected": true,
"text": "\"Install\"=dword:00000001\n REG_SZ REG_DWORD #,#,####,# #,#,#### v4.5 HKLM\\Software\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full Release"
},
{
"answer_id": 644266,
"author": "mapache",
"author_id": 41422,
"author_profile": "https://Stackoverflow.com/users/41422",
"pm_score": 2,
"selected": false,
"text": "AboutTools.FrameworkVersions().ToConsole();\n//Writes in my machine:\n//v2.0.50727 SP2\n//v3.0 SP2\n//v3.5 SP1\n"
},
{
"answer_id": 2451408,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Collections.ObjectModel;\nusing Microsoft.Win32;\n\nclass Program\n{\n static void Main(string[] args)\n {\n foreach(Version ver in InstalledDotNetVersions())\n Console.WriteLine(ver);\n\n Console.ReadKey();\n }\n\n\n public static Collection<Version> InstalledDotNetVersions()\n {\n Collection<Version> versions = new Collection<Version>();\n RegistryKey NDPKey = Registry.LocalMachine.OpenSubKey(@\"SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\");\n if (NDPKey != null)\n {\n string[] subkeys = NDPKey.GetSubKeyNames();\n foreach (string subkey in subkeys)\n {\n GetDotNetVersion(NDPKey.OpenSubKey(subkey), subkey, versions);\n GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey(\"Client\"), subkey, versions);\n GetDotNetVersion(NDPKey.OpenSubKey(subkey).OpenSubKey(\"Full\"), subkey, versions);\n }\n }\n return versions;\n }\n\n private static void GetDotNetVersion(RegistryKey parentKey, string subVersionName, Collection<Version> versions)\n {\n if (parentKey != null)\n {\n string installed = Convert.ToString(parentKey.GetValue(\"Install\"));\n if (installed == \"1\")\n {\n string version = Convert.ToString(parentKey.GetValue(\"Version\"));\n if (string.IsNullOrEmpty(version))\n {\n if (subVersionName.StartsWith(\"v\"))\n version = subVersionName.Substring(1);\n else\n version = subVersionName;\n }\n\n Version ver = new Version(version);\n\n if (!versions.Contains(ver))\n versions.Add(ver);\n }\n }\n }\n}\n"
},
{
"answer_id": 2810884,
"author": "abhishek mehta",
"author_id": 338291,
"author_profile": "https://Stackoverflow.com/users/338291",
"pm_score": 3,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\wow6432Node\\Microsoft\\NET Framework Setup\\NDP\\\n"
},
{
"answer_id": 19560439,
"author": "Olivier de Rivoyre",
"author_id": 740362,
"author_profile": "https://Stackoverflow.com/users/740362",
"pm_score": 1,
"selected": false,
"text": "v2.0.50727 2.0.50727.4016 SP2\nv3.0 3.0.30729.4037 SP2\nv3.5 3.5.30729.01 SP1\nv4\n Client 4.0.30319\n Full 4.0.30319\n"
},
{
"answer_id": 23349906,
"author": "Mayank Agarwal",
"author_id": 1643414,
"author_profile": "https://Stackoverflow.com/users/1643414",
"pm_score": 1,
"selected": false,
"text": "wmic /namespace:\\\\root\\cimv2 path win32_product where \"name like '%%.NET%%'\" get version\n"
},
{
"answer_id": 34773812,
"author": "cezarypiatek",
"author_id": 876060,
"author_profile": "https://Stackoverflow.com/users/876060",
"pm_score": 2,
"selected": false,
"text": "function Get-KeyPropertyValue($key, $property)\n{\n if($key.Property -contains $property)\n {\n Get-ItemProperty $key.PSPath -name $property | select -expand $property\n }\n}\n\nfunction Get-VersionName($key)\n{\n $name = Get-KeyPropertyValue $key Version\n $sp = Get-KeyPropertyValue $key SP\n $install = Get-KeyPropertyValue $key Install\n if($sp)\n {\n \"$($_.PSChildName) $name SP $sp\"\n }\n else{\n \"$($_.PSChildName) $name\"\n }\n}\n\nfunction Get-FrameworkVersion{\n dir \"hklm:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\\" |? {$_.PSChildName -like \"v*\"} |%{\n if( $_.Property -contains \"Version\")\n {\n Get-VersionName $_\n }\n else{\n $parent = $_\n Get-ChildItem $_.PSPath |%{\n $versionName = Get-VersionName $_\n \"$($parent.PSChildName) $versionName\"\n }\n }\n }\n}\n\n\n$v4Directory = \"hklm:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\"\nif(Test-Path $v4Directory)\n{\n $v4 = Get-Item $v4Directory\n $version = Get-KeyPropertyValue $v4 Release\n switch($version){\n 378389 {\".NET Framework 4.5\"; break;}\n 378675 {\".NET Framework 4.5.1 installed with Windows 8.1 or Windows Server 2012 R2\"; break;}\n 378758 {\".NET Framework 4.5.1 installed on Windows 8, Windows 7 SP1, or Windows Vista SP2\"; break;}\n 379893 {\".NET Framework 4.5.2\"; break;}\n { 393295, 393297 -contains $_} {\".NET Framework 4.6\"; break;}\n { 394254, 394271 -contains $_} {\".NET Framework 4.6.1\"; break;}\n { 394802, 394806 -contains $_} {\".NET Framework 4.6.2\"; break; }\n }\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1559/"
] |
199,099
|
<p>I'm using <code>$.post()</code> to call a servlet using Ajax and then using the resulting HTML fragment to replace a <code>div</code> element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the <code>div</code> element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed. </p>
<p>How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?</p>
|
[
{
"answer_id": 199156,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 6,
"selected": false,
"text": "$.ajax() $.ajax({\n url: \"/yourservlet\",\n data: { },\n complete: function(xmlHttp) {\n // xmlHttp is a XMLHttpRquest object\n alert(xmlHttp.status);\n }\n});\n if (xmlHttp.code != 200) {\n top.location.href = '/some/other/page';\n}\n"
},
{
"answer_id": 216245,
"author": "Vladimir Prudnikov",
"author_id": 29364,
"author_profile": "https://Stackoverflow.com/users/29364",
"pm_score": -1,
"selected": false,
"text": "$.ajax({\n //.... other definition\n complete:function(xmlHttp){\n if(xmlHttp.status.toString()[0]=='3'){\n top.location.href = xmlHttp.getResponseHeader('Location');\n }\n});\n"
},
{
"answer_id": 291376,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "response.setStatus(response.SC_MOVED_PERMANENTLY); .toString() if (xmlHttp.status == 301) {\n top.location.href = 'xxxx.jsp';\n}"
},
{
"answer_id": 484541,
"author": "Elliot Vargas",
"author_id": 2024,
"author_profile": "https://Stackoverflow.com/users/2024",
"pm_score": 8,
"selected": true,
"text": "function cbWrapper(data, funct){\n if($(\"#myForm\", data).length > 0)\n top.location.href=\"login.htm\";//redirection\n else\n funct(data);\n}\n $.post(\"myAjaxHandler\", \n {\n param1: foo,\n param2: bar\n },\n function(data){\n cbWrapper(data, myActualCB);\n }, \n \"html\"\n);\n"
},
{
"answer_id": 579895,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "public ActionResult Index(){\n if (!HttpContext.User.Identity.IsAuthenticated)\n {\n HttpContext.Response.AddHeader(\"REQUIRES_AUTH\",\"1\");\n }\n return View();\n}\n ajaxSuccess $(document).ajaxSuccess(function(event, request, settings) {\n if (request.getResponseHeader('REQUIRES_AUTH') === '1') {\n window.location = '/';\n }\n});\n"
},
{
"answer_id": 1241149,
"author": "Graham King",
"author_id": 146620,
"author_profile": "https://Stackoverflow.com/users/146620",
"pm_score": 4,
"selected": false,
"text": " if request.is_ajax():\n response.status_code = 278\n $('#my-form').submit(function(event){ \n\n event.preventDefault(); \n var options = {\n url: $(this).attr('action'),\n type: 'POST',\n complete: function(response, textStatus) { \n if (response.status == 278) { \n window.location = response.getResponseHeader('Location')\n }\n else { ... your code here ... } \n },\n data: $(this).serialize(), \n }; \n $.ajax(options); \n});\n"
},
{
"answer_id": 1534662,
"author": "Steg",
"author_id": 121872,
"author_profile": "https://Stackoverflow.com/users/121872",
"pm_score": 10,
"selected": false,
"text": "$.ajax({\n type: \"POST\",\n url: reqUrl,\n data: reqBody,\n dataType: \"json\",\n success: function(data, textStatus) {\n if (data.redirect) {\n // data.redirect contains the string URL to redirect to\n window.location.href = data.redirect;\n } else {\n // data.form contains the HTML for the replacement form\n $(\"#myform\").replaceWith(data.form);\n }\n }\n});\n data.redirect data.form"
},
{
"answer_id": 3408763,
"author": "Bretticus",
"author_id": 411075,
"author_profile": "https://Stackoverflow.com/users/411075",
"pm_score": 3,
"selected": false,
"text": "// redirect ajax requests that are redirected, not found (404), or forbidden (403.)\n$('body').bind('ajaxComplete', function(event,request,settings){\n switch(request.status) {\n case 301: case 404: case 403: \n window.location.replace(\"http://mysite.tld/login\");\n break;\n }\n});\n $('body').bind('ajaxError', function(event,request,settings){\n window.location.replace(\"http://mysite.tld/login\");\n}\n"
},
{
"answer_id": 3505514,
"author": "Timmerz",
"author_id": 408992,
"author_profile": "https://Stackoverflow.com/users/408992",
"pm_score": 4,
"selected": false,
"text": "$(document).ready(function ()\n{\n $(document).ajaxSend(\n function(event,request,settings)\n {\n var intercepted_success = settings.success;\n settings.success = function( a, b, c ) \n { \n if( request.responseText.indexOf( \"<html>\" ) > -1 )\n window.location = window.location;\n else\n intercepted_success( a, b, c );\n };\n });\n});\n"
},
{
"answer_id": 3861414,
"author": "podeig",
"author_id": 284405,
"author_profile": "https://Stackoverflow.com/users/284405",
"pm_score": 4,
"selected": false,
"text": " $(document).ready(function () {\n if ($(\"#site\").length > 0) {\n window.location = \"<%= Url.Content(\"~\") %>\" + \"Login/LogOn\";\n }\n });\n"
},
{
"answer_id": 7166385,
"author": "BrianY",
"author_id": 908376,
"author_profile": "https://Stackoverflow.com/users/908376",
"pm_score": 6,
"selected": false,
"text": "$.ajax(\n error: function (jqXHR, timeout, message) {\n var contentType = jqXHR.getResponseHeader(\"Content-Type\");\n if (jqXHR.status === 200 && contentType.toLowerCase().indexOf(\"text/html\") >= 0) {\n // assume that our login has expired - reload our current page\n window.location.reload();\n }\n\n});\n"
},
{
"answer_id": 7220299,
"author": "Benny Jobigan",
"author_id": 262748,
"author_profile": "https://Stackoverflow.com/users/262748",
"pm_score": 2,
"selected": false,
"text": "HttpResponseRedirect('/the-redirect/') response = HttpResponse(status='300')\nresponse['Location'] = '/the-redirect/' \nreturn response\n <button onclick=\"*the-jquery*\">Delete</button>\n\nwhere *the-jquery* =\n$.ajax({ \n type: 'DELETE', \n url: '/resource-url/', \n complete: function(jqxhr){ \n window.location = jqxhr.getResponseHeader('Location'); \n } \n});\n"
},
{
"answer_id": 7373118,
"author": "Priyanka",
"author_id": 705876,
"author_profile": "https://Stackoverflow.com/users/705876",
"pm_score": 4,
"selected": false,
"text": " <script>\n function showValues() {\n var str = $(\"form\").serialize();\n $.post('loginUser.html', \n str,\n function(responseText, responseStatus, responseXML){\n if(responseStatus==\"success\"){\n window.location= \"adminIndex.html\";\n }\n }); \n }\n</script>\n"
},
{
"answer_id": 8391074,
"author": "Paul Richards",
"author_id": 1082225,
"author_profile": "https://Stackoverflow.com/users/1082225",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\n if (top.location.href.indexOf('login.php') == -1) {\n top.location.href = '/login.php';\n }\n</script>\n"
},
{
"answer_id": 8752354,
"author": "Tyr",
"author_id": 547524,
"author_profile": "https://Stackoverflow.com/users/547524",
"pm_score": 5,
"selected": false,
"text": "class AjaxRedirect(object):\n def process_response(self, request, response):\n if request.is_ajax():\n if type(response) == HttpResponseRedirect:\n r = HttpResponse(json.dumps({'redirect': response['Location']}))\n return r\n return response\n $('body').ajaxComplete(function (e, xhr, settings) {\n if (xhr.status == 200) {\n var redirect = null;\n try {\n redirect = $.parseJSON(xhr.responseText).redirect;\n if (redirect) {\n window.location.href = redirect.replace(/\\?.*$/, \"?next=\" + window.location.pathname);\n }\n } catch (e) {\n return;\n }\n }\n}\n"
},
{
"answer_id": 10095275,
"author": "Curtis Yallop",
"author_id": 854342,
"author_profile": "https://Stackoverflow.com/users/854342",
"pm_score": 2,
"selected": false,
"text": "// Hook XMLHttpRequest\nvar oldXMLHttpRequestSend = XMLHttpRequest.prototype.send;\n\nXMLHttpRequest.prototype.send = function() {\n //console.dir( this );\n\n this.onreadystatechange = function() {\n if (this.readyState == 4 && this.status == 500 && this.responseText.indexOf(\"Expired\") != -1) {\n try {\n document.documentElement.innerHTML = this.responseText;\n } catch(error) {\n // IE makes document.documentElement read only\n document.body.innerHTML = this.responseText;\n }\n }\n };\n\n oldXMLHttpRequestSend.apply(this, arguments);\n}\n"
},
{
"answer_id": 10717647,
"author": "Juri",
"author_id": 50109,
"author_profile": "https://Stackoverflow.com/users/50109",
"pm_score": 5,
"selected": false,
"text": "$(document).ajaxComplete(function(e, xhr, settings){\n if(xhr.status === 302){\n //check for location header and redirect...\n }\n});\n ajaxComplete status 200 LoginPage if(xhr.status === 200){\n var loginPageRedirectHeader = xhr.getResponseHeader(\"LoginPage\");\n if(loginPageRedirectHeader && loginPageRedirectHeader !== \"\"){\n window.location.replace(loginPageRedirectHeader);\n }\n}\n LoginPage GET xhr"
},
{
"answer_id": 13035088,
"author": "rynop",
"author_id": 563420,
"author_profile": "https://Stackoverflow.com/users/563420",
"pm_score": 5,
"selected": false,
"text": "401 Unauthorized $('body').bind('ajaxSuccess',function(event,request,settings){\nif (401 == request.status){\n window.location = '/users/login';\n}\n}).bind('ajaxError',function(event,request,settings){\nif (401 == request.status){\n window.location = '/users/login';\n}\n});\n"
},
{
"answer_id": 14191048,
"author": "karthik339",
"author_id": 563436,
"author_profile": "https://Stackoverflow.com/users/563436",
"pm_score": 3,
"selected": false,
"text": "<% HttpSession ses = request.getSession(true);\n String temp=request.getAttribute(\"what_you_defined\"); %>\n"
},
{
"answer_id": 14730592,
"author": "jocull",
"author_id": 97964,
"author_profile": "https://Stackoverflow.com/users/97964",
"pm_score": 3,
"selected": false,
"text": "$.get $.post function handleAjaxResponse(data, callback) {\n //Try to convert and parse object\n try {\n if (jQuery.type(data) === \"string\") {\n data = jQuery.parseJSON(data);\n }\n if (data.error) {\n if (data.error == 'login') {\n window.location.reload();\n return;\n }\n else if (data.error.length > 0) {\n alert(data.error);\n return;\n }\n }\n }\n catch(ex) { }\n\n if (callback) {\n callback(data);\n }\n}\n function submitAjaxForm(form, url, action) {\n //Lock form\n form.find('.ajax-submit').hide();\n form.find('.loader').show();\n\n $.post(url, form.serialize(), function (d) {\n //Unlock form\n form.find('.ajax-submit').show();\n form.find('.loader').hide();\n\n handleAjaxResponse(d, function (data) {\n // ... more code for if auth passes ...\n });\n });\n return false;\n}\n"
},
{
"answer_id": 16409097,
"author": "jwaliszko",
"author_id": 270315,
"author_profile": "https://Stackoverflow.com/users/270315",
"pm_score": 5,
"selected": false,
"text": "$.ajaxSetup({\n beforeSend: checkPulse,\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n document.open();\n document.write(XMLHttpRequest.responseText);\n document.close();\n }\n});\n CheckPulse [Authorize]\npublic virtual void CheckPulse() {}\n Authorize protected void Application_EndRequest()\n{\n if (Context.Response.StatusCode == 302\n && (new HttpContextWrapper(Context)).Request.IsAjaxRequest())\n { \n Context.Response.StatusCode = 200;\n Context.Response.AddHeader(\"REQUIRES_AUTH\", \"1\");\n }\n}\n window.location function checkPulse(XMLHttpRequest) {\n var location = window.location.href;\n $.ajax({\n url: \"/Controller/CheckPulse\",\n type: 'GET',\n async: false,\n beforeSend: null,\n success:\n function (result, textStatus, xhr) {\n if (xhr.getResponseHeader('REQUIRES_AUTH') === '1') {\n XMLHttpRequest.abort(); // terminate further ajax execution\n window.location = location;\n }\n }\n });\n}\n"
},
{
"answer_id": 18854676,
"author": "John",
"author_id": 795252,
"author_profile": "https://Stackoverflow.com/users/795252",
"pm_score": 4,
"selected": false,
"text": "public class AjaxAwareAuthenticationEntryPoint extends\n LoginUrlAuthenticationEntryPoint {\n\n public AjaxAwareAuthenticationEntryPoint(String loginUrl) {\n super(loginUrl);\n }\n\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {\n if (isAjax(request)) {\n response.sendError(HttpStatus.UNAUTHORIZED.value(), \"Please re-authenticate yourself\");\n } else {\n super.commence(request, response, authException);\n }\n }\n\n public static boolean isAjax(HttpServletRequest request) {\n return request != null && \"XMLHttpRequest\".equals(request.getHeader(\"X-Requested-With\"));\n }\n}\n"
},
{
"answer_id": 21781321,
"author": "Rob",
"author_id": 755949,
"author_profile": "https://Stackoverflow.com/users/755949",
"pm_score": 4,
"selected": false,
"text": " void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)\n {\n string requestedWithHeader = HttpContext.Current.Request.Headers[\"X-Requested-With\"];\n\n if (!string.IsNullOrEmpty(requestedWithHeader) && requestedWithHeader.Equals(\"XMLHttpRequest\", StringComparison.OrdinalIgnoreCase))\n {\n e.RedirectToIdentityProvider = false;\n }\n }\n $(document).ajaxError(function (event, jqxhr, settings, exception) {\n\n if (jqxhr.status == 401) { //Forbidden, go to login\n //Use a reload, WIF will redirect to Login\n location.reload(true);\n }\n});\n"
},
{
"answer_id": 22426015,
"author": "camara90100",
"author_id": 1001610,
"author_profile": "https://Stackoverflow.com/users/1001610",
"pm_score": -1,
"selected": false,
"text": "success: function(data, textStatus, xhr) {\n\n console.log(xhr.status);\n}\n"
},
{
"answer_id": 23417149,
"author": "morten.c",
"author_id": 2236166,
"author_profile": "https://Stackoverflow.com/users/2236166",
"pm_score": 4,
"selected": false,
"text": "$.ajaxsetup() statusCode 3xx 4xx $.ajaxSetup({ \n statusCode : {\n 400 : function () {\n window.location = \"/\";\n }\n }\n});\n 400 401 Unauthorized 400 401 4xx"
},
{
"answer_id": 31716188,
"author": "Ali Adlavaran",
"author_id": 1249792,
"author_profile": "https://Stackoverflow.com/users/1249792",
"pm_score": 3,
"selected": false,
"text": "HTTP Header Asp.Net MVC Global.asax Application_EndRequest public class MvcApplication : System.Web.HttpApplication\n {\n\n // ...\n // ...\n\n protected void Application_EndRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n app.Context.Response.Headers.Add(\"CurrentUrl\",app.Context. Request.CurrentExecutionFilePath);\n }\n\n }\n JQuery $.post url POST 302 303"
},
{
"answer_id": 36510887,
"author": "Tomer",
"author_id": 2279765,
"author_profile": "https://Stackoverflow.com/users/2279765",
"pm_score": 3,
"selected": false,
"text": "@Secured\n@Provider\n@Priority(Priorities.AUTHENTICATION)\npublic class AuthenticationFilter implements ContainerRequestFilter {\n\n private final Logger m_logger = LoggerFactory.getLogger(AuthenticationFilter.class);\n\n public static final String COOKIE_NAME = \"token_cookie\"; \n\n @Override\n public void filter(ContainerRequestContext context) throws IOException { \n // Check if it has a cookie.\n try {\n Map<String, Cookie> cookies = context.getCookies();\n\n if (!cookies.containsKey(COOKIE_NAME)) {\n m_logger.debug(\"No cookie set - redirect to login page\");\n throw new AuthenticationException();\n }\n }\n catch (AuthenticationException e) {\n context.abortWith(Response.ok(\"\\\"NEED TO AUTHENTICATE\\\"\").type(\"json/application\").build());\n }\n }\n}\n $.ajaxPrefilter(function(options, originalOptions, jqXHR) {\n var originalSuccess = options.success;\n\n options.success = function(data) {\n if (data == \"NEED TO AUTHENTICATE\") {\n window.location.replace(\"/login.html\");\n }\n else {\n originalSuccess(data);\n }\n }; \n});\n"
},
{
"answer_id": 40285917,
"author": "Przemek Marcinkiewicz",
"author_id": 1449780,
"author_profile": "https://Stackoverflow.com/users/1449780",
"pm_score": 4,
"selected": false,
"text": "$.ajaxSetup({\n dataFilter: function (data, type) {\n if (data && typeof data == \"string\") {\n if (data.indexOf('window.location') > -1) {\n eval(data);\n }\n }\n return data;\n }\n});\n"
},
{
"answer_id": 49416672,
"author": "Darren Parker",
"author_id": 4505142,
"author_profile": "https://Stackoverflow.com/users/4505142",
"pm_score": 2,
"selected": false,
"text": "public class CustomLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {\n\n public CustomLoginUrlAuthenticationEntryPoint(final String loginFormUrl) {\n super(loginFormUrl);\n }\n\n // For AJAX requests for user that isn't logged in, need to return 403 status.\n // For normal requests, Spring does a (302) redirect to login.jsp which the browser handles normally.\n @Override\n public void commence(final HttpServletRequest request,\n final HttpServletResponse response,\n final AuthenticationException authException)\n throws IOException, ServletException {\n if (\"XMLHttpRequest\".equals(request.getHeader(\"X-Requested-With\"))) {\n response.sendError(HttpServletResponse.SC_FORBIDDEN, \"Access Denied\");\n } else {\n super.commence(request, response, authException);\n }\n }\n}\n <security:http auto-config=\"false\" use-expressions=\"true\" entry-point-ref=\"customAuthEntryPoint\" >\n <security:form-login login-page='/login.jsp' default-target-url='/index.jsp' \n authentication-failure-url=\"/login.jsp?error=true\"\n /> \n <security:access-denied-handler error-page=\"/errorPage.jsp\"/> \n <security:logout logout-success-url=\"/login.jsp?logout\" />\n...\n <bean id=\"customAuthEntryPoint\" class=\"com.myapp.utils.CustomLoginUrlAuthenticationEntryPoint\" scope=\"singleton\">\n <constructor-arg value=\"/login.jsp\" />\n </bean>\n...\n<bean id=\"requestCache\" class=\"org.springframework.security.web.savedrequest.HttpSessionRequestCache\">\n <property name=\"requestMatcher\">\n <bean class=\"org.springframework.security.web.util.matcher.NegatedRequestMatcher\">\n <constructor-arg>\n <bean class=\"org.springframework.security.web.util.matcher.MediaTypeRequestMatcher\">\n <constructor-arg>\n <bean class=\"org.springframework.web.accept.HeaderContentNegotiationStrategy\"/>\n </constructor-arg>\n <constructor-arg value=\"#{T(org.springframework.http.MediaType).APPLICATION_JSON}\"/>\n <property name=\"useEquals\" value=\"true\"/>\n </bean>\n </constructor-arg>\n </bean>\n </property>\n</bean>\n $( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {\n if ( jqxhr.status === 403 ) {\n window.location = \"login.jsp\";\n } else {\n if(thrownError != null) {\n alert(thrownError);\n } else {\n alert(\"error\");\n }\n }\n });\n var str = $(\"#viewForm\").serialize();\n $.ajax({\n url: \"get_mongoDB_doc_versions.do\",\n type: \"post\",\n data: str,\n cache: false,\n async: false,\n dataType: \"json\",\n success: function(data) { ... },\n// error: function (jqXHR, textStatus, errorStr) {\n// if(textStatus != null)\n// alert(textStatus);\n// else if(errorStr != null)\n// alert(errorStr);\n// else\n// alert(\"error\");\n// }\n });\n always-use-default-target=\"true\""
},
{
"answer_id": 51314921,
"author": "Chaim Klar",
"author_id": 1475310,
"author_profile": "https://Stackoverflow.com/users/1475310",
"pm_score": 4,
"selected": false,
"text": "301/302 location status: 308 location status: 204 No Content\nx-status: 308 Document Redirect\nx-location: /login.html\n status: 204 x-status: 308 location"
},
{
"answer_id": 59501322,
"author": "Sumit Kumar",
"author_id": 842050,
"author_profile": "https://Stackoverflow.com/users/842050",
"pm_score": 0,
"selected": false,
"text": "$.ajax({\n type: <HTTP_METHOD>,\n url: {server.url},\n data: {someData: true},\n statusCode: {\n 301: function(responseObject, textStatus, errorThrown) {\n //yor code goes here\n },\n 302: function(responseObject, textStatus, errorThrown) {\n //yor code goes here\n } \n }\n})\n.done(function(data){\n alert(data);\n})\n.fail(function(jqXHR, textStatus){\n alert('Something went wrong: ' + textStatus);\n})\n.always(function(jqXHR, textStatus) {\n alert('Ajax request was finished')\n});\n"
},
{
"answer_id": 67684994,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 0,
"selected": false,
"text": "@ExceptionHandler @Order(HIGHEST_PRECEDENCE)\npublic class ExceptionHandlerAdvise {\n\n private static Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvise.class);\n\n @Autowired\n private UserInfo userInfo;\n\n @ExceptionHandler(value = Exception.class)\n protected ResponseEntity<Object> handleException(Exception ex, WebRequest request) {\n HttpHeaders headers = new HttpHeaders();\n if (isBusinessException(ex)) {\n logger.warn(getRequestURL(request), ex);\n return new ResponseEntity<>(getUserFriendlyErrorMessage(ex), headers, BAD_REQUEST);\n } else {\n logger.error(getRequestURL(request), ex);\n userInfo.setLastError(ex);\n headers.add(\"Location\", \"/euc-portal/fault\");\n return new ResponseEntity<>(null, headers, isAjaxRequest(request) ? INTERNAL_SERVER_ERROR : FOUND);\n }\n }\n}\n\nprivate boolean isAjaxRequest(WebRequest request) {\n return request.getHeader(\"x-requested-with\") != null;\n}\n\nprivate String getRequestURL(WebRequest request) {\n if (request instanceof ServletWebRequest) {\n HttpServletRequest servletRequest = ((ServletWebRequest) request).getRequest();\n StringBuilder uri = new StringBuilder(servletRequest.getRequestURI());\n if (servletRequest.getQueryString() != null) {\n uri.append(\"?\");\n uri.append(servletRequest.getQueryString());\n }\n return uri.toString();\n }\n return request.getContextPath();\n}\n @Service\npublic class LoginHandlerInterceptor implements HandlerInterceptor {\n\n @Autowired\n private UserInfo userInfo;\n\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n if (userInfo.getPrincipal() == null && !(request.getRequestURI().contains(LOGIN_URL) || request.getRequestURI().contains(FAULT_URL) || request.getRequestURI().startsWith(\"/app/css\"))) {\n response.addHeader(\"Location\", LOGIN_URL);\n response.setStatus(isAjaxRequest(request) ? BAD_REQUEST.value() : FOUND.value());\n return false;\n }\n return true;\n }\n}\n $.post('/app/request', params).done(function(response) {\n ...\n}).fail(function(response) {\n if (response.getResponseHeader('Location')) {\n window.top.location.href = response.getResponseHeader('Location');\n return;\n }\n alert(response);\n});\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
] |
199,113
|
<p>I have a <code>BasePage</code> which inherits from <code>System.Web.UI.Page</code>, and every page that inherits the <code>BasePage</code> will have the same master page.</p>
<p>How do I cast the <code>Page.Master</code> of the <code>BasePage</code> to the specific master page so I can access properties on it?</p>
|
[
{
"answer_id": 199116,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 0,
"selected": false,
"text": "MasterPageVariable = Ctype(page.MasterPage, MasterPageClass)\n"
},
{
"answer_id": 199122,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "public CustomMasterPage MasterPage\n{\n get { return this.Master as CustomMasterPage; }\n}\n"
},
{
"answer_id": 199124,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 3,
"selected": false,
"text": "<%@ MasterType VirtualPath=\"~/site.master\" %>\n this.Master.propertyName\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
] |
199,127
|
<p>I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client.</p>
<p>However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null. </p>
<p>My questions are:</p>
<ol>
<li>Are hidden fields on a child window
not accessible when the window is
launched from a parent asp.net form?</li>
<li>Has anyone attempted this with Telerik controls and run into issues?</li>
</ol>
<p><strong>EDIT</strong>
Craig pointed out that the id may be different. Two additional questions then:</p>
<ol>
<li>Can you ensure that the id you assign at the server is actually used?</li>
<li>Is using getElementByName() a better mechanism to access DOM elements?</li>
</ol>
|
[
{
"answer_id": 199524,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 2,
"selected": true,
"text": "<%= theControl.ClientID %>\n"
},
{
"answer_id": 440701,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 1,
"selected": false,
"text": "function OnIncidentDateChange(ctrl, dtDate, bErr)\n{\n var weekday = new Array(7);\n weekday[0] = \"Sunday\";\n weekday[1] = \"Monday\";\n weekday[2] = \"Tuesday\";\n weekday[3] = \"Wednesday\";\n weekday[4] = \"Thursday\";\n weekday[5] = \"Friday\";\n weekday[6] = \"Saturday\";\n\n <%=LabelDayOfWeek.ClientID %>.innerText = weekday[dtDate.getDay()];\n}\n // Dummy function?\nfunction OnIncidentDateChange()\n{\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19799/"
] |
199,130
|
<p>For my Java apps with very long classpaths, I cannot see the main class specified near the end of the arg list when using ps. I think this stems from my Ubuntu system's size limit on /proc/pid/cmdline. How can I increase this limit?</p>
|
[
{
"answer_id": 199199,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": " 274 int res = 0;\n 275 unsigned int len;\n 276 struct mm_struct *mm = get_task_mm(task);\n 277 if (!mm)\n 278 goto out;\n 279 if (!mm->arg_end)\n 280 goto out_mm; /* Shh! No looking before we're done */\n 281\n 282 len = mm->arg_end - mm->arg_start;\n 283 \n 284 if (len > PAGE_SIZE)\n 285 len = PAGE_SIZE;\n 286 \n 287 res = access_process_vm(task, mm->arg_start, buffer, len, 0);\n"
},
{
"answer_id": 1286297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "mv /x/jdks/jdk1.6.0_16_x32/bin/java /x/jdks/jdk1.6.0_16_x32/bin/java.orig\n #!/bin/bash\n\n echo \"$@\" > /tmp/java.$$.cmdline\n /x/jdks/jdk1.6.0_16_x32/bin/java.orig $@\n chmod a+x /x/jdks/jdk1.6.0_16_x32/bin/java\n"
},
{
"answer_id": 3418186,
"author": "Matt",
"author_id": 401688,
"author_profile": "https://Stackoverflow.com/users/401688",
"pm_score": 3,
"selected": false,
"text": "jconsole"
},
{
"answer_id": 3669146,
"author": "Kevin Cross",
"author_id": 219424,
"author_profile": "https://Stackoverflow.com/users/219424",
"pm_score": 5,
"selected": false,
"text": "jps -vl | grep <pid>\n"
},
{
"answer_id": 37454888,
"author": "kamstrup",
"author_id": 2285564,
"author_profile": "https://Stackoverflow.com/users/2285564",
"pm_score": 0,
"selected": false,
"text": "jps -m\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27635/"
] |
199,142
|
<p>I'm designing some VB based ASP.NET 2.0, and I am trying to make more use of the various ASP tags that visual studio provides, rather than hand writing everything in the code-behind. I want to pass in an outside variable from the Session to identify who the user is for the query.</p>
<pre><code><asp:sqldatasource id="DataStores" runat="server" connectionstring="<%$ ConnectionStrings:MY_CONNECTION %>"
providername="<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>"
selectcommand="SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))"
onselecting="Data_Stores_Selecting">
<SelectParameters>
<asp:parameter name="user" defaultvalue ="" />
</SelectParameters>
</asp:sqldatasource>
</code></pre>
<p>And on my code behind I have:</p>
<pre><code>Protected Sub Data_Stores_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting
e.Command.Parameters("user").Value = Session("userid")
End Sub
</code></pre>
<p>Oracle squaks at me with ORA-01036, illegal variable name. Am I declaring the variable wrong in the query? </p>
<p>I thought external variables share the same name with a @ prefixed. from what I understand, this should be placing the value I want into the query when it executes the select.</p>
<p>EDIT: Okay, thanks for the advice so far, first error was corrected, I need to use : and not @ for the variable declaration in the query. Now it generates an ORA-01745 invalid host/bind variable name.</p>
<p>EDIT AGAIN: Okay, looks like user was a reserved word. It works now! Thanks for other points of view on this one. I hadn't thought of that approach.</p>
|
[
{
"answer_id": 199574,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<SelectParameters>\n <SessionParameter Name=\"userID\" SessionField=\"user\" DefaultValue=\"\" />\n</SelectParameters>\n"
},
{
"answer_id": 249466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<asp:sqldatasource id=\"DataStores\" runat=\"server\" connectionstring=\"<%$ ConnectionStrings:MY_CONNECTION %>\"\n providername=\"<%$ ConnectionStrings:MY_CONNECTION.ProviderName %>\"\n selectcommand=\"SELECT THING1, THING2 FROM DATA_TABLE WHERE (THING2 IN (SELECT THING2 FROM RELATED_DATA_TABLE WHERE (USERNAME = @user)))\"\n onselecting=\"NAME_OF_SUB_Selecting\">\n <SelectParameters>\n <asp:parameter name=\"@user1\" defaultvalue =\"\" />\n </SelectParameters>\n </asp:sqldatasource>\n\n\nProtected Sub NAME_OF_SUB_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles Data_Stores.Selecting\n e.Command.Parameters(\"@user1\").Value = Membership.GetUser.ProviderUserKey.ToString()\nEnd Sub\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12545/"
] |
199,151
|
<p>I'm trying to link a Qt application with its libraries and the linker (MinGW) spews hundreds of lines like the following, and I am unsure how to proceed.</p>
<pre>
cpp: undefined reference to `_Unwind_SjLj_Register'
c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x29d):qcoreapplication_win.
cpp: undefined reference to `_Unwind_SjLj_Unregister'
c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x38c):qcoreapplication_win.
cpp: undefined reference to `_Unwind_SjLj_Resume'
c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x4ce):qcoreapplication_win.
cpp: undefined reference to `_Unwind_SjLj_Register'
c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x53e):qcoreapplication_win.
cpp: undefined reference to `_Unwind_SjLj_Unregister'
c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x635):qcoreapplication_win.
cpp: undefined reference to `_Unwind_SjLj_Resume'
</pre>
|
[
{
"answer_id": 199372,
"author": "Colin Jensen",
"author_id": 9884,
"author_profile": "https://Stackoverflow.com/users/9884",
"pm_score": 3,
"selected": false,
"text": "CONFIG += exceptions\n CONFIG -= exceptions\n"
},
{
"answer_id": 11979569,
"author": "chacham15",
"author_id": 516813,
"author_profile": "https://Stackoverflow.com/users/516813",
"pm_score": 0,
"selected": false,
"text": "-lstdc++"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8923/"
] |
199,152
|
<p>I have a Java Applet that uses AWT. In some (rare) circumstances, the platform does not refresh the screen properly. I can move or minimize/maximize the window and see that my applet refreshed properly. I am looking for code that will give me the fullest possible applet screen repaint, simulating the behaviour of a minimize/maximize. </p>
<p>I've tried calling various combinations of paint()/repaint()/invalidate()/update() on the parent containers and recursing on various children. However, no combination (that I've found) cleans up the framework bugs that I am encountering. I am looking for techniques to fully refresh the applet, even if they may cause some slight flickering, as I will be invoking this code only on the problematic platform. </p>
<p>In my tests, moving to Swing did not help resolve my problem. </p>
<p>By the way, this is a simplification of my previous (more complicated) post: <a href="https://stackoverflow.com/questions/184491/java-applet-awt-refresh-problem-mac-os-x-104">Java Applet, AWT Refresh problem Mac OS X 10.4</a> </p>
<p>Edit: Investigation in threading did not solve this problem. Marking best answer as the good one. </p>
|
[
{
"answer_id": 201067,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 0,
"selected": false,
"text": "public class VeryFastPanel extends JPanel {\n\n\n\n /**\n *\n */\n private static final long serialVersionUID = 1L;\n\n public void update(Graphics g) {\n\n paint(g);\n }\n\n}\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/199152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20893/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.