instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this?</p>
|
<p><code>svn log</code> has a <code>--verbose</code> parameter. I don't have a repository here to test with, but does that return a list of modified files?</p>
<p>You can also use <code>svn diff -r <revision></code> to retrieve the full change details, which you can parse or read manually to find out which files were changed.</p>
|
<p><code>svn log</code> has a <code>--verbose</code> parameter. I don't have a repository here to test with, but does that return a list of modified files?</p>
<p>You can also use <code>svn diff -r <revision></code> to retrieve the full change details, which you can parse or read manually to find out which files were changed.</p>
| 6,684
|
<p>In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?</p>
|
<p>If all you are doing is exposing an object instance that is relevant to the state of the current object you should use a property.</p>
<p>A method should be used when you have some logic that is doing more than accessing an in memory object and returning that value or when you are performing an action that has a broad affect on the state of the current object.</p>
|
<p>I confused about the using property and method before. But now I am using this rule according to <a href="https://msdn.microsoft.com/en-us/library/vstudio/ms229054%28v=vs.100%29.aspx" rel="nofollow">MSDN Guideline</a>:</p>
<p>methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.</p>
| 19,890
|
<p>I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:</p>
<pre><code>public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
</code></pre>
<p>I need to add attributes to the at OnEventConsumed runtime, so I'm generating a subclass using System.Reflection.Emit. What I want is the MSIL equivalent of this:</p>
<pre><code>public override void OnEventConsumed(object sender, EventArgs e)
{
base.OnEventConsumed(sender, e);
}
</code></pre>
<p>What I have so far is this:</p>
<pre><code>...
MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
baseMethod.Attributes,
baseMethod.CallingConvention,
typeof(void),
new Type[] {typeof(object),
typeof(EventArgs)});
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// load the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
...
</code></pre>
<p>I create the type, create an instance of the type, and call its OnEventConsumed function, and I get:</p>
<pre><code>Common Language Runtime detected an invalid program.
</code></pre>
<p>...which is not exactly helpful. What am I doing wrong? What's the correct MSIL to call the base class's event handler?</p>
|
<p>Here's the IL from a sample app:</p>
<pre><code>
.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: ldarg.2
L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)
L_0009: nop
L_000a: ret
}
</code></pre>
<p>So I think you aren't loading the instance because you aren't doing a ldarg.0</p>
|
<p>The using</p>
<pre><code>public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
</code></pre>
<p>should be</p>
<pre><code>public virtual void OnEventConsumed(EventArgs e)
{
EventHandler handler = this.EventConsumed;
if ( null != handler ) handler( this, e );
}
</code></pre>
<p>.</p>
<p>I think, you should use a <a href="http://msdn.microsoft.com/en-us/library/d81ee808.aspx" rel="nofollow noreferrer">ILGenerator.EmitCalli</a> and you should pass a type of return value ( i think null in this case ) and pass the types of arguments - i think "new Type[]{ typeof(EventArgs)}</p>
| 33,735
|
<p>I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page. </p>
<ul>
<li>I don't need to do any DOM updates before, after, or during the callbacks. </li>
<li>I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.</li>
</ul>
<p>What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.</p>
<p>I really just want to be able to call a single method on the page, nothing else.</p>
<p>Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.</p>
<p><strong>UPDATE</strong><br>
I've decided to accept <a href="https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270">DanP</a>'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does. </p>
<p>What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?</p>
<p>The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible?</p>
|
<p>If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:</p>
<pre><code>public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
context.Response.Write( sXml );
}
public bool IsReusable
{
get { return true; }
}
}
</code></pre>
|
<p>You can also use WebMethods which are built into the asp.net ajax library. You simply create a static method on the page's codebehind and call that from your Ajax.</p>
<p>There's a pretty basic example of how to do it <a href="https://web.archive.org/web/20200803212711/http://geekswithblogs.net/frankw/archive/2008/03/13/asp.net-ajax-callbacks-to-web-methods-in-aspx-pages.aspx" rel="nofollow noreferrer">here</a></p>
| 4,691
|
<p>On a recent project I have been working on in C#/ASP.NET I have some fairly complicated JavaScript files and some nifty Style Sheets. As these script resources grow in size it <a href="http://developer.yahoo.com/yui/compressor/" rel="nofollow noreferrer">is advisable to minify the resources</a> and keep your web pages as light as possible, of course. I know many developers who hand-feed their JavaScript resources into compressors after debugging and then deploy their applications.</p>
<p>When it comes to source control and automated builds in the satisfying world of continuous integration (thank you <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl.NET</a>); hand compression will simply not do. The only way to maintain source control and offer compressed resources is to keep JS/CSS source & their minified brethren in a separate directory structure. Then register only one set of resources or the other in code-behind. However, if a developer makes a change to JS/CSS source and then fails to re-compact it and check in both versions, then you’re code-line is now out of sync. Not to mention inelegant.</p>
<p>I am thinking that it would be nice to write a custom executable (if one does not exist yet) for the CC.NET task block which would find and compress all JavaScript and CSS resources in the target directory after the build action but before the asp.net publish to target. This way, developers would only work on JS and CSS source and users would only get the minified resources.</p>
<p><strong>Is there an application that already performs this task and if not, what kind of resource(s) should I look to install on the build server to have CC.NET execute?</strong></p>
<p>(The <a href="https://stackoverflow.com/questions/258781/best-packing-strategy-for-js-during-continuous-integration">closest question</a> I could find here to this one required NAnt, which is not an option in my case.)</p>
<p><strong>EDIT:</strong>
Dave Ward now has a great article on <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/" rel="nofollow noreferrer">how to automatically minify in Visual Studio</a> at his site.</p>
|
<p>The <a href="https://github.com/loresoft/msbuildtasks/" rel="noreferrer">MSBuildCommunityTasks Project</a> has a few MSBuild tasks that may do what you are looking for including Merge and JSCompress. </p>
<p>You could add these into your MSBuild project in the AfterBuild target to allow the project to perform this action every time the project is built and nothing would ever be out of sync. Your web application could then reference the compacted version for run but the developers would edit the full versions.</p>
<p>Nothing else would be needed on the server except the MSBuild community tasks assembly. You can put this assembly in your own source tree and reference from there and your CI build should get that assembly and everything it needs when it builds.</p>
|
<p>Not a perfect answer, but if you're using MVC4 they've built this in as a new feature. When running a Debug configuration, it outputs individual files with comments and such but when you switch to Release, it will automatically bundle, minify, and change in page references to the minified files. You can setup separate bundles for, say, jquery and your own js. This works with CSS and JS files.</p>
<p><a href="http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification" rel="nofollow">http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification</a></p>
<p>If MVC4 doesn't work for you, you can also find packages on Nuget that can help such as this:</p>
<p><a href="https://www.nuget.org/packages?q=minify" rel="nofollow">https://www.nuget.org/packages?q=minify</a></p>
| 35,218
|
<p>In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses.</p>
<p>My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes.</p>
<p>How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?</p>
|
<p>I think developing a custom solution for running background tasks doesn't always worth, so I recommend to use the <a href="http://www.quartz-scheduler.org/" rel="nofollow noreferrer">Quartz Scheduler</a> in Java.</p>
<p>In your situation (need to run background tasks in a web application) you could use the ServletContextListener included in the distribution to <a href="http://www.quartz-scheduler.org/api/2.2.1/org/quartz/ee/servlet/QuartzInitializerListener.html" rel="nofollow noreferrer">initialize the engine at the startup of your web container</a>.</p>
<p>After that you have a number of possibilities to start (trigger) your background tasks (jobs), e.g. you can use Calendars or cron-like expressions. In your situation most probably you should settle with <a href="http://www.quartz-scheduler.org/api/2.2.1/org/quartz/CronTrigger.html" rel="nofollow noreferrer">SimpleTrigger</a> that lets you run jobs in fixed, regular intervals.</p>
<p>The jobs themselves can be described easily too in Quartz, however you haven't provided any details about what you need to run, so I can't provide a suggestion in that area.</p>
|
<p>Here is how they do it on StackOverflow.com:</p>
<p><a href="https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/">https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/</a></p>
| 7,070
|
<p>We are considering a move from SVN to Mercurial, and have encountered a stumbling block.</p>
<p>We currently use <code>svn:externals</code> to automatically pull a common set of libraries into the working directory. I can't find support for anything like this in Mercurial.</p>
<p>Is there a way to do this automatically with Mercurial, or do I need to fake it as part of my build process?</p>
|
<p>There's no good way to do it using mercurial only. The Forest Extension mentioned elsewhere causes more problems that in fixes nowadays. Most folks just use a large repo and include all their components in the repo and then have their build scripts download and use 3rd party libraries -- using maven if they're Java-heads.</p>
<p>Short answer "fake it in your build process".</p>
<p><strong>Update:</strong></p>
<p>In Mercurial 1.3 a new sub repos feature was added. it's like the old forest extension, but started as all new code.</p>
<p><a href="https://www.mercurial-scm.org/wiki/Subrepository" rel="nofollow noreferrer">Subrepos</a> are considered a "<strong>feature of last resort</strong>".</p>
|
<p>Try Mercurial's <a href="https://www.mercurial-scm.org/wiki/ForestExtension" rel="nofollow noreferrer">Forest Extension</a>.</p>
| 26,731
|
<p>MSIE v7 does not (in my hands) open a Modeless Dialog or trigger an onLoad event if there is a Javascript alert in the target page. The following fails in MSIE v7 but is OK in v6 (zip file of full source available if required). </p>
<p>Would appreciate others confirming this and discussing why this should be so.</p>
<p>index.htm (only javascript function shown here)</p>
<pre><code>function openDialog(n) {
if (typeof(window.showModalDialog) == 'object') { /* Ensure of browser support */
var sURL = 'modeless.htm'; /* Set the URL */
var oWin = window.showModelessDialog(sURL); /* Create new modeless window */
}
else {
alert('"showModlessDialog" not supported!');
}
}
</code></pre>
<p>modeless.htm</p>
<pre><code><html>
<head>
<title>Modeless dialog</title>
</head>
<body bgcolor="#ff0000" text="#ffffff" onLoad="alert('Modeless is now loaded')">
<center>
<h1>Modeless</h1>
</center>
<script type="text/javascript" language="JavaScript">
/* If the next line is included, it prevents the onLoad event occurring in MSIE v7 */
alert('This alert stops the onLoad event in MSIE v7!');
</script>
</body>
</html>
</code></pre>
|
<p>It appears that IE7 is displaying the proper behavior. HTML is read and parsed sequentially, including scripts. When the parser reaches the javascript alert, it executes it and waits for a return. Then, it can finish parsing the page and raise the onLoad event.</p>
<p>If you want the alert to be displayed after the page has been loaded, you must handle the onLoad event itself. You can do this natively with:</p>
<pre><code>window.onload = function() {
//do stuff here
}
</code></pre>
<p>Or, you can do this with any number of javascript libraries, like jQuery:</p>
<pre><code>$(document).ready(function() {
//do stuff here
});
</code></pre>
|
<p>Are you sure it's not your inline onload event that's stopping it? The code below works for me.</p>
<p>Index.htm</p>
<pre><code><html>
<head>
<title>Index</title>
<script type="text/javascript" language="JavaScript">
function openDialog() {
if (window.showModalDialog) {
var sURL = 'Modeless.htm';
var oWin = window.showModelessDialog(sURL);
}
else
{
alert('"showModlessDialog" not supported!');
}
}
function addEventSimple(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
function removeEventSimple(obj,evt,fn) {
if (obj.removeEventListener)
obj.removeEventListener(evt,fn,false);
else if (obj.detachEvent)
obj.detachEvent('on'+evt,fn);
}
addEventSimple(window, "load", openDialog);
</script>
</head>
<body text="#ffffff">
<h1 align="center">Index</h1>
</body>
</html>
</code></pre>
<p>Modeless.htm</p>
<pre><code><html>
<head>
<title>Modeless dialog</title>
<script type="text/javascript" language="JavaScript">
addEventSimple(window, "load", showAlert);
function showAlert() {
alert('Modeless is now Loaded');
}
function addEventSimple(obj,evt,fn) {
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
function removeEventSimple(obj,evt,fn) {
if (obj.removeEventListener)
obj.removeEventListener(evt,fn,false);
else if (obj.detachEvent)
obj.detachEvent('on'+evt,fn);
}
</script>
</head>
<body text="#ffffff" >
<h1 align="center">Modeless</h1>
<script type="text/javascript" language="JavaScript">
/* If the next line is included, it prevents the onLoad event occurring in MSIE v7 */
alert('This alert stops the onLoad event in MSIE v7!');
</script>
</body>
</html>
</code></pre>
<p>Note: For some reason I need to clear my browser cache to get any changes to the modeless window to update.</p>
| 47,810
|
<p>Does anyone know a trick in Visual Studio 2008 to make it remember the outline toggles you have in place on aspx files between restarts? (the little plus or minus symbol on the left for code blocks)</p>
<p>In the code behind cs file it remembers the toggle on the #region tags... hoping for something like that I can do on the aspx HTML side.</p>
<p>So far I am forced to either re-close them when I open it, or do a Edit -> Outlining -> Toggle all Outlining to close them all when opening. Nothing happy in the middle.</p>
|
<p>I turn those suckers off. That way, the state is always the same, I see all the code, and it reminds me that I have to clean it up.</p>
<p>However, to answer your question, I don't think there is active way to control that after you close the file.</p>
|
<p>I turn those suckers off. That way, the state is always the same, I see all the code, and it reminds me that I have to clean it up.</p>
<p>However, to answer your question, I don't think there is active way to control that after you close the file.</p>
| 29,130
|
<p>It often happens that characters such as <em>é</em> gets transformed to <em>é</em>, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the <em>Content-Type</em> for the page is also set to UTF8.</p>
<p>I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.</p>
<p>I have read the "<a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>" article, but I need some MySQL / PHP specific pointers.</p>
<p>How do I ensure that user entered data containing international characters doesn't get corrupted?</p>
|
<p>On the first look at <a href="http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet" rel="noreferrer">http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet</a> I think that one important thing is missing (perhaps I overlooked this one).
Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a</p>
<pre><code>SET NAMES utf8
</code></pre>
<p>query prior to any other query you send to the MySQL server.</p>
<p>If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using</p>
<pre><code>$db=new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
</code></pre>
<p>when initializing your db connection.</p>
|
<p>For better unicode correctness, you should use utf8_unicode_ci (though the documentation is a little vague on the differences). You should also make sure the following Mysql flags are set correctly -</p>
<ul>
<li>default-character-set=utf8</li>
<li>skip-character-set-client-handshake //Important so the client doesn't enforce another encoding</li>
</ul>
<p>Those can be set in the mysql configuration file (under the [mysqld] tab) or at run time by sending the appropriate queries.</p>
| 17,007
|
<p>We've got dozens of versions of an SWF modified for different customers of a big Flash project, and now would have to replace some strings embedded in scripts in each copy. The FLA file for some of these is very difficult to locate or even missing (I inherited this mess and refactoring it is currently not an option).</p>
<p>Is there a (free) tool to replace strings used inside ActionScript? I tried swfmill to convert the files to XML and back but it can't handle international characters contained in the strings so I could get them only partially converted. Most of the strings were correctly extracted so another tool might do the job.</p>
|
<p>You could try Burak's <a href="http://www.buraks.com/uae/" rel="nofollow noreferrer">URL Action Editor</a> -- it says URL, but I'm pretty sure it lets you edit any text in a SWF. I haven't used it, but I have used his ActionScript Viewer, which works wonderfully.</p>
|
<p>tricky - it might not be any easier, but you could load the 'locked' swf into one you control, then spider through its objects until you hit TextBox, using some for...in loops - it'd be a long, arduous process to map them out then change them, especially if the previous developer didn't name things in a helpful way, but if it's a fairly simple .swf then it might be too bad...</p>
<p>Also, there's a mac-only utility for decompiling swfs that I remember a coworker swearing by, but I don't recall the name... anybody?</p>
| 14,552
|
<p>I have an application where a user has to remember and insert an unix timestamp like 1221931027. In order to make it easier to remember the key I like to reduce the number of characters to insert through allowing the characters [a-z]. So I'm searching for an algorithm to convert the timestamp to a shorter alphanum version and do the same backwards. Any hints?</p>
|
<p>You could just convert the timestamp into base-36.</p>
|
<p>convert the timestamp to HEX. That will generate a shorter alphanumeric number for you out of the timestamp. </p>
| 13,411
|
<p>I have a asp.net 2.0 web site with numerous asp:DropDownList controls.
The DropDownList control contains the standard info city, state, county etc... info.
In addition to the standard codes the site also has custom codes that the users can configure themselves.
For example a animal dropdown may contain the values Dog, Cat, Fish, ect...</p>
<p>I am popluating the DropDownList from a SQL 2005 table that I created e.g. tblCodes</p>
<p>Everything works great and users are able to add orders using the numerous DropDownList controls to choose items from the list.</p>
<p>The problem occurrs if a user wants to change one of their custom dropdowns. For example a user would like to change the verbage
on a animal type control from Dog to K9. This is where the problem starts.</p>
<p>For all new orders the drop down works fine. When the user retrieved an old order
I get the following error in the C# codebehind
"'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items."</p>
<p>What's happening is the old order has a database field value of Dog and the DropDownList no longer has Dog in its list since the user changed it to K9.</p>
<p>Any ideas on a workaround?<br>
Is there a way to make the asp:DropDownList accept items not seeded in its list?
Is there another control I could use?</p>
|
<p>I solved this exact same problem just two days ago. First, I moved the code that set the SelectedValue to a PreRender handler for the DropDownList. Then, I add logic to first check to see if the value is in the drop down list. If not, I add it.</p>
<p>Here's my code. ddSpecialty is my drop-down list, populated with "specialties" from the database. registration.Specialty is the specialty that the user chose, which may or may not be in the drop down, since that particular specialty may have been deleted since they last chose it.</p>
<pre><code>protected void ddSpecialty_PreRender(object sender, EventArgs e)
{
if (!ddSpecialty.Items.Contains(new ListItem(registration.Specialty)))
ddSpecialty.Items.Add(registration.Specialty);
ddSpecialty.SelectedValue = registration.Specialty;
}
</code></pre>
|
<p>Try this: </p>
<pre><code>if (ddl.Items.Contains(new ListItem(selectedFacility)))
ddl.SelectedValue = selectedFacility;
</code></pre>
| 5,952
|
<p>I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit.</p>
<p>Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?</p>
|
<p>You can do something like this (using the <a href="http://commons.apache.org/fileupload/" rel="nofollow noreferrer">Commons</a> library):</p>
<pre><code> public class UploadFileServiceImpl extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
response.setContentType("text/plain");
try
{
FileItem uploadItem = getFileItem(request);
if (uploadItem == null)
{
// ERROR
}
// Add logic here
}
catch (Exception ex)
{
response.getWriter().write("Error: file upload failure: " + ex.getMessage());
}
}
private FileItem getFileItem(HttpServletRequest request) throws FileUploadException
{
DiskFileItemFactory factory = new DiskFileItemFactory();
// Add here your own limit
factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
ServletFileUpload upload = new ServletFileUpload(factory);
// Add here your own limit
upload.setSizeMax(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
List<?> items = upload.parseRequest(request);
Iterator<?> it = items.iterator();
while (it.hasNext())
{
FileItem item = (FileItem) it.next();
// Search here for file item
if (!item.isFormField() &&
// Check field name to get to file item ...
{
return item;
}
}
return null;
}
}
</code></pre>
|
<p>You might try doing this in the doPost() method of your servlet </p>
<pre><code>multi = new MultipartRequest(request, dirName, FILE_SIZE_LIMIT);
if(submitButton.equals(multi.getParameter("Submit")))
{
out.println("Files:");
Enumeration files = multi.getFileNames();
while (files.hasMoreElements()) {
String name = (String)files.nextElement();
String filename = multi.getFilesystemName(name);
String type = multi.getContentType(name);
File f = multi.getFile(name);
if (f.length() > FILE_SIZE_LIMIT)
{
//show error message or
//return;
return;
}
}
</code></pre>
<p>This way you don't have to wait to completely process your HttpRequest and can return or show an error message back to the client side. HTH</p>
| 19,014
|
<p>In Model-View-Presenter pattern where should we write validations of user input.</p>
|
<p>Domain specific rules/validations should be in the Model. You can have a model.validate() to let you know if the rules are not violated. Look at Rails model (ActiveRecord) classes for a good implementation of this concept.</p>
<p>The View should make it difficult for the user to key in invalid input. So 'entering a string for a numeric value' class of input errors should be nipped before reaching the presenter.
There may be some duplication of validations between model and view. E.g. AttributeX must range between 1-100. This must be validated in the model.. at the same time you may want to slot in a spinner in the UI with the minValue and maxValue range set to 1-100.</p>
|
<p>Presenter....</p>
<p>The view should have have "widgets" that prevent invalid input where possible.</p>
| 26,759
|
<p>I have a bowling web application that allows pretty detailed frame-by-frame information entry. One thing it allows is tracking which pins were knocked down on each ball. To display this information, I make it look like a rack of pins:</p>
<pre>o o o o
o o o
o o
o</pre>
<p>Images are used to represent the pins. So, for the back row, I have four <em>img</em> tags, then a <em>br</em> tag. It works great... mostly. The problem is in small browsers, such as IEMobile. In this case, where there are may 10 or 11 columns in a table, and there may be a rack of pins in each column, Internet Explorer will try to shrink the column size to fit on the screen, and I end up with something like this:</p>
<pre>o o o
o
o o o
o o
o</pre>
<p>or</p>
<pre>o o
o o
o o
o
o o
o</pre>
<p>The structure is:</p>
<pre><code><tr>
<td>
<!-- some whitespace -->
<div class="..."><img .../><img .../><img .../><img .../><br/>...</div>
<!-- some whitespace -->
</td>
</tr>
</code></pre>
<p>There is no whitespace inside the inner div. If you look at <a href="http://www.bowlsk.com/games/view-series.html?series=13717" rel="nofollow noreferrer">this page</a> in a regular browser, it should display fine. If you look at it in IEMobile, it does not.</p>
<p>Any hints or suggestions? Maybe some sort of &nbsp; that doesn't actually add a space?</p>
<hr/>
<h3>Follow-up/Summary</h3>
<p>I have received and tried several good suggestions, including:</p>
<ul>
<li>Dynamically generate the whole image on the server. It is a good solution, but doesn't really fit my need (hosted on <a href="https://en.wikipedia.org/wiki/Google_App_Engine" rel="nofollow noreferrer">GAE</a>), and a bit more code than I'd like to write. These images could also be cached after the first generation.</li>
<li>Use CSS white-space declaration. It is a good standards-based solution, but it fails miserably in the IEMobile view.</li>
</ul>
<h3>What I ended up doing</h3>
<em>*hangs head and mumbles something*</em>
<p>Yes, that's right, a transparent GIF at the top of the div, sized to the width I need. End code (simplified) looks like:</p>
<pre><code><table class="game">
<tr class="analysis leave">
<!-- ... -->
<td> <div class="smallpins"><img class="spacer" src="http://seasrc.th.net/gif/cleardot.gif" /><br/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/pinsmall.gif"/><img src="/img/pinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/><img src="/img/nopinsmall.gif"/><br/><img src="/img/nopinsmall.gif"/></div> </td>
<!-- ... -->
</tr>
</table>
</code></pre>
<p>And CSS:</p>
<pre class="lang-css prettyprint-override"><code>div.smallpins {
background: url(/img/lane.gif) repeat;
text-align: center;
padding: 0;
white-space: nowrap;
}
div.smallpins img {
width: 1em;
height: 1em;
}
div.smallpins img.spacer {
width: 4.5em;
height: 0px;
}
table.game tr.leave td{
padding: 0;
margin: 0;
}
table.game tr.leave .smallpins {
min-width: 4em;
white-space: nowrap;
background: none;
}
</code></pre>
<p>P.S.: No, I will not be hotlinking someone else's clear dot in my final solution :)</p>
|
<p>You could try the css "nowrap" option in the containing div.</p>
<pre class="lang-css prettyprint-override"><code>{white-space: nowrap;}
</code></pre>
<p>Not sure how widely that is supported.</p>
|
<p>Would it not be easier if you do it like this?</p>
<pre><code><div id="container">
<div id="row1">
<img/><img/><img/><img/>
</div>
<div id="row2">
<img/><img/><img/>
</div>
<div id="row3">
<img/><img/>
</div>
<div id="row4">
<img/>
</div>
</div>
</code></pre>
<p>Whereby your CSS would handle the alignment?</p>
<pre><code>.container div{
text-align:center;
}
</code></pre>
| 11,868
|
<p>I am working on a ASP.net project created with local file system settings. I am using MVC and Jquery. Jquery is working fine when I run the application in debug mode i.e. in ASP.net Development server. I am trying to host the application in IIS 7. In hosted mode, it does not recognize Jquery and gives scripting error 'Jquery is undefined'. The locations of the script files is unchanged in both modes. Can anybody have any clue what can be the reason and how to solve this.</p>
<p>My code look like this;</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="../../Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<!-- YUI Styles -->
<link href="../../Content/reset.css" rel="stylesheet" type="text/css" />
<link href="../../Content/fonts.css" rel="stylesheet" type="text/css" />
<link href="../../Content/grids.css" rel="stylesheet" type="text/css" />
<!-- /YUI Styles -->
<link href="../../Content/knowledgebase.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//this hides the javascript warning if javascript is enabled
(function($) {
$(document).ready(function() {
$('#jswarning').hide();
});
})(jQuery);
</script>
<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
</code></pre>
<p>
....</p>
|
<p>Try using Firebug 'Net' tab to see if the file gets loaded.</p>
<p>You can also configure Firebug to fail on all errors and see when the error happens as compared to when jQuery gets loaded.</p>
|
<p>This usually occurs when you have malformed HTML or JavaScript.</p>
| 44,064
|
<p>I have two windows services running on the same machine. Both the services uses</p>
<p>private HttpListener listener;</p>
<p>I specify the baseURL as "<a href="http://IPAddress:8080/" rel="noreferrer">http://IPAddress:8080/</a>" & "<a href="http://IPAddress:8081/" rel="noreferrer">http://IPAddress:8081/</a>" respectively for each of the services. Then I do the needful and call</p>
<p>listener.Start();</p>
<p>The first service starts successfully at 8080 port. But when I now start the 2nd service,
I get HTTPListenerException "The process cannot access the file because it is being used by another process" for listener object.</p>
<p>Could anybody please tell me:
1) If it is possible to start two HTTP listeners on the same IIS at two different ports.
2) If yes, how can we achecive this?
3) Is there any other way of doing this?</p>
<p>For your information:
I am using C#.NET 2.0 and IIS 6.0 server.</p>
<p>Thanks & Regards,</p>
<p>Hari</p>
|
<p>Doesn't HttpListener work independently from IIS? Can you stop the IIS service and see what happens?</p>
<p>Or maybe port 8081 is <strong>used by another program</strong> or process. I suggest to try to set the port to another number. You could open a command line and execute the "<a href="http://en.wikipedia.org/wiki/Netstat" rel="nofollow noreferrer">netstat</a>" command to see <strong>if the port is used</strong> before starting your services.</p>
<p><a href="https://i.stack.imgur.com/uqVPV.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uqVPV.gif" alt="alt text"></a><br>
<sub>(source: <a href="http://simpleinformation213421.googlepages.com/netstat_ano.gif" rel="nofollow noreferrer">googlepages.com</a>)</sub> </p>
|
<p>It's usually a good idea to take a quick look at <a href="http://www.iana.org/assignments/port-numbers" rel="nofollow noreferrer">this</a> page when using port numbers...just to make sure a temp number you're trying to use isn't in use already.</p>
| 26,383
|
<p>I'm developing a compiler framework for .NET and want a flexible way of defining pipelines. I've considered the following options:</p>
<ul>
<li>WWF</li>
<li>Custom XML pipeline description</li>
<li>Custom pipeline description in code (using Nemerle's macros to define syntax for it)</li>
<li>Other code-based description</li>
</ul>
<p>Requirements:</p>
<ul>
<li>Must not depend on functionality only in the later versions of .NET (3+) since it's intended to be cross-platform and be used on top of managed kernels, meaning semi-limited .NET functionality.</li>
<li>Must allow conditional pipeline building, so you can specify that certain command line options will correspond to certain elements and orders.</li>
</ul>
<p>WWF would be nice, but doesn't meet the first requirement. The others would work but are less than optimal due to the work involved.</p>
<p>Does anyone know of a solution that will meet these goals with little to no modification?</p>
|
<p>If you know Ruby then a solution is to write a simple internal DSL that can generate whatever pipeline data types and reader/writer code you need. Generating XML is a quick way to get started. You can always change the DSL to generate another format later if required.</p>
<p>You may also want to look at the <a href="http://en.wikipedia.org/wiki/Phoenix_(compiler_framework)" rel="nofollow noreferrer">Microsoft Phoenix compiler</a> project for inspiration.</p>
|
<p>I know <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">Boo</a> let you have fun with the compiler, not sure if it does in the manner you want.</p>
| 8,746
|
<p>We have scalar functions in our database for returning things like "number of tasks for a customer" or "total invoice amount for a customer". </p>
<p>We are experimenting and looking to try to do this w/o stored procedures ... normally we would just call this function in our stored procedure and return it as a single value. </p>
<p>Is there a way to use or access scalar functions with LINQ to SQL? If so, I would be interested in see an example of how to ... if not, how would it be best to handle this type of situation ... if it is even doable.</p>
|
<p>LINQ-to-SQL supports use with UDFs, if that is what you mean. Just drag the UDF onto the designer surface and you're done. This creates a matching method on the data-context, marked <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.functionattribute.aspx" rel="noreferrer"><code>[Function(..., IsComposable=true)]</code></a> or similar, telling LINQ-to-SQL that it can use this in queries (note that EF doesn't support this usage).</p>
<p>You would then use it in your query like:</p>
<pre><code>var qry = from cust in ctx.Custs
select new {Id = cust.Id, Value = ctx.GetTotalValue(cust.Id)};
</code></pre>
<p>which will become TSQL something like:</p>
<pre><code>SELECT t1.Id, dbo.MyUdf(t1.Id)
FROM CUSTOMER t1
</code></pre>
<p>(or there-abouts).</p>
<p>The fact that it is composable means that you can use the value in queries - for example in a <code>Where()</code>/<code>WHERE</code> - and so reduce the data brought back from the server (although obviously the UDF will still need to be executed in some way).</p>
<p><a href="http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/608b6b08532ed7eb/4cf42640934bf45e#bfc790be1a24e37a" rel="noreferrer">Here's a similar example</a>, showing a pseudo-UDF at use on a data-context, illustrating that the C# version of the method is not used.</p>
<p>Actually, I'm currently looking at such UDFs to provide "out of model" data in a composable way - i.e. a particular part of the system needs access to some data (that happens to be in the same database) that isn't really part of the same model, but which I want to <code>JOIN</code> in interesting ways. I also have existing SPs for this purpose... so I'm looking at porting those SPs to tabular UDFs, which provides a level of contract/abstraction surrounding the out-of-model data. So because it isn't part of my model, I can only get it via the UDF - yet I retain the ability to compose this with my regular model.</p>
|
<p>I believe <a href="http://msdn.microsoft.com/en-us/library/bb386973.aspx" rel="nofollow noreferrer">this MSDN documentation</a> is what you're after (as part of <a href="http://msdn.microsoft.com/en-us/library/bb546175.aspx" rel="nofollow noreferrer">this wider topic of calling user-defined functions in LINQ to SQL</a>). Can't say I've done it myself, but it sounds right...</p>
| 35,577
|
<p>I've got a web page that's using jquery to receive some product information as people are looking at things and then displays the last product images that were seen. This is in a jquery AJAX callback that looks pretty much like this:</p>
<pre><code>if(number_of_things_seen > 10) {
$('#shots li:last-child').remove();
}
$('<li><img src="' + p.ProductImageSmall + '"></li>').prependTo('#shots');
</code></pre>
<p>However, it seems to leak quite a bit of memory. Visually, it does the right thing, but the footprint grows indefinitely.</p>
<p>Safari's DOM inspector shows the DOM is how I would expect it to be, but it seems to maintain references to every image that it has displayed (as seen in <a href="http://skitch.com/dlsspy/7m5k/img-leaks" rel="nofollow noreferrer">this screenshot</a> in case anyone is interested).</p>
<p>I've added</p>
<pre><code>$('#shots li:last-child img').remove();
</code></pre>
<p>to the removal statement to no noticable effect.</p>
<p>Is there some magic necessary to let the browser release some of this stuff?</p>
|
<p>Browsers are notorious for memory leaks. It sounds like the problem occurs when the page is left running for a long time. How about refreshing the page before it runs out of memory?</p>
<pre><code>window.setTimeout("location.reload()",1000*60*60);//refresh in an hour
</code></pre>
|
<p>how long have you observed this 'growing indefinitely' ? some implementations of garbage collectors don't necessarily give memory back to the OS so quickly if at all. can you distill what you are trying to do into a real simple test (eg, setting src of image over and over) w/o ajax or callbacks ? have you / can you try this w/ the other browsers ? </p>
| 43,632
|
<p>Is it possible for Eclipse to read stdin from a file?</p>
|
<h3>Pure Java</h3>
<p>You can redirect System.in with a single line of code:</p>
<pre><code>System.setIn(new FileInputStream(filename));
</code></pre>
<p>See <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setIn-java.io.InputStream-" rel="noreferrer">System.setIn()</a>.</p>
<h3>Eclipse config</h3>
<p>In Eclipse 4.5 or later, the launch configuration dialog can set System.in to read from a file. See <a href="http://www.eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file" rel="noreferrer">the announcement here</a>.</p>
<p><a href="https://i.stack.imgur.com/63POd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/63POd.png" alt="Common tab of Launch Configuration dialog" /></a></p>
|
<p>What I did was to create an Ant target and launch it as "Run External" from Eclipse, here are the steps:</p>
<ul>
<li>I have one input file to read from: <code>res\in.txt</code> and one for the output: <code>res\out.txt</code></li>
<li><p>Create a <code>build.xml</code> with the targets you require (this is just an example):</p>
<pre><code><project basedir="." default="run" name="Tests">
<target name="clean">
<delete dir="bin"/>
</target>
<target name="compile">
<mkdir dir="bin"/>
<javac srcdir="src" destdir="bin" includeantruntime="false"/>
</target>
<target name="build" depends="clean,compile"/>
<target name="run" depends="build">
<java classname="Main" input="res\in.txt" output="res\out.txt" classpath="bin" />
</target>
</project>
</code></pre></li>
<li><p>In Eclipse go to: <code>Run->External Tools->External Tools Configurations->Ant Build-> New Launch Configuration</code> use the following configuration:</p></li>
</ul>
<p><code>Section Main</code></p>
<p>Buildfile: <code>${workspace_loc:/Tests/build.xml}</code></p>
<p>Base Directory: <code>${workspace_loc:/Tests}</code></p>
<p>*Note: Tests is the name of my Eclipse project</p>
<p>Now you can run your project by clicking in the Run Extenal tool bar button and change the input or output files as you needed</p>
| 22,863
|
<p>Using <a href="http://search.cpan.org/dist/DBIx-Class/" rel="nofollow noreferrer">DBIx::Class</a> and I have a resultset which needs to be filtered by data which cannot be generated by SQL. What I need to do is something effectively equivalent to this hypothetical example:</p>
<pre><code>my $resultset = $schema->resultset('Service')->search(\%search);
my $new_resultset = $resultset->filter( sub {
my $web_service = shift;
return $web_service->is_available;
} );
</code></pre>
<p>Reading through the docs gives me no clue how to accomplish a strategy like this.</p>
|
<p>You can’t really, due to the goals for which DBIC result sets are designed:</p>
<ul>
<li>They compile down to SQL and run a single query, which they do no earlier than when you ask for results.</li>
<li>They are composable.</li>
</ul>
<p>Allowing filtering by code that runs on the Perl side would make it extremely hairy to achieve those properties, and would hide the fact that such result sets actually run N queries when composed.</p>
<p>Why do you want this, anyway? Why is simply retrieving the results and filtering them yourself insufficient?</p>
<ul>
<li><p><b>Encapsulation</b>? (Eg. hiding the filtering logic in your business logic layer but kicking off the query in the display logic layer.) Then write a custom ResultSet subclass that has an accessor that runs the query and does the desired filtering.</p></li>
<li><p><b>Overhead</b>? (Eg. you will reject most results so you don’t want the overhead of creating objects for them.) Then use HashRefInflator.</p></li>
</ul>
|
<p>If you filter the results and end up with a list of rows you can create a new resultset like this: <a href="http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows" rel="nofollow">http://search.cpan.org/~abraxxa/DBIx-Class-0.08127/lib/DBIx/Class/Manual/Cookbook.pod#Creating_a_result_set_from_a_set_of_rows</a>.</p>
<p>This may keep things consistent in keeping the results as a resultset but I imagine you would not be able to chain it or use any other resultset methods on it.</p>
| 34,155
|
<p>I'm looking for an easy way to debug RESTful services. For example, most webapps can be debugged using your average web browser. Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST.</p>
<p>I am not looking to automate tests. I'd like to run new services through a quick sanity check, ideally without having to writing my own client.</p>
|
<p>Use an existing 'REST client' tool that makes it easy to inspect the requests and responses, like <a href="https://github.com/wiztools/rest-client" rel="noreferrer">RESTClient</a>.</p>
|
<p>Aside from using one of the tools in Peter Hilton's response, I would have to say that scripting the tests with LWP or some similar tool may be your only option. You <em>could</em> bypass the use of LWP by just opening a socket, sending a raw HTTP request in and examining what you get in return. But as far as I know, there are a dearth of testing tools for this sort of domain-- most look at this problem-space primarily from the lens of a web-site developer, and for them the browser is enough of a testing platform.</p>
| 20,012
|
<p>I'm thinking about making a networked game. I'm a little new to this, and have already run into a lot of issues trying to put together a good plan for dead reckoning and network latency, so I'd love to see some good literature on the topic. I'll describe the methods I've considered.</p>
<p>Originally, I just sent the player's input to the server, simulated there, and broadcast changes in the game state to all players. This made cheating difficult, but under high latency things were a little difficult to control, since you dont see the results of your own actions immediately.</p>
<p><a href="http://www.gamasutra.com/features/19970919/aronson_01.htm" rel="noreferrer">This GamaSutra article</a> has a solution that saves bandwidth and makes local input appear smooth by simulating on the client as well, but it seems to throw cheat-proofing out the window. Also, I'm not sure what to do when players start manipulating the environment, pushing rocks and the like. These previously neutral objects would temporarily become objects the client needs to send PDUs about, or perhaps multiple players do at once. Whose PDUs would win? When would the objects stop being doubly tracked by each player (to compare with the dead reckoned version)? Heaven forbid two players engage in a sumo match (e.g. start pushing each other).</p>
<p><a href="http://www.gamedev.net/reference/articles/article1370.asp" rel="noreferrer">This gamedev.net bit</a> shows the gamasutra solution as inadequate, but describes a different method that doesn't really fix my collaborative boulder-pushing example. Most other things I've found are specific to shooters. I'd love to see something more geared toward games that play like SNES Zelda, but with a little more physics / momentum involved.</p>
<ul>
<li>Note: I'm not asking about physics simulation here -- other libraries have that covered. Just strategies for making games smooth and reactive despite network latency.</li>
</ul>
|
<p>Check out how Valve does it in the Source Engine: <a href="http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking" rel="noreferrer">http://developer.valvesoftware.com/wiki/Source_Multiplayer_Networking</a></p>
<p>If it's for a first person shooter you'll probably have to delve into some of the topics they mention such as: prediction, compensation, and interpolation.</p>
|
<p>Check out Networking education topics at the XNA Creator's Club website. It delves into topics such as network architecture (peer to peer or client/server), Network Prediction, and a few other things (in the context of XNA of course). This may help you find the answers you're looking for.</p>
<p><a href="http://creators.xna.com/education/catalog/?contenttype=0&devarea=19&sort=1" rel="nofollow noreferrer">http://creators.xna.com/education/catalog/?contenttype=0&devarea=19&sort=1</a></p>
| 6,404
|
<p>Is there a way that you can have SERVEROUTPUT set to ON in sqlplus but somehow repress the message "PL/SQL procedure successfully completed" that is automatically generated upon completed execution of a plsql procedure?</p>
|
<p>Use the command:</p>
<pre><code>SET FEEDBACK OFF
</code></pre>
<p>before running the procedure. And afterwards you can turn it back on again:</p>
<pre><code>SET FEEDBACK ON
</code></pre>
|
<p>This has worked well for me in sqlplus, but I did just notice that "set feedback off" suppresses errors in Sql Developer (at least version 17.2.0.188). Just something to be aware of if you use Sql Developer:</p>
<pre><code>create or replace procedure test_throw_an_error as buzz number; begin dbms_output.put_line('In test_throw_an_error. Now, to infinity!'); buzz:=1/0; end;
/
set serveroutput on
set feedback off
exec test_throw_an_error;
exec dbms_output.put_line('Done, with feedback off');
set feedback on
exec test_throw_an_error;
exec dbms_output.put_line('Done, with feedback on');
</code></pre>
<p>Result:</p>
<pre><code>Procedure TEST_THROW_AN_ERROR compiled
In test_throw_an_error. Now, to infinity!
Done, with feedback off
In test_throw_an_error. Now, to infinity!
Error starting at line : 11 in command -
BEGIN test_throw_an_error; END;
Error report -
ORA-01476: divisor is equal to zero
ORA-06512: at "ECTRUNK.TEST_THROW_AN_ERROR", line 1
ORA-06512: at line 1
01476. 00000 - "divisor is equal to zero"
*Cause:
*Action:
Done, with feedback on
PL/SQL procedure successfully completed.
</code></pre>
| 31,173
|
<p>My application needs to set cookies for specific paths in the application. For example (in php):</p>
<pre><code>setcookie(*cookie_name*,*value*,*date*,"/subpath/subpath/unique_name");
setcookie(*cookie_name*,*value*,*date*,"/subpath/subpath/another unique name");
</code></pre>
<p>Oddly enough, the first setcookie works fine. The second doesn't generate an error and when I view my cookies in Firefox the cookie is there with the correct values. However, I can't access it in my code. I believe the whitespaces are causing the trouble but I haven't found any documentation or specs on how cookie paths should be encoded. </p>
<p>Has anyone encountered this problem before? Does anyone know how to deal with special characters in cookie paths?</p>
|
<p>I see no problem with spaces in cookies.<br>
Maybe you should check how you read back your value...<br>
My read routine is:</p>
<pre><code>function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
</code></pre>
<p>Obviously, the only thing you have to encode is semi-colon.</p>
|
<p>No access to a webserver atm. You haven't tried one of these?</p>
<pre><code>setcookie(*cookie_name*,*value*,*date*, "/subpath/subpath/another unique name/");
setcookie(*cookie_name*,*value*,*date*, urlencode("/subpath/subpath/another unique name"));
setcookie(*cookie_name*,*value*,*date*, rawurlencode("/subpath/subpath/another unique name"));
</code></pre>
<p>I believe different browsers and web servers might treat these differently. I hope you don't have to use whitespace in the url.</p>
| 43,906
|
<p>While developing products, we often need to create proprietary tools to test some of their unique features or diagnose problems. In fact the tools can be at lest as interesting as the products themselves, and some of our internal groups have asked for copies of them.</p>
<p>So, aside from the obvious business-driven rules (<em>e.g.</em> don't retrieve sensitive data), <strong>what do you differently when you build personal or internal tools, as opposed to for-sale products, and why?</strong></p>
<p>What's more (or less) important to you in internal tools, and do you consider overall value to the company when you build them?</p>
<p>Thanks for your thoughts!</p>
|
<ol>
<li>First, internal tools are always developed quick and dirty. Almost no testing - it just has to do the work.</li>
<li>UI is not as important as with a customer-facing app.</li>
<li>Internal tool can use internal/private/proprietary knowledge of the products and frameworks they test. For example, our last product bypassed part of our published API and used a non-documented web service call to achieve better results.</li>
<li>This is an important point,but a losing battle: <strong>NEVER EVER</strong> leave internal tools with a customer.
As a consultant, I sometimes had to use and even develop those tools in the field. I try to hide it from my clients, but from time to time, they demand I leave the tool with them (or worse, call the sales rep and ask for that "magic tool"). You don't want customers judging your entire company's production level based on tools build according to points 1-3.</li>
</ol>
|
<p>Since the diagnostics I build are usually very special-purpose, I tend to provide more options and built-in examples than I would for customer-facing products. In other words, I assume the user is more familiar with the technology than a customer would generally be, and I provide more ability to tweak the way the tool operates without worrying that it might overwhelm the user. But I also try to make it satisfy 80% of the use cases without much "help" from the user.</p>
| 34,745
|
<p>I need to make my dropdown menu apprear over the top of a flash movie, how is this done cross browser?</p>
<p>It can be done, IBM do it: <a href="http://www.ibm.com/us/" rel="noreferrer">http://www.ibm.com/us/</a> so do GE: <a href="http://www.ge.com/" rel="noreferrer">http://www.ge.com/</a></p>
<p>Setting the the WMODE to transparent doesn't work for Firefox</p>
<p>Putting it into an Iframe doesnt work below IE7</p>
<p>Any one know the best way to achieve this?</p>
|
<p>Set the wmode to transparent and if necessary, use z-index as you would on any other element, that really should work for Firefox too.</p>
|
<p>Firefox for linux shows flash on top of everything. Regardles of wmode or z-index.</p>
<p>EDIT:
I just found out that the Linux issue described above can be "fixed".</p>
<p>You need to add an iframe with a z-index between the swf and the layer you want to put on top of it. The iframe needs to have style="display:none" initially and you must use javascript to set display:block on it after the flash plugin has initialized. The Iframe will hide all swfs that are below it on linux.</p>
| 30,135
|
<p>I have a struts2 application with a single page that may show one of a number of values stored in a database. The application is for a school with many departments and each department has many programs. The department page is accessed using a url like this</p>
<pre><code>department.action?id=2
</code></pre>
<p>and the DepartmentAction will load the Department with id = 2 for display. All this is fine if the user is just browsing around the site but it gets uncomfortable if I want to provide a link to say the Engineering department in the newspapers. The link will have to be www.myschooldomain.com/department.action?id=2. I see a number of problems with this.</p>
<p>First, it is not user friendly. Second, it is prone to be broken because the departments are dynamically maintained and the id for a department could change without warning making the link unstable.</p>
<p>I would prefer to print a url like this: www.myschooldomain.com/department/engineering and have that somehow go to department.action?id=2.</p>
<p>My thoughts so far: create an action that will parse the url for the department name at the end then look it up by name. Maybe I could add a friendlyurl field to the database for each department.</p>
<p>But the question is: Is there a better way to do this in struts2?</p>
<p>Thanks.</p>
<p><strong>Update (May 2009):</strong> I just happened to stumble back over this question and thought that I would say what I did to solve it. </p>
<p>I created a new package in the struts.xml called departments. In this package there is only one action mapped to *. So it catches all requests to mydomain.com/departments/anything.html.</p>
<p>In the action class I simply parse the url and look for the part between departments/ and .html and that is the name of the department so I can do a lookup in the database for it. This has been working fine for almost 5 months now and I have implemented it for other areas of the site.</p>
|
<p>This is normally done by mapping a servlet to, in your case '/department', and then using the <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo()" rel="nofollow noreferrer">path</a> information (e.g., '/engineering') within the servlet to determine the ID. </p>
<p>Since the Struts2 dispatcher doesn't implement this behavior, it might be simplest to write your own servlet. This servlet would be configured with a map of valid "friendly" names to the unfriendly numeric identifiers. This could be an actual <code>Map</code> or it could be done with a database finder method. </p>
<p>The result of <code>getPathInfo()</code> would be used to look up the ID, and the request would be <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)" rel="nofollow noreferrer">forwarded</a> to the department.action. Handle the <code>null</code> case too, which means the user is trying to browse the <code>/departments/</code> directory.</p>
|
<p>This is normally done by mapping a servlet to, in your case '/department', and then using the <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getPathInfo()" rel="nofollow noreferrer">path</a> information (e.g., '/engineering') within the servlet to determine the ID. </p>
<p>Since the Struts2 dispatcher doesn't implement this behavior, it might be simplest to write your own servlet. This servlet would be configured with a map of valid "friendly" names to the unfriendly numeric identifiers. This could be an actual <code>Map</code> or it could be done with a database finder method. </p>
<p>The result of <code>getPathInfo()</code> would be used to look up the ID, and the request would be <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)" rel="nofollow noreferrer">forwarded</a> to the department.action. Handle the <code>null</code> case too, which means the user is trying to browse the <code>/departments/</code> directory.</p>
| 28,043
|
<p>Is there any built-in utility or helper to parse <code>HttpContext.Current.User.Identity.Name</code>, e.g. <code>domain\user</code> to get separately domain name if exists and user?</p>
<p>Or is there any other class to do so?</p>
<p>I understand that it's very easy to call <code>String.Split("\")</code> but just interesting</p>
|
<p>This is better (<em>easier to use, no opportunity of <code>NullReferenceExcpetion</code> and conforms MS coding guidelines about treating empty and null string equally</em>):</p>
<pre><code>public static class Extensions
{
public static string GetDomain(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(0, stop) : string.Empty;
}
public static string GetLogin(this IIdentity identity)
{
string s = identity.Name;
int stop = s.IndexOf("\\");
return (stop > -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>IIdentity id = HttpContext.Current.User.Identity;
id.GetLogin();
id.GetDomain();
</code></pre>
<p>This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.</p>
|
<p>Seems like a problem made to be solved by regular expressions:</p>
<pre><code>public static class UserExtensions
{
public static string GetDomain(this IIdentity identity)
{
Regex.Match(identity.Name, ".*\\\\").ToString()
}
public static string GetLogin(this IIdentity identity)
{
return Regex.Replace(identity.Name, ".*\\\\", "");
}
}
</code></pre>
| 45,474
|
<p>I'm going to make an application (in Swing) that uses a tree to visualize a data structure (JTree). A tree will be on the left side of a window. The user will be able to browse a tree. The parameters of every tree node will be displayed on the right side of the window.
The example windows will be looking like this</p>
<pre><code>===========================
| tree panel | data panel |
| | |
| | |
| | |
---------------------------
</code></pre>
<p>The problem arises when a user wants to change that data. when should I validate them ?
The easy approach is to open a new modal dialog (JDialog) and let the user to change this data in it. Validation of data would take place in an "ok" button listener method but this is a little clunky. I would like to allow the user to edit those data right in the data panel. In that case when should I validate them?</p>
<p>Is there a pattern of such solution in Swing?</p>
<p>Or any online tutorial how to do it?</p>
<p>Thanks in advance.</p>
|
<p>Dialogs are bad.</p>
<p>Immediately discard any complete nonsense input immediately. For instance, typing a letter in the numerical field (use Document filters). Don't beep. Don't require any particular commit step. You may have retain partially entered data.</p>
|
<p>I'm not totally sure what you're after, but..</p>
<p>You could maybe add this "ok" button (or "commit changes" or whatever) to data panel and when the button would be pressed, you would validate the data and save the changes if the changes are valid?</p>
<p>(So you'd have editable components at the data panel)</p>
<p>Edit: if this wasn't good, could you clarify me a bit:</p>
<ul>
<li>Is the data panel showing data for one item of the tree at time?</li>
<li>What kind of data is there to change (and to validate)</li>
</ul>
<p>Anyway, if you want to validate straight the changes made to an edit component (for example JTextField), you can use for example</p>
<ul>
<li>Formatted text fields, see <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html" rel="nofollow noreferrer">How to Use Formatted Text Fields</a></li>
<li>For more general validating, see <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/InputVerifier.html" rel="nofollow noreferrer">InputVerifier</a></li>
<li>More ideas, see <a href="http://java.sun.com/developer/JDCTechTips/2001/tt1120.html" rel="nofollow noreferrer">Validating Numerical Input in a JTextField</a> (concentrates of numerical input but usable for other purposes also)</li>
</ul>
| 39,159
|
<p>I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:</p>
<pre><code>SerialTestDataContext db = new SerialTestDataContext();
relation_table row = db.relation_tables.First();
MemoryStream memStream = new MemoryStream();
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(memStream, row);
Console.WriteLine("Serilized successfully");
TestTable tt = new testTable();
tt.data = new System.Data.Linq.Binary(memStream.ToArray());
db.testTables.InsertOnSubmit(tt);
db.SubmitChanges();
Console.WriteLine("Inserted successfully");
</code></pre>
<p>Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?</p>
|
<p>With linq-to-sql (from tags), then yes: you can mark the dmbl as serializable, which uses the [DataContract]/[DataMember] approach. You do this by setting the "Serialization Mode" to "Unidirectional" in the designer, or you can do it in the dbml itself:</p>
<pre><code><Database ... Serialization="Unidirectional">...
</code></pre>
<p>You can then use DataContractSerializer or NetDataContractSerializer to write this (as xml or binary respectively). If you need something portable (i.e. not MS/.NET specific), then <a href="http://code.google.com/p/protobuf-net/" rel="noreferrer">protobuf-net</a> will serialize data-contracts using the "protocol buffers" spec.</p>
|
<p>Linq classes are partial classes. You can change the definition to mark the classes as implementing <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx" rel="nofollow noreferrer">ISerializable</a> and then provide the code...</p>
<pre><code>public partial class User : ISerializable
{
// implement GetObjectData here
}
</code></pre>
<p>There might still be issues with deserialization, however (I'm not 100% on this). An alternative is to use xml serialization and implement <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="nofollow noreferrer">IXmlSerializable</a>, which has methods for serializing and deserializing, allowing you to control the entire process...</p>
| 43,059
|
<p>I have a WCF service, hosted in IIS 7.0 that needs to run database queries. In order to get the right permissions to do this I am impersonating within the service as follows:</p>
<h3>Code</h3>
<pre><code>[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public void MyOperation(int arg)
</code></pre>
<h3>Configuration</h3>
<pre><code><behavior name="ReceivingServiceBehavior">
<!-- Other behaviors -->
<serviceAuthorization impersonateCallerForAllOperations="true" />
</behavior>
</code></pre>
<p>When I try to connect and run my query I get the following:</p>
<pre>
Exception - System.IO.FileLoadException: Could not load file or
assembly 'System.Transactions, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. Either a
required impersonation level was not provided, or the provided
impersonation level is invalid. (Exception from HRESULT: 0x80070542)
File name: 'System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Fourth.GHS.MessageRelay.RegistrationDBStorage.FindRegistration(SystemKey key)
</pre>
|
<p>If you want the SQL queries to be executed as the impersonated identity, you may actually need to enable delegation to your SQL server. Check out this article for more info:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms730088.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms730088.aspx</a></p>
|
<p>Hmmm... I don't know. However, you could force the dll to load early on. Since you are using IIS, this would presumably be in your global.asax - something like creating and throwing away a TransactionScope should do the job...</p>
| 35,068
|
<p>C#: How do you pass an object in a function parameter?</p>
<pre><code>public void MyFunction(TextBox txtField)
{
txtField.Text = "Hi.";
}
</code></pre>
<p>Would the above be valid? Or?</p>
|
<p>So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods.</p>
|
<p>For any reference-type, that is fine - you have passed the <em>reference</em> to the object, but there is only one object, so changes are visible to the caller.</p>
<p>The main time that <em>won't</em> work is for "structs" (value-types) - but they really shouldn't be mutable anyway (i.e. they shouldn't really have editable properties).</p>
<p>If you <em>needed</em> to do this with a struct, you could add "ref" - i.e.</p>
<pre><code>public void MyFunction(ref MyMutableStruct whatever)
{
whatever.Value = "Hi."; // but avoid mutable structs in the first place!
}
</code></pre>
| 34,833
|
<p>Some iPhone applications, such as Pandora seem to directly manipulate the hardware volume and respond to physical volume button. How is this done?</p>
<p>AudioSessionServices allows you to get the current hardware output volume with the <code>kAudioSessionProperty_CurrentHardwareOutputVolume</code> property, but it is (allegedly) read-only.</p>
|
<p>They use the MPVolumeView, simple add it and it's makes the rest when the user touch it. Note: Doesn't work in iPhone Simulator. I think the release note also mentioned do not use it direct in Interface Builder. </p>
<pre><code>MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(25, 378, 270, 30)];
[self.view addSubview:volumeView];
[volumeView release];
</code></pre>
|
<p>Here is another (complete) example of setting the hardware volume AND retrieving the volume after pressing the hardware keys:</p>
<pre><code>// AVAudiosession Delegate Method
- (void)endInterruptionWithFlags:(NSUInteger)flags
{
// When interruption ends - set the apps audio session active again
[[AVAudioSession sharedInstance] setActive:YES error:nil];
if( flags == AVAudioSessionInterruptionFlags_ShouldResume ) {
// Resume playback of song here!!!
}
}
// Hardware Button Volume Callback
void audioVolumeChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void *inData)
{
UISlider * volumeSlider = (__bridge UISlider *) inUserData;
Float32 newGain = *(Float32 *)inData;
[volumeSlider setValue:newGain animated:YES];
}
// My UISlider Did Change Callback
- (IBAction)volChanged:(id)sender
{
CGFloat oldVolume = [[MPMusicPlayerController applicationMusicPlayer] volume];
CGFloat newVolume = ((UISlider*)sender).value;
// Don't change the volume EVERYTIME but in discrete steps.
// Performance will say "THANK YOU"
if( fabsf(newVolume - oldVolume) > 0.05 || newVolume == 0 || newVolume == 1 )
[[MPMusicPlayerController applicationMusicPlayer] setVolume:newVolume];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// Set the volume slider to the correct value on appearance of the view
volSlider.value = [[MPMusicPlayerController applicationMusicPlayer] volume];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// Activate the session and set teh delegate
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[AVAudioSession sharedInstance] setDelegate:self];
// Create a customizable slider and add it to the view
volSlider = [[UISlider alloc] init];
CGRect sliderRect = volSlider.frame;
sliderRect.origin.y = 50;
sliderRect.size.width = self.view.bounds.size.width;
volSlider.frame = sliderRect;
[volSlider addTarget:self action:@selector(volChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:volSlider];
// Regoister the callback to receive notifications from the hardware buttons
AudioSessionAddPropertyListener (
kAudioSessionProperty_CurrentHardwareOutputVolume ,
audioVolumeChangeListenerCallback,
(__bridge void*)volSlider
);
[...]
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Remove the Hardware-Button-Listener
AudioSessionRemovePropertyListenerWithUserData(
kAudioSessionProperty_CurrentHardwareOutputVolume,
audioVolumeChangeListenerCallback,
(__bridge void*)volSlider);
}
</code></pre>
| 26,490
|
<p>Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.</p>
<p>Edit: Instructors and Students <em>must</em> be the same; instructors could be students in other classes, and vice versa.</p>
<p>I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.</p>
|
<p>There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance:</p>
<pre><code>class Person < ActiveRecord::Base; end # btw, model names are singular in rails
class Student < Person; end
class Instructor < Person; end
</code></pre>
<p>then</p>
<pre><code>class Course < ActiveRecord::Base # renamed here because class Class already exists in ruby
has_many :students
has_many :instructors
end
</code></pre>
<p>Just remember that for single table inheritance to work, you need a <code>type</code> column in the <code>people</code> table.</p>
<h3>using an association model might solve your issue</h3>
<pre><code>class Course < ActiveRecord::Base
has_many :studentships
has_many :instructorships
has_many :students, :through => :studentships
has_many :instructors, :through => :instructorships
end
class Studentship < ActiveRecord::Base
belongs_to :course
belongs_to :student, :class_name => "Person", :foreign_key => "student_id"
end
class Instructorship < ActiveRecord::Base
belongs_to :course
belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id"
end
</code></pre>
|
<p>in my case i have Asset and User model
Asset can be create by an user and could be assigned to a user
and User can create many assets and can have many Asset
solution of my problem was
asset.rb</p>
<pre><code>class Asset < ActiveRecord::Base
belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User'
end
</code></pre>
<p>and </p>
<pre><code>user.rb
class User < ActiveRecord::Base
has_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'
has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'
end
</code></pre>
<p>so your solution could be</p>
<pre><code>class Course < ActiveRecord::Base
has_many :students ,:foreign_key => 'student_id', :class_name => 'Person'
has_many :teachers, :foreign_key => 'teacher_id', :class_name => 'Person'
end
</code></pre>
<p>and </p>
<pre><code>class Person < ActiveRecord::Base
belongs_to :course_enrolled,:class_name=>'Course'
belongs_to :course_instructor,:class_name=>'Course'
end
</code></pre>
| 12,156
|
<p>MSTest produces an XML file with a .trx extension containing test results.</p>
<p>If I have a .trx file on a machine without Visual Studio installed, I get prompted to "Use the Web Service..." or "Select from a list...", which is expected.
If I have a .trx file on my development machine and I open it, it opens in Visual Studio, which is expected.
If I click a link on a web page or in an email which gets a .trx file from my build server, it ALWAYS opens the XML in IE.</p>
<p>How do I configure IE (or IIS on the build server) to open the remote .trx file in Visual Studio, if it's installed, or prompt if it's not? </p>
<p>UPDATE: If I rename the .trx file on the server and give it various extensions (eg. .bmp, .msi, .txt, .zip), it still opens as XML in IE, so it's clearly going by the content of the file and not the declared MIME type.</p>
|
<p>It should be a matter of defining a MIME type for the file (i.e. "application/x-test") If I'm not mistaken, if the MIME type is not provided by the server, the client has to guess (and if it looks like a XML file, it gets treated like a XML file). I could be mistaken, but it is worth a try. You can access the MIME list for IIS from the MMC console snap-in for IIS by bringing up the properties of the server (not any of the configured sites)</p>
|
<p>Have you tried changing the file association for .xml to Visual Studio instead of IE? I'm using Win7 and IE8 and I can set the associations here:
Internet Options > Programs > Set Programs > Default Programs\Set Associations</p>
| 27,998
|
<p>In a world where manual memory allocation and pointers still rule (Borland Delphi) I need a general solution for what I think is a general problem:</p>
<p>At a given moment an object can be referenced from multiple places (lists, other objects, ...). Is there a good way to keep track of all these references so that I can update them when the object is destroyed?
</p>
|
<p>If you want to notify others of changes you should implement the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">"Observer Pattern"</a>. Delphi has already done that for you for TComponent descendants. You can call the TComponent.FreeNotification method and have your object be notified when the other component gets destroyed. It does that by calling the Notification method. You can remove yourself from the notification list by calling TComponent.RemoveFreeNotification. Also see <a href="http://delphi.about.com/library/bluc/text/uc083101a.htm" rel="nofollow noreferrer">this page</a>.</p>
<p>Most Garbage Collectors do not let you get a list of references, so they won't help in this case. Delphi can do reference counting if you would use interfaces, but then again you need to keep track of the references yourself.</p>
|
<p>Are you trying to keep track of who's referencing an object so you can clear those references when the object is destroyed, or are you trying to keep track of when it's safe to destroy the object?</p>
<p>If the latter then it sounds like you're looking for a garbage collector. I've never dealt with Delphi so I don't know if there are GCs for it you can use, but I'd be surprised if there weren't.</p>
<p>If the former then a GC probably wouldn't help. If Delphi supports OOP/inheritence (I honestly don't know if it does) you could do something like this (pseudocode):</p>
<pre><code>// Anything that will use one of your tracked objects implements this interface
interface ITrackedObjectUser {
public void objectDestroyed(TrackedObject o);
}
// All objects you want to track extends this class
class TrackedObject {
private List<ITrackedObjectUser> users;
public void registerRef(ITrackedObjectUser u) {
users.add(u);
}
public void destroy() {
foreach(ITrackedObjectUser u in users) {
u.objectDestroyed(this);
}
}
}
</code></pre>
<p>Basically, whenever you add one of your tracked objects to a collection that collection would register itself with that object. When the object is being destroyed (I figure you'd call destroy() in the object's destructor) then the object signals the collection that it's being destroyed so the collection can do whatever it needs to.</p>
<p>Unfortunately, this isn't really a good solution if you want to use build-in collections. You'd have to write your own collection objects (they could just wrap build-in ones though). And it would require to to make sure you're registering everywhere you want to track the object. It's not what I would consider a "happy" solution, though for small projects it probably wouldn't be too bad. I'm mainly hoping this idea will help spawn other ideas. :)</p>
| 3,874
|
<p>Can anyone explain this behavior or how to get around it?</p>
<p>If you execute this query:</p>
<pre><code>select *
from TblA
left join freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
inner join DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
</code></pre>
<p>It will be very very very slow.</p>
<p>If you change that query to use two inner joins instead of a left join, it will be very fast. If you change it to use two left joins instead of an inner join, it will be very fast.</p>
<p>You can observe this same behavior if you use a sql table variable instead of the freetexttable as well. </p>
<p>The performance problem arises any time you have a table variable (or freetexttable) and a table in a different database catalog where one is in an inner join and the other is in a left join.</p>
<p>Does anyone know why this is slow, or how to speed it up?</p>
|
<p>A general rule of thumb is that OUTER JOINs cause the number of rows in a result set to <em>increase,</em> while INNER JOINs cause the number of rows in a result set to <em>decrease.</em> Of course, there are plenty of scenarios where the opposite is true as well, but it's more likely to work this way than not. What you want to do for performance is keep the size of the result set (working set) as small as possible for as long as possible. </p>
<p>Since both joins match on the first table, changing up the order won't effect the accuracy of the results. Therefore, you probably want to do the INNER JOIN before the LEFT JOIN:</p>
<pre><code>SELECT *
FROM TblA
INNER JOIN DifferentDbCatalog.dbo.TblC on TblA.ID = TblC.TblAID
LEFT JOIN freetexttable ( TblB, *, 'query' ) on TblA.ID = [Key]
</code></pre>
<p>As a practical matter, the query optimizer <em>should</em> be smart enough to compile to use the faster option, regardless of which order you specified for the joins. However, it's good practice to pretend that you have a dumb query optimizer, and that query operations happen in order. This helps future maintainers spot potential errors or assumptions about the nature of the tables.</p>
<p>Because the optimizer should re-write things, this probably isn't good enough to fully explain the behavior you're seeing, so you'll still want to <em>examine the execution plan</em> used for each query, and probably add an index as suggested earlier. This is still a good principle to learn, though.</p>
|
<p>Index the field you use to perform the join.</p>
<p>A good rule of thumb is to assign an index to any commonly referenced <a href="http://en.wikipedia.org/wiki/Foreign_key" rel="nofollow noreferrer">foreign</a> or <a href="http://en.wikipedia.org/wiki/Candidate_key" rel="nofollow noreferrer">candidate keys</a>.</p>
| 6,929
|
<p><strong>Problem:</strong></p>
<p>Ajax suggest-search on [<em>n</em>] ingredients in recipes. That is: match recipes against multiple ingredients.</p>
<p>For instance: <code>SELECT Recipes using "flower", "salt"</code> would produce: <code>"Pizza", "Bread", "Saltwater"</code> and so forth.</p>
<p><strong>Tables:</strong></p>
<pre><code>Ingredients [
IngredientsID INT [PK],
IngredientsName VARCHAR
]
Recipes [
RecipesID INT [PK],
RecipesName VARCHAR
]
IngredientsRecipes [
IngredientsRecipesID INT [PK],
IngredientsID INT,
RecipesID INT
]
</code></pre>
<p><strong>Query:</strong></p>
<pre><code>SELECT
Recipes.RecipesID,
Recipes.RecipesName,
Ingredients.IngredientsID,
Ingredients.IngredientsName
FROM
IngredientsRecipes
INNER JOIN Ingredients
ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID
INNER JOIN Recipes
ON IngredientsRecipes.RecipesID = Recipes.RecipesID
WHERE
Ingredients.IngredientsName IN ('salt', 'water', 'flower')
</code></pre>
<p>I am currently constructing my query using ASP.NET C# because of the dynamic nature of the <code>WHERE</code> clause.</p>
<p>I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster.</p>
<p>Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing?</p>
<p>I am thinking along the lines of temporary tables:</p>
<p><strong>Step one</strong>: <code>SELECT IngredientsID FROM Ingredients</code> and <code>INSERT INTO temp-table</code></p>
<p><strong>Step two</strong>: <code>SELECT RecipesName FROM Recipes</code> joined with <code>IngredientsRecipes</code> joined with <code>temp-table.IngredientsID</code></p>
|
<p>You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a <a href="http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters" rel="nofollow noreferrer">table value parameter</a>. </p>
<p>If you're using SQL Server 2005, you can use <a href="http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx" rel="nofollow noreferrer">XML to simulate this capability</a></p>
<p>If you're using something earlier than 2005, you need to concatenate the ids in a single string and create a UDF to parse them.</p>
|
<p>Depending on how you are processing the input ingredients I think this current method has some sql injection risks. </p>
<p>You could append the ingrediant name to the join conditions which may be quicker.</p>
<p>You could also hash combinations of ingredients for receipes for a quick lookup.</p>
| 17,433
|
<p>As a beginner to TDD I am trying to write a test that assumes a property has had its value changed on a PropertyGrid (C#, WinForms, .NET 3.5).</p>
<p>Changing a property on an object in a property grid does not fire the event (fair enough, as it's a UI raised event, so I can see why changing the owned object may be invisible to it).</p>
<p>I also had the same issue with getting an AfterSelect on a TreeView to fire when changing the SelectedNode property.</p>
<p>I could have a function that my unit test can call that simulates the code a UI event would fire, but that would be cluttering up my code, and unless I make it public, I would have to write all my tests in the same project, or even class, of the objects I am testing (again, I see this as clutter). This seems ugly to me, and would suffer from maintainability problems.</p>
<p>Is there a convention to do this sort of UI based unit-testing</p>
|
<p>To unit test your code you will need to mock up an object of the UI interface element. There are many tools you can use to do this, and I can't recommend one over another. There's a good comparison between MoQ and Rhino Mocks here <a href="http://haacked.com/archive/2008/03/23/comparing-moq-to-rhino-mocks.aspx" rel="noreferrer">at Phil Haack's blog</a> that I've found useful and might be useful to you.</p>
<p>Anothing thing to consider if you're using TDD is creating an interface to your views will assist in the TDD process. There is a design model for this (probably more than one, but this is one I use) called Model View Presenter (now split into Passive View and Supervisor Controller). Following one of these will make your code behind far more testable in the future.</p>
<p>Also, bear in mind that testing the UI itself cannot be done through unit testing. A test automation tool as already suggested in another answer will be appropriate for this, but not for unit testing your code.</p>
|
<p>One option I would recommend for its simplicty is to have your UI just call a helper class or method on the firing of the event and unit test that. Make sure it (your event handler in the UI) has as little logic as possible and then from there I'm sure you'll know what to do.</p>
<p>It can be pretty difficult to reach 100% coverage in your unit tests. By difficult I mean of course inefficient. Even once you get good at something like that it will, in my opinion, probably add more complexity to your code base than your unit test would merit. If you're not sure how to get your logic segmented into a separate class or method, that's another question I would love to help with.</p>
<p>I'll be interested to see what other techniques people have to work with this kind of issue.</p>
| 12,366
|
<p>I have a single line CEikLabel in my application that needs to scroll text.</p>
<p>The simple solution that comes to mind (but possibly naive) would be something like..</p>
<pre><code>[begin pseduo code]
on timer.fire {
set slightly shifted text in label
redraw label
}
start timer
[end pseudo code]
</code></pre>
<p>Using a CPeriodic class as the timer and label.DrawDeferred() on each update.</p>
<p>Do you think this is the best way, it may be rather inefficient redrawing the label two or three times a second.. but is there any other way?</p>
<p>Thanks :)</p>
|
<p>You can never receive an error, or notice for a UDP packet that did not reach destination.</p>
|
<p>If you need reliable UDP as in ordering or verification such that TCP/IP will give you take a look at RUDP or Reliable UDP. Sometimes you do need verification but a mixture of UDP and TCP can be held up on the TCP reliability causing a bottleneck.</p>
<p>For most large scale MMO's for isntance UDP and Reliablity UDP are the means of communication and reliability. All RUDP does is add a smaller portion of TCP/IP to validate and order certain messages but not all.</p>
<p>A common game development networking library is Raknet which has this built in.</p>
<p>RUDP
<a href="http://www.javvin.com/protocolRUDP.html" rel="nofollow noreferrer">http://www.javvin.com/protocolRUDP.html</a></p>
<p>An example of RUDP using Raknet and Python
<a href="http://pyraknet.slowchop.com/" rel="nofollow noreferrer">http://pyraknet.slowchop.com/</a></p>
| 43,248
|
<p>What other frameworks should ASP.Net programmers consult for code inspiration?</p>
|
<p>Broaden your search - don't look just at ASP.NET MVC. Different approaches will help you better understand things you want to do.</p>
<p>Some suggestions:</p>
<ul>
<li><a href="http://www.rubyonrails.org/" rel="nofollow noreferrer">RoR</a></li>
<li><a href="http://www.djangoproject.com/" rel="nofollow noreferrer">Django</a></li>
<li><a href="http://grails.org/" rel="nofollow noreferrer">Grails</a></li>
</ul>
|
<p>Well ASP.NET in pretty much unique in it's own respect. You've got user controls, master pages, web forms, a plethora of hooks for IIS...</p>
<p>I'd say you should look into other peoples code for inspiration, see how they've done it.</p>
| 45,452
|
<p>I have a web app protected by ASP.NET Forms Authentication. The site uses jQuery's $.ajax() functionality to call a web service in the same app. </p>
<p>Browsing to the web service .asmx does cause forms authentication to kick in and I once authenticated and make a $.ajax() call to the server I also see the ASP.NET session cookie and forms auth cookie being posted back to the server in Fiddler.</p>
<p>So...although all appears to be well, I'd like to put my mind at rest that indeed the web service will be protected by ASP.NET forms authentication when called from any of the pages in the web app using $.ajax().</p>
|
<p>From the server's perspective, an ajax request is not very different from normal GET/POST request - just some extra headers added on in the request. It passes through your normal authentication routine, the same as any other request - if that was not the case, you should be much more worried about the overall security of your application as requests can be forged very easily by people who know what they are doing.</p>
<p>You can easily setup a test to see if a resource requiring authentication successfully blocks out unauthorized requests arriving by Ajax. That should put your mind at ease.</p>
|
<p>As long as your checking on the server that the user is authenticated then yes you should be protected. I am using $ajax to call both PageMethods and to call an ASP.Net WCF service, and things look good.</p>
| 38,110
|
<p>I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:</p>
<pre><code>warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1
</code></pre>
<p>How can I track down where this is happening at? Viewing the memory doesn't give me any clues.</p>
<p>Thanks!</p>
|
<p>So you're busting your heap. Here's a nice <a href="http://www.cs.princeton.edu/courses/archive/spring99/cs126/help/gdbtut.html" rel="nofollow noreferrer">GDB tutorial</a> to keep in mind.</p>
<p>My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way. </p>
<p>Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).</p>
|
<p>I had similar problem when I was trying to realloc array of pointers to my structures, but instead I was reallocating as array of ints (because I got the code from tutorial and forgot to change it). The compiler wasnt correcting me because it cannot be checked whats in size argument.
My variable was:</p>
<p><code>itemsetList_t ** iteration_isets;</code></p>
<p>So in realloc instead of having:</p>
<p><code>iteration_isets = realloc(iteration_isets, sizeof(itemsetList_t *) * max_elem);</code></p>
<p>I had:</p>
<p><code>iteration_isets = realloc(iteration_isets, sizeof(int) * max_elem);</code></p>
<p>And this caused my heap problem.</p>
| 32,560
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/16991/what-ruby-ide-do-you-prefer">What Ruby IDE do you prefer?</a> </p>
</blockquote>
<p>I've generally been doing stuff on Microsoft .NET out of college almost 2 years ago. I just started looking at Ruby on Rails. So what editor should I use? I'm using <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="nofollow noreferrer">Notepad++</a> right now but can I get debugging etc. somehow?</p>
|
<p>Try both NetBeans and RadRails for maybe a week each, then you can find which works best for you. The best advice is to learn your tool. If you are not checking out something new about your editor, something that could potentially save you time (regexp, etc) then you are doing yourself a huge disservice.</p>
<p>I have been using Eclipse/Aptana/RadRails and unlike Gaius have been pretty happy with it.
I recommend the Eclipse IDE for Java Developers from Eclipse Downloads: <a href="http://www.eclipse.org/downloads/" rel="noreferrer">http://www.eclipse.org/downloads/</a></p>
<p>Then grab Aptana Studio, following these <a href="http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration#Eclipse_3.4_Instructions" rel="noreferrer">instructions</a>.</p>
<p>When Eclipse restarts Aptana will have a view, click on rad rails and you are good to go. Just make sure you have ruby installed already, or it becomes a pain to resolve.</p>
|
<p>I mainly code ColdFusion or PHP (and JS/CSS/xHTML), but have dabbled in a bit of RoR. RadRails/Apatana has been great for me, because it's built on Eclipse, which I was already using for my other work. It also integrates with Subversion via the Subclipse plugin. </p>
<p>The Eclipse platform is so extensible that it's worth investing a bit of time in to learn, but then again I like having a single IDE rather than having to switch between different apps.</p>
<p>I briefly looked at Netbeans, but TBH Eclipse just felt better for me, and Aptana itself is great when you come to do anything in JavaScript.</p>
<p>YMMV...</p>
| 3,677
|
<p>Is there any code coverage tool available for PHP?
I wish to check the code coverage of my code and API's written in PHP, but have not been able to lay my hands on any code coverage tool for PHP, as it is more of a server side language and dynamic in nature.</p>
<p>Does anyone know of a method by which code coverage for PHP can be executed?</p>
|
<p><a href="http://www.xdebug.org/" rel="noreferrer">xdebug</a> has <a href="http://www.xdebug.org/docs/code_coverage" rel="noreferrer">Code Coverage Analysis</a>.</p>
<p>Check <a href="https://phpunit.de/manual/current/en/code-coverage-analysis.html" rel="noreferrer">this chapter</a> of the PHPUnit Manual</p>
|
<p>Using Xdebug in combination with <a href="http://www.phpunit.de/manual/3.0/en/code-coverage-analysis.html" rel="nofollow noreferrer">PHPUnit</a> can give you code coverage analysis.</p>
| 45,389
|
<p>What does the quote "Level of Indirection solves every Problem" mean in Computer Science?</p>
|
<p>Generally it means that by increasing the level of abstraction one can make the problem easier to understand/resolve.</p>
<p>Be careful with your abstractions though, the full quote at least as I heard it is, "You can solve every problem with another level of indirection, except for the problem of too many levels of indirection".</p>
|
<p>It originates from <em>Bulter Lampson</em>:</p>
<blockquote>
<p><em>"All problems in computer science can be solved by another level of indirection"</em></p>
</blockquote>
<p>It is clearly an <em>aphorism</em> and not intended to be taken literally. It is certainly not a provable theorem.</p>
| 36,748
|
<p>I have just moved from phase 1 to phase 2 of a project. In this transition we got rid of all of the XML configuration for spring and struts2, switching to a fully annotated regime.</p>
<p>All of the participants are amazed at the actual effect this has on development speed. There are a number of reasons for this:</p>
<ul>
<li>Structured thinking about which roles are needed lead to clear understanding that we needed @StubRepository, @TestService and @NotTestService annotations to facilitate all the different run-time models that our project uses (runtime, unit test, integration test, selenium test)</li>
<li>These annotations replaced a <em>large</em> number of duplicate xml definitions.</li>
<li>All dependencies are fully trackable in the ide.</li>
<li>Simpler to work with code because dependencies are clear</li>
</ul>
<p>Some of these gains could probably have been realized by re-structuring the xml as well, but that would not have been a trivial task.</p>
<p>I honestly believe this has given somewhere around 10% boost in productivity for our 20,000 man hour project. I almost find it hard to believe. </p>
<p>Anyone else sharing this same experience ? What's your gain, and how do you explain it ?</p>
|
<p>Basically, this could be viewed as a question about config files vs. annotation.</p>
<p>If you experienced an amelioration in productivity boost when putting some data as annotations, that means they were not "configuration" material in the first place.</p>
<p>The difference between the two:</p>
<ul>
<li><p>annotation: everything is in one place and the configuration information is associated directly with the Java component. Many types of refactorings of the source code are transparent to annotations for this reason -- the annotations will always apply to the component they're attached to, even when that component is moved or renamed. For other refactorings that require new or modified annotations, everything is in the same location, assuring that the annotations are visible to the developer and increasing the likelihood that they'll remember to make the necessary changes.</p></li>
<li><p>Configuration files can provide an organized view of a web of relationships that span different components of an application. Because they're separate from the actual source code, they don't interfere with the readability of the Java source code. </p></li>
</ul>
<p>What you experienced is the disparition of the need to maintain config files in parallel with the source code of an application, with no obvious connection between the two.</p>
<p>BUT: annotations have their drawbacks: source code can become cluttered with all sorts of annotations that are irrelevant to the actual program logic, interfering with the readability of the code. And that while annotations are ideal for metadata that relates to a particular component, they're not well suited to metadata with cross-component application.</p>
|
<p>I don't have productivity figures like you but I have seen significant improvement when moving from xml configurations to annotations. I think its because the configuration information is in the same place with the code.</p>
<p>Before you had to look at a separate file to find configurations and that slowed things down.</p>
| 35,955
|
<p>I know that I can <code> svn diff -r a:b repo </code> to view the changes between the two specified revisions. What I'd like is a diff for every revision that changed the file. Is such a command available?</p>
|
<p>There's no built-in command for it, so I usually just do something like this:</p>
<pre><code>#!/bin/bash
# history_of_file
#
# Outputs the full history of a given file as a sequence of
# logentry/diff pairs. The first revision of the file is emitted as
# full text since there's not previous version to compare it to.
function history_of_file() {
url=$1 # current url of file
svn log -q $url | grep -E -e "^r[[:digit:]]+" -o | cut -c2- | sort -n | {
# first revision as full text
echo
read r
svn log -r$r $url@HEAD
svn cat -r$r $url@HEAD
echo
# remaining revisions as differences to previous revision
while read r
do
echo
svn log -r$r $url@HEAD
svn diff -c$r $url@HEAD
echo
done
}
}
</code></pre>
<p>Then, you can call it with:</p>
<pre><code>history_of_file $1
</code></pre>
|
<p>I've seen a bunch of partial answers while researching this topic. This is what worked for me and hope it helps others. This command will display output on the command line, showing the revision number, author, revision timestamp and changes made:</p>
<pre><code>svn blame -v <filename>
</code></pre>
<p>To make your search easier, you can write the output to a file and grep for what you're looking for.</p>
| 35,826
|
<p>I am working on an Adobe Flex app, which needs to parse a relativley large XML file. ATM it is only 35MB, but in an ideal world would get much larger in the future.
**Edit: I have no control over the XML file</p>
<p>I am essentially dropping it's contents right into an SQLITE database, so I could use the SimpleXML class to turn it into an object and then iterate through it, but I am worried that this would be a bad approach as the file gets larger. Am I being paranoid, or is there a better way of doing this?</p>
|
<p>You will definitely run into some performance issues parsing an XML file that large. Back in Flex 2 days we used SOAP for services and had one data call that pulled back about 5K records and the Flash Player would hang / browser go unresponsive for about 10 seconds on a reasonably fast machine. I can't remember the size of that SOAP message but it couldn't have been more than 1-2 MB.</p>
<p>If it's possible for your backend to transform the XML into an object graph and send it back over AMF you will see much better performance. Flash Player does really well with large datasets provided they're encoded in AMF (condensed binary format).</p>
<p>Even stil, I'd really consider whether you want to send a single result that large of break it up into pieces. At least that way you have a path for better scaling and can give the user some better feedback, i.e. displaying a message such as "Processing Item 6 of 35..."</p>
|
<p>In SQL, there is always a WHERE clause because no one ever wants to see more than 100 results.</p>
<p>You might not have control over the original XML file, but perhaps you can insert something on the server-side that does the parsing and extracting the data you actually want.</p>
<p>Cheers</p>
| 45,357
|
<p>When Visual Studio (2005) has <em>Options -> Text Editor -> C/C++ -> Tabs -> Indenting</em> set to Smart it will automatically indent code blocks and line up squiggly brackets, {}, as expected. However, if you hit enter inside a code block, move the cursor to another line, and then move it back, the inserted tabs are gone and the cursor is positioned all the way to the left. Is there a way to set Visual Studio to keep these tabs?</p>
|
<p>As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and you'll never see it there until you return to that line.</p>
<p>Once VS determines that you've edited a line of text, it won't automatically modify it for you (at least, not in that way that you've described).</p>
|
<p>This is an annoyance to myself as well. Anytime the code is reformatted the blank lines are de-tabbed.
You might look at this: <a href="http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/ac4d4d6b-b017-4a42-8f72-55f0ffe850d7</a> it's not exactly a solution but a step in the right direction</p>
| 9,956
|
<p>What is the best way to get and set the meta data for mp3, mp4, avi files etc. with .NET?</p>
|
<p>I use <a href="http://mediainfo.sourceforge.net/en" rel="noreferrer">MediaInfo</a> with my C# apps, gives you a lot of information about media files.</p>
|
<p>Looks like MediaInfo is read-only at this point, by the way: <a href="http://sourceforge.net/forum/message.php?msg_id=4241318&abmode=1" rel="nofollow noreferrer">http://sourceforge.net/forum/message.php?msg_id=4241318&abmode=1</a></p>
<p>Very cool project, though. It's fun finding out about all this cool stuff here on SO.</p>
| 3,056
|
<p>I'm just wondering if there is a quick way to echo undefined variables without getting a warning? (I can change error reporting level but I don't want to.) The smallest I have so far is:</p>
<p><code>isset($variable)?$variable:''</code></p>
<p>I dislike this for a few reasons:</p>
<ul>
<li>It's a bit "wordy" and complex</li>
<li><code>$variable</code> is repeated</li>
<li>The echoing of a blank string always kind of annoys me.</li>
<li>My variable names will probably be longer, eg <code>$arrayvar['parameter']</code></li>
</ul>
|
<p>You can run it with the <a href="http://www.php.net/operators.errorcontrol" rel="noreferrer">error suppression operator</a> @.</p>
<pre><code>echo @$variable;
</code></pre>
<p>However, it's best not to ignore unset variables. Unset variables could indicate a logical error on the script, and it's best to ensure all variables are set before use.</p>
|
<p>Suppress errors using the @-operator forces the interpreter to change error level, executing the function and then change back error level. This decreases your scripts runtime.</p>
<p>Build a function like this will eliminate at least 3 of your reasons:</p>
<pre><code>function echoVar($var, $ret=NULL) {
return isset($var)?$var:$ret;
}
echoVar($arrayvar['parameter']);
</code></pre>
<p>But why echoing undefined variables? This sounds like not really well coded...</p>
| 49,304
|
<p>Is it allowable to pass parameters to a web page through the URL (after the question mark) when using the POST method? I know that it works (most of the time, anyways) because my company's webapp does it often, but I don't know if it's actually supported in the standard or if I can rely on this behavior. I'm considering implementing a SOAP request handler that uses a parameter after the question mark to indicate that it is a SOAP request and not a normal HTTP request. The reason for this that the webapp is an IIS extension, so everything is accessed via the same URL (ex: example.com/myisapi.dll?command), so to get the SOAP request to be processed, I need to specify that "command" parameter. There would be one generic command for SOAP, not a specific command for each SOAP action -- those would be specified in the SOAP request itself.</p>
<p>Basically, I'm trying to integrate the Apache Axis2/C library into my webapp by letting the webapp handle the HTTP request and then pass off the incoming SOAP XML to Axis2 for handling if it's a SOAP request. Intuitively, I can't see any reason why this wouldn't work, since the URL you're posting to is just an arbitrary URL, as far as all the various components are concerned... it's the server that gives special meaning to the parts after the question mark.</p>
<p>Thanks for any help/insight you can provide.</p>
|
<p>Lets start with the simple stuff. HTTP GET request variables come from the URI. The URI is a requested resource, and so any webserver <em>should</em> (and apache does) have the entire URI stored in some variable available to the modules or appserver components running within the webserver.</p>
<p>An http POST which is different from an http GET is a separate logical call to the webserver, but it still defines a URI that should process the post. A good webserver (apache being one) will again make the URI available to whatever module or appserver is running within it, then will additionally make available the variables which were sent in the POST headers.</p>
<p>At the point where your application takes control from apache during a POST you should have access to both the GET and POST variables and be able to do whatever control logic you wish, including replying with a SOAP protocol instead of HTML.</p>
|
<p>If you are asking whether it is possible to send parameters via both GET and POST in a single HTTP request, then the answer is "YES". This is standard functionality that can be used reliably AFAIK. </p>
<p>One such example is sending authentication credentials in two pieces, one over GET and the other through POST so that any attempt to hijack a session would require hijacking both the GET and POST variables.</p>
<p>So in your case, you can use POST to contain the actual SOAP request but test for whether it is a SOAP request based on the parameter passed in GET (or in other words through the URL).</p>
| 32,913
|
<p>I am looking to stream a file housed in a SharePoint 2003 document library down to the browser. Basically the idea is to open the file as a stream and then to "write" the file stream to the reponse, specifying the content type and content disposition headers. Content disposition is used to preserve the file name, content type of course to clue the browser about what app to open to view the file. </p>
<p>This works all good and fine in a development environment and UAT environment. However, in the production environment, things do not always work as expected,however only with IE6/IE7. FF works great in all environments. </p>
<p>Note that in the production environment SSL is enabled and generally used. (When SSL is not used in the production environment, file streams, is named as expected, and properly dislays.)</p>
<p>Here is a code snippet:</p>
<pre><code>System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(".") + "\\" + "test.doc", System.IO.FileMode.Open);
long byteNum = fs.Length;
byte[] pdfBytes = new byte[byteNum];
fs.Read(pdfBytes, 0, (int)byteNum);
Response.AppendHeader("Content-disposition", "filename=Testme.doc");
Response.CacheControl = "no-cache";
Response.ContentType = "application/msword; charset=utf-8";
Response.Expires = -1;
Response.OutputStream.Write(pdfBytes, 0, pdfBytes.Length);
Response.Flush();
Response.Close();
fs.Close();
</code></pre>
<p>Like I said, this code snippet works fine on the dev machine and in the UAT environment. A dialog box opens and asks to save, view or cancel Testme.doc. But in production onnly when using SSL, IE 6 & IE7 don't use the name of the attachment. Instead it uses the name of the page that is sending the stream, testheader.apx and then an error is thrown. </p>
<p>IE does provide an advanced setting "Do not save encrypted pages to disk". </p>
<p>I suspect this is part of the problem, the server tells the browser not to cache the file, while IE has the "Do not save encrypted pages to disk" enabled.</p>
<p>Yes I am aware that for larger files, the code snippet above will be a major drag on memory and this implimentation will be problematic. So the real final solution will not open the entire file into a single byte array, but rather will open the file as a stream, and then send the file down to the client in bite size chunks (e.g. perhaps roughly 10K in size).</p>
<p>Anyone else have similar experience "streaming" binary files over ssl? Any suggestions or recommendations?</p>
|
<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.</p>
<pre><code>
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc");
</code></pre>
<p>failing that i've included my code below as I know that works over https://</p>
<pre>
<code>
private void ReadFile(string URL)
{
try
{
string uristring = URL;
WebRequest myReq = WebRequest.Create(uristring);
NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(),
ConfigurationManager.AppSettings["Password"].ToString(),
ConfigurationManager.AppSettings["Domain"].ToString());
myReq.Credentials = netCredential;
StringBuilder strSource = new StringBuilder("");
//get the stream of data
string contentType = "";
MemoryStream ms;
// Send a request to download the pdf document and then get the response
using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
{
contentType = response.ContentType;
// Get the stream from the server
using (Stream stream = response.GetResponseStream())
{
// Use the ReadFully method from the link above:
byte[] data = ReadFully(stream, response.ContentLength);
// Return the memory stream.
ms = new MemoryStream(data);
}
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;");
// Write the memory stream containing the pdf file directly to the Response object that gets sent to the client
ms.WriteTo(Response.OutputStream);
}
catch (Exception ex)
{
throw new Exception("Error in ReadFile", ex);
}
}
</code>
</pre>
|
<p>It might be something really simple, believe it or not I coded exactly the same thing today, i think the issue might be that the content disposition doesnt tell the browser its an attachment and therefore able to be saved.</p>
<pre><code>
Response.AddHeader("Content-Disposition", "attachment;filename=myfile.doc");
</code></pre>
<p>failing that i've included my code below as I know that works over https://</p>
<pre>
<code>
private void ReadFile(string URL)
{
try
{
string uristring = URL;
WebRequest myReq = WebRequest.Create(uristring);
NetworkCredential netCredential = new NetworkCredential(ConfigurationManager.AppSettings["Username"].ToString(),
ConfigurationManager.AppSettings["Password"].ToString(),
ConfigurationManager.AppSettings["Domain"].ToString());
myReq.Credentials = netCredential;
StringBuilder strSource = new StringBuilder("");
//get the stream of data
string contentType = "";
MemoryStream ms;
// Send a request to download the pdf document and then get the response
using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
{
contentType = response.ContentType;
// Get the stream from the server
using (Stream stream = response.GetResponseStream())
{
// Use the ReadFully method from the link above:
byte[] data = ReadFully(stream, response.ContentLength);
// Return the memory stream.
ms = new MemoryStream(data);
}
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;");
// Write the memory stream containing the pdf file directly to the Response object that gets sent to the client
ms.WriteTo(Response.OutputStream);
}
catch (Exception ex)
{
throw new Exception("Error in ReadFile", ex);
}
}
</code>
</pre>
| 7,596
|
<p>Currently our dev team set up all the websites they're working on in IIS on their local machine. We're thinking of switching to using the built in ASP.NET development server instead.</p>
<p>Is this a good idea? What are the pros / cons of using the ASP.NET dev Server? Are there any gotchas we should be aware of?</p>
<p>Thanks.</p>
<p>NB: Running on Win XP / IIS 5 / VS2005</p>
<p><strong>Edit:</strong></p>
<p>Didn't realise it was called Cassini.. More answers for <a href="https://stackoverflow.com/questions/103785/what-are-the-disadvantages-of-using-cassini-instead-of-iis">Cassini v IIS here</a>.</p>
|
<p>There is nothing that the ASP.NET Dev WebService can do that IIS can't (You can set breakpoints etc, just attach the VS debugger to the ASP.NET runtime).</p>
<p>However, the ASP.NET Dev WebService does not represent a true production environment, and as such you can get caught by gotchas that you wouldn't expect when you deploy to production.</p>
<p>Because of that, I mandate that all development is done using IIS on a local machine. It doesn't take much work to configure a site in IIS.</p>
|
<p>The main issue I've run into with the dev server is SerializationExceptions with custom security principals stored on the thread context. Details <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=274696" rel="nofollow noreferrer" title="here">here</a>.</p>
| 35,648
|
<p>What is the way of creating a local mailbox for a user that have a NIS account, but doesn't have any local one?</p>
|
<p>I solved the issue by creating a local account with exactly the same login name, UID and GID that it has in NIS. This way a mail box is created for the user and after the user with NIS account logs in it has that mailbox working.</p>
|
<p>Im not sure it's directly possible. Maybe you could add the user as local with Nologin shell and that way give ham an account with mail?</p>
| 16,000
|
<p>I have the following code which is trivial at first sight. I simply set want to set the font type to Georgia with a size of 14 if the cell is from the result of a search or if there is a count of zero in my students array. </p>
<p>However, with this particular code cell that's last in my <code>tableView</code> is taking on the font of Georgia with size 14. All other cells are working proper. Where in my code is the logic wrong?</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
static NSString *CellIdentifier = @"Student";
cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell
if([studentsSearch count] > 0) {
cell.text = (NSString *)[[[studentsSearch objectAtIndex:section] objectAtIndex:row] valueForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
} else {
if(isSearching == YES)
cell.text = @"No students available.";
else
cell.text = @"No students have been added for this school.";
cell.font = [UIFont fontWithName:@"Georgia" size:14];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>What appears to be happening is when the view controller gets instantiated and pushed on top of the navigation controller's stack, my <code>studentsSearch</code> array is <code>nil</code>. I populate it within that controller. </p>
<p>So upon initialization, the cell has its font set to Georgia with a size of 14 because the <code>count</code> is < 0. However, once I populate the <code>studentsSearch</code> array and reload the <code>tableView</code>'s data, the font seems to be sticking from when the view first got initialized.</p>
<p>I suppose now I need to find how to set the font back to that cell to what the default is.</p>
|
<p>I'm not <i>quite</i> sure what you're asking, but I do note that you're only setting the font to Georgia 14 when you have a search result; otherwise, you're ignoring it. If you have a cell with it's font set in the second if/then branch, and then retrieve that cell (using dequeueReusableCellWithIdentifier:), it will already have it's font set.</p>
<p>The simplest solution is to add</p>
<pre><code>cell.font = [UIFont systemFontOfSize: 14];
</code></pre>
<p>after </p>
<pre><code> cell.text = (NSString *)[[[...
cell.accessoryType = ...
</code></pre>
<p>in the first branch.</p>
|
<p>I'd suggest that you identify the 'special' cell by giving it a different cell identifier.</p>
<p>In this case, you'd request the special cell with cell reuse identifier, e.g. @"None", and if cell has not yet been created, then create one and set its font.</p>
<p>This way, you create an extra cell with a special identifier, and it is kept separate from the other regular cells in your table.</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSInteger section = [indexPath section];
static NSString *StudentCellIdentifier = @"Student";
static NSString *NoneCellIdentifier = @"None";
// did we find students?
BOOL found = [studentsSearch count] > 0;
// get/create correct cell type
cell = [tv dequeueReusableCellWithIdentifier:(found ? StudentCellIdentifier : NoneCellIdentifier)];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:(found ? StudentCellIdentifier : NoneCellIdentifier)];
}
// return a student, or None cell if no studnts found
if( found )
{
cell.text = (NSString *)[[[studentsSearch objectAtIndex:section] objectAtIndex:row] valueForKey:@"name"];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
else
{
if(isSearching == YES)
cell.text = @"No students available.";
else
cell.text = @"No students have been added for this school.";
cell.font = [UIFont fontWithName:@"Georgia" size:14];
cell.accessoryType = UITableViewCellAccessoryNone;
}
return [cell autorelease];
}
</code></pre>
| 42,553
|
<p>Currently, primary keys in our system are 10 digits longs, just over the limit for Java Integers. I want to avoid any maintenance problems down the road caused by numeric overflow in these keys, but at the same time I do not want to sacrifice much system performance to store infinitely large numbers that I will never need.</p>
<p>How do you handle managing the size of a primary key? Am I better off sticking with Java integers, for the performance benefit over the larger Long, and increasing the size when needed, or should I bite the bullet, go with Java Long for most of my PKs, and never have to worry about overflowing the sequence size?</p>
|
<p>I've always gone with long keys (number(18,0) in database) because they simply remove the possibility of this situation happening in pretty much all situations (extreme data hoarding style applications aside). Having the same data-type across all tables for the key means you can share that field across all of your model objects in a parent class, as well as having consistent code your your SQL getters, and so on.</p>
|
<p>It's a balance between the cost of storing and using Long integers, versus the likelihood of overflowing a 32-bit integer.</p>
<p>Consider that an unsigned 32-bit integer stores over 4 billion values. If you think you are going to average more than 1 new row every second in this table for the next 136 years, then you need to use a Long.</p>
| 21,652
|
<p>My motivation for trying out git-svn is the effortless merging and branching. Then I noticed that man git-svn(1) says: </p>
<blockquote>
<p>Running git-merge or git-pull is NOT recommended on a branch you plan
to dcommit from. Subversion does not represent merges in any
reasonable or useful fashion; so users using Subversion cannot see any
merges you've made. Furthermore, if you merge or pull from a git
branch that is a mirror of an SVN branch, dcommit may commit to the
wrong branch.</p>
</blockquote>
<p>Does this mean I cannot create a local branch from svn/trunk (or a branch), hack away, merge back into svn/trunk, then dcommit? I understand that svn users will see the same mess that merges in svn pre 1.5.x have always been, but are there any other drawbacks? That last sentence worries me, too. Do people routinely do these kinds of things?</p>
|
<p>Actually, I found an even better way with the <code>--no-ff</code> option on git merge.
All this squash technic I used before is no longer required. </p>
<p>My new workflow is now as follows: </p>
<ul>
<li><p>I have a "master" branch that is the only branch that I dcommit from and that clone the SVN repository (<code>-s</code> assume you have a standard SVN layout in the repository <code>trunk/</code>, <code>branches/</code>, and <code>tags/</code>):</p>
<pre><code>git svn clone [-s] <svn-url>
</code></pre></li>
<li><p>I work on a local branch "work" (<code>-b</code> creates the branch "work")</p>
<pre><code>git checkout -b work
</code></pre></li>
<li><p>commit locally into the "work" branch (<code>-s</code> to sign-off your commit message). In the sequel, I assume you made 3 local commits</p>
<pre><code>...
(work)$> git commit -s -m "msg 1"
...
(work)$> git commit -s -m "msg 2"
...
(work)$> git commit -s -m "msg 3"
</code></pre></li>
</ul>
<h2>Now you want to commit onto the SVN server</h2>
<ul>
<li><p>[Eventually] stash the modifications you don't want to see committed on the SVN server (often you commented some code in the main file just because you want to accelerate the compilation and focus on a given feature)</p>
<pre><code>(work)$> git stash
</code></pre></li>
<li><p>rebase the master branch with the SVN repository (to update from the SVN server)</p>
<pre><code>(work)$> git checkout master
(master)$> git svn rebase
</code></pre></li>
<li><p>go back to the work branch and rebase with master</p>
<pre><code>(master)$> git checkout work
(work)$> git rebase master
</code></pre></li>
<li><p>Ensure everything is fine using, for instance: </p>
<pre><code>(work)$> git log --graph --oneline --decorate
</code></pre></li>
<li><p>Now it's time to merge all three commits from the "work" branch into "master" using this wonderful <code>--no-ff</code> option</p>
<pre><code>(work)$> git checkout master
(master)$> git merge --no-ff work
</code></pre></li>
<li><p>You can notice the status of the logs: </p>
<pre><code>(master)$> git log --graph --oneline --decorate
* 56a779b (work, master) Merge branch 'work'
|\
| * af6f7ae msg 3
| * 8750643 msg 2
| * 08464ae msg 1
|/
* 21e20fa (git-svn) last svn commit
</code></pre></li>
<li><p>Now you probably want to edit (<code>amend</code>) the last commit for your SVN dudes (otherwise they will only see a single commit with the message "Merge branch 'work'"</p>
<pre><code>(master)$> git commit --amend
</code></pre></li>
<li><p>Finally commit on the SVN server</p>
<pre><code>(master)$> git svn dcommit
</code></pre></li>
<li><p>Go back to work and eventually recover your stashed files:</p>
<pre><code>(master)$> git checkout work
(work)$> git stash pop
</code></pre></li>
</ul>
|
<p>A safe way to merge svn branches in git is to use git merge --squash. This will create a single commit and stop for you to add a message.</p>
<p>Let's say you have a topic svn branch, called svn-branch.</p>
<pre><code>git svn fetch
git checkout remotes/trunk -b big-merge
git merge --squash svn-branch
</code></pre>
<p>at this point you have all the changes from the svn-branch squashed into one commit waiting in the index</p>
<pre><code>git commit
</code></pre>
| 23,108
|
<p>I'm trying to highlight the search results but I want to include the surrounding text that is limited by the enclosing tags.</p>
<p>So if the $term is "cool" the preg_replace should end up with:</p>
<pre><code><div><span style="background: #f00">My hair cut so cool!</span></div>
</code></pre>
<p>Unfortunately my regex doesn't seem to capture the surrounding text, only the $term. The surrounding tags could be any kind of valid tag.</p>
<pre><code> 0:
1: $term = 'cool';
2: ob_start();
3:
10: foreach($items as $item) {
11: // echoing results here
12: echo '<div>' . $item->text . '</div>';
13: }
30: $content = ob_get_contents();
31: ob_clean() ;
32:
33: $pattern = "/(?<!<[^>])($term)/i";
34: $replace = "<span style=\"background: #f00\">$1</span>";
35: echo preg_replace($pattern, $replace, $content);
36:
</code></pre>
<p>EDIT: The foreach loop is one of many and is located in a separate class. Because of this I can't do the replacement in the loop itself. Also it seems more efficient to process the final output instead of each loop over the data.</p>
|
<p>Finding a term and everything up to the HTML tags before and after it is the same as finding the term an all characters before and after it that aren't angular brackets. This is trivial with a regex:</p>
<pre><code>$pattern = "/[^<>]*$term[^<>]*/i";
$replace = "<span style=\"background: #f00\">$0</span>";
</code></pre>
|
<p>Why the need of preg_replace?</p>
<p>This is how i would have solved the problem:</p>
<p>Case 1: <strong>Highlight a substring of the result:</strong>
Use strpos() or stripos() to get the index of the first occurrence in a string. Next: Get the substring from index-X to index+L+Y, where X and Y is definded constants that describe number of characters to be highlighted before and after the word, and L is the length of the word. Then apply some -tag around the generated substring.</p>
<p>Case 2: <strong>Highlight the hole tag:</strong> You can still do the search by strpos/stripos. Then devide the string into two parts: Part one will be the substring from zero to the pointer, and part two consist of the rest of the string. Then: Find last occurrense (strrpos/strripos) of '>' in string 1 and first occurense of '<' in string 2. Insert your highlighting, and enjoy ;)</p>
<blockquote>
<p>Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems - Jamie Zawinski</p>
</blockquote>
| 37,259
|
<p>Based on their work, how do you distinguish a great SQL developer? </p>
<p>Examples might include:</p>
<p>Seldom uses CURSORs, and tries to refactor them away.<br>
Seldom uses temporary tables, and tries to refactor them away.<br>
Handles NULL values in OUTER JOINs with confidence.<br>
Avoids SQL extensions that are not widely implemented.
Knows how to indent with elegance.</p>
|
<p>I've found that a great SQL developer is usually also a great database designer, and will prefer to be involved in both the design and implementation of the database. That's because a bad database design can frustrate and hold back even the best developer - good SQL instincts don't always work right in the face of pathological designs, or systems where RI is poor or non-existent. So, one way to tell a great SQL developer is to test them on data modeling.</p>
<p>Also, a great DB developer has to have complex join logic down cold, and know exactly what the results of various multi-way joins will be in different situations. Lack of comfort with joins is the #1 cause of bad SQL code (and bad SQL design, for that matter).</p>
<p>As for specific syntax things, I'd hesitate at directives like:</p>
<blockquote>
<p>Does not use CURSORs.</p>
<p>Does not use temporary tables.</p>
</blockquote>
<p>Use of those techniques might allow you to tell the difference between a dangerously amateur SQL programmer (who uses them when simple relational predicates would be far better) and a decent starting SQL programmer (who knows how to do most stuff without them). However, there are many situations in real world usage where temp tables and cursors are perfectly adequate ways (sometimes, the only ways) to accomplish things (short of moving to another layer to do the processing, which is sometimes better anyway).</p>
<p>So, use of advanced concepts like these isn't forbidden, but unless you're clearly dealing with a SQL expert working on a really tough problem that, for some reason, doesn't lend itself to a relational solution ... yeah, they're probably warning signs.</p>
|
<p>Knows how to use INFORMATION_SCHEMA and table metadata in order to write either generic code or to code generate code in order to save repetitive database tasks.</p>
| 37,375
|
<p>I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes.
Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.</p>
<p>Is there a function available in the CRT or somewhere in the linux headers to safely escape a string to pass to the command line ?</p>
|
<p>There isn't a single solution that works everywhere because different shells have different ideas of what special characters are and how they are interpreted. For bash, you could probably get away with surrounding the entire filename in single quotes after replacing every single quote in the file name with <code>'"'"'</code> (the first single quote stops the sequence, the <code>"'"</code> appends the literal single quote to the string, the final single quote starts the quoted sequence again). A better solution would be to find a way to call the program without using system, such as by using fork with one of the exec functions so there is no shell interpolation.</p>
|
<p>And now here is a complete solution to the shell escape problem. Although this
doesn't answer the exact question of escaping a string for shell. It solves the problem of passing arguments to program. This solution is a POSIX portable way to execute commands with arguments properly passed into the command without worrying about needing to escape them.</p>
<pre><code>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <vector>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
std::vector<std::string> split(std::string delimiter, std::string str){
std::size_t nextPos = 0;
std::size_t delimiterSize = delimiter.size();
std::vector<std::string> list;
while(true){
std::size_t pos = str.find(delimiter, nextPos);
std::string subStr;
if(pos == std::string::npos){
list.push_back(str.substr(nextPos));
break;
}
subStr = str.substr(nextPos, pos - nextPos);
list.push_back(subStr);
nextPos = pos + delimiterSize;
}
return list;
}
bool isFileExecutable(const std::string &file)
{
struct stat st;
if (stat(file.c_str(), &st) < 0)
return false;
if ((st.st_mode & S_IEXEC) != 0)
return true;
return false;
}
std::string ensureEndsWithSlash(std::string path){
if(path[path.length()-1] != '/'){
path += "/";
}
return path;
}
std::string findProgram(std::string name){
// check if it's relative
if(name.size() > 2){
if(name[0] == '.' && name[1] == '/'){
if(isFileExecutable(name)){
return name;
}
return std::string();
}
}
std::vector<std::string> pathEnv = split(":", getenv("PATH"));
for(std::string path : pathEnv){
path = ensureEndsWithSlash(path);
path += name;
if(isFileExecutable(path)){
return path;
}
}
return std::string();
}
// terminal condition
void toVector(std::vector<std::string> &vector, const std::string &str){
vector.push_back(str);
}
template<typename ...Args>
void toVector(std::vector<std::string> &vector, const std::string &str, Args ...args){
vector.push_back(str);
toVector(vector, args...);
}
int waitForProcess(pid_t processId){
if(processId == 0){
return 0;
}
int status = 0;
int exitCode = -1;
while(waitpid(processId, &status, 0) != processId){
// wait for it
}
if (WIFEXITED(status)) {
exitCode = WEXITSTATUS(status);
}
return exitCode;
}
/**
Runs the process and returns the exit code.
You should change it so you can detect process failure
vs this function actually failing as a process can return -1 too
@return -1 on failure, or exit code of process.
*/
template<typename ...Args>
int mySystem(Args ...args){
std::vector<std::string> command;
toVector(command, args...);
command[0] = findProgram(command[0]);
if(command[0].empty()){
// handle this case by returning error or something
// maybe std::abort() with error message
return -1;
}
pid_t pid = fork();
if(pid) {
// parent wait for child
return waitForProcess(pid);
}
// we are child make a C friendly array
// this process will be replaced so we don't care about memory
// leaks at this point.
std::vector<char*> c_command;
for(int i = 0; i < command.size(); ++i){
c_command.push_back(strdup(command[i].c_str()));
}
// null terminate the sequence
c_command.push_back(nullptr);
execvp(c_command[0], &c_command[0]);
// just incase
std::abort();
return 0;
}
int main(int argc, char**argv){
// example usage
mySystem("echo", "hello", "world");
}
</code></pre>
| 36,652
|
<p>I'm building a web application and would like to use the strongest hashing algorithm possible for passwords. What are the differences, if any, between sha512, whirlpool, ripemd160 and tiger192,4? Which one would be considered cryptographically stronger?</p>
|
<p>bCrypt - Why would be a very long explanation, for which I recommend <a href="http://www.securityfocus.com/blogs/262" rel="noreferrer">Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes</a></p>
<p>Basically, it's secure, it's slow, it's already implemented.</p>
|
<p>Here's a good <a href="http://www.codinghorror.com/blog/archives/000953.html" rel="nofollow noreferrer">post on coding horror about storing passwords</a>. In short, he suggests bcrypt or SHA-2 with a random unique salt.</p>
| 22,263
|
<p>I'm trying to get authentication working to my liking in a CakePHP app and running into a snag. </p>
<p>I want to let the user login from either the home page or from a dedicated login page. I'm using the Auth component to manage login and right now the login itself works. I am submitting the form on the home page to /Users/Login and it does log them in and create session. The problem is it then redirects the user back to the home page. I'd rather they redirect to the location specified in loginRedirect. </p>
<p>If i login from /users/login directly it does forward to loginRedirect. I think the problem has something to do with posting the form from one page to another page instead of to itself, auth automatically thinks you want to go back to the previous page. </p>
<p>Any thoughts?</p>
|
<p>in the AppController</p>
<pre><code>public function beforeFilter( )
{
$this->Auth->autoRedirect = false;
}
</code></pre>
<p>in UsersController</p>
<pre><code>public function login( )
{
if( $this->Auth->user( ) )
{
$this->redirect( array(
'controller' => 'users' ,
'action' => 'index' ,
));
}
}
</code></pre>
<p>Also, if you haven't already you should move the form into an element, so that you can make absolutely certain that the login form is identical between the 2 login views.</p>
|
<p>Yes auth has a feature where it will redirect you to the page you tried to access before logging in. If setting the loging redirect did not work, you can try to set the loginRedirect to false and do a manual ($this->redirect([..] ) in the UsersController::login action.</p>
| 29,475
|
<p>First let me say that I really feel directionless on this question. I am using windows integrated security, and I can use vb.net to look up information about a user from AD. I also have other information about users I can look up from a MS SQL 2005 server by getting the logon identity name.</p>
<p>What I would like to do is display information about all the users actively viewing the web page to any one of the users viewing the web page. The information comes both from AD and SQL, and I have no problem retrieving it.</p>
<p>My route so far has been using SQL to store when the user first loads the page. I am stuck not knowing how to show when the user <em>leaves</em> the page. I tried using an ajax timer to update a timestamp for the user's visit every one second that also triggers the table to change the status to inactive of any record that has not been updated in 5 seconds. This works with only a few users, but I find when I have more than a few people viewing the page the 1 second update is not reliable. I also seem to have problems when the user minimizes the page. This sometimes stops the updates from the ajax timer and kicks the user off the list while they are still viewing the page.</p>
<p>This feature is not important to the function of the site it would be on, so I'd given up on it over a year ago. Since then it has really been a pain to me that I can not figure a way to make this work. My searches have led me down many fruitless paths, so I really will appreciate any help that can be offered even if it's only a lead in the correct direction.</p>
|
<p>The answer probably depends on how accurate you need the display to be. If it's just to give users a sense of the other people using the site I'd suggest something similar to what you've described, but backing off on the update frequency:</p>
<ul>
<li>on a page request associate the user with the page (and a timestamp)</li>
<li>use an Ajax timer to update the timestamp every minute or so</li>
<li>kill the association via a window.onbeforeunload event (or similar)</li>
<li>assume that any timestamps older than a minute (and a bit) are dead</li>
</ul>
<p>You can try and catch some of the ways people leave a page, but it's never bullet proof. And with regards to the minimised page, I guess it's debatable whether they're actually viewing the page ;)</p>
|
<p>For the body have an onunload script:
< body onunload="userLeftPage()"</p>
<p>In that script, send an ajax call to say the user left the page.</p>
| 12,147
|
<p>What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown?</p>
|
<p>There is no inherent limit. The maximum number of threads is determined by the amount of physical resources available. See this <a href="https://devblogs.microsoft.com/oldnewthing/20050729-14/?p=34773" rel="noreferrer">article by Raymond Chen</a> for specifics.</p>
<p>If you need to ask what the maximum number of threads is, you are probably doing something wrong. </p>
<p>[<strong>Update</strong>: Just out of interest: .NET Thread Pool default numbers of threads:</p>
<ul>
<li>1023 in Framework 4.0 (32-bit environment)</li>
<li>32767 in Framework 4.0 (64-bit environment)</li>
<li>250 per core in Framework 3.5</li>
<li>25 per core in Framework 2.0</li>
</ul>
<p>(These numbers may vary depending upon the hardware and OS)]</p>
|
<p>You can <strong>test</strong> it by using this snipped code:</p>
<pre><code>private static void Main(string[] args)
{
int threadCount = 0;
try
{
for (int i = 0; i < int.MaxValue; i ++)
{
new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
threadCount ++;
}
}
catch
{
Console.WriteLine(threadCount);
Console.ReadKey(true);
}
}
</code></pre>
<p>Beware of 32-bit and 64-bit mode of application.</p>
| 17,520
|
<p>I'm using Visual Studio 6.0 and Visual Basic 6.0.</p>
<p>I have them integrated but when I check out a Project and then try to edit a module in that project it's locked and I have to manually right-click on it and do a Check Out to unlock it.</p>
<p>I thought there was a way to have VSS automatically check out the file for editing.</p>
<p>Any suggestions?</p>
|
<p>I agree with kris here. Now I know that a bunch of folks saying your "software stinks" doesn't really answer your question. But there is a world of difference between a check out style source control and a file locking system like Source safe. The general consensus is that Check out systems are far superior. </p>
<p>With check out, what you do is you check out the project from your repository. All the files are editable. You work on your project as normally. Then before you checkin you do another update. If anybody else in your team did a update the software will automatically merge in the changes into your code. You will have a chance to review the merges and resolve any conflicts. After the update you can then check in your changes which everyone else can retrieve. </p>
<p>The big scary part is the merging part. Back when CVS and subversion where just command line tools it was a little scary as it was a pain to retrieve what happened with the merging. But with today's tools like Tortoise is all visual. In the last couple of years I can't think of any instance where a automatic merge failed. Any conflicts (basically two people edit the same line of code) are display right here for you to resolve.</p>
<p><a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a> </p>
<p><a href="http://tortoisesvn.tigris.org/" rel="nofollow noreferrer">Tortoise SVN</a></p>
|
<p>I never figured out a way to do this. It was always a huge pain. Sorry for posting a negative answer, but I figured that you might want to know that you aren't alone in hating this, but that there wasn't an immediate and obvious answer. I'll be following this question along with you in case someone out there does know of a solution...</p>
| 21,063
|
<p>I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.</p>
<p>However, in Adobe AIR, there is a restriction on using <a href="http://labs.adobe.com/wiki/index.php/AIR:HTML_Security_FAQ#Why_restrict_eval.28.29_for_all_Application_content_if_there_are_legitimate_use_cases_for_using_it.3F" rel="nofollow noreferrer">eval()</a> for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately.</p>
<p>Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now</p>
<hr>
<p><strong>Update:</strong></p>
<p>Thanks to <a href="https://stackoverflow.com/a/24919/7750640">Theo</a> and <a href="https://stackoverflow.com/a/21716/7750640">jsight</a> for their answers; </p>
<p>One important thing I learnt today is that I can actually make use of ActionScript libraries by using the <pre><script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script></pre> tag extended by Adobe AIR. Check out <a href="https://stackoverflow.com/a/24919/7750640">Theo's</a> link for more details!</p>
|
<p>You can find a <a href="http://www.JSON.org/js.html" rel="noreferrer">JSON parser written in JavaScript here</a> (<a href="https://github.com/douglascrockford/JSON-js/blob/master/json2.js" rel="noreferrer">source code here</a>). You can also use the as3corelib JSON parser from JavaScript, there's <a href="http://help.adobe.com/en_US/AIR/1.1/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7ed9.html" rel="noreferrer">a description of how to access ActionScript libraries from JavaScript here</a>.</p>
|
<p>JSON is Javascript Object Notation, so if you are using Javascript you are already there!
Have a look at these links, they give examples of how to create Javascript objects from JSON:</p>
<p><a href="http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)" rel="nofollow noreferrer">http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)</a></p>
<p><a href="http://betterexplained.com/articles/using-json-to-exchange-data/" rel="nofollow noreferrer">http://betterexplained.com/articles/using-json-to-exchange-data/</a></p>
<p>If you decide to go the Flex / AS3 route, then as the jsight said, as3corelib is a good place to start.</p>
| 4,178
|
<p>In C#</p>
<p>I have a processing time number data column in the database which is in in this format "###" or "##" ( eg: "813" or "67")</p>
<p>When I bind it to the grid view I wanted to display it in this format "0.###" (eg: "0.813" or "0.067")</p>
<p>I tried using {0:0.000} and other formatings. But none seem to work. Can anyone tell me how to write the format string?</p>
|
<p>You need to disable HTML encoding on that column for the format string to take effect.</p>
<p><a href="http://weblogs.asp.net/rajbk/archive/2005/10/31/429090.aspx" rel="nofollow noreferrer">Further Reading</a></p>
|
<p>If for some reason you can't change the value before you bind it to the grid, you can handle the RowDataBound event and divide the number by 1000 before displaying it.</p>
<pre><code>// Handle the grid's RowDataBound event
MyGridView.RowDataBound += new GridViewRowEventHandler(MyGridView_RowDataBound);
// Set the value to x / 1000 in the RowDataBound event
protected void MyGridView_RowDataBound( object sender, GridViewRowEventArgs e )
{
if( e.Row.RowType != DataControlRowType.DataRow )
return;
// Cast e.Row.DataItem to whatever type you're binding to
BindingObject bindingObject = (BindingObject)e.Row.DataItem;
// Set the text of the correct column. Replace 0 with the position of the correct column
e.Row.Cells[0].Text = bindingObject.ProcessingTime / 1000M;
}
</code></pre>
| 40,587
|
<p>I am working on a Software Project that needs to be translated into 30 languages. This means that changing any string incurs into a relatively high cost. Additionally, translation does not happen overnight, because the translation package needs to be worked by different translators, so this might take a while.</p>
<p>Adding new features is cumbersome somehow. We can think up all the Strings that will be needed before we actually code the UI, but sometimes still we need to add new strings because of bug fixes or because of an oversight.</p>
<p>So the question is, how do you manage all this process? Any tips in how to ease the impact of translation in the software project? How to rule the strings, instead of having the strings rule you?</p>
<p>EDIT: We are using Java and all Strings are internationalized using Resource Bundles, so the problem is not the internationalization per-se, but the management of the strings.</p>
|
<p>I'm not sure the platform you're internationalizing in. I've written an answer before on the best way to il8n an application. See <a href="https://stackoverflow.com/questions/59130/what-do-i-need-to-know-to-globalize-an-asp-net-application/59184#59184">What do I need to know to globalize an asp.net application?</a></p>
<p>That said - managing the translations themselves is hard. The problem is that you'll be using the same piece of text across multiple pages. Your framework may not, however, support only having that piece of text in one file (resource files in asp.net, for instance, encourage you to have one resource file per language).</p>
<p>The way that we found to work with things was to have a central database repository of translations. We created a small .net application to import translations from resource files into that database and to export translations from that database to resource files. There is, thus, an additional step in the build process to build the resource files.</p>
<p>The other issue you're going to have is passing translations to your translation vendor and back. There are a couple ways for this - see if your translation vendor is willing to accept XML files and return properly formatted XML files. This is, really, one of the best ways, since it allows you to automate your import and export of translation files. Another alternative, if your vendor allows it, is to create a website to allow them to edit the translations.</p>
<p>In the end, your answer for translations will be the same for any other process that requires repetition and manual work. Automate, automate, automate. Automate every single thing that you can. Copy and paste is <em>not</em> your friend in this scenario.</p>
|
<p>In Java, internationalization is accomplished by moving the strings to resource bundles ... the translation process is still long and arduous, but at least it's separated from the process of producing the software, releasing service packs etc. One thing that helps is to have a CI system that repackages everything any time changes are made. We can have a new version tested and out in a matter of minutes whether it's a code change, new language pack or both.</p>
| 23,199
|
<blockquote>
<p>HyperTerminal is a program that you can use to connect to other
computers, Telnet sites, bulletin
board systems (BBSs), online services,
and host computers, using either your
modem, a null modem cable or Ethernet
connection.</p>
</blockquote>
<p>But My main usage of Hyperterminal is to communicate with hardware through local (virtual )COM ports. I suppose it is removed in Vista for some reason.</p>
<p>Are there any other tools that functions similar to Hyperterminal?</p>
<p>[I am curious to know even if it is not for vista]</p>
|
<p>Here are two:</p>
<p><a href="http://hp.vector.co.jp/authors/VA002416/teraterm.html" rel="nofollow noreferrer">Tera Term</a></p>
<blockquote>
<p>Tera Term (Pro) is a free software terminal emulator (communication program) for MS-Windows. It supports VT100 emulation, telnet connection, serial port connection, and so on.</p>
</blockquote>
<p><a href="http://www.columbia.edu/kermit/k95.html" rel="nofollow noreferrer">Kermit 95</a></p>
<blockquote>
<p>Kermit 95: Internet and serial communications for Microsoft Windows® 95, Windows 98, Windows ME, Windows NT (4.0 and later), Windows 2000, Windows XP, and IBM OS/2 from the Kermit Project at Columbia University, offers you text-based terminal connections to Unix, VMS, and many other kinds of hosts, allowing you to interact directly with their shells and applications, to transfer files, and, if desired, to automate interactions and file transfers with its built-in platform- and transport-independent scripting language.</p>
</blockquote>
|
<p>Here is a better tool specificaly designed to test serial devices: <a href="http://www.caerustech.com/UDT.php" rel="nofollow noreferrer">http://www.caerustech.com/UDT.php</a> . You can save settings and commands for various devices - I use it often at work.</p>
| 8,586
|
<p>I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad. There is an interesting white paper here:</p>
<p><a href="http://www.west-wind.com/weblog/posts/484172.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/484172.aspx</a></p>
<p>I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way. </p>
<p>I make business web apps which call for data entry forms. I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user. I use Telerik controls, and my skills with CSS are approaching passable.</p>
<p>People often mention that they don't use the designer, but they rarely state what approach they DO use.</p>
<p>What are some of the alternatives to using the VS designer? </p>
|
<pre><code>string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
</code></pre>
<p>Output:</p>
<pre><code><book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
<p>The Xml Declaration isn't output by ToString(), but it is by Save() ...</p>
<pre><code> XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
</code></pre>
<p>Output:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
|
<p>Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:</p>
<pre><code>XmlDocument xml = new XmlDocument();
xml.LoadXml( YourString );
</code></pre>
| 23,687
|
<p>Does anyone know of a good dictionary API or ruby library to lookup the definitions of words?</p>
<p>I'm thinking it should work something like:</p>
<ol>
<li>I call get_definition(word)</li>
<li>It returns the definition for that word (ideally in some way to easily format the definition for display.</li>
</ol>
<p>Thanks</p>
|
<p>I discovered a webservice for this yesterday.</p>
<p>Go to the <a href="http://www.britishcouncil.org/new/" rel="noreferrer">British Council</a> homepage and double click on any word (that isn't already a hyperlink).</p>
<p>This should open a popup window with a Cambridge Dictionary definition in it. The API is relatively simple (and <em>it is</em> a public API, I checked it yesterday):</p>
<pre><code>http://dictionary.cambridge.org/learnenglish/results.asp?searchword=SEARCH_PHRASE&dict=L
</code></pre>
<p>For reference, here's the code they use to launch this on double-click:</p>
<pre><code>/* BC double-click pop-up dictionary */
var NS = (navigator.appName == "Netscape" || navigator.product == 'Gecko') ? 1 : 0;
if (NS) document.captureEvents(Event.DBLCLICK);
document.ondblclick = dict;
var dictvar;
function dict() {
if (NS) {
t = document.getSelection();
pass_to_dictionary(t);
} else {
t = document.selection.createRange();
if(document.selection.type == 'Text' && t.text != '') {
document.selection.empty();
pass_to_dictionary(t.text);
}
}
}
function pass_to_dictionary(text) {
//alert(text);
if (text > '') {
window.open('http://dictionary.cambridge.org/learnenglish/results.asp?searchword='+text+ '&dict=L', 'dict_win', 'width=650,height=400,resizable=yes,scrollbars=yes');
}
}
</code></pre>
|
<p>there's also wrappers for dictionary.com's API (a few years old)</p>
<p><a href="http://rubyforge.org/snippet/detail.php?type=snippet&id=53" rel="nofollow noreferrer">http://rubyforge.org/snippet/detail.php?type=snippet&id=53</a></p>
<p><a href="http://rubyforge.org/snippet/detail.php?type=snippet&id=52" rel="nofollow noreferrer">http://rubyforge.org/snippet/detail.php?type=snippet&id=52</a></p>
<p>and wiktionary</p>
<p><a href="http://eightpence.com/ninjawords-a-fast-online-dictionary-fast-like-a-ninja/" rel="nofollow noreferrer">http://eightpence.com/ninjawords-a-fast-online-dictionary-fast-like-a-ninja/</a></p>
| 26,628
|
<p>As part of a larger project, i'm trying to print a translucent green dome. I set it up as follows:</p>
<ul>
<li>In Blender, create an icosphere of the maximum allowed complexity. Cut it in half and throw away one of the hemispheres.</li>
<li>Duplicate the hemisphere. Move the second one down slightly and use Subtract, to hollow it out. Clean up the vertex garbage left behind.</li>
<li>Export the model. Import it in the slicer, scale to the proper size, and export as gcode.</li>
<li>Print the model with <a href="https://rads.stackoverflow.com/amzn/click/com/B00ZB48IZE" rel="nofollow noreferrer" rel="nofollow noreferrer">translucent green filament</a> at 100% solid infill.</li>
</ul>
<p>I ended up with a beautifully rounded dome that doesn't feel at all like a polyhedron, so that worked out fine. The only problem is, it's solid green. The filament seems to lose its translucency past a certain thickness, and the fact that my "solid" print is actually made up of thousands of tiny strings pressed up against each other probably doesn't help.</p>
<p>I tried reprinting it in Spiral Vase mode, and while the print turned out to be transparent, it was also extremely thin and fragile, and it failed anyway because of lack of support once the dome's angle got bad enough.</p>
<p>I've been trying to think of how to print this properly, but nothing I think of will work:</p>
<ul>
<li>Scaling can make the walls thinner, but only by reducing the size of the model. Its basic dimensions need to remain unchanged.</li>
<li>Doing the same trick again that I used to create the dome, subtracting a copy of itself moved down slightly, would lead to non-uniform thickness in the model. (Which I already have some of. But when the thickness is directly correlated to the degree of transparency, this is problematic.)</li>
</ul>
<p>Does anyone know of any tricks I can use to get it to come out properly? For reference, I'm using Blender as my 3D software, IdeaMaker as my slicer, and printing on a Raise3D N2 Plus printer.</p>
|
<blockquote>
<p>The filament seems to lose its translucency past a certain thickness</p>
</blockquote>
<p>That's exactly the point. Think of translucency as a percentage of light being allowed through, per amount of material. 2x the material means 1/2 the light. You need either less material (which becomes brittle as you saw), or a more translucent material. I think it has little to do with the model itself.</p>
<p>Also - check out OnShape. One of the features it has is a "shell" function, that does what you're describing - takes a single 3D feature and creates a shell out of it of consistent thickness.</p>
|
<p>For the modeling, I suggest to change to a proper CAD software, design a half sidecut and create the model by rotating it around Z. That way you'd create an evenly thick part.</p>
<p>As for loosing transparency, that has several reasons:</p>
<ul>
<li>light loss into printed materials is mainly due to air being captured in the model. To get the air out as much as possible and generate an almost entirely transparent print, I have printed some lens-tests with extra heat and deliberately overextruding to fill all the cavities and voids.</li>
<li>light loss in materials is also dependant on the material factor and thickness.</li>
</ul>
<p>If you go away from FDM and look into resin-based SLA/DLP systems, you can get almost fully transparent prints with very low colored resins.</p>
| 1,215
|
<p>I am currently trying to import a semi-colon delimited text file into a database in c# using OleDb where I don't know the type (SQL Server, Access, Oracle, MySQL, postgreSQL, etc.) Currently I'm reading in the file as a database using the Jet text reader then creating a prepared insert statement, populating the fields, then commiting at the end. While that works, it's slow and for millions of rows, it takes way too long.</p>
<p>So my question: Does anybody have any other thoughts on how to best import a text file to a generic database, or comments on my approaches that will lead to a faster import?</p>
<p>I cannot use 3rd party libraries or software to do this as it is part of a larger project</p>
|
<p>Try this</p>
<p><a href="http://filehelpers.sourceforge.net" rel="nofollow noreferrer">http://filehelpers.sourceforge.net</a></p>
<p>....why would you want to load the db into the dataset? Have another database keep track of the uniqueness (if there is such a word). While importing, check if exists in the logging database, if no, then load to Generic Database.</p>
<p>Wait for some other responses to this thread, we may get a better idea.</p>
|
<p>Your best bet is to buy an off the shelf application for doing this. </p>
<p>Professional Off The Shelf applications use native drivers and fine tune for each type of datasource they will hit against. This is always under the covers so you don't see how they go about it. For example, bulkcopy is used against SQL Server; Oracle has a Data Pump. </p>
<p>The problem with rolling your own is that you can either spend the money to fine tune your application to work with each of the source types you're likely to encounter OR you take a huge performance hit by using the generic ODBC / ADO / Whatever drivers.</p>
<p>At the end of the day, you are better off either leaving this out of your product or just dealing with the inevitable slow approach that you are forced to take. In this case that means using single insert statements for everything.</p>
<p>So, how much money do you have for development resources?</p>
| 21,196
|
<p>I'd like to automate TortoiseSVN as part of a commit process.
Specifically I'd like to dynamically create a log entry for the commit dialog.</p>
<p>I know that I can launch the commit dialog either from the commandline or by right clicking on a folder and selecting svncommit.</p>
<p>I'd like to use the start commit hook to setup a log entry.
I thought this worked by passing an entry file name in the MESSAGEFILE variable but when I add a hook script it cannot see this variable (hook launched successfully after right clicking and choosing svncommit).</p>
<p>When I try using the commandline I use the /logmsgfile parameter but it seems to have no effect.</p>
<p>I'm using tortoisesvn 1.5.3.</p>
|
<p>Looks like it was my own misunderstanding of the the API that caused by a problem.</p>
<p>Solution:<br>
1) I've added a start commit hook script to TortoiseSVN using the hooks gui in the settings area of the right click menu.</p>
<p>2) The script receive 3 pieces of information: PATH MESSAGEFILE CWD<br>
For details see: <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-bugtracker.html" rel="nofollow noreferrer" title="Manual">Manual</a><br>
These are passed as command line arguements to the script - for some reason I had thought they were set as temporary environmental variables.</p>
<p>My script then simply opens the file specified by the second arguement and adds in the custom text.</p>
<p>When the commit dialog comes up the custom text is there.</p>
<p>3) Best of all if tortoisesvn is launched from a script directly into the commit dialog:<br>
e.g. [ tortoiseproc /command:commit /path:. /closeonend:1 ]<br>
The hooks are still called.</p>
|
<p>If you just need a static template, set the tsvn:logtemplate property.</p>
<p>For dynamic generation, the /logmsgfile parameter does work, but it seems to need the full path. A batch file that looks like the following might work for you.</p>
<pre><code>GenerateLogMsg.exe > tmp.msg
"C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe" /command:commit /path:. /logmsgfile:"C:\Documents and Settings\User\My Documents\Visual Studio Projects\Project\tmp.msg"
</code></pre>
| 8,346
|
<p>I have a button, I need to display a pop-up in javascript. So on its client click I call a javascript function which does that.</p>
<p>if user clicks "yes", I need to do a post back and call buttons server side click event, here is what I am doing inside the javascript function</p>
<pre><code>__doPostBack(deleteLinkButton, 'Click');
' Where deleteLinkButton is a variable that has client Id of the button.
</code></pre>
<p>Postback happens but it does not go in the click handler for that button.</p>
<p>What can be wrong?</p>
|
<p>You are looking for a technology called Comet. <a href="http://en.wikipedia.org/wiki/Comet_(programming)" rel="nofollow noreferrer">Wikipedia entry</a>
If you Google "comet wcf" you'll find articles that should point you in the right direction.</p>
|
<p>Yes.
You can use WSDualHttpBinding or NetTcpBinding.</p>
| 49,463
|
<p>Let's say I have the following ruby code :</p>
<pre><code>
def use_object(object)
puts object.some_method
end
</code></pre>
<p>and , this will work on any object that responds to <strong>some_method</strong>,right?</p>
<p>Assuming that the following java interface exists :</p>
<pre><code>
interface TestInterface {
public String some_method();
}
</code></pre>
<p>Am I right to presume that interfaces are java's way to achieving the same thing ( with the only difference that the parameter's type would be <strong>TestInterface</strong> ) ?</p>
|
<p>You are right except that you can not define the body of a function in Java Interfaces, only prototypes. </p>
<p>Interfaces are the only way to implemente a pseudo multi-derivation in Java, since normal class derivation is only simple (just one parent).</p>
|
<p>It look like you are trying to program in Ruby using Java, you want want to rethink your approach to use more the idioms of the language.</p>
| 29,469
|
<p>I have a function that exports a table to CSV and in the query I set which fields will export.</p>
<p>Here is the query:</p>
<pre><code>SELECT lname, fname, email, address1, address2, city,
state, zip, venue_id, dtelephone, etelephone, tshirt FROM volunteers_2009
</code></pre>
<p>The field venue_id is the the id of the venue which is referred to in another table (venues)</p>
<p>So volunteers_2009.venue_id = venues.id</p>
<p>When I open the CSV file it displays the venue_id which I understand, but I need help modifying the query to put in the name of the venue (venues.venue_name) within the CSV file.</p>
<p>Any help is appreciated.</p>
|
<pre><code>SELECT a.lname, a.fname,a. email, a.address1,a. address2, a.city,
a.state, a.zip, a.venue_id, a.dtelephone, a.etelephone, a.tshirt,
COALESCE(b.venue_name,'') AS VenueName
FROM volunteers_2009 a
LEFT JOIN venues b ON b.id=a.venue_id
</code></pre>
|
<p>Standard SQL query for this is (assuming you want both ID and name for the venue):</p>
<pre><code>SELECT a.lname as lname, a.fname as fname, a.email as email,
a.address1 as address1, a.address2 as address2, a.city as city,
a.state as state, a.zip as zip, a.venue_id as venue_id,
b.venue_name as venue_name, a.dtelephone as dtelephone,
a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a, venues b
WHERE a.venue_id = b.id
AND a.venue_id IS NOT NULL
UNION ALL
SELECT a.lname as lname, a.fname as fname, a.email as email,
a.address1 as address1, a.address2 as address2, a.city as city,
a.state as state, a.zip as zip, a.venue_id as venue_id,
'' as venue_name, a.dtelephone as dtelephone,
a.etelephone as etelephone, a.tshirt as tshirt
FROM volunteers_2009 a
WHERE a.venue_id IS NULL
</code></pre>
| 40,839
|
<p>I read the <a href="http://en.wikipedia.org/wiki/Scenario_testing" rel="nofollow noreferrer">Wikipedia</a> article on scenario testing, but I am sad to say it is very short. I am left wondering: are scenario tests a collection of sequential unit tests? Or, perhaps, like a single multi-step unit test? Do many frameworks support scenario tests, or are they covered by unit testing?</p>
<p>If they have nothing to do with automation, what are they?</p>
|
<p>I don't think there's any fixed relationship between the number and distribution of tests and scenario tests.</p>
<p>I think the most common code-representation of a scenario is a specific set of business data required to support a specific story (scenario). This is often provided in the form of database data, fake stub data or a combination of both.</p>
<p>The idea is that this dataset has known and well-defined characteristics that will provide well defined results all across a given business process. </p>
<p>For a web application I could have a single web-test (or several for variations) that click through the full scenario. In other cases the scenario is used at a lower level, possibly testing a part of the scenario in a functional test or a unit test. In this case I normally never group the tests by scenario, but choose the functional grouping of tests I normally use for unit/functional tests. Quite often there's a method within "Subsystem1Test" that is called "testScenario1" or maybe "testScenarioInsufficientCredit". I prefer to give my scenarios names.</p>
|
<p>IMHO, scenario testing is a testing activity, as opposed to development activity ; hence it's about testing a product, not unit(s) of that product. The test scenario are end-to-end scenarios, using the <strong>natural interfaces</strong> of the product. If the product has programmatic interfaces, then you could use an unit test framework, or <a href="http://fitnesse.org/" rel="nofollow noreferrer">Fitnesse</a>.</p>
| 45,834
|
<p>I'm trying to implement a Load / Save function for a Windows Forms application.</p>
<p>I've got following components:</p>
<ul>
<li>A tree view</li>
<li>A couple of list views</li>
<li>A couple of text boxes</li>
<li>A couple of objects (which holds a big dictionarylist)</li>
</ul>
<p>I want to implement a way to save all of this into a file, and resume/load it later on.</p>
<p>What's the best way to do this? </p>
<p>I think XML serialization is the way to go, but I'm not quite sure how, or where to start. Or will it require a really complex solution to be able to do this?</p>
|
<p>Here's an example that binds an object and some ancestors
to the UI; the use of C# 3.0 here is purely for brevity -
everything would work with C# 2.0 too.</p>
<p>Most of the code here is setting up the form, and/or
dealing with property-change notifications -
importantly, there isn't any code devoted to updating
the UI from the object model, or the object model from
the UI.</p>
<p>Note also the IDE can do a lot of the data-binding code
for you, simply by dropping a BindingSource onto the
form and setting the DataSource to a type via
the dialog in the property grid.</p>
<p>Note that it isn't essential to provide property change
notifications (the PropertyChanged stuff) - however,
most 2-way UI binding will work considerably better
if you do implement this. Not that PostSharp has some
interesting ways of doing this with minimal code.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
static class Program { // formatted for vertical space
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Button load, save, newCust;
BindingSource source = new BindingSource { DataSource = typeof(Customer) };
XmlSerializer serializer = new XmlSerializer(typeof(Customer));
using (Form form = new Form {
DataBindings = {{"Text", source, "Name"}}, // show customer name as form title
Controls = {
new DataGridView { Dock = DockStyle.Fill, // grid of orders
DataSource = source, DataMember = "Orders"},
new TextBox { Dock = DockStyle.Top, ReadOnly = true, // readonly order ref
DataBindings = {{"Text", source, "Orders.OrderRef"}}},
new TextBox { Dock = DockStyle.Top, // editable customer name
DataBindings = {{"Text", source, "Name"}}},
(save = new Button { Dock = DockStyle.Bottom, Text = "save" }),
(load = new Button{ Dock = DockStyle.Bottom, Text = "load"}),
(newCust = new Button{ Dock = DockStyle.Bottom, Text = "new"}),
}
})
{
const string PATH = "customer.xml";
form.Load += delegate {
newCust.PerformClick(); // create new cust when loading form
load.Enabled = File.Exists(PATH);
};
save.Click += delegate {
using (var stream = File.Create(PATH)) {
serializer.Serialize(stream, source.DataSource);
}
load.Enabled = true;
};
load.Click += delegate {
using (var stream = File.OpenRead(PATH)) {
source.DataSource = serializer.Deserialize(stream);
}
};
newCust.Click += delegate {
source.DataSource = new Customer();
};
Application.Run(form);
}
}
}
[Serializable]
public sealed class Customer : NotifyBase {
private int customerId;
[DisplayName("Customer Number")]
public int CustomerId {
get { return customerId; }
set { SetField(ref customerId, value, "CustomerId"); }
}
private string name;
public string Name {
get { return name; }
set { SetField(ref name, value, "Name"); }
}
public List<Order> Orders { get; set; } // XmlSerializer demands setter
public Customer() {
Orders = new List<Order>();
}
}
[Serializable]
public sealed class Order : NotifyBase {
private int orderId;
[DisplayName("Order Number")]
public int OrderId {
get { return orderId; }
set { SetField(ref orderId, value, "OrderId"); }
}
private string orderRef;
[DisplayName("Reference")]
public string OrderRef {
get { return orderRef; }
set { SetField(ref orderRef, value, "OrderRef"); }
}
private decimal orderValue, carriageValue;
[DisplayName("Order Value")]
public decimal OrderValue {
get { return orderValue; }
set {
if (SetField(ref orderValue, value, "OrderValue")) {
OnPropertyChanged("TotalValue");
}
}
}
[DisplayName("Carriage Value")]
public decimal CarriageValue {
get { return carriageValue; }
set {
if (SetField(ref carriageValue, value, "CarriageValue")) {
OnPropertyChanged("TotalValue");
}
}
}
[DisplayName("Total Value")]
public decimal TotalValue { get { return OrderValue + CarriageValue; } }
}
[Serializable]
public class NotifyBase { // purely for convenience
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetField<T>(ref T field, T value, string propertyName) {
if (!EqualityComparer<T>.Default.Equals(field, value)) {
field = value;
OnPropertyChanged(propertyName);
return true;
}
return false;
}
protected virtual void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
</code></pre>
|
<blockquote>
<p>it is fairly trivial to use
data-binding to tie an object model to
the UI.</p>
</blockquote>
<p>How can I tie an object with a GUI control without a persistent storage? If I do it manually that means I have to write ridiculous amount of code for every single object in memory. I already have some sort of class storage for this data but it's not bind sort scenario, it's like read this write here.</p>
<p>Am I supposed to write a loader which loads serialized XML and get the object and then read the object and fill up the whole GUI? Obviously this more like manual loading not binding. Am I missing something ?</p>
| 45,287
|
<p>I'm writing some code that id like to be able to work with any window, such as a window created through the windows API, MFC, wxWidgets, etc.</p>
<p>The problem is that for some things I need to use the same thread that created the window, which in many cases is just sat in a message loop.</p>
<p>My first thought was to post a callback message to the window, which would then call a function in my code when it recieves the message using one of the params and a function pointer of some sorts. However there doesnt seem to be a standard windows message to do this, and I cant create my own message since I dont control the windows code, so cant add the needed code to the message handler to implement the callback...</p>
<p>Is there some other way to get the thread that created the window to enter my function?</p>
<p>EDIT:
John Z sugessted that I hooked the windows messages. If I do that is there some way to get "ids" for custom messages without the risk of conflicting with any custom messages the window already has?</p>
<p>eg I might do</p>
<pre><code>WM_CALLBACK = WM_APP+1
</code></pre>
<p>But if the window I'm hooking has already done something with WM_APP+1 I'm gonna run into problems.</p>
<p>EDIT2:
just found RegisterWindowMessage :)</p>
|
<p>If you are in the same process as the window you can hook its messages by subclassing it. Check out <a href="http://msdn.microsoft.com/en-us/library/ms633570(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms633570(VS.85).aspx</a></p>
<p>The key API is SetWindowLong.</p>
<pre><code>// Subclass the edit control.
wpOrigEditProc = (WNDPROC) SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG)EditSubclassProc);
// Remove the subclass from the edit control.
SetWindowLong(hwndEdit, GWL_WNDPROC, (LONG)wpOrigEditProc);
</code></pre>
|
<p>Alternatively to subclassing, you can use <a href="http://msdn.microsoft.com/en-us/library/ms644906(VS.85).aspx" rel="nofollow noreferrer">SetTimer</a> to call a function in the window thread.</p>
<pre><code>VOID CALLBACK Function(
HWND hwnd,
UINT uMsg,
UINT_PTR idEvent,
DWORD dwTime
)
{
// stuff
}
SetTimer(hWnd, event, 0, Function);
</code></pre>
| 44,841
|
<p>I'm architecting a new app at the moment, with a high read:write ratio. At my current employer we have lots of denormalised data on our tables for performance reasons. Is it better practice to have totally 3NF tables and then use indexed views to do all the denormalisation? Should I run queries against the tables or views?</p>
<p>An example of some of the things I am interested are aggregates of columns child tables (e.g. having user post count stored somewhere).</p>
|
<p>From your description, if you're looking for a pattern that matches better than Factory, try Strategy:</p>
<p><a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">Strategy Pattern</a></p>
<ol>
<li>Your <strong>context</strong> could be a custom class which encapsulates and abstracts the different report inputs (you could use the AbstractFactory pattern for this part)</li>
<li>Your <strong>strategy</strong> could implement any number of different query filters or additional logic needed. And if you ever need to change the system in the future, you can switch between report tools by simply creating a new strategy.</li>
</ol>
<p>Hope that helps!</p>
|
<p>We had a similar problem and went with the concept of "connectors" that are interfaces between the main report generator application and the different report engines. By doing this, we were able to create a "universal report server" application. You should check it out at www.versareports.com.</p>
| 23,273
|
<p>I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like <a href="http://www.nike.com/nikeskateboarding/v3/" rel="noreferrer">http://www.nike.com/nikeskateboarding/v3/</a>...)</p>
<p>I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's?</p>
|
<p>The trick is to use some simple JavaScript to resize the Flash DOM node:</p>
<pre><code>function resizeFlash( h ) {
// "flash-node-id" is the ID of the embedded Flash movie
document.getElementById("flash-node-id").style.height = h + "px";
}
</code></pre>
<p>Which you call from within the Flash movie like this:</p>
<pre><code>ExternalInterface.call("resizeFlash", 400);
</code></pre>
<p>You don't actually need to have the JavaScript code externally, you can do it all from Flash if you want to:</p>
<pre><code>ExternalInterface.call(
"function( id, h ) { document.getElementById(id).style.height = h + 'px'; }",
ExternalInterface.objectID,
400
);
</code></pre>
<p>The anonymous function is just to be able to pass in the ID and height as parameters instead of concatenating them into the JavaScript string.</p>
<p>I think that the JavaScript is fairly cross-platform. If you want to see a live example look at this site: <a href="http://www.talkoftheweather.com/" rel="noreferrer">talkoftheweather.com</a>. It may not look as though it does anything, but it automatically resizes the Flash movie size to accommodate all the news items (it does this just after loading the news, which is done so quickly that you don't notice it happening). The resize forces the browser to show a vertical scroll bar.</p>
|
<p>I halfway looked at swffit but the height (and width sometimes but mainly height) would be dynamic - swffit let's you declare a maxHeight but that number would be constantly changing...maybe I could figure out how to set it dynamically. A great place for me to start though - thanks!</p>
| 5,286
|
<p>In PHP, depending on your error reporting level, if you don't define a constant and then call it like so:</p>
<pre><code><?= MESSAGE ?>
</code></pre>
<p>It may print the name of the constant instead of the value!</p>
<p>So, I wrote the following function to get around this problem, but I wanted to know if you know a way to do it in faster code? I mean, when I did a speed test without this function, I can define and dump 500 constants in .0073 seconds. But use this function below, and this switches to anywhere from .0159 to .0238 seconds. So, it would be great to get the microseconds down to as small as possible. And why? Because I want to use this for templating. I'm thinking there simply has to be a better way than toggling the error reporting with every variable I want to display.</p>
<pre><code>function C($constant) {
$nPrev1 = error_reporting(E_ALL);
$sPrev2 = ini_set('display_errors', '0');
$sTest = defined($constant) ? 'defined' : 'not defined';
$oTest = (object) error_get_last();
error_reporting($nPrev1);
ini_set('display_errors', $sPrev2);
if (strpos($oTest->message, 'undefined constant')>0) {
return '';
} else {
return $constant;
}
}
<?= C(MESSAGE) ?>
</code></pre>
|
<p>As long as you don't mind using quotes on your constants, you can do this:</p>
<pre><code>function C($constant) {
return defined($constant) ? constant($constant) : 'Undefined';
}
echo C('MESSAGE') . '<br />';
define('MESSAGE', 'test');
echo C('MESSAGE') . '<br />';
</code></pre>
<p>Output:</p>
<blockquote>
<p>Undefined</p>
<p>test</p>
</blockquote>
<p>Otherwise, there's no way around it without catching the notice thrown by using an undefined constant.</p>
|
<p>try </p>
<pre>if (isset(constant($constant)) ...</pre>
<p>This shouldn't trigger any E_NOTICE messages, so you don't have to set and reset error_reporting.</p>
| 42,778
|
<p>i created a register page n login page 4 members in php n mysql.and also i created a admin account and now i want to do something like if the member register he will be added only when the administrator approves it.please help</p>
|
<p>The knee jerk reaction is to add a boolean column to the users table with a default value of false. However the best route is probably a CHAR(1) column with a default of 'P' for pending. Then when an admin makes a choice they can approve (set to 'Y') or deny (set to 'N') they won't have to look at everything (just list all users where the column is ='P')</p>
|
<ol>
<li>Introduce an "approved" column into the user table which indicates whether or not the account is approved</li>
<li>Provide an interface for administrators to view a list of such accounts and toggle their approval status</li>
<li>Update existing authentication code to check this column and disallow the use of "unapproved" accounts</li>
</ol>
| 43,620
|
<p>We used to use SourceSafe, and one thing I liked about it was that when you checked out a file, it automatically got you its latest version.</p>
<p>Now we work with Team System 2005, and it doesn't work that way - you have to "get latest version" before you start working on a file that you've checked out.</p>
<p>Is there a way to configure Team System (2005) to automatically get the latest version when checking out a file?</p>
|
<p>There's a Visual Studio Add-in for this that someone wrote: </p>
<p><a href="http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/03/24/TFS-GetLatest-version-on-check_2D00_out-Add_2D00_In.aspx" rel="nofollow noreferrer">http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/03/24/TFS-GetLatest-version-on-check_2D00_out-Add_2D00_In.aspx</a></p>
|
<p>Are you sure you want that?</p>
<p>It means that when you check out a file, it will be out of sync with the rest of your files. Your project may not build or function properly until you update all files.</p>
| 8,022
|
<p>This page displays beautifully in firefox but i get all kinds of problems when testing the site in opera or internet explorer, mostly with the menu. I would like to know what techniques have caused this and how to avoid them. </p>
<p><a href="http://www.jkhbdesign.se/" rel="nofollow noreferrer">http://www.jkhbdesign.se/</a></p>
<p>Edit 2: Here are some screenshots of some specific problems</p>
<p>The dropdown as it should look:</p>
<p><a href="http://nibbo.se/slask/correct.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/correct.png</a></p>
<p>The way it looks in IE 7:</p>
<p><a href="http://nibbo.se/slask/dropdownie.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/dropdownie.png</a></p>
<p>The way it looks in Opera:</p>
<p><a href="http://nibbo.se/slask/dropdownopera.png" rel="nofollow noreferrer">alt text http://nibbo.se/slask/dropdownopera.png</a></p>
|
<p>At the very least you are going to have to deal with the fact that the CSS :hover is not supported in IE for any tag except the anchor tag. You'll need to use onmouseover, onmouseout in IE to accomplish the same thing. Or change the li:hover to an a:hover but that would be a bigger overhaul of your design I think.</p>
<p>Specifically, CSS like this:</p>
<pre><code>ul.menu li:hover ul.submenu {
background:white none repeat scroll 0 0;
border:1px solid #A6A6A6;
display:block;
margin-left:-25px;
margin-top:23px;
padding:2px 0;
position:absolute;
}
</code></pre>
<p>Is not going to work properly in Internet Explorer. I don't know about Opera.</p>
|
<p>If you're familiar with javascript, you might want to look into the JQuery Superfish plugin. (<a href="http://plugins.jquery.com/project/Superfish" rel="nofollow noreferrer">http://plugins.jquery.com/project/Superfish</a>). Most of the hard work and weird browser issues are already taken care of for you.</p>
| 25,761
|
<p>Kind of a weird question, but. I need to have a list of strings i need to make sure that every string in that list is the same.</p>
<p>E.g:</p>
<pre><code>a = ['foo', 'foo', 'boo'] #not valid
b = ['foo', 'foo', 'foo'] #valid
</code></pre>
<p>Whats the best way to go about doing that?</p>
<p>FYI, i don't know how many strings are going to be in the list. Also this is a super easy question, but i am just too tired to think straight.</p>
|
<p>Use list.count to get the number of items in a list that match a value. If that number doesn't match the number of items, you know they aren't all the same.</p>
<pre><code>if a.count( "foo" ) != len(a)
</code></pre>
<p>Which would look like...</p>
<pre><code>if a.count( a[0] ) != len(a)
</code></pre>
<p>...in production code.</p>
|
<p>try (if the lists are not too long):</p>
<pre><code>b == [b[0]] * len(b) #valid
a == [a[0]] * len(a) #not valid
</code></pre>
<p>this lets you compare the list to a list of the same size that is all of the same first element</p>
| 46,962
|
<p>I want my emacs buffer to have a different name than the file name. Rather than setting this manually every time, I want to have this happen automatically based on the file contents, something like:</p>
<p>// Local Variables:<br>
// buffer-name: MyName<br>
// End:</p>
<p>But this doesn't work because buffer-name is a function, not a variable. How can I do this?</p>
|
<p>You could say:</p>
<pre><code>// Local Variables:
// eval: (rename-buffer "my-buffer-name-here")
// end:
</code></pre>
<p>It is a trick though. </p>
<p>You could otherwise program a <code>find-file-hook</code> hook in your <code>.emacs</code> which rename the buffer to a specific local variable contents. Something like:</p>
<pre><code>(defvar pdp-buffer-name nil)
(defun pdp-rename-buffer-if-necessary ()
"Rename the current buffer according to the value of variable"
(interactive)
(if (and pdp-buffer-name (stringp pdp-buffer-name))
(rename-buffer pdp-buffer-name)))
(add-hook 'find-file-hook 'pdp-rename-buffer-if-necessary)
</code></pre>
<p>Then in your specific file you have</p>
<pre><code>// Local Variables:
// pdp-buffer-name: "pierre"
// end:
</code></pre>
<p>With more brain power you could have a nicer solution.</p>
<p>Note that there could already exist an extension for your need. Look in the <a href="http://www.emacswiki.org" rel="noreferrer">Emacs wiki</a>.</p>
|
<p>Thanks Pierre. Your pdp-buffer-name elisp example worked very well.</p>
<p>I made one enhancement because I noticed emacs was treating the local variable as "unsafe" i.e., always prompting to ask if the value should be applied. Since I want this to work with many different values without cluttering up my .emacs with a list of "safe" values, I added a piece of advice. With the nomenclature of the previous example, it looks like this:</p>
<pre><code>;; allow all values for "pdp-buffer-name"
(defadvice safe-local-variable-p (after allow-pdp-buffer-name (sym val) activate)
(if (eq sym 'pdp-buffer-name)
(setq ad-return-value t))
)
</code></pre>
| 46,004
|
<p>I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?</p>
|
<p>This <a href="http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c12645__2/" rel="nofollow noreferrer">article</a> seems to Discuss something quite like what you're talking about.
Good luck.
Ola</p>
<p><strong>EDIT:</strong> From the linked article, your DataSource is exposed to your test via an attribute.</p>
<pre><code>[DataSource("System.Data.SqlClient",
"Data Source=VSTS;Initial Catalog=ContactManagerWebTest;
Integrated Security=True", "ValidContactInfo",
DataAccessMethod.Sequential), TestMethod()]
</code></pre>
<p>There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the <code>DataAccessMethod.Sequential</code>. If there are multiple rows in the table indicated by the <code>DataSourceAttribute</code>, then each test run will have <code>TestContext.DataRow</code> pointing to the current row/iteration for the test.</p>
|
<p>Open Local.testsettings file from solution explorer and go to Web Test -> Select "One run per data source now" option. That's it.</p>
| 11,496
|
<p>How exactly do you make an auto-refreshing <code>div</code> with JavaScript (specifically, jQuery)?</p>
<p>I know about the <code>setTimeout</code> method, but is it really a good practice ? Is there a better method?</p>
<pre><code>function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
});
window.setTimeout("update();", 10000);
}
</code></pre>
|
<p>Another modification:</p>
<pre><code>function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
</code></pre>
<p>The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening. </p>
<p>Also, if the server fails to respond, it won't keep trying. </p>
<p>I've used a similar method in the past using .ajax to handle even more complex behaviour:</p>
<pre><code>function update() {
$("#notice_div").html('Loading..');
$.ajax({
type: 'GET',
url: 'response.php',
timeout: 2000,
success: function(data) {
$("#some_div").html(data);
$("#notice_div").html('');
window.setTimeout(update, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Timeout contacting server..');
window.setTimeout(update, 60000);
}
}
</code></pre>
<p>This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.</p>
<p>This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.</p>
|
<p><a href="http://plugins.jquery.com/project/Timer" rel="nofollow noreferrer">There's a jQuery Timer plugin</a> you may want to try</p>
| 27,187
|
<p>I have an application written in Delphi 7 which does not require an admin privilages to run. </p>
<p>For some reason I am able to save files to c:\windows and c:\windows\system32 from within the application even though the application <b>has not requested UAC elevation</b>. I am logged in as an admin with <b>UAC turned on</b> and I haven't changed any of the default UAC settings. The files actually show up under Windows Explorer as well. I am not using the 'Run as Administrator' option.</p>
<p>If I try to do the same thing using WordPad under the same profile I get an error as expected.</p>
<p>Any ideas what is going on?</p>
<p>Th application is using Ole Structured Storage to save and includes the following manifest, if that helps.</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="DelphiApplication" version="1.0.0.0" processorArchitecture="*"/>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
publicKeyToken="6595b64144ccf1df"
language="*"
processorArchitecture="*"/>
</dependentAssembly>
</dependency>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="asInvoker"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
</code></pre>
<p>Edit: To be clear my application does not save anything to these locations by default. I am choosing these locations via the standard file save dialog. </p>
<p><strong>Update</strong></p>
<p>I have found out why my application was being treated as legacy despite including the above manifest. It turns out a 2nd manifest was also being included which did not have the 'trustInfo' section. I have removed this 2nd manifest and all is well now.</p>
<p>Thanks for all the help</p>
|
<p>This is a feature of UAC to make old applications compatible with Vista. It redirects any request to write to a system folder that the user lacks permission to a local folder.</p>
<p>They are stored under "AppData\Local\VirtualStore" folder under the current user's profile.
There is a group policy setting to disable this feature: "Virtualize file and registry write failures to per-user locations"</p>
<p>This file and registry virtualization features are designed to allow legacy applications to run under Windows Vista standard user accounts. Legacy application is defined as a 32-bit executable without a specific Vista manifest. If you provider a Vista manifest to decorate your application as Vista-compatible, this virtualization setting won't affect your application (as in your Wordpad example)</p>
<p>Mark Russinovich has a great article on this: <a href="http://technet.microsoft.com/en-us/magazine/cc138019.aspx" rel="nofollow noreferrer">Inside Windows Vista User Account Control</a></p>
|
<blockquote>
<p>I am running as an admin with UAC turned on.</p>
</blockquote>
<p>Do you mean that you are logged on as Administrator or do you mean that you run your Delphi application with the option "Run as administrator" (i.e. with an elevated token)?</p>
<p>If the latter is the case than your application will have permission to write to C:\Windows.</p>
| 48,457
|
<p>This question is a follow-up from <a href="https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful">How to indicate that a method was unsuccessful</a>. The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.</p>
<p>What is best:</p>
<pre><code>public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
</code></pre>
<p>or</p>
<pre><code>public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
</code></pre>
<p>I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?</p>
|
<p>Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.</p>
<p>If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:</p>
<pre><code>public int DoSomething(string input)
{
int ret;
Exception exception = DoSomethingImpl(input, out ret);
if (exception != null)
{
// Note that you'll lose stack trace accuracy here
throw exception;
}
return ret;
}
public bool TrySomething(string input, out int ret)
{
Exception exception = DoSomethingImpl(input, out ret);
return exception == null;
}
private Exception DoSomethingImpl(string input, out int ret)
{
ret = 0;
if (input != "bad")
{
ret = 5;
return null;
}
else
{
return new ArgumentException("Some details");
}
}
</code></pre>
<p>Time this before you commit to it though!</p>
|
<p>The first example is correct if you are just going to catch the exception and not do anything but return false with it. </p>
<p>You could change TrySomething to look like below.</p>
<pre><code>public bool TrySomething(string a, out result, bool throwException)
{
try
{
// Whatever
}
catch
{
if(throwException)
{
throw;
}
else
{
return false;
}
}
}
public bool TrySomething(string a, out result)
{
return TrySomething(a, out result, false);
}
</code></pre>
<p>So DoSomething would look like</p>
<pre><code>public int DoSomething(string a)
{
int result;
// This will throw the execption or
// change to false to not, or don't use the overloaded one.
TrySomething(a, out result, true)
return result;
}
</code></pre>
<p>If you did not want TrySomething with throwException exposed to the public you can make it a private member.</p>
<p>Exceptions could get expensive and you could do some RegEx checking on the string to prevent one from being thrown. It depends on what you are trying to do.</p>
| 22,046
|
<p>We are having a problem where IE6 (the only browser we have noticed this happening on) seems to be caching an empty version of our main stylesheet. The only way to resolve the problem is to request the stylesheet directly by typing the its url directly into the browser, and then when you refresh the page, it will appear with the styles. About a week or so later, it will happen again.</p>
<p>This isn't happening to all users, but we can't figure out why it is happening.</p>
<p>We are running IIS on Server 2003, and this problem started happening a couple of months ago (never had any problems before that).</p>
<p>I appreciate any help you can offer.</p>
<p>Paul</p>
<p>*I have looked closer and now it is doing the same for certain Javascripts as well.</p>
<ul>
<li>12-12-2008</li>
</ul>
<p>Thanks for the help Grant, IE is fairly locked down, but have checked what can be changed and it is fine, and no extra plug-ins are installed.</p>
<p>If you Ctrl-F5 or kill the temp files it doesn't seem to do anything. It's not until you request the file directly that it actually it actually fixes the problem which does indicate that there is a problem with IE caching a broken or empty version. Unfortunately, I must now wait until it happens again and I'm going to check the log files on the server.</p>
<p>Again thanks for the help.</p>
|
<p>I can't give you a direct answer, but I would start by installing <a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">Fiddler</a> and investigating the <code>Content-type</code> and <code>last-modified</code> response headers of the files that are causing you problems.</p>
<p>Also take note of the <code>If-Modified-Since</code> and <code>Pragma</code> request header values.</p>
<p>As well, I would check the Accessibility settings in IE (Tools > Internet Options... > Accessibility).</p>
<p>In addition, ensure they haven't installed any add-ons that might be causing this type of behaviour. An unrelated example: a couple of years ago, we had a problem where IE6 stopped sharing Session cookies between browser windows for one of our users. It turned out to be some cursor add-on to IE causing the problem.</p>
<p>Obviously if your users are using a locked down copy of IE, the above suggestions don't apply.</p>
<p>Lastly, what happens if the user holds CTRL and hits F5 to refresh the page unconditionally, do they get the latest copy of the stylesheet and JavaScript files then? And have you tried clearing the browser history completely and loading a fresh copy of the page (perhaps the cache itself is corrupt somehow)?</p>
|
<p>I also had the same behaviour once. However, I was using a php generated stylesheet, with the headers and every other information (client-side cache, server-side cache, compression) finely tuned in PHP for optimal performance.</p>
<p>Worked like a charm, but it seemed that IE6 did not load the stylesheets on some computers, in a non-reproducible way. I didn't have the time to investigate,and I didn't have access to the problematic computers, so we went back to plain-old simple stylesheets, and everything went back to normal. We said it was firewall-related, but I'm sure there's something nasty hiding inside IE6.</p>
<p>I beg to know what it is...</p>
| 46,787
|
<p>I want to know how to create a table where you can adjust the column widths. I have not figured out how to do this. If you know the secret sauce to this technique please let me know.</p>
|
<p>There is no simple answer such as "use some foobar html property".
This is done with javascript and DOM manipulations. <br>If you are curious to see an implementation of this feature with Prototype you can take a look at <a href="http://www.millstream.com.au/view/code/tablekit/" rel="nofollow noreferrer">TableKit</a>.<br>I am sure there are jQuery implementations out there... I like my good old Prototype ;)</p>
|
<p>The Yahoo UI (YUI) <a href="http://developer.yahoo.com/yui/datatable/" rel="nofollow noreferrer">data table</a> widget allows resizing of columns. It's publicly available, but still in Beta, and the YUI library is pretty bulky. Any implementation will have to be in JavaScript/DHTML, because the default HTML tables don't have that kind of capabilities.</p>
| 16,184
|
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p>
<p>For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..<br>
How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p>
<p><strong>Edit:</strong><br>
I managed to do it in this way</p>
<pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))
</code></pre>
<p>but is there a way to use a string as primaryjoin instead?</p>
|
<p>The and_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the & operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators. </p>
<p>You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.</p>
<p>For logical deletion, it might be better to map the whole class over a select that ignores deleted values:</p>
<pre><code>mapper(Something, select([sometable], sometable.c.deleted == False))
</code></pre>
|
<p>I'm only currently developing agains 0.4.something, but here's how I'd suggest it:</p>
<pre><code>db.query(Object).filter(Object.first==value).filter(Object.second==False).all()
</code></pre>
<p>I think that's what you are trying to do, right?</p>
<p>(Note: written in a web browser, not real code!)</p>
| 33,601
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.