input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Quick way to return a list of custom objects from a page method w/o a separate BLL <p>I am using jQuery to retrieve a JSON object from a page method. I have a DAL which uses SubSonic and if I return objects created from SubSonic-generated classes I will clog up the pipes. :) You know, all public properties get serialized. I don't want a separate business layer for this application, because it's small and focused on read operations and yet another layer seems like an overkill. To avoid downloading some SubSonic bloated objects (possibly with sensitive information as well) and avoid building a separate layer I tried returning a list of objects, like this:</p>
<pre><code>[WebMethod]
public static List<object> GetFiles()
{
FileCollection collection = DB
.Select()
.From(DataAccess.File.Schema)
.ExecuteAsCollection<FileCollection>();
List<object> files = new List<object>(collection.Count);
foreach (DataAccess.File file in collection)
{
files.Add(new {
file.FileId,
file.ApplicantFirstName,
file.ApplicantLastName,
file.UploadDate
}
);
}
return files;
}
</code></pre>
<p>It works and I get a nice JSON object in return (disregard the DateTime value):</p>
<pre><code>[{"FileId":1,"ApplicantFirstName":"PaweÅ","ApplicantLastName":"Krakowiak","UploadDate":"\/Date(1235656448387
)\/"}]
</code></pre>
<p>Is this a good approach? I am concerned about <code>List<object></code> - is it worse than returning say a <code>List<SomeDomainObject</code>>? Performance? Something else?</p>
<p>This is .NET 2.0, I can't use 3.5 features. At least anonymous types work...</p>
| <p>The biggest recommendation might be to make it a "Collection" rather than a List, but with a simple webservice return, it isn't as big of a deal, as that recommendation is most typically in environments where the object still lives in a .NET assembly.</p>
<p>I think it is easy to read as well.</p>
|
Passing variables to a view using Asp.net mvc and jQuery load() <p>I'm currently loading a view(ascx) into a div using jQuery load(). I want to pass some variables to the view when loading it though so i'm using $.load(view, data); This does not seem to cause any problems but i have no idea how to access the Json object i'm passing in to the control.</p>
<p>Here is the jQuery:</p>
<pre><code>var val = {"Id":"1"};
$("#DynamicForm").empty().load('/controller/view', val);
</code></pre>
| <p>In this case jQuery issues a POST request:</p>
<pre><code>POST /controller/view HTTP/1.1
...
Id=1
</code></pre>
<p>So, you can access the Id parameter as <code>Request.Form["Id"]</code>, or just as an action parameter:</p>
<pre><code>public class Controller...
{
public ActionResult Index(string Id) { ... }
}
</code></pre>
|
Trigger to update data on another sql server <p>I'm using two SQL Server, one is SQL Server 2000 and the other one is SQL Server 2005.</p>
<p>When the table1 in SQL Server 2000 gets updated/inserted/deleted, I have to update another table in SQL Server 2005. Is it possible to achieve that in a trigger? If not, what would be the possible options? </p>
<p>Thank you, have a nice day!</p>
| <p>If you're wanting to replicate the data, not just set something differently, you should look at SQL Replication as it'll manage things a lot better. eg it will do the updates asynchronously.</p>
<p>If you have to do them synchronously, or you just decide it's simpler or you need the whole operation wrapped as a single transaction, I'd put the logic in a procedure for cleanliness. You can create a linked server from 2000 to 2005 and refer to the table from there as SERVER.DATABASE.SCHEMA.TABLE. Alternatively you could execute a stored procedure on the remote server to do the insert/update/delete.</p>
<p>If you don't want SQL replication you might instead consider writing the insert/update/deletes from 2000 into a separate table within the same database, via the trigger. Then have a separate job that writes these changes to 2005 then removes them from the table. This would mean you could batch up the changes, mean updates to the original table would be done quicker, would deal better with lost connectivity between the two servers. However, you have less guarantee that the updates would actually be applied to the 2005 server, and you have the added complexity of a sql job that must be run. So it's a tradeoff. And once you start writing and maintaining this sort of logic you realise that's why MS wrote replication stuff, so you don't have to.</p>
|
Finding the farthest point in one set from another set <p>My goal is a more efficient implementation of the algorithm posed <a href="http://stackoverflow.com/questions/589145/what-does-this-mysterious-color-method-do-what-does-it-return">in this question</a>.</p>
<p>Consider two sets of points (in N-space. 3-space for the example case of RGB colorspace, while a solution for <strike>1-space</strike> 2-space differs only in the distance calculation). How do you find the point in the first set that is the farthest from its nearest neighbor in the second set?</p>
<p>In a 1-space example, given the sets A:{2,4,6,8} and B:{1,3,5}, the answer would be
8, as 8 is 3 units away from 5 (its nearest neighbor in B) while all other members of A are just 1 unit away from their nearest neighbor in B. edit: 1-space is overly simplified, as sorting is related to distance in a way that it is not in higher dimensions.</p>
<p>The solution in the source question involves a brute force comparison of every point in one set (all R,G,B where 512>=R+G+B>=256 and R%4=0 and G%4=0 and B%4=0) to every point in the other set (colorTable). Ignore, for the sake of this question, that the first set is elaborated programmatically instead of iterated over as a stored list like the second set.</p>
| <p>First you need to find every element's nearest neighbor in the other set.</p>
<p>To do this efficiently you need a <a href="http://en.wikipedia.org/wiki/Nearest%5Fneighbor%5Fsearch">nearest neighbor</a> algorithm. Personally I would implement a <a href="http://en.wikipedia.org/wiki/Kd%5Ftree">kd-tree</a> just because I've done it in the past in my algorithm class and it was fairly straightforward. Another viable alternative is an <a href="http://en.wikipedia.org/wiki/R-tree">R-tree</a>.</p>
<p>Do this once for each element in the smallest set. (Add one element from the smallest to larger one and run the algorithm to find its nearest neighbor.)</p>
<p>From this you should be able to get a list of nearest neighbors for each element.</p>
<p>While finding the pairs of nearest neighbors, keep them in a sorted data structure which has a fast addition method and a fast getMax method, such as a <a href="http://en.wikipedia.org/wiki/Heap%5F%28data%5Fstructure%29">heap</a>, sorted by <a href="http://en.wikipedia.org/wiki/Euclidean%5Fdistance">Euclidean distance</a>.</p>
<p>Then, once you're done simply ask the heap for the max.</p>
<p>The run time for this breaks down as follows:</p>
<p>N = size of smaller set<br />
M = size of the larger set</p>
<ul>
<li>N * O(log M + 1) for all the kd-tree nearest neighbor checks.</li>
<li>N * O(1) for calculating the Euclidean distance before adding it to the heap.</li>
<li>N * O(log N) for adding the pairs into the heap.</li>
<li>O(1) to get the final answer :D</li>
</ul>
<p>So in the end the whole algorithm is O(N*log M).</p>
<p>If you don't care about the order of each pair you can save a bit of time and space by only keeping the max found so far.</p>
<p>*Disclaimer: This all assumes you won't be using an enormously high number of dimensions and that your elements follow a mostly random distribution.</p>
|
How do I import an Excel Spreadsheet into a blog..? <p>We are interested in trying to import an Excel spreadsheet into our Blog.</p>
<p>A sample of the Excel spreadsheet that we generate each day and want to export into our Blog is located at:</p>
<p><a href="http://www.wallstreetsignals.com/WhatsWorking.html" rel="nofollow">http://www.wallstreetsignals.com/WhatsWorking.html</a></p>
<p>Our Blog is located at:</p>
<p><a href="http://whatsworkinginthestockmarket.blogspot.com/" rel="nofollow">http://whatsworkinginthestockmarket.blogspot.com/</a></p>
<p>We are interested in a program or method that would allow us to just import the Excel spreadsheet into our Blog instead of having to hand input all the data, which is what we are doing now.</p>
<p>Thank you for your thoughts and the cost to have you help accomplish our goal.</p>
<p>Philip
WallStreetSignals.com</p>
| <p>Well, outside of creating a program (which is possible, using PHP, Perl, Java, etc and either an excel input module or converting to CSV or XML and processing that)...</p>
<p>Have you considered using Google Documents or another online spreadsheet software? It's easy to import an excel spreadsheet, and then embed the spreadsheet in the blog post or webpage. Then if you need to change it, modify the google document spreadsheet and the changes are rendered on the webpage or blog post immediately.</p>
|
What successful conversion/rewrite of software have you done? <p>What successful conversion/rewrite have you done of software you were involved with? What where the languages and framework involved in the process? How large was the software in question? Finally what is the top one or two thing you learned from being involved with the process.</p>
<p>This is related to this <a href="http://stackoverflow.com/questions/592354/what-failed-conversion-rewrite-of-sofware-have-you-done">question</a></p>
| <p>I'm going for "most abstruse" here:</p>
<ul>
<li>Ported an 8080 simulator written in
FORTRAN 77 from a DECSystem-10 running TOPS-10 to an
IBM 4381 mainframe running VM/CMS.</li>
</ul>
|
Javascript: Error 'Object Required'. I can't decipher it. Can you? <p>I am using a javascript called 'Facelift 1.2' in one of my websites and while the script works in Safari 3, 4b and Opera, OmniWeb and Firefox it does not in any IE version.
But even in the working browser i get the following error I cannot decipher.</p>
<p>Maybe in due timeâwith more experience in things JavascriptâI will be able to but for now I thought I would ask some of you, here at SO.</p>
<p>The following is the error popup i get in IETester testing the page for Interet Explorer 6,7 and 8:
<img src="http://img21.imageshack.us/img21/3651/err2.png" alt="IE Error Pop Up" /></p>
<p>The following is from the Firebug console in Firefox 3.0.6:
<img src="http://img100.imageshack.us/img100/3636/err3.png" alt="Firebug Console Log" /></p>
<p>The website is: <a href="http://www.457cc.co.nz/index.php" rel="nofollow">http://www.457cc.co.nz/index.php</a> In case it helps you see the problem mentioned in action.</p>
<p>I have also looked up what line 620 corresponds to which is:
<em>"line 76" is:</em> </p>
<pre><code>this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
</code></pre>
<p>which is part of this block of code (taken from the flir.js):</p>
<pre><code>// either (options Object, fstyle FLIRStyle Object) or (fstyle FLIRStyle Object)
,init: function(options, fstyle) { // or options for flir style
if(this.isFStyle(options)) { // (fstyle FLIRStyle Object)
this.defaultStyle = options;
}else { // [options Object, fstyle FLIRStyle Object]
if(typeof options != 'undefined')
this.loadOptions(options);
if(typeof fstyle == 'undefined') {
this.defaultStyle = new FLIRStyle();
}else {
if(this.isFStyle(fstyle))
this.defaultStyle = fstyle;
else
this.defaultStyle = new FLIRStyle(fstyle);
}
}
this.calcDPI();
if(this.options.findEmbededFonts)
this.discoverEmbededFonts();
this.isIE = (navigator.userAgent.toLowerCase().indexOf('msie')>-1 && navigator.userAgent.toLowerCase().indexOf('opera')<0);
this.isCraptastic = (typeof document.body.style.maxHeight=='undefined');
if(this.isIE) {
this.flirIERepObj = [];
this.flirIEHovEls = [];
this.flirIEHovStyles = [];
}
}
</code></pre>
<p>The whole script is also available on my server: <a href="http://www.457cc.co.nz/facelift-1.2/flir.js" rel="nofollow">http://www.457cc.co.nz/facelift-1.2/flir.js</a></p>
<p>I just don't know where to start looking for the error, especially since it only affects IE but works in the rest. Maybe you guys have an idea. I would love to hear them.</p>
<p>Thanks for reading.
Jannis</p>
<p>PS: This is what Opera's error console reports:</p>
<pre><code>JavaScript - http://www.457cc.co.nz/index.php
Inline script thread
Error:
name: TypeError
message: Statement on line 620: Cannot convert undefined or null to Object
Backtrace:
Line 620 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
document.body.appendChild(test);
Line 70 of linked script http://www.457cc.co.nz/facelift-1.2/flir.js
this.calcDPI();
Line 2 of inline#1 script in http://www.457cc.co.nz/index.php
FLIR.init();
stacktrace: n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'
</code></pre>
| <p>I agree with tvanfosson - the reason you're getting that error is quite likely because you're calling <code>init()</code> before the page is done loading, so <code>document.body</code> is not yet defined. </p>
<p>In the page you linked, you should move the following code to the bottom of the page (just before the closing html tag:</p>
<pre><code><script type="text/javascript">
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
</script>
</code></pre>
<p>Even better, you should attach the initialization to the document's <code>ready</code> event. If you do it this way, there is no need to even move your javascript to the bottom of the file. Using jquery:</p>
<pre><code>$(document).ready( function(){
FLIR.init({ path: 'http://www.457cc.co.nz/facelift-1.2/' });
FLIR.auto();
});
</code></pre>
<p><a href="http://docs.jquery.com/Tutorials:Introducing%5F%24%28document%29.ready%28%29" rel="nofollow">More on jquery's document.ready event »</a></p>
|
How do I interpret this JVM fault? <p>I have a Java app that makes use of some native code, and it's faulting. I want to find out <em>where</em> it's faulting, but I'm not sure how to read the hs_err_pid dump file:</p>
<pre><code>Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V [libjvm.so+0x256cbc]
V [libjvm.so+0x25df69]
V [libjvm.so+0x25dbac]
V [libjvm.so+0x25e8c8]
V [libjvm.so+0x25e49f]
V [libjvm.so+0x16fa3e]
j br.com.cip.spb.single.SPBRequestApplicationController.processJob(Lcom/planet/core360/docgen/ProcessingEnvironment;Lcom/planet/core360/dsmv2/processing/ApplicationDataJob;)V+158
j com.planet.core360.cgen.CgenProcessor.processJob(Ljava/lang/String;Lcom/planet/core360/docgen/ProcessingEnvironment;Lcom/planet/core360/dsmv2/processing/ApplicationDataJob;)V+108
j com.planet.core360.cgen.CgenProcessor.processJob(Ljava/lang/String;Lcom/planet/core360/docgen/ProcessingEnvironment;Lcom/planet/core360/dsmv2/processing/ScheduledJob;)V+7
v ~StubRoutines::call_stub
V [libjvm.so+0x17af0c]
V [libjvm.so+0x28b9d8]
V [libjvm.so+0x17ad3f]
V [libjvm.so+0x1a58a3]
V [libjvm.so+0x18bc24]
C [cgen+0xa6d6]
C [cgen+0xae1e] cgen_process_job+0x336
C [cgen+0x10442]
C [cgen+0x7714]
C [cgen+0x38216]
C [cgen+0x3a29d]
C [cgen+0x37e3c]
C [cgen+0x7558]
C [libc.so.6+0x166e5] __libc_start_main+0xe5
</code></pre>
<p>Basically, what are the 'j' frames pointing to? Is <code>V+158</code> referring to the
bytecode offset in the class? How can I trace back from this to the source
lines in play?</p>
<p>Actually, I'd love a general guide to grokking these dumps. That'd be fantastic, too.</p>
| <p>For a general guide have a look at these two links <a href="http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/felog.html">Fatal Error Log Troubleshooting</a> and <a href="http://weblogs.java.net/blog/kohsuke/archive/2009/02/crash%5Fcourse%5Fon.html">Crash Course on JVM Crash Analysis</a></p>
|
How do I grow a database file? <p>I am trying to grow a database using the following the code below. However I get the following error. How do I check for size (3600MB) and grow it if necessary?</p>
<pre><code>USING MyDatabase
ALTER DATABASE MyDatabase
MODIFY FILE (NAME = MyDatabase_data, SIZE = 3600MB)
</code></pre>
<p>Error: MODIFY FILE failed. Specified size is less than or equal to current size.</p>
<p>UPDATE: I am not using Auto Grow due to the heavy traffic. Due to the setup I have here (long unrelated story) I need to make the change using code. However, if this code runs more than once I get the error described above. I need to check the size first before attempting the change again.</p>
| <p>The size of the DB will be shown by</p>
<pre><code>USE MyDatabase
EXEC sp_spaceused
</code></pre>
<p>looking at the code for sp_spaceused (I happen to be looking at a SQL 2000 server, but same/similar would be true for SQL2005 / SQL2008)</p>
<pre><code>USE master
EXEC sp_helptext 'sp_spaceused'
</code></pre>
<p>and the relevant code is:</p>
<pre><code>declare @dbsize dec(15,0)
declare @logsize dec(15)
declare @bytesperpage dec(15,0)
declare @pagesperMB dec(15,0)
select @dbsize = sum(convert(dec(15),size))
from dbo.sysfiles
where (status & 64 = 0)
select @logsize = sum(convert(dec(15),size))
from dbo.sysfiles
where (status & 64 <> 0)
select @bytesperpage = low
from master.dbo.spt_values
where number = 1
and type = 'E'
select @pagesperMB = 1048576 / @bytesperpage
select database_name = db_name(),
database_size =
ltrim(str((@dbsize + @logsize) / @pagesperMB,15,2) + ' MB')
</code></pre>
<p>so from that you could save the size to a variable and compare again the size you were trying to set:</p>
<pre><code>DECLARE @database_size bigint
SELECT @database_size = (@dbsize + @logsize) / @pagesperMB
IF @database_size < 3600
BEGIN
PRINT 'Expanding MyDatabase ...'
ALTER DATABASE MyDatabase
MODIFY FILE (NAME = MyDatabase_data, SIZE = 3600MB)
PRINT 'Expanding MyDatabase DONE'
END
ELSE
BEGIN
PRINT 'No expansion of MyDatabase required'
END
</code></pre>
|
Sharing single application across a 2 subdomains in IIS7 <p>I have an application that is currently deployed (ex. www.example.com ). However, now we have a "secure" subdomain, which will take all of the requests that need to be encrypted (ex. secure.example.com). The site that is at www.example.com is currently mapped to C:\inetpub\example.com\wwwroot\, and I've mapped secure.example.com to C:\inetpub\example.com\wwwroot\secure. </p>
<p>However, since secure.example.com was setup as a new website within the IIS Manager, when the secure site is visited, it displays an error since there is no web.config associated with this website; however, this is the way I want it since I want this to be a part of the application that is in the parent directory. </p>
| <p>I think what you really meant to do was just right click on the web site for example.com and edit the bindings. In there you can add host names to that site.</p>
<p>Make sure you add them for port 443 which is SSL.</p>
|
Check if a program exists from a Bash script <p>How would I validate that a program exists?</p>
<p>Which would then either return an error and exit or continue with the script?</p>
<p>It seems like it should be easy, but it's been stumping me.</p>
| <p>Yes; avoid <code>which</code>. Not only is it an external process you're launching for doing very little (meaning builtins like <code>hash</code>, <code>type</code> or <code>command</code> are way cheaper), you can also rely on the builtins to actually do what you want, while the effects of external commands can easily vary from system to system.</p>
<p>Why care?</p>
<ul>
<li>Many operating systems have a <code>which</code> that <strong>doesn't even set an exit status</strong>, meaning the <code>if which foo</code> won't even work there and will <strong>always</strong> report that <code>foo</code> exists, even if it doesn't (note that some POSIX shells appear to do this for <code>hash</code> too).</li>
<li>Many operating systems make <code>which</code> do custom and evil stuff like change the output or even hook into the package manager.</li>
</ul>
<p>So, don't use <code>which</code>. Instead use one of these:</p>
<pre><code>$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
$ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Â Aborting."; exit 1; }
</code></pre>
<p>(Minor side-note: some will suggest <code>2>&-</code> is the same <code>2>/dev/null</code> but shorter â <em>this is untrue</em>. <code>2>&-</code> closes FD 2 which causes an <strong>error</strong> in the program when it tries to write to stderr, which is very different from successfully writing to it and discarding the output (and dangerous!))</p>
<p>If your hash bang is <code>/bin/sh</code> then you should care about what POSIX says. <code>type</code> and <code>hash</code>'s exit codes aren't terribly well defined by POSIX, and <code>hash</code> is seen to exit successfully when the command doesn't exist (haven't seen this with <code>type</code> yet). <code>command</code>'s exit status is well defined by POSIX, so that one is probably the safest to use.</p>
<p>If your script uses <code>bash</code> though, POSIX rules don't really matter anymore and both <code>type</code> and <code>hash</code> become perfectly safe to use. <code>type</code> now has a <code>-P</code> to search just the <code>PATH</code> and <code>hash</code> has the side-effect that the command's location will be hashed (for faster lookup next time you use it), which is usually a good thing since you probably check for its existence in order to actually use it.</p>
<p>As a simple example, here's a function that runs <code>gdate</code> if it exists, otherwise <code>date</code>:</p>
<pre><code>gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
</code></pre>
<h2>In summary:</h2>
<p>Where <code>bash</code> is your shell/hashbang, consistently use <code>hash</code> (for commands) or <code>type</code> (to consider built-ins & keywords).</p>
<p>When writing a POSIX script, use <code>command -v</code>.</p>
|
MATLAB: determine dependencies from 'command line' excluding built in dependencies <p>Is there a way to determine all the dependencies of an .m file and any of the dependencies of the files it calls using a command in a script (command-line)?</p>
<p>There was a question like this before and it was really good because it suggested using the <code>depfun</code> function. BUT the issue with this was that it is outputting the <a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB</a> related files that it depends on as well.</p>
<p>EXAMPLE:
testing.m</p>
<pre><code>disp('TESTING!!');
</code></pre>
<p>The output of depfun('testing')</p>
<pre><code>'C:\testing.m'
'C:\MATLAB\R2008a\toolbox\matlab\datatypes\@opaque\char.m'
'C:\MATLAB\R2008a\toolbox\matlab\datatypes\@opaque\double.m'
'C:\MATLAB\R2008a\toolbox\matlab\datatypes\@opaque\toChar.m'
'C:\MATLAB\R2008a\toolbox\matlab\elfun\log10.m'
'C:\MATLAB\R2008a\toolbox\matlab\elmat\ans.m'
</code></pre>
<p>etc.</p>
<p>The list is a little bit longer.</p>
<p>The point here is that I was hoping there would be some similar function or a flag that would remove these unwanted dependencies.</p>
| <p>Here are a couple of links I found helpful when I wrote up a simple function to create a <a href="http://www.mathworks.com/matlabcentral/fileexchange/20164" rel="nofollow">table of contents for an m-file</a>:</p>
<ul>
<li>A thread discussing the undocumented function <a href="http://www.mathworks.co.uk/matlabcentral/newsreader/view%5Fthread/145245" rel="nofollow">MLINTMEX</a></li>
<li><a href="http://www.mathworks.com/matlabcentral/fileexchange/17291" rel="nofollow">FDEP</a> by Urs Schwarz on the MathWorks File Exchange</li>
<li><a href="http://www.mathworks.com/matlabcentral/fileexchange/15924" rel="nofollow">FARG</a> by Urs Schwarz on the MathWorks File Exchange</li>
</ul>
<p>EDIT: Since this problem piqued my curiosity, I started trying out a few ways I might approach it. Finding the dependencies on non-toolbox .m and .mex files was relatively trivial (I did this in MATLAB version 7.1.0.246):</p>
<pre><code>fcnName = 'myfile.m';
fcnList = depfun(fcnName,'-quiet');
listIndex = strmatch('C:\Program Files\MATLAB71\toolbox',fcnList);
fcnList = fcnList(setdiff(1:numel(fcnList),listIndex));
</code></pre>
<p>Here, I just used <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/depfun.html" rel="nofollow">DEPFUN</a> to get the dependencies, then I removed any files that began with 'C:\Program Files\MATLAB71\toolbox', where the MATLAB toolboxes are located on my machine. Note that this assumes you aren't placing any of your own code in these MATLAB directories (which you shouldn't do anyway).</p>
<p>To get dependencies on .mat and .txt files, I took another approach. For each of the files you get from the above code, you could load the text of the file into MATLAB and parse it with a regular expression to find strings that end in a '.mat' or '.txt':</p>
<pre><code>fid = fopen(fcnName,'rt');
fcnText = fscanf(fid,'%c');
fclose(fid);
expr = '[^\'']\''([^\''\n\r]+(?:\w\.(?:mat|txt)){1})\''[^\'']';
dataFiles = regexp(fcnText,expr,'tokens');
dataFiles = unique([dataFiles{:}]).';
</code></pre>
<p>There are a few limitations to the regular expression I used:</p>
<ul>
<li><p>If you have a string like 'help.txt' that appears in a comment (such as the help comment block of a function), it will still be detected by the regular expression. I tried to get around this with a lookaround operator, but that took too long to run.</p></li>
<li><p>If you build a string from variables (like "fileString = [someString '.mat']"), it will not be detected by the regular expression.</p></li>
<li><p>The returned strings of file names will be relative path strings. In other words, if you have the strings 'help.txt' or 'C:\temp\junk.mat' in the function, the regular expression matching will return 'help.txt' or 'C:\temp\junk.mat', exactly as they appear in the function. To find the full path, you can use the <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/which.html" rel="nofollow">WHICH</a> function on each data file (assuming the files reside somewhere on the MATLAB path).</p></li>
</ul>
<p>Hope you find these useful! =)</p>
|
Directory to store cached files in Rails? <p>I am generating some large files in my Rails application. Fortunately, they only need to be generated once. I would like to save these files to disk so that I don't have to generate them again.</p>
<p>Which directory in my Rails application is the most appropriate place to put application generated files?</p>
<p>Thanks!</p>
| <p>If security of the files is not an issue you can put them in a subdirectory of <code>public</code> (for example, <code>public/assets</code>) which in your deploy script is symlinked to a directory in <code>shared/public</code> so that when you redeploy the files are retained.</p>
<p>If security is an issue, the solution is similar, though you would not want the directory to be web accessible. Instead you would use a controller to control access and serve up the files with <code>send_file</code>.</p>
|
Overriding int on a bit enum <p>I saw some .NET 2.0 code which looked like this:</p>
<pre><code> public enum abc : int
{
value1 = 1,
value2 = 2,
value3 = 4
}
</code></pre>
<p>etc...</p>
<p>Now I know the flags enum can be used for bit values (like above, right?) so you can do | "or" &, etc, but what is the reason for not using that? What is the point in overriding int?</p>
<p>If I design an enum for choosing multiple values I would use the flags attribute and not override anything (what I don't understand). What does the above approach net?</p>
<p>Thanks</p>
| <p>It's not "overriding" <code>int</code>, it's indicating what type the enumeration is based on. The default is <code>int</code> so this actually isn't achieving anything, but in some cases you might want to base an enum on <code>long</code> to store more flags, or <code>byte</code> to save space if there will be very many instances of the enum around and it only has a few values, however the recommendation in the framework design guidelines is to use <code>int</code> unless you have a very good reason not to.</p>
<p>If this is intended to be a flags enumeration then it should be marked with <code>[Flags]</code>, and this appears to be the intention here, so the omission looks like a mistake. You can still combine the values using the bitwise operators even if it isn't marked with <code>[Flags]</code>, but from memory I think you get a compiler warning (or it might be an FxCop warning, or possibly a ReSharper warning...).</p>
|
Wtf IE7 - AJAX calls using setTimeout <p>I have tested this on Firefox, Opera and Seamonkey. It works fine. When it comes to Internet Explorer 7. It works but upto a certain point. I am making an AJAX call to a PHP script every few seconds. In IE7 it makes the first AJAX call and it retrieves the data but it doesn't do it again ever. Even though i have a setTimeout function in the else block. <strong>WHY?</strong> :(</p>
<pre><code>startTime = setTimeout('getStatus()', 5000);
}//function convertNow
</code></pre>
<p>function getStatus()
{</p>
<pre><code> $.ajax({
type: "GET",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("Downloading & Converting Video...<b style='font-size:17px;color:green;'>" + textFileResponse[0] + "</b><br /><b>" + properFileName + '</b>');
}
});//ajax
if(textFileResponse[0]=='100.0%'){
}
else{
continueTime = setTimeout('getStatus();', 3000);
alert('call end');
}
</code></pre>
<p>}</p>
<p>Apologies if any frustration comes through this question. I've been running around like a headless chicken for the past 3 hours.</p>
<p>Thank you for any help.</p>
<h2>EDIT 2</h2>
<p>I have added the full function. The setTimeout seems to be working correctly. It must be the AJAX call, am just checking what is being returned. Even stranger! It keeps returning the same value from the AJAX request and its not getting any newer values!! I think Answer 2 might have something.It may be due with cache but how do you over come that?</p>
| <p>Are you requesting the ajax call via HTTP GET as opposed to HTTP POST? IE tends to use cached results of ajax calls unless you use POST instead of GET.</p>
<p>EDIT: Since you've updated your question, I can see that you are indeed using the GET verb. Change it to POST and I bet your issue will be resolved.</p>
|
Client Certs on IIS - not sure I get it - experiences please? <p>Looking for some advice about the use of client certs to retro-fit access control to an existing app.</p>
<p>Our company has an existing intranet app (classic ASP/IIS) which we licence to others. Up till now it's been hosted within each organisation that used it and the security consisted of "if you're able to access the intranet you're able the access the application". </p>
<p>I'm now looking for a way to host this app externally so that other organisations who don't wish to host it themselves can use it (each new client would have their own installation).</p>
<p>All user in the new organisation would have a client cert so what I'd like to do is use the 'Require Client Certificate' stuff in IIS. It allows you to say "if Organisation=BigClientX then pretend they're local userY".</p>
<p>What I would prefer is something that says "if Organisation=BigClientX then let them access resources in virtualdirectoryZ otherwise ignore them".</p>
<p>I would be very happy to buy an addon (perhaps an ISAPI filter ?) which would do this for me if that was the best approach. <strong>Any advice / war stories would be welcomed</strong>.</p>
| <p>I've done something similar...</p>
<p>Generate the certificates internally from your org's domain controller. Export them both as PFX format for distribution, and CER format for you to import in IIS.</p>
<p>Distribute the PFX format exports along with the CA certificate for your DC, so your customers machines will "trust" your CA.</p>
<p>Now in the app properties IIS, go to the Directory Security tab, and under "Secure Communications" click "Edit". In there, click "Accept client certificates", "Enable Client Certificate Mapping", then "Edit".</p>
<p>Under the 1-to-1 tab, click "Add" and import the CER file. Enter the account you'd like to map this certificate to.</p>
<p>As for the "let them access resources" I'd advise doing that by the user account they're mapped through - that is, you can provide access to resources based on that account either through NTFS permissions, or through code by identifying the security context of the logged-in user.</p>
|
Parsing an HTML file with selectorgadget.com <p>How can I use beautiful soup and <a href="http://selectorgadget.com" rel="nofollow">selectorgadget</a> to scrape a website. For example I have a website - <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819115017" rel="nofollow">(a newegg product)</a> and I would like my script to return all of the specifications of that product (click on SPECIFICATIONS) by this I mean - Intel, Desktop, ......, 2.4GHz, 1066Mhz, ...... , 3 years limited. </p>
<p>After using selectorgadget I get the string-
.desc</p>
<p>How do I use this?</p>
<p>Thanks :)</p>
| <p>Inspecting the page, I can see that the specifications are placed in a div with the ID pcraSpecs:</p>
<pre><code><div id="pcraSpecs">
<script type="text/javascript">...</script>
<TABLE cellpadding="0" cellspacing="0" class="specification">
<TR>
<TD colspan="2" class="title">Model</TD>
</TR>
<TR>
<TD class="name">Brand</TD>
<TD class="desc"><script type="text/javascript">document.write(neg_specification_newline('Intel'));</script></TD>
</TR>
<TR>
<TD class="name">Processors Type</TD>
<TD class="desc"><script type="text/javascript">document.write(neg_specification_newline('Desktop'));</script></TD>
</TR>
...
</TABLE>
</div>
</code></pre>
<p>desc is the class of the table cells.</p>
<p>What you want to do is to extract the contents of this table.</p>
<p><code>soup.find(id="pcraSpecs").findAll("td")</code> should get you started.</p>
|
Tricks to debugging UITextField <p>I'm debugging some code and finding it difficult to see & track the values being entered by the iPhone's keyboard into a UITextField (and from the UIDatePicker.)</p>
<p>I would expect Arguments>self>textField>_text to reflect the value that was entered into the textField but it isn't. It show's a different value ($0.00 instead of $1.25 for instance). When I write the value out via NSLog(@"textField.text:%@", textField.text); it shows the correct $1.25 value. What gives?</p>
<p>I wonder if this might be related to the fact that the UITextField is still first responder and this code I'm debugging is in a "Save" button that is pressed immediately after entering data in said UITextField?!? If so, question remains, where is that data stored and how can I debug it? I have similar trouble with a UIDatePicker used in a similar situation to modify a UITextField's value. </p>
<p>Thanks!</p>
| <p>What you are asking is essentially;</p>
<blockquote>
<p>How can I view private class data in the debugger and have it reflect what I expect?</p>
</blockquote>
<p>The answers is basically that you can't. The _text field may be updated at a later date, or not used at all. </p>
<p>If you do want a way to debug what's entered in a UITextField you can consider using the textField:shouldChangeCharactersInRange in the delegate to print out characters are they're typed.</p>
|
Is a "master preferences" class a good idea? <p>I have a class that manages user preferences for a large software project. Any class in the project that may need to set or retrieve a user preference from a persistent store is to call the static methods on this class. This centralized management allows the preferences to be completely wiped programmatically - which would be impossible if each pref was handled close to its use code, sprinkled throughout the project.</p>
<p>I ran into another implication of the centralization design in the course of this. The software has a public API. That API can be provided by itself in a jar. Classes in that API might refer to the pref management class. So, the pref manager has to go in the API jar.</p>
<p>Each preference might have a default value. Upon software startup, that default might be computed. The algorithm depends on the preference, and thus tends to reside near the use code. So if the pref manager needs to come up with a default, it calls the class in question.</p>
<p>But now that pref manager has become an "octopus class", sucking in all sorts of classes into the API jar that shouldn't be there. If it doesn't, then programs using the API jar quickly run into ClassDef exceptions. If it does, then the API jar is now bloated, as each of those other classes may refer to still others.</p>
<p>In general, do other Java programmers manage their preferences with a centralized class?</p>
<p>Does it make sense to distribute that static pref management class as part of a public API?</p>
<p>Should that pref manager be the keeper of the code for determining defaults?</p>
| <p>IMHO, I think that the answer to your first question is "yes" and "no".</p>
<p>Preferences are commonly handled as a centralized class, in the sense that the class is a "sink" for many classes in the project. Trying to do it closer to the calling code means that if the same preference is later useful elsewhere, you are in trouble. In my experience, trying to put the preferences "too close" also results in a very inconsistent handling.</p>
<p>That being said, it is often preferable to use multiple preference classes or "preference set", each supporting a module or submodule. If you look at the main components of your architecture, you will often find that the set of preferences can be logically partitioned. This reduces the mess in each preference class. More importantly, it will allow you to split your program into multiple jars in the future. Now, the "default value" calculators can be placed in the module but still in a global enough area. </p>
<p>I would also suggest not setting preferences directly as static methods, but rather using some getInstance() like operation to obtain a shared instance of the preferences manage, and then operating on it. Depending on your semantics, you may want to lock that object for a while (e.g., while the user is editing preferences in a UI) and this is easier if you have an actual object.</p>
<p>For your other questions, I would say that your public API should have a way of letting users change preferences, but only if you can document well enough what the results of these changes could be. </p>
<p>If you use a single API function to get the "reference manager", you can give users the possibility of providing their own "default values calculator". The preference manager will ask this calculator first before resorting to the one you have provided by default.</p>
|
@âData Source=(local)\ SIRSYSTEM \ HEY;â â canât connect if a string includes SIRSYSTEM <p>The name of my MS Sql server instance is HEY, but when trying to log on to Sql server via Microsoft Sql management studio, the login window displays as the name of a server
"SIRSYSTEM\HEY". </p>
<p>What is SIRSYSTEM? A name of default server instance? If so, then why canât I connect to HEY using the following connection string ( in Ado.net ):</p>
<p>@"Data Source=(local)\ SIRSYSTEM \ HEY;Initial Catalog=FilmClub;"+
"Integrated Security=true";</p>
<p>cheers</p>
| <p>SIRSYSTEM is the server or workstation name hosting the instance; to connect to, it the datasource would be either .\HEY, or SIRSYSTEM\HEY, get rid of the (local)\</p>
|
Regular expressions for non-strings <p>I was wondering if there is such a thing as regular expressions for sequential data that isn't a string.</p>
<p>I know that regular expressions essentially boil down to DFAs, but I'm more interested in higher-level languages for specifying these DFAs.</p>
| <p>You can argue that a grammar is a form of regular expression for things that are more complex than just strings. In principle, you can devise regular expressions on other tokens than just characters. As one option, you could argue that a regex for Unicode is such a creature - it certainly isn't matching simple bytes as the classic regex does.</p>
|
Why canât I use a SqlConnection instance until the SqlDataReader is closed? <p>From MSDN:</p>
<blockquote>
<p>While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.</p>
</blockquote>
<p>a) Why couldnât you use SqlConnection for anything else? After all, when <code>ExecuteQuery()</code> returns SqlDataReader object, the data from DB has already been retrieved and populated SqlDatareader object. Thus I donât see how or why SqlConnection should still be serving SqlDataReader object?! </p>
<p>b) More importantly, for what reason would it be bad idea to retrieve output parameters before you call <code>Close()</code> on SqlDataReader?</p>
<p>c) When above quote mentions that no other operations can be performed on SqlConnection, what operations does it have in mind? Just those that would require to connect to remote sql server, or we canât use any members of SqlConnection instance? </p>
<p>Thank you.</p>
| <p>a) When <code>ExecuteReader</code> returns, the data has not all been retrieved and populated in the reader, it may still be streaming back from the database. That's the whole point of the <code>SqlDataReader</code> because it's more efficient to do this than to load it all up front.</p>
<p>b) You can't retrieve output parameters until after the reader has finished because of the way the Tabular Data Stream (TDS) protocol is structured. The output parameters are not physically sent down the stream until after the result set data.</p>
<p>c) It means none of the operations except <code>Close</code> are documented as being guaranteed to work. Whether they actually do work or not is irrelevant because that is an implementation detail rather than a contract, and programming against implementation details is a recipe for disaster.</p>
<p>Why do you want to re-use the connection anyway? The connections that <code>SqlConnection</code> uses are pooled behind the scenes, so when you dispose one it doesn't really get rid of all the resources, it just returns the connection to the pool. This means you can use the connection for the shortest time possible, ideally within a <code>using</code> block, and not have to worry about this type of thing. Just create a new connection whenever you need one, and don't bother trying to re-use them as it's already happening behind the scenes.</p>
|
TableAdapter - updating without a key <p>I'm a total newbie at the .net c# business and dove in this last week creating a form application to shuffle data around for SSIS configurations. The geniuses at MS decided not to apply a key to the table I'm working with - and generating a composite key of the two candidate fields will not work due to their combined length being too long. I don't particularly want to mess with the [ssis configurations] table schema by adding an autoincrement field. </p>
<p>So I've been having alot of trouble getting an update from a DataGridView control to work with a TableAdapter. </p>
<p>I need the update statement to be update table set a = x where b = y and c = z.</p>
<p>Can I set the update method of the TableAdapter, and if so, how. If not, what to do?</p>
<p>I see this autogenerated code:</p>
<pre><code>this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.InsertCommand.Connection = this.Connection;
this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[SSIS Configurations Staging] ([ConfigurationFilter], [Configur" +
"edValue], [PackagePath], [ConfiguredValueType]) VALUES (@ConfigurationFilter, @C" +
"onfiguredValue, @PackagePath, @ConfiguredValueType)";
</code></pre>
<p>But in my form code, the UpdateCommand is not available. I'm assuming this is because the above code is a class definition which I cannot change after creating the object. I see this code has a recommendation not to be changed since it is autogenerated by VS.</p>
<p>Thanks for your most excellent advice.</p>
| <p>From your code i assume you are using a typed Dataset with the designer.</p>
<p>Not having a primary key is one of the many reasons the designer will not generate Insert, Update or Delete commands. This is a limitation of the CommandBuilder.</p>
<p>You could use the properties window to add an Update Command to the Apdapter but I would advice against that, if you later configure your main query again it will happily throw away all your work. The same argument holds against modifying the code in any *.Designer.cs file.</p>
<p>Instead, doubleclick on the caption with the Adaptername. The designer will create (if necessary) the accompanying non-designer source file and put the outside of a partial class in it. Unfortunately that is how far the code-generation of the designer goes in C#, you'll have to take it from there. (Aside: The VB designer knows a few more tricks).</p>
<p>Edit:</p>
<p>You will have to provide your own Update(...) method and setup an UpdateCommand etc.</p>
<pre><code> var updateCommand = new SqlCommand();
...
</code></pre>
|
When is it best to use a new class rather than add to an existing class <p>I have a class called Player in the business layer of my web application.</p>
<p>Player class has fields PlayerID, CategoryID and CountryID</p>
<p>A function in Player Class calls a function in PlayerDB Class in the Data Access Layer which in turn calls a stored proc which returns data for PlayerID, CategoryID (foreign key to Category table) and CountryID(foreign key to Country table) from the Player table.</p>
<p>I now have a situation where I want to add Country Name and Country Image (url path) to the above call, returning the new fields from the Country table for each CountryID.</p>
<p>My question is, do I add the country name and country image as additional fields to the Player class or do I have new classes called Country(BLL) and CountryDB(DAL) and a new stored proc?</p>
<p>I want to do what is best practice rather than what may be the easiest way.</p>
<p>If it is relevant I am using ASP.NET, VB.NET and SQL2005.</p>
<p>As you can probably tell I am a newbie so forgive me if I have not used the correct terminology in my question. I hope you get the idea.</p>
| <p>Create a new class. If it makes sense as a separate logical entity then it should be it's own class.</p>
|
Struggling with currency in Cocoa <p>I'm trying to do something I'd think would be fairly simple: Let a user input a dollar amount, store that amount in an NSNumber (NSDecimalNumber?), then display that amount formatted as currency again at some later time. </p>
<p>My trouble is not so much with the setNumberStyle:NSNumberFormatterCurrencyStyle and displaying floats as currency. The trouble is more with how said numberFormatter works with this UITextField. I can find few examples. <a href="http://stackoverflow.com/questions/276382/best-way-to-enter-numeric-values-with-decimal-points">This thread</a> from November and <a href="http://stackoverflow.com/questions/317311/obtaining-an-nsdecimalnumber-from-a-locale-specific-string">this one</a> give me some ideas but leaves me with more questions.</p>
<p>I am using the UIKeyboardTypeNumberPad keyboard and understand that I should probably show $0.00 (or whatever local currency format is) in the field upon display then as a user enters numerals to shift the decimal place along:</p>
<ul>
<li>Begin with display $0.00</li>
<li>Tap 2 key: display $0.02 </li>
<li>Tap 5 key: display $0.25</li>
<li>Tap 4 key: display $2.54</li>
<li>Tap 3 key: display $25.43</li>
</ul>
<p>Then [numberFormatter numberFromString:textField.text] should give me a value I can store in my NSNumber variable. </p>
<p>Sadly I'm still struggling: Is this <em>really</em> the best/easiest way? If so then maybe someone can help me with the implementation? I feel UITextField may need a delegate responding to every keypress but not sure what, where and how to implement it?! Any sample code? I'd greatly appreciate it! I've searched high and low...</p>
<p><strong>Edit1:</strong> So I'm looking into NSFormatter's <strong>stringForObjectValue:</strong> and the closest thing I can find to what benzado recommends: <strong>UITextViewTextDidChangeNotification</strong>. Having really tough time finding sample code on either of them...so let me know if you know where to look?</p>
| <p>My solution:</p>
<p><pre><code>
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
// Clear all characters that are not numbers
// (like currency symbols or dividers)
NSString *cleanCentString = [[textField.text
componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
// Parse final integer value
NSInteger centAmount = cleanCentString.integerValue;
// Check the user input
if (string.length > 0)
{
// Digit added
centAmount = centAmount * 10 + string.integerValue;
}
else
{
// Digit deleted
centAmount = centAmount / 10;
}
// Update call amount value
[_amount release];
_amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f];
// Write amount with currency symbols to the textfield
NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];
[_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[_currencyFormatter setCurrencyCode:@"USD"];
[_currencyFormatter setNegativeFormat:@"-¤#,##0.00"];
textField.text = [_currencyFormatter stringFromNumber:_amount];
[_currencyFormatter release]
// Since we already wrote our changes to the textfield
// we don't want to change the textfield again
return NO;
}
</pre></code></p>
|
Why can some arrays be published but not others? <pre><code>type
TStaticArray = array[1..10] of integer;
TDynamicArray = array of integer;
TMyClass = class(TObject)
private
FStaticArray: TStaticArray;
FDynamicArray: TDynamicArray;
published
property staticArray: TStaticArray read FStaticArray write FStaticArray; //compiler chokes on this
property dynamicArray: TDynamicArray read FDynamicArray write FDynamicArray; //compiler accepts this one just fine
end;
</code></pre>
<p>What's going on here? A static array gives the error, "published property 'staticArray' cannot be of type ARRAY" but dynamic arrays are just fine? I'm confused. Anyone know the reasoning behind this, and how I can work around it? (And no, I don't want to redeclare all my static arrays as dynamic. They're the size they are for a reason.)</p>
| <p>Published declaration tells the compiler to store information in the virtual method table. Only certain kinds of information can be stored.<br />
The type of a published property cannot be a pointer, record, or array. If it is a set type, it must be small enough to be stored in an integer.<br />
(O'REILLY, DELPHİ IN A NUTSHELL)</p>
|
Can someone explain why MySQL returns both values when name = 'test': "test" and "test " <p>I have the following table and data:</p>
<pre><code>CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(8) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
INSERT INTO `test` (`id`, `name`) VALUES (1, 'test');
INSERT INTO `test` (`id`, `name`) VALUES (2, 'test ');
</code></pre>
<p>When I do either of the following queries, it returns 2 rows (both rows):</p>
<pre><code>SELECT * FROM test WHERE name = 'test';
SELECT * FROM test WHERE name IN ('test');
</code></pre>
<p>Can anyone explain this to me and/or how to fix it?</p>
<p>I'm runing MySQL 5.0.27.</p>
| <p>From the mysql manual:</p>
<blockquote>
<p>Note that all MySQL collations are of type PADSPACE. This means that all CHAR and VARCHAR values in MySQL are compared without regard to any trailing spaces.</p>
</blockquote>
<p>Take note that MySQL does <strong>not</strong> remove the trailing spaces in a version 5.0.3 or higher, they are stored, but not used during comparisons:</p>
<blockquote>
<p>VARCHAR values are not padded when they are stored. Handling of trailing spaces is version-dependent. As of MySQL 5.0.3, trailing spaces are retained when values are stored and retrieved, in conformance with standard SQL. Before MySQL 5.0.3, trailing spaces are removed from values when they are stored into a VARCHAR column; this means that the spaces also are absent from retrieved values. </p>
</blockquote>
<p>Both of these quotes come from this page of the manual: <a href="http://dev.mysql.com/doc/refman/5.0/en/char.html" rel="nofollow">10.4.1. The CHAR and VARCHAR Types</a></p>
|
IIS - Different processing of default document in Integrated Pipeline mode? <p>I have an HTTP Module to handle authentication from Facebook, which works fine in classic pipeline mode. </p>
<p>In integrated pipeline mode, however, I'm seeing an additional request pass through for the default document, which is causing the module to fail. We look at the request (from Facebook) to retrieve and validate the user accessing our app. The initial request authenticates fine, but then I see a <em>second</em> request, which lacks the posted form variables, and thus causes authentication to fail.</p>
<p>In integrated pipeline mode, an http request for "/" yields 2 AuthenticateRequests in a row:</p>
<ol>
<li>A request where AppRelativeCurrentExecutionFilePath = "~/"</li>
<li>A request where AppRelativeCurrentExecutionFilePath = "~/default.aspx"</li>
</ol>
<p>That second request loses all of the form values, so it fails to authenticate. In classic mode, that second request is the only one that happens, and it preserves the form values.</p>
<p>Any ideas what's going on here?</p>
<p>UPDATE: Here is an image of the trace from module notifications in IIS. Note that my module, FBAuth, is seeing AUTHENTICATE_REQUEST multiple times (I'd expect 2 - one for authenticate and one for postauthenticate, but I get 4).</p>
<p><a href="http://www.flickr.com/photos/lianza/3314934429/" rel="nofollow" title="Events raised multiple times by tlianza, on Flickr"><img src="http://farm4.static.flickr.com/3389/3314934429_d1bd35ced0_m.jpg" width="240" height="186" alt="Events raised multiple times" /></a></p>
<p>I'm starting to believe this has something to do with module/filter configuration because I've found a (Vista) box running the same code that doesn't fire these events repeatedly - it behaves as expected. I'm working through trying to figure out what the difference could be...</p>
<p>Thanks!
Tom</p>
| <p>Did you find a solution? Mine was to add the following code at the end of Application_BeginRequest:</p>
<pre><code>if (Request.RawUrl.TrimEnd('/') == HostingEnvironment.ApplicationVirtualPath.TrimEnd('/'))
Server.Transfer(Request.RawUrl+"Default.aspx", true);
</code></pre>
|
What is the best way to store configuration variables in PHP? <p>I need to store a bunch of configuration information in PHP.</p>
<p>I have considered the following....</p>
<pre><code>// Doesn't seem right.
$mysqlPass = 'password';
// Seems slightly better.
$config = array(
'mysql_pass' => 'password'
);
// Seems dangerous having this data accessible by anything. but it can't be
// changed via this method.
define('MYSQL_PASSWORD', 'password');
// Don't know if this is such a good idea.
class Config
{
const static MYSQL_PASSWORD = 'password';
}
</code></pre>
<p>This is all I have thought of so far. I intend to import this configuration information into my application with <code>require /config.inc.php</code>.</p>
<p>What works for you with regard to storing configuration data, and what are best practices concerning this?</p>
| <p>I've always gone with option #2 and just ensure that no one but the owner has ANY sort of access to it. It's the most popular method among PHP applications like Joomla, vBulletin, Gallery, and numerous others.</p>
<p>First method is too messy to me (readability) and the third is WAY too dangerous to do. I've never thought about the Class method, so someone else can provide their input on that one. But I guess it's fine so long as the right access is used on the class' usage.</p>
<p><hr /></p>
<p>Example..</p>
<pre><code>define('EXAMPLE1', "test1"); // scenario 1
$example2 = "test2"; // scenario 2
function DealWithUserInput($input)
{
return eval($input);
}
</code></pre>
<p>Now this example of code is really dumb, but just an example. Consider what could be returned by the function depending on which scenario the user could try to use in their input.</p>
<p>Scenario 2 would only cause an issue if you made it a global within the function. Otherwise it's out of scope and unreachable.</p>
|
Netfiler hook not getting called <p>I am writing a kernel module which registers a hook with netfilter. The handler is not being called if I ssh/telnet into the machine where the module is loaded. </p>
<pre><code>struct nf_hook_ops my_hook_ops;
my_hook_ops.hook = hook_handler;
my_hook_ops.pf = PF_INET;
my_hook_ops.hooknum = NF_INET_PRE_ROUTING;
my_hook_ops.priority = NF_IP_PRI_FIRST;
nf_register_hook(&my_hook_ops);
</code></pre>
<p>The handler function:</p>
<pre><code>unsigned int hook_handler(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
if(!skb)
return NF_ACCEPT;
struct iphdr* ip_header;
struct tcphdr* tcp_header;
union ip_address ipaddr;
printk(KERN_INFO "Entered handler\n");
if(skb->protocol == 8)
return NF_ACCEPT;
// Log the received packet
ip_header = ip_hdr(skb);
tcp_header = tcp_hdr(skb);
ipaddr.saddr = ip_header->saddr;
printk(KERN_INFO "Received packet:\nIP Address: %u.%u.%u.%u\nProtocol: %d\nSource port: %d\nDestination port: %d\n",
ipaddr.a[0],ipaddr.a[1],ipaddr.a[2],ipaddr.a[3],
skb->protocol,
tcp_header->source,
tcp_header->dest);
return NF_ACCEPT;
}
</code></pre>
<p>The hook is being called for protocol 8 (Exterior Gateway Protocol). The second printk never gets printed. Am I missing anything?</p>
| <p>The protocol used here is different from the IP protocol number as assigned by IANA, for which 8 is for EGP and EGP has been outdated.</p>
<p>The protocol field for sk_buff is defined in , for which 8 is for ETH_P_IP. As your data is allways IP traffic,the first conditional check is always true. So the second part of code never get executed.</p>
|
Cocoa - Modal Window With Animating NSOpenGLView behind it <p>I have an NSWindow subclass (GameWindow) containing an NSOpenGLView subclass (GameView).</p>
<p>The app is windowed (does not go fullscreen).</p>
<p>An OpenGL animation in GameView is fired ~30 times a second by a timer.</p>
<p>For presentation reasons, the GameView animation MUST continue regardless of what else is happening in the app. The only time it should stop is in the case of a fatal error.</p>
<p>I need to present various "modal" Cocoa windows (e.g. choose new game, confirm quit, etc.) while the animation in GameWindow continues. Some of these could be sheets, but major ones need to appear as standalone windows (complete with WebViews).</p>
<p>MY QUESTION: how can I display these "dialog" windows such that my app timer continues to fire, my animation continues, but user input to the GameView in the GameWindow is blocked until the "dialog" window is dismissed by the user?</p>
<p>(I need to support Tiger + Leopard at this time).</p>
| <p>Have you tried the regular sheet/dialog techniques? They should work fine for this situation. Timers are scheduled as part of the run loop, which doesn't stop when you have a modal sheet or window, so it should be able to continue on rendering in the background while events are blocked.</p>
<pre><code>[NSApp beginSheet:sheetWindow modalForWindow:mainWindow modalDelegate:nil didEndSelector:NULL contextInfo:nil];
</code></pre>
<p>(Except fill in your own delegate and end selector if needed.)</p>
|
C#: Comparing with null <p>Are these equivalent:</p>
<pre><code>if (null==myobject)
{
//do something
}
</code></pre>
<p>and</p>
<pre><code>if (myobject==null)
{
//do something
}
</code></pre>
<p>or will they produce different code?</p>
| <p>In the 99% case this code is equivalent. </p>
<p>The one exception is when the type of the object in question overrides the == operator. It's possible for a bug to be introduced in == which causes problems when one parameter is null. </p>
<p>A particular example I've seen before is the following</p>
<pre><code>public static bool operator==(Student left, Student right) {
return left.Equals(right);
}
</code></pre>
<p>This will fail when null is on the left, but likely not when null in on the right. </p>
<p>This is a pretty far out corner case though. </p>
|
Does n tier architecture break OO concept of encapsulation <p>I have an n tier application with presentation layer, business layer, DAL and business objects layer. Separating the objects and the operation written on the objects break the object oriented concept of encapsulation.</p>
| <p>No. Consider what "encapsulation" means: the implementation details of a class are concealed behind the interface (messages, or methods) of the class.</p>
<p>In fact, you can derive the n-tier architecture directly from OO principles and Parnas's Law: a module should encapsulate what's likely to change. The presentation tier encapsulates the details of creating a "visible" interface; the middle tier the model of the business itself; and the back end the details of accessing the persistent data store.</p>
|
Recognize Missing Space <p>How can I recognize when a user has missed a space when entering a search term? For example, if the user enters "usbcable", I want to search for "usb cable". I'm doing a REGEX search in MySQL to match full words.</p>
<p>I have a table with every term used in a search, so I know that "usb" and "cable" are valid terms. Is there a way to construct a WHERE clause that will give me all the rows where the term matches part of the string?</p>
<p>Something like this:</p>
<pre><code>SELECT st.term
FROM SearchTerms st
WHERE 'usbcable' LIKE '%' + st.term + '%'
</code></pre>
<p>Or any other ideas?</p>
| <p><a href="http://en.wikipedia.org/wiki/Text%5Fsegmentation" rel="nofollow">Text Segmentation</a> is a part of <a href="http://en.wikipedia.org/wiki/Natural%5Flanguage%5Fprocessing" rel="nofollow">Natural Language Processing</a>, and is what you're looking for in this specific example. It's used in search engines and spell checkers, so you might have some luck with example source code looking at open source spell checkers and search engines.</p>
<p>Spell checking might be the correct paradigm to consider anyway, as you first need to know whether it's a legitimate word or not before trying to pry it apart.</p>
|
Why does "int[] is uint[] == true" in C# <p>Can somebody clarify the C# <code>is</code> keyword please. In particular these 2 questions:</p>
<p>Q1) line 5; Why does this return true?</p>
<p>Q2) line 7; Why no cast exception?</p>
<pre><code>public void Test()
{
object intArray = new int[] { -100, -200 };
if (intArray is uint[]) //why does this return true?
{
uint[] uintArray = (uint[])intArray; //why no class cast exception?
for (int x = 0; x < uintArray.Length; x++)
{
Console.Out.WriteLine(uintArray[x]);
}
}
}
</code></pre>
<p>MSDN's description does not clarify the situation. It states that <code>is</code> will return true if either of these conditions are met. (http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx>MDSN Article)</p>
<pre>
expression is not null.
expression can be cast to type.
</pre>
<p>I don't believe that you can do a valid cast of int[] into uint[]. Because:</p>
<p>A) This code does not compile:</p>
<pre><code>int[] signed = new int[] { -100 };
uint[] unsigned = (uint[])signed;
</code></pre>
<p>B) Doing the cast in the debugger gives an error:</p>
<pre><code>(uint[])signed
"Cannot convert type 'int[]' to 'uint[]'"
</code></pre>
<p>Sure enough, if line 3 was int[] instead of object then it would never compile. Which brings me to a final question related to Q2.</p>
<p>Q3) Why does C# raise a cast/conversion error in the debugger and compiler but not at runtime?</p>
| <p>C# and the CLR have somewhat different conversion rules.</p>
<p>You can't <em>directly</em> cast between <code>int[]</code> and <code>uint[]</code> in C# because the <em>language</em> doesn't believe any conversion is available. However, if you go via <code>object</code> the result is up to the CLI. From the CLI spec section 8.7 (I hope - I'm quoting an <a href="http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse%5Fthread/thread/2d21bf036a23918e#5a5c351206ebd999">email exchange I had on this topic with Eric Lippert</a> a while ago):</p>
<blockquote>
<p>Signed and unsigned integral primitive
types can be assigned to each other;
e.g., int8 := uint8 is valid. For this
purpose, bool shall be considered
compatible with <code>uint8</code> and vice versa,
which makes <code>bool := uint8</code> valid, and
vice versa. This is also true for
arrays of signed and unsigned integral
primitive types of the same size;
e.g., <code>int32[] := uint32[]</code> is valid.</p>
</blockquote>
<p>(I haven't checked, but I assume that this sort of reference type conversion being valid is what makes <code>is</code> return true as well.)</p>
<p>It's somewhat unfortunate that there are disconnects between the language and the underlying execution engine, but it's pretty much unavoidable in the long run, I suspect. There are a few other cases like this, but the good news is that they rarely seem to cause significant harm.</p>
<p>EDIT: As Marc deleted his answer, I've linked to the full mail from Eric, as posted to the C# newsgroup.</p>
|
Is there any way of throttling CPU/Memory of a process? <p>Problem: I have a developers machine (read: fast, lots of memory), but the user has a users machine (read: slow, not very much memory).</p>
<p>I can simulate a slow network using Fiddler (<a href="http://www.fiddler2.com/fiddler2/">http://www.fiddler2.com/fiddler2/</a>)
I can look at how CPU is used over time for a process using Process Explorer (<a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx">http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx</a>).</p>
<p>Is there any way I can restrict the amount of CPU a process can have, or the amount of memory a process can have in order to simulate a users machine more effectively? (In order to isolate performance problems for instance)</p>
<p>I suppose I could use a VM, but I'm looking for something a bit lighter.</p>
<p>I'm using Windows XP, but a solution for any Windows machine would be welcome. Thanks.</p>
| <p>The platform SDK used to come with stress tools for doing just this back in the good old days (<code>STRESS.EXE</code>, <code>CPUSTRESS.EXE</code> in the SDK), but they might still be there (check your platform SDK and/or Visual Studio installation for these two files -- unfortunately I have niether the PSDK nor VS installed on the machine I'm typing from.)</p>
<p>Other tools:</p>
<ul>
<li><strong>memory</strong>: performance & reliability (e.g. handling failed memory allocation): can use <a href="http://msdn.microsoft.com/en-us/magazine/cc163613.aspx" rel="nofollow">EatMem</a></li>
<li><strong>CPU</strong>: performance & reliability (e.g. race conditions): can use <a href="http://users.bigpond.net.au/CPUburn/" rel="nofollow">CPU Burn</a>, <a href="http://www.mersenne.org/freesoft/" rel="nofollow">Prime95</a>, etc</li>
<li><strong>handles</strong> (GDI, User): reliability (e.g. handling failed GDI resource allocation): ??? may have to write your own, but running out of GDI handles (buggy GTK apps would usually eat them all away until all other apps on the system would start falling dead like flies) is a real test for any Windows app</li>
<li><strong>disk</strong>: performance & reliability (e.g. handling disk full): <a href="http://askywhale.com/diskfiller/" rel="nofollow">DiskFiller</a>, etc.</li>
</ul>
<p>Also see <a href="http://stackoverflow.com/questions/14518/what-tools-do-you-use-to-stress-test-programs-on-windows-xp">this existing thread</a>.</p>
|
Can humor cut down on perceived response time? <p>After reading a StackoOverflow question
<a href="http://stackoverflow.com/questions/182112/funny-loading-statements-to-keep-users-amused">http://stackoverflow.com/questions/182112/funny-loading-statements-to-keep-users-amused</a>,
I was really intrigued to ponder upon this question "Can humor cut down on response time?"</p>
<p>In a page loading lots of data, instead of just "please wait" or "loading data", can a humorous / funny / witty message cut down the perceived response time (as perceived by the user)?
I guess it can take 3-5 secs off the user's count of response time.</p>
<p>What do Joel, Jeff, and others feel about this ?</p>
| <p>After the 42nd time the widgetObject takes 40 seconds to load, the humor becomes annoying.</p>
<p>When you are waiting for something to happen, it gives you a chance to see the flaw in the joke.</p>
<p>Why didn't the #@#$ spend more time writing better code than writing jokes?</p>
|
Masked TextBox, how to include the promptchar to value? <p>How to include the prompt char on masked textbox's Text? I also want to save the prompt char</p>
<p>Example i specify mask:
&&&&/&&</p>
<p>And prompt char of _</p>
<p>Then I enter 12 4/5. the program should save it as 12_4/5. Anything left blank should be converted to prompt char when getting the masked Textbox's Text</p>
<p>[EDIT]</p>
<p>Found it, set TaskMaskFormat to IncludePromptAndLiterals</p>
| <p>You could create a derived class from the MaskedTextBox and then override the Text property. On setting you would find/replace the prompt char with a space and when getting replace the space with the prompt char.</p>
|
Fixing the auth_permission table after renaming a model in Django <p>Every now and then, you have the need to rename a model in Django (or, in one recent case I encountered, split one model into two, with new/different names). Yes, proper planning helps to avoid this situation, but sometimes reality intervenes. </p>
<p>After renaming corresponding tables in the db and fixing affected code, one problem remains: Any permissions granted to Users or Groups to operate on those models still references the old model names. Is there any automated or semi-automated way to fix this, or is it just a matter of manual db surgery? (in development you can drop the auth_permissions table and syncdb to recreate it, but production isn't so simple).</p>
| <p>Here's <a href="http://www.djangosnippets.org/snippets/698/" rel="nofollow">a snippet</a> that fills in missing contenttypes and permissions. I wonder if it could be extended to at least do some of the donkey work for cleaning up auth_permissions.</p>
|
Display BMP in JLabel <p>Java can display png, jpg a some other picture formats, but i have to display a bmp file in a JLable by getting the file path.</p>
<pre><code>ImageIcon imageIcon = new ImageIcon(imageFile.getAbsolutePath());
</code></pre>
<p>ImageIcon support the typical <code>png,gif,jpg</code> images.</p>
<p>In the project i am working, i can not open a bmp file and store the same file as a jpg, because i am not allow to store something at runtime. I could only generate the image in hold it in memory. But i dont know how to do this.</p>
<p>How can i show <code>BMP</code> in <code>Java</code> <code>1.4</code>?</p>
<p>Thanks</p>
| <p><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/imageio/ImageIO.html">javax.imageio.ImageIO</a> supports the BMP format:</p>
<pre><code>Image image = ImageIO.read(imageFile);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
</code></pre>
<p>ImageIO can also be used to convert between different formats.</p>
|
user guide and read me question <p>What is the difference between an application User Guide and a Read Me file?</p>
| <p>I think the <code>README</code> file you see nowadays in the installation directory of an application is related with:</p>
<ul>
<li>installation pre-requisite</li>
<li>post-installation steps</li>
<li>first run precautions/caveat</li>
<li>quick release notes</li>
<li>current known limitations and support phone number/address</li>
</ul>
<p>In short, <code>README</code> has to do with "<strong>quick first run steps</strong>".</p>
<p>User Guide deals with the full life-cycle of the application (how to operate the program, advanced error messages and support topics, list of support sources of information)</p>
|
Verify signature Facebook Connect <p>I have followed the instructions in this great <a href="http://stackoverflow.com/questions/323019/facebook-connect-and-asp-net">Stackoverflow question</a> but i am not sure about this verify signature thing. Is this provided in some way in the Facebook Toolkit or do i have to do something myself? The <a href="http://wiki.developers.facebook.com/index.php/Verifying%5FThe%5FSignature" rel="nofollow">documentation</a> is not superclear on how to do this and if it is already baked in the facebook toolkit i don't want to spend to much time on it.</p>
<p>Anyone have done this? Should mention i use a standard ASP.NET Web Application in C#. Any help would be appreciated!</p>
| <p>At the moment, you have to do it yourself. I've provided a simple method you can call to see if the signature is valid or not.</p>
<pre><code>private bool IsValidFacebookSignature()
{
//keys must remain in alphabetical order
string[] keyArray = { "expires", "session_key", "ss", "user" };
string signature = "";
foreach (string key in keyArray)
signature += string.Format("{0}={1}", key, GetFacebookCookie(key));
signature += SecretKey; //your secret key issued by FB
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signature.Trim()));
StringBuilder sb = new StringBuilder();
foreach (byte hashByte in hash)
sb.Append(hashByte.ToString("x2", CultureInfo.InvariantCulture));
return (GetFacebookCookie("") == sb.ToString());
}
private string GetFacebookCookie(string cookieName)
{
//APIKey issued by FB
string fullCookie = string.IsNullOrEmpty(cookieName) ? ApiKey : ApiKey + "_" + cookieName;
return Request.Cookies[fullCookie].Value;
}
</code></pre>
<p>Note: SecretKey and ApiKey are values provided by Facebook that you need to set.</p>
|
hierarchical grid <p>Can anyone help me how to create a hierarchical Ultrawebgrid in ASP.net using C#... I'm very new to this... So i need some basics and sample codes .. Can u help me ?</p>
| <p>One way to make an UltraWebGrid "Hierarchical" is to establish a data relation in a dataset and bind the dataset to the UltraWebGrid.</p>
<p>As an example, let's say we have a Blog and we want to show the Blog Articles as the parent and then any comments made to each article as children in a Hierarchical UltraWebGrid. The parent table is named "BlogArticle" and is keyed by "BlogArticleID" and the child table is named "BlogComment" and contains a "BlogArticleID" column as a foreign key to "BlogArticle".</p>
<p>First we would establish 2 datasets and fill them using whatever mechanism you prefer with the data we want. In this case I am simply retrieving all the Blog Articles and all the Comments. Then we would "merge" the dataset that is to be the child into the dataset that is to the parent. Finally, we would set our data relationship in the dataset and bind the dataset to the UltraWebGrid.</p>
<p>An example of the code for this is as follows...</p>
<pre><code>DataSet dsBlogArticle = new DataSet();
DataSet dsBlogComment = new DataSet();
//
// Fill each dataset appropriately.
//
// Set Table Names. This is needed for the merge operation.
dsBlogArticle.Tables[0].TableName = "BlogArticle";
dsBlogComment.Tables[0].TableName = "BlogComment";
//
// Merge the Blog Comment dataset into the Blog Article dataset
// to create a single dataset object with two tables.
dsBlogArticle.Merge(dsBlogComment);
//
// Define Hierarchical relationships in the Dataset.
DataRelation dr = new DataRelation(
"BlogArticleToComments",
dsBlogArticle.Tables["BlogArticle"].Columns["BlogArticleID"],
dsBlogArticle.Tables["BlogComment"].Columns["BlogArticleID"],
false);
dsBlogArticle.Relations.Add(dr);
//
// Bind the dataset to the grid.
this.grdBlogArticle.DataSource = dsBlogArticle;
this.grdBlogArticle.DataBind();
</code></pre>
<p>The UltraWebGrid will automatically handle creating the Hierarchical grid based on the Data Relationship that is established in the dataset. To see this code populate an UltraWebGrid you can <a href="http://www.innovaapps.net/samples/" rel="nofollow">go here</a> to view an example that I put together.</p>
<p>I hope this helps, Thanks</p>
|
Which C# design pattern would suit writing custom workflow in asp.net <p>Trying to find some examples on the intertubes. I am thinking of state or strategy pattern but if anyone has any war stories, examples or resources that they could point me to it would be appreciated.</p>
<p>I don't/can't use windows workflow.</p>
<p>My example is that i have a complex wizard that changes the state of the process based on what user is doing and by who the user is.</p>
<p>For example:</p>
<ul>
<li>Cancelled</li>
<li>Requested by user</li>
<li>Request by manager</li>
<li>Confirmed</li>
<li>Refereed </li>
<li>Administrator Received</li>
<li>Administrator Confirmed</li>
<li>Administrator Cancelled </li>
</ul>
<p>Cheers
John</p>
| <p>How about the <a href="http://www.sloppycode.net/articles/csharp-design-patterns.aspx#state" rel="nofollow">State</a> pattern (<a href="http://en.wikipedia.org/wiki/State_pattern" rel="nofollow">wikipedia link</a>)?</p>
<pre><code>public abstract class State
{
/// <summary>
/// Holds the current state we're in.
/// </summary>
public State CurrentState
{
get;
set;
}
public virtual string Cancelled(State context)
{
return "";
}
public virtual string RequestedByUser(State context)
{
return "";
}
public virtual string RequestedByManager(State context)
{
return "";
}
}
public class CancelledState : State
{
public override string Cancelled(State context)
{
context.CurrentState = new SittingState();
return "Cancelled.";
}
public override string RequestedByUser(State context)
{
context.CurrentState = new RequestedByUserState();
return "Requested by User.";
}
public override string RequestedByManager(State context)
{
return "You can't do this before it's been requested by the User";
}
}
// (RequestedByUserState and RequestedByManagerState classes have been cut out)
</code></pre>
<p><em>As you can see, the pattern does fit exactly though.</em></p>
<p><a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" rel="nofollow">Chain of Responsibility</a> might be also be relevant if there's security concerns. If the wikipedia article makes no sense then <a href="http://www.amazon.co.uk/3-0-Design-Patterns-Judith-Bishop/dp/059652773X/ref=sr_1_4?ie=UTF8&s=books&qid=1216066920&sr=8-4" rel="nofollow">this book</a> has a good examples of both. Another is the Command pattern for wizards. None of them fit perfectly but they give you some good ideas to start with.</p>
|
Is the 'synchronized' keyword in a classic enterprise application suspicious? <p>I am talking about classic enterprise applications. Typically hosted in some kind of application-server or container. Nothing fancy, just entities, services, Presentation/UI and relational storage.</p>
<p>Whenever I see the <code>synchronized</code> keyword (either on methods or for blocks) in such an application I get very suspicious.
In my opinion this is either a sign for not understanding basic architectural concepts (for instance that a domain model is not shared between several clients) or even worse a sign that the architecture is actually very botched.</p>
<p>Do you share my mindset here? Or am I completely off track?
Do you have use cases where synchronization is actually necessary in a classic enterprise application?</p>
| <p>I agree with you for business logic code, but in an enterprise application you also have technical code and sometimes you need some synchronization for shared 'technical' state. The synchronized keyword may be used for this. (You also may relay on atomic variable, or use something outside your application like a DB sequence to share technical state...)</p>
<p>If you want to create sequential bill number - with no holes in the sequence - you need a way to share some state, and a way to synchronize...</p>
|
Wait for two threads to finish <p>If you have one main thread that starts two other threads.
what is the cleanest way to make the primary thread wait for the two other threads?</p>
<p>I could use bgndworker and sleep spinner that checks for both the bgnd workers's IsBusy, but I would think there's a better way.</p>
<p><strong>EDIT</strong>
Some more requirements:</p>
<ul>
<li>The main thread has some other work to do (e.g. GUI).</li>
<li>The two spawned threads should be able to report exceptions and return result values</li>
</ul>
| <p>Quick example using Thread.Join();</p>
<pre><code> Thread t1 = new Thread(new ThreadStart(delegate()
{
System.Threading.Thread.Sleep(2000);
}));
Thread t2 = new Thread(new ThreadStart(delegate()
{
System.Threading.Thread.Sleep(4000);
}));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
</code></pre>
<p><strong>EDIT Another 3example using Wait Handles:</strong></p>
<pre><code> ManualResetEvent[] waitHandles = new ManualResetEvent[]{
new ManualResetEvent(false),
new ManualResetEvent(false)
};
Thread t1 = new Thread(new ParameterizedThreadStart(delegate(object state)
{
ManualResetEvent handle = (ManualResetEvent)state;
System.Threading.Thread.Sleep(2000);
handle.Set();
}));
Thread t2 = new Thread(new ParameterizedThreadStart(delegate(object state)
{
ManualResetEvent handle = (ManualResetEvent)state;
System.Threading.Thread.Sleep(4000);
handle.Set();
}));
t1.Start(waitHandles[0]);
t2.Start(waitHandles[1]);
WaitHandle.WaitAll(waitHandles);
Console.WriteLine("Finished");
</code></pre>
|
Setup of TFS 2008 for automated testing <p>I'm confused.</p>
<p>I have TFS installed on my development server, which also doubles as the build machine. The builds work fine when I check-in code, but when the build attempts to run the tests I get an error:</p>
<p>MSBUILD : warning MSB6004: The specified task executable location "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" is invalid.
The previous error was converted to a warning because the task was called with ContinueOnError=true.
Build continuing because "ContinueOnError" on the task "TestToolsTask" is set to "true".
Done executing task "TestToolsTask" -- FAILED.</p>
<p>I have searched various forums and several people have suggested that visual studio 2008 test edition has to be installed on the build server. Can anyone confirm that this is true and more importantly whether it will solve me problem? Or can I merely install professional edition?</p>
<p>Thanks, Confused.</p>
| <p>Yes - you need either the Developer or the Test edition of VSTS 2008 (Or the Team Suite Edition installed). This is so that the version of MSTest.exe that is able to publish the unit test results back into TFS is installed on the build server.</p>
<p>So long as the people who check in stuff have a license to the appropriate version of Visual Studio Team System for the artifact that they are checking in then you are covered in terms of licensing for it being built on the build server AFAIK. (Though I only have a degree in Physics so I am woefully under-qualified for figuring out Microsoft licensing terms :-) )</p>
<p>Hope that helps,</p>
<p>Martin.</p>
|
Is it worth learning SharePoint 2007? <p>Is it worth learning MOSS (Microsoft Office SharePoint Server) 2007? What could be the future of it?</p>
| <p>SharePoint is <strong>the</strong> fastest growing product in Microsoft history.</p>
<p>Even MS can't get enough experienced MOSS developers for support.</p>
<p>Learn MOSS and you should be pretty sure to stay in business, crises and all.</p>
<p>Also it's <strong>fun</strong>. I am aware that it has a rugged reputation when it comes to development, and the lack of good tools can be discouraging for many developers, but the truth is that it's a true ASP.NET application. Especially the deployment can seem cumbersome, but if you do it and do it good, you can move your code from environment to environment without a sweat. I haven't worked with any other CMS products that could do that, and I worked on a few!</p>
<p>So grab a SharePoint book and get coding :-)</p>
|
Constraints on SMTP Message-Id? <p>Are there constraints on the length and/or format of SMTP message-id's? I.e.: How long may they be, and are only certain characters allowed? (I plan to use only ASCII, but I fear that there may even be ASCII characters which aren't allowed.)</p>
<p>RFC822 defines this, but are there updated RFCs or common real-World aspects (such as common bugs in mail software) which should be considered?</p>
| <p>The updated RFC is RFC2822.</p>
<p>As of characters allowed, it basically ::alpha::|::digit::|[!#$%&'<em>+-/=?^</em>`{}|~.] (It's also possible to quote literals).</p>
<p>It has to contain @ separating "local part" and "domain part". It <strong>MUST</strong> be <strong>globally</strong> unique.</p>
|
C# How do I do I replace EventLogEntryType with a value from a comboBox? <p>In the code below I want to replace EventLogEntryType.Warning with a value selected from a combo box, the combobox values are EventLogEntryType.Warning, EventLogEntryType.Information, EventLogEntryType.Error. The combo box would just show "Warning", "Information" and "Error". How can I do this?</p>
<p>Thanks</p>
<pre><code>EventLog myLog = new EventLog(); myLog.Source = "Test";
int intEventID = int.Parse(txtEventID.Text);
myLog.WriteEntry(txtDescription.Text, EventLogEntryType.Warning, intEventID);
</code></pre>
<p>Newbie</p>
| <p>Assuming that EventLogEntryType is an enum and that you don't need to localize, you can do this very easy.</p>
<p>In Form_Load</p>
<pre><code> combobox1.Items.Add(EventLogEntryType.Warning);
combobox1.Items.Add(EventLogEntryType.Information);
...
</code></pre>
<p>and later</p>
<pre><code> myLog.WriteEntry(txtDescription.Text, (EventLogEntryType)combobox1.Selecteditem, intEventID);
</code></pre>
|
Cross OS virtual drive functionality <p>Looking for online resources to implement a virtual drive functionality similar to ones implemented in products listed <img src="http://stackoverflow.com/questions/593971/what-online-file-storage-system-do-use-use/593999#593999" alt="here" /></p>
<p>The solution should be cross OS (win, pc, linux) preferably using a well behaving framework. Currently the answer to this question is widely dispersed with no clear option on what to use:</p>
<p>Current suggestions I've found:</p>
<ol>
<li><a href="http://apps.sourceforge.net/mediawiki/fuse/index.php?title=OperatingSystems" rel="nofollow">Fuse</a> (not really sure on the status of various windows ports)</li>
<li><a href="http://dokan-dev.net/en/" rel="nofollow">Dokan</a> library </li>
<li>Custom namespace extensions (windows only, sources in <a href="http://www.codeproject.com/KB/shell/shlext.aspx" rel="nofollow">various</a> <a href="http://www.codeproject.com/KB/shell/namespcextguide1.aspx" rel="nofollow">CodeProject</a> <a href="http://www.codeproject.com/KB/shell/TipsInNSE%5FSubFld.aspx" rel="nofollow">articles</a>)</li>
<li>Commercial frameworks (windows) - <a href="http://www.ssware.com/eznamespaceextensions/eznamespaceextensions.htm" rel="nofollow">LogicNP</a>, <a href="http://www.eldos.com/" rel="nofollow">Eldos</a></li>
<li><a href="http://www.webdav.org/" rel="nofollow">WebDav</a></li>
</ol>
<p>Please list one suggestion per answer and I'll update the question accordingly. The purpose of the question is to create the best reference point for such questions...</p>
<p>It seems WebDav would be easiest to implement cross OS so further information on this would be appreciated.</p>
| <p>A simple solution is to use the native SMB client for each of your target platforms, then use that to mount a custom Samba filesystem implemented using Samba's VFS API. Custom NFS servers have been used to implement cross platform Unix virtual file systems, but SMB is a much better choice to support Windows and Linux.</p>
<p>If you need the VFS to access client-side resources, you must run the Samba server with your VFS on the client and then use a loopback or localhost network to mount the drive. Samba is widely ported including a port to Win32 using Cygwin as an adapter.</p>
|
Am I missing something with my ListView selection event handling <p>...or are c# listviews really such a nightmare to manage?</p>
<p>Okay the problem I'm working on is very simple. Or at least it appears to be so:</p>
<p>I have a text file which contains information about customer orders on separate lines. The data items are separated by semi-colons.</p>
<p>My form iterates through these orders, puts the item information into hashtables and puts each hashtable into a master hashtable. Some summary information about each order (product/order#/customer name/customer#) is displayed in my listview separated by sortable columns. Below the listview is a tab control with textboxes for the editable parts of the order details spread across three tabs.</p>
<p>Here is what I would like to happen:</p>
<ul>
<li>User clicks on single entry: tab control textboxes fill with Order Details.</li>
<li>User edits details in tab control.</li>
<li>User clicks on another order: confirmation message checks that the change should be committed, if "Yes" then the details should be saved back to the relevant Hashtable and the display in the listview updates.</li>
<li>User selects multiple listview items: the top item should be editable in the tab control.</li>
<li>User presses "Remove Item(s)" button on a tool strip at the top of the form: the item(s) are removed from the hashtable and the listview control is updated to reflect the deletion. The textboxes are all set back to blank across the tab control.</li>
</ul>
<p>This seems to me like pretty ordinary and reasonable behaviour. I guessed that using the SelectedIndexChanged event would offer the opportunities to do the data work. But the event fires twice on every selection/deselection and it's not always clear which items should be updated in the listview at which point.</p>
<p>The code for testing what kind of "selection/deselection" has just taken place and decide what action should thus be taken is starting to get quite long and I'm just wondering if I'm making things too complicated.</p>
<p>So:</p>
<ul>
<li>Is there another event I could use to achieve my functionality goals? Or</li>
<li>Is there something about the SelectedIndexChanged event that I don't know that would help the program decide what it should be doing at any given point? Or</li>
<li>Am I just going about this the wrong way?</li>
</ul>
<p>Any suggestions, even ones about redesigning my form would be most welcome.</p>
<p>EDIT: While trying to attack this problem from a different angle I am changing my master hashtable to a sortedlist. The rest of the problem remains the same.</p>
| <p>Without knowing the code that's "starting to get quite long" I would suggest the following:</p>
<p>Make sure Listview1.MultiSelect is false.
Use a field (or property) on your Form to track the SelectedItem.
In the event, check if the new ListView1.Selecteditems[0] != this.SelectedItem</p>
<p>Part 2: Take a look at the DataGridView and DataTables as an alternative solution. Your data sounds quite "relational" and the Data stuff has a lot of Filtering/Sorting/Linking functionality. You could attach a List as DataSource to a Grid or go a bit further and read your data into DataTables.</p>
|
Possible bug in ASP.NET MVC with form values being replaced <p>I appear to be having a problem with ASP.NET MVC in that, if I have more than one form on a page which uses the same name in each one, but as different types (radio/hidden/etc), then, when the first form posts (I choose the 'Date' radio button for instance), if the form is re-rendered (say as part of the results page), I seem to have the issue that the hidden value of the SearchType on the other forms is changed to the last radio button value (in this case, SearchType.Name).</p>
<p>Below is an example form for reduction purposes.</p>
<pre><code><% Html.BeginForm("Search", "Search", FormMethod.Post); %>
<%= Html.RadioButton("SearchType", SearchType.Date, true) %>
<%= Html.RadioButton("SearchType", SearchType.Name) %>
<input type="submit" name="submitForm" value="Submit" />
<% Html.EndForm(); %>
<% Html.BeginForm("Search", "Search", FormMethod.Post); %>
<%= Html.Hidden("SearchType", SearchType.Colour) %>
<input type="submit" name="submitForm" value="Submit" />
<% Html.EndForm(); %>
<% Html.BeginForm("Search", "Search", FormMethod.Post); %>
<%= Html.Hidden("SearchType", SearchType.Reference) %>
<input type="submit" name="submitForm" value="Submit" />
<% Html.EndForm(); %>
</code></pre>
<p>Resulting page source (this would be part of the results page)</p>
<pre><code><form action="/Search/Search" method="post">
<input type="radio" name="SearchType" value="Date" />
<input type="radio" name="SearchType" value="Name" />
<input type="submit" name="submitForm" value="Submit" />
</form>
<form action="/Search/Search" method="post">
<input type="hidden" name="SearchType" value="Name" /> <!-- Should be Colour -->
<input type="submit" name="submitForm" value="Submit" />
</form>
<form action="/Search/Search" method="post">
<input type="hidden" name="SearchType" value="Name" /> <!-- Should be Reference -->
<input type="submit" name="submitForm" value="Submit" />
</form>
</code></pre>
<p>Please can anyone else with RC1 confirm this?</p>
<p>Maybe it's because I'm using an enum. I don't know. I should add that I can circumvent this issue by using 'manual' input () tags for the hidden fields, but if I use MVC tags (<%= Html.Hidden(...) %>), .NET MVC replaces them every time.</p>
<p>Many thanks.</p>
<p><strong>Update:</strong></p>
<p>I've seen this bug again today. It seems that this crops its head when you return a posted page and use MVC set hidden form tags with the Html helper. I've contacted <a href="http://haacked.com">Phil Haack</a> about this, because I don't know where else to turn, and I don't believe that this should be expected behaviour as specified by David.</p>
| <p>Yes, this behavior is currently by design. Even though you're explicitly setting values, if you post back to the same URL, we look in model state and use the value there. In general, this allows us to display the value you submitted on postback, rather than the original value.</p>
<p>There are two possible solutions:</p>
<h3>Solution 1</h3>
<p>Use unique names for each of the fields. Note that by default we use the name you specify as the id of the HTML element. It's invalid HTML to have multiple elements have the same id. So using unique names is good practice.</p>
<h3>Solution 2</h3>
<p>Do not use the Hidden helper. It seems like you really don't need it. Instead, you could do this:</p>
<pre><code><input type="hidden" name="the-name"
value="<%= Html.AttributeEncode(Model.Value) %>" />
</code></pre>
<p>Of course, as I think about this more, changing the value based on a postback makes sense for Textboxes, but makes less sense for hidden inputs. We can't change this for v1.0, but I'll consider it for v2. But we need to think through carefully the implications of such a change.</p>
|
INotifyPropertyChanged not working on ObservableCollection property <p>I have a class called <code>IssuesView</code> which implements <code>INotifyPropertyChanged</code>. This class holds an <code>ObservableCollection<Issue></code> and exposes it as a <code>DependencyProperty</code> called Issues for consumption by <code>Bindings</code>. It is defined as below -</p>
<pre><code> public class IssuesView : DependencyObject, INotifyPropertyChanged
{
public Issues Issues
{
get { return (Issues)GetValue(IssuesProperty); }
set
{
SetValue(IssuesProperty, value);
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Issues"));
}
}
}
// Using a DependencyProperty as the backing store for Issues. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IssuesProperty =
DependencyProperty.Register("Issues", typeof(Issues), typeof(IssuesView), new UIPropertyMetadata(null));
public IssuesView()
{
Refresh();
}
public void Refresh()
{
this.Issues = new Issues();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
</code></pre>
<p>I have a test page declared like this - </p>
<pre><code><Page x:Class="Tracker.Pages.DEMO"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cont="clr-namespace:Tracker.Controls"
Title="DEMO">
<StackPanel>
<Button Click="Button_Click">Change</Button>
<cont:IssueTimeline IssuesForTimeline="{Binding Source={StaticResource issuesView},Path = Issues}"/>
</StackPanel>
</code></pre>
<p></p>
<p>The <code>IssuesView</code> class is defined in <code>Application.Resources</code>.<br />
Now in the event hadnler for the button i have this code - </p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
IssuesView iv = Application.Current.FindResource("issuesView") as IssuesView;
if (!once)
{
foreach (Issue i in iv.Issues)
{
i.DormantFor = new TimeSpan(30, 0, 0, 0);
i.AssignedUserID = 12;
i.Name = "MyName";
i.Priority = Issue.Priorities.Critical;
i.Status = Issue.Statuses.New;
i.Summary = "NewSummary";
}
once = true;
}
else
{
iv.Refresh();
}
</code></pre>
<p>once is a simple boolean to test mutation of the collection versus repopulation.</p>
<p>The first button click alters the collection's items and the UI is updated properly since the items implement INotifyPropertyChanged but the second click repopulates the collection but does not update the UI even though the event is not null and fires properly.</p>
<p>Why does the UI not update on the second click? How can i make it so that repopulating the collection will cause a UI update?</p>
| <p>First: there's no reason to implement <code>INotifyProperty</code> changed for DependencyProperties. DependencyProperties know when they change.</p>
<p>Second: I don't see an <code>ObservableCollection</code> in your code.</p>
<p>Third: it's not entirely clear to me (from the code you posted) where the issues you modify in the first click come from. I assume from another action, not posted here.</p>
<p>Am I correct if I assume that you want to clear the issues list with the second click (since I don't know what the <code>Issues</code> constructor does)?</p>
|
What's the "right" way to isolate control dependencies <p>I've made it a personal rule to inherit every UI control before using it. In a previous life I'd always considered this one of the less useful things you could do because the justification always seemed to be "I might want to change the font on all the buttons at once"... a motivation that never paid off... once... ever.</p>
<p>Two recent projects have changed my mind about the practice, though. In the first, we needed a consistent "ValueChanged" event so that we could easily implement a "dirty" flag on our forms without a massive switch statement to choose between a Textbox's "TextChanged" event, or a ListBox's "SelectedIndexChanged" etc. We just wanted one consistent thing to listen for on all controls, and subclassing the built-in controls bought us that pretty easily.</p>
<p>In the second project, every effort was made to get by with the base controls because the UI was expected to be pretty simple, but a few months in, it became obvious that they just weren't going to cut it anymore, and we purchased the Telerik control suite. If we had inherited all the controls to begin with, then changing our derived controls to inherit from the Telerik controls would have applied the changes for us globally. Instead, we had to do some searching and replacing in all the form designers.</p>
<p>So here's my question: What are the relative strengths and weaknesses of</p>
<ol>
<li>Simply adding a Class, and making it inherit from a control.</li>
<li>Adding a new "Custom Control" and inheriting.</li>
<li>Adding a new "Component" and inheriting.</li>
</ol>
<p>All three have the same effect in the end, you get a new type of Button to put on your forms. I've seen all three used by different people, and everyone seems to think that their way is the best. I thought I should put this discussion on StackOverflow, and maybe we can nail down a concensus as a community as to which one is the "right" way.</p>
<p>Note: I already have my personal opinion of which is "right", but I want to see what the world thinks.</p>
| <p>If both 1 & 2 are inheriting, then they are functionally identical, no? Should one of them be <em>encapsulating</em> a control? In which case you have a lot of pass-thru members to add. I wouldn't recommend it.</p>
<p>Peronally, I simply wouldn't add extra inheritance without a very good reason... for example, the "changed event" could perhaps have been handled with some overloads etc. With C# 3.0 this gets even cleaner thanks to extension methods - i.e. you can have things like:</p>
<pre><code>public static AddChangeHandler(
this TextBox textbox, EventHandler handler) {
testbox.TextChanged += handler;
}
public static AddChangeHandler(
this SomethingElse control, EventHandler handler) {
control.Whatever += handler;
}
</code></pre>
<p>and just use <code>myControl.AddChangeHandler(handler);</code> (relying on the static type of <code>myControl</code> to resolve the appropriate extension method).</p>
<p>Of course, you could take a step back and listen to events on your own <strong>model</strong>, not the UI - let the UI update the model in a basic way, and have logic in your own object model (that has nothing to do with controls).</p>
|
C# binary literals <p>Is there a way to write binary literals in C#, like prefixing hexadecimal with 0x? 0b doesn't work.</p>
<p>If not, what is an easy way to do it? Some kind of string conversion?</p>
| <p>Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<code><<</code>) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.</p>
<pre><code>[Flags]
enum Days
{
None = 0,
Sunday = 1,
Monday = 1 << 1, // 2
Tuesday = 1 << 2, // 4
Wednesday = 1 << 3, // 8
Thursday = 1 << 4, // 16
Friday = 1 << 5, // etc.
Saturday = 1 << 6,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
</code></pre>
|
Overriding static variables when subclassing <p>I have a class, lets call it A, and within that class definition I have the following:</p>
<pre><code>static QPainterPath *path;
</code></pre>
<p>Which is to say, I'm declaring a static (class-wide) pointer to a path object; all instances of this class will now have the same shared data member. I would like to be able to build upon this class, subclassing it into more specialised forms, layering behaviour, and with each class having its own unique path object (but not having to repeat the boring bits like calculating bounding boxes or calling the painting routines).</p>
<p>If I subclass it to create a class F (for example), I want F to use the inherited drawing routines from A, but to use the static (class-wide) path object declared in F. I have tried having the declaration above in the private section (and repeating it in the derived class F), and tried having it in the protected section, all with no joy.</p>
<p>I can sort of see why this is happening:</p>
<pre><code>void A::paint() {
this->path...
</code></pre>
<p>is referring to A::path instead of F::path, even when the object is of class F.</p>
<p>Is there an elegant way to get round this, and allow each class to maintain a static path object, while still using drawing code defined in the base class, and having all classes (except perhaps the base class) be real and instantiatable?</p>
| <p>Use a virtual method to get a reference to the static variable.</p>
<pre><code>class Base {
private:
static A *a;
public:
A* GetA() {
return a;
}
};
class Derived: public Base {
private:
static B *b;
public:
A* GetA() {
return b;
}
};
</code></pre>
<p>Notice that B derives from A here. Then:</p>
<pre><code>void Derived::paint() {
this->GetA() ...
}
</code></pre>
|
How to Set Form Validation Rules for CodeIgniter Dynamically? <p>With the new version of CodeIgniter; you can only set rules in a static <code>form_validation.php</code> file. I need to analyze the posted info (i.e. only if they select a checkbox). Only then do I want certain fields to be validated. What's the best way to do this, or must I use the old form validation class that is deprecated now?</p>
| <p>You cannot only set rules in the config/form_validation.php file. You can also set them with:</p>
<pre><code> $this->form_validation->set_rules();
</code></pre>
<p>More info on: <a href="http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules">http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules</a></p>
<p>However, the order of preference that CI has, is to first check if there are rules set with set_rules(), if not, see if there are rules defined in the config file.</p>
<p>So, if you have added rules in the config file, but you make a call to set_rules() in the action, the config rules will never be reached.</p>
<p>Knowing that, for conditional validations, I would have a specific method in a model that initializes the form_validation object depending on the input (for that particular action). The typical situation where I've had the need to do this, is on validating shipping and billing addresses (are they the same or different).</p>
<p>Hope that helps. :)</p>
|
C# Running a winform program as someone other than the logged on user <p>I need my winform program to run as another user (it will run under task scheduler) and not the logged on user. I suspect the trouble is my app is gui based and not command line based (does this make a difference) so the gui needs to load do its thing and then close. Is this possibly under XP or Vista?</p>
<p>Thanks</p>
| <p>Scheduled Tasks can be 'run as' a specified user, which can be different to the logged-in user.</p>
<p>You can specify this user when creating the task, or by editing the properties of an existing task.</p>
|
Fix for background-position in IE <p>I get this problem in IE7 when running a piece of code that uses jquery and 2 jquery plugins. The code works in FF3 and Chrome.</p>
<p>The full error is:</p>
<pre><code>Line: 33
Char: 6
Error: bg is null or not an object
Code: 0
URL: http://localhost/index2.html
</code></pre>
<p>However line 33 is a blank line.</p>
<p>I am using 2 plugins: draggable and zoom. No matter what I do to the code it is always line 33 that is at fault. I check the source has update via view source but I feel this could be lying to me.</p>
<pre><code><body>
<div id="zoom" class="zoom"></div>
<div id="draggable" class="main_internal"><img src="tiles/mapSpain-smaller.jpg" alt=""></div>
<script type="text/javascript">
$(document).ready(function() {
$('#draggable').drag();
$('#zoom').zoom({target_div:"draggable", zoom_images:new Array('tiles/mapSpain-smaller.jpg', 'tiles/mapSpain.jpg') });
});
</script>
</body>
</code></pre>
<p>Essentially what I am trying to do is recreate the Pragmatic Ajax map demo with jQuery.</p>
<hr>
<p>It would appear that the second line of this snippet is causing the trouble:</p>
<pre><code>bg = $(this).css('background-position');
if(bg.indexOf('%')>1){
</code></pre>
<p>It seems to be trying to select the background-position property of <code>#draggable</code> and not finding it? Manually adding a <code>background-position: 0 0;</code> didn't fix it. Any ideas on how to get around this problem?</p>
<p>I tried using the MS Script Debugger but that is nearly useless. Can't inspect variables or anything else.</p>
| <p>A bit more digging about on the Interweb has revealed the answer: IE doesn't understand the selector <code>background-position</code>. It understands the non-standard <code>background-position-x</code> and <code>background-position-y</code>.</p>
<p>Currently hacking something together to workaround it.</p>
<p>Nice one, Redmond.</p>
|
Why does this WPF button stretch across the window? <p>The button below always expands to be as wide as the TextBlock. I've tried StackPanel, DockPanel, Width="Auto", etc.</p>
<p>How can I make the button expand to the <strong>size of its own text</strong> (as in HTML) and not to the size of text in its environement? </p>
<pre><code> <DockPanel HorizontalAlignment="Left">
<Button x:Name="ButtonFavorite"
DockPanel.Dock="Top"
Content="Customers"
Margin="10"
Width="Auto"
Click="ButtonFavorite_Click">
</Button>
<TextBlock DockPanel.Dock="Top" Text="this is a long text which makes the button stretch across the window, if this text is just a couple words, the button will be smaller, and this drives me up the wall" Margin="10" TextWrapping="Wrap" />
</DockPanel>
</code></pre>
<h1>ANSWER:</h1>
<p>Thanks Greg, that did it. Here is the full XAML that works now, you can right-click the button to change its Content so see that the button expands and contracts appropriately.</p>
<pre><code><Window x:Class="Test3784234.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<DockPanel HorizontalAlignment="Left">
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" >
<Button x:Name="ButtonFavorite"
Padding="5"
Cursor="Hand"
DockPanel.Dock="Top"
Content="Customers"
Margin="10"
Click="ButtonFavorite_Click">
<Button.ContextMenu>
<ContextMenu>
<MenuItem x:Name="menuItemReports" Header="Reports" Click="MenuItem_Click" />
<MenuItem x:Name="menuItemContracts" Header="Contracts" Click="MenuItem_Click"/>
<MenuItem x:Name="menuItemCustomers" Header="Customers" Click="MenuItem_Click" />
<MenuItem x:Name="menuItemDocumentation" Header="Documentation Creation Instructions" Click="MenuItem_Click" />
<MenuItem x:Name="menuItemEmail" Header="E-Mail" Click="MenuItem_Click" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</StackPanel>
<TextBlock x:Name="TheMessage" DockPanel.Dock="Top" Text="Right-click the 'favorites' button to change its function." Margin="10" TextWrapping="Wrap"/>
</DockPanel>
</Window>
</code></pre>
| <p>All you need to do is set the HorizontalAlignment property on your button. It defaults to stretch therefore filling the available space.</p>
<pre><code><Button x:Name="ButtonFavorite"
HorizontalAlignment="Left"
Content="Customers"
Margin="10"
Width="Auto"
Click="ButtonFavorite_Click">
</code></pre>
|
Prefered Editor for Linux Kernel Development Newbies <p>Before you answer <strong>vi</strong>...
I'm looking to set a development environment for programmers with mainly Windows/Visual Studio background. Of course Emacs and Eclipse come to mind as IDEs, but I just want to make sure I'm not missing anything with relation to things like build tool integration etc.
Thanks in advance</p>
| <p>Well, if you are doing Linux Kernel work, perhaps you will be interested in Mr Torvalds <a href="http://marc.info/?l=git&m=122955159617722&w=2" rel="nofollow">opinion of emacs</a>...</p>
|
xslt hyperlink, separate the url and descption <p>I have a list in sharepoint with a hyperlink column.</p>
<p>I'm putting this list into xml and applying xslt to it.</p>
<p>the xml is producing output in the form of:</p>
<pre><code><link>http://www.foo.com, http://www.foo.com</link>
</code></pre>
<p>how can i display this link using xslt?</p>
<p>thanks</p>
| <p>How about:</p>
<pre><code><xsl:template match="link">
<a href="{substring-before(.,',')}">
<xsl:value-of select="substring-after(.,',')"/>
</a>
</xsl:template>
</code></pre>
|
What are the pitfalls of setting enable_nestloop to OFF <p>I have a query in my application that runs very fast when there are large number of rows in my tables. But when the number of rows is a moderate size (neither large nor small) - the same query runs as much as 15 times slower. </p>
<p>The explain plan shows that the query on a medium sized data set is using <em>nested loops</em> for its join algorithm. The large data set uses <em>hashed joins</em>.</p>
<p>I can discourage the query planner from using nested loops either at the database level (postgresql.conf) or per session (<code>SET enable_nestloop TO off</code>).</p>
<p>What are the potential pitfalls of <code>set enable_nestloop to off</code>?</p>
<p>Other info: PostgreSQL 8.2.6, running on Windows.</p>
| <blockquote>
<p>What are the potential pitfalls of setting <code>enable_nestloop</code> to <code>off</code>?</p>
</blockquote>
<p>This means that you will never be able to use indexes efficiently.</p>
<p>And it seems that you don't use them now.</p>
<p>The query like this:</p>
<pre><code>SELECT u.name, p.name
FROM users u
JOIN profiles p ON p.id = u.profile_id
WHERE u.id = :id
</code></pre>
<p>will most probably use <code>NESTED LOOPS</code> with an <code>INDEX SCAN</code> on <code>user.id</code> and an <code>INDEX SCAN</code> on <code>profile.id</code>, provided that you have built indices on these fields.</p>
<p>Queries with low selectivity filters (that is, queries that need more than <code>10%</code> of data from tables they use) will benefit from <code>MERGE JOINS</code> and <code>HASH JOINS</code>.</p>
<p>But the queries like one given above require <code>NESTED LOOPS</code> to run efficiently.</p>
<p>If you post your queries and table definitions here, probably much may be done about the indexes and queries performance.</p>
|
Return index value datetime.now.dayofweek but how? <p>is there any function of datetime return dayofweekindex? such as:<br>
int Todaywhat_is_Index= = DateTime.Now.IndexOfDayofThisWeek;<br>
if Today is friday, it must be return 5<br>
ifToday is Saturday, it must be return 6<br>
ifToday is Sunday, it must be return 0<br></p>
| <p>This little one-liner works independent of locale, with always Friday == 5</p>
<pre><code>int x = (int)System.Globalization.CultureInfo
.InvariantCulture.Calendar.GetDayOfWeek(DateTime.Now);
</code></pre>
|
svn repository path changed: how to re-bind my local folder to it? <p>hello
i have an repository that is visible as e:/svn/repository and it is checked out to a local folder c:/work
Now repository path is changed to f:/general/svn/repository
what svn command to use in order for c:/work to be bound to the new repository path? i do not want to delete c:/work and doing fresh check out since c:/work contains lots on unversioned temp files that i want to keep in place</p>
<p>i have tried checkout f:/general/svn/repository into c:/work, svn gives error:
c:/work is already a working copy for a different url</p>
| <pre><code>cd c:\work
svn switch --relocate file:///E:/svn/repository file:///F:/general/svn/repository
</code></pre>
|
Stemming - code examples or open source projects? <p>Stemming is something that's needed in tagging systems. I use delicious, and I don't have time to manage and prune my tags. I'm a bit more careful with my blog, but it isn't perfect. I write software for embedded systems that would be much more functional (helpful to the user) if they included stemming.</p>
<p>For instance:<br />
Parse<br />
Parser<br />
Parsing </p>
<p>Should all mean the same thing to whatever system I'm putting them into.</p>
<p>Ideally there's a BSD licensed stemmer somewhere, but if not, where do I look to learn the common algorithms and techniques for this?</p>
<p>Aside from BSD stemmers, what other open source licensed stemmers are out there?</p>
| <p><a href="http://snowball.tartarus.org/" rel="nofollow">Snowball</a> stemmer (C & Java)
I've used it's Python binding, <a href="http://pypi.python.org/pypi/PyStemmer" rel="nofollow">PyStemmer</a></p>
|
Configuring IntelliJ IDEA to create main class for new projects <p>A friend is just starting to learn Java, using IntelliJ.
He asks how can he set up some template so creating a new project will contain a default main class.</p>
<p>Currently, when he creates a new project, it has no source files, and he has to add a Run/Debug application configuration manually, and then select the main class.</p>
| <p>I don't know if Settings->File Templates is what you have in mind, but I'll point it out just in case.</p>
<p>You can easily create a class and add a main method by typing "psvm " and filling in the method body. You run it by right clicking on the class and selecting "Run". It's automatically be added to your Run/Config list, you just have to save it to make it permanent.</p>
<p>But my gut feeling is that IntelliJ has no such a feature for reading somebody's mind about a "default main class", nor should it. </p>
|
.Net PropertyGrid DropDownList - return value different from show value <p>I want to be able to show in a propertygrid a dropdownlist that show some "string" value but return an "int" value.</p>
<p>For example, let set I got this class :</p>
<pre><code>public class MyObjectOptions : StringConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
MyObjectCollection mm = new MyObjectCollection();
List<String> names = new List<String>
foreach (MyObject m in mm)
{
m.Id // Need to store this somewhere ...
names.Add(m.Name);
}
return new StandardValuesCollection(name);
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return true;
}
}
</code></pre>
<p>Here is my class use in the propertygrid control</p>
<pre><code>public class MyObjectProperty
{
[TypeConverter(typeof(MyObjectOptions))]
public int Id
{
get { return this.id; }
set { this.id = value; }
}
}
</code></pre>
<p>Like you can see, I want to store the id of the object, but I want to show it's name in the dropdownlist ... I try use a hashtable but it's doesn't work ...</p>
<p>BTW - I use the version 3.5 of .Net but I only use WinForm (not WPF).</p>
| <p>You can not use GetStandardValues for that. This method would be useful if you had to restrict your integer values to let's say 1, 5 and 10.</p>
<p>If you want to show strings in your property value, you just need to override the ConvertTo and ConvertFrom methods of your TypeConverter. The PropertyGrid will use the converted strings in the dropdown list.</p>
<p>About your hashtable, you can store it in your TypeConverter if its content is static. If it's dynamic, the best is to let the target instance of the grid manage it. From your converter, you will be able to access it through the TypeDescriptorContext.Instance property.</p>
<p>Hope that helps.</p>
|
Why am I having trouble with a deep copy in Objective C? <p>I'm assuming my understanding of how to perform a deep copy isn't just there yet. The same with some sub-optimal memory handling that I'm performing down below. This code below probably depicts a shallow copy, and I believe that's where my problem might be. I have some cookie-cutter code for an example that looks like the following:</p>
<pre><code>NSArray *user = [[xmlParser createArrayWithDictionaries:dataAsXML
withXPath:kUserXPath] retain];
if([user count] > 0) {
self.name = [[user valueForKey:@"name"] copy];
}
// Crash happens if I leave the next line un-commented.
// But then we have a memory leak.
[user release];
[xmlParser release];
</code></pre>
<p>Unfortunately when I comment out <code>[user release]</code>, the code works, but we have an obvious memory leak. The method <code>createArrayWithDictionaries:withXPath:</code> was refactored last night when the SO community helped me understand better memory management. Here's what it looks like:</p>
<pre><code>- (NSArray *)createArrayWithDictionaries:(NSString *)xmlDocument
withXPath:(NSString *)XPathStr {
NSError *theError = nil;
NSMutableArray *dictionaries = [NSMutableArray array];
CXMLDocument *theXMLDocument = [CXMLDocument alloc];
theXMLDocument = [theXMLDocument initWithXMLString:xmlDocument
options:0
error:&theError];
NSArray *nodes = [theXMLDocument nodesForXPath:XPathStr error:&theError];
for (CXMLElement *xmlElement in nodes) {
NSArray *attributes = [xmlElement attributes];
NSMutableDictionary *attributeDictionary;
attributeDictionary = [NSMutableDictionary dictionary];
for (CXMLNode *attribute in attributes) {
[attributeDictionary setObject:[attribute stringValue]
forKey:[attribute name]];
}
[dictionaries addObject:attributeDictionary];
}
[theXMLDocument release];
return dictionaries;
}
</code></pre>
<p>I'm guessing there's a couple of issues that might be going on here:</p>
<ul>
<li>Auto release on my dictionaries array is happening, thus my app crashing.</li></li>
<li>I'm not performing a deep copy, only a shallow copy. Thus when the user array is released, <code>self.name</code> is done for.</li>
</ul>
<p>With <code>NSZombieEnabled</code>, I see the following:</p>
<pre>
*** -[CFString respondsToSelector:]:
message sent to deallocated instance 0x1ae9a0
</pre>
<p>Also, the final call where the backtrace shows this is crashing contains the following code in a separate module from the other two methods:</p>
<pre><code>User *u = self.user;
NSString *uri = [NSString stringWithFormat:@"%@/user/%@/%@",
[self groupName], u.userId, kLocationsUri];
</code></pre>
<p>Between all the auto releasing/copies/retain happening between the client code and <code>createArrayWithDictionaries:withXPath</code>, I'm a bit confused as to the real problem here. Thanks again for helping me understand.</p>
| <p>OK, you don't need to retain the return value from <code>createArrayWithDictionaries:</code> since you're not keeping it around. The return value is autoreleased. I'd strongly recommend reading up on how autoreleasing works. You only retain things that you intend to keep around in your object.</p>
<p>Also, <code>user</code> is an <code>NSArray</code>. If you call <code>[user valueForKey:@"name"]</code>, you'll get another <code>NSArray</code> of values representing the values of the <code>name</code> key for each of the objects in <code>users</code>. Furthermore, how is the <code>name</code> property on your object defined? If you declared it as <code>copy</code> or <code>retain</code> (I believe <code>retain</code> is the default if you don't specify it yourself), you don't need to copy or retain the value. Indeed, the accessor should always be responsible for doing the memory management, not the caller. If you wrote your own accessor (i.e. you didn't use the <code>@synthesize</code> keyword), you need to make sure you do the memory management there.</p>
<p>I'm guessing what you meant to write was something more like this:</p>
<pre><code> NSArray *user = [xmlParser createArrayWithDictionaries:dataAsXML withXPath:kUserXPath];
if ([user count] > 0)
self.name = [[user objectAtIndex:0] objectForKey:@"name"];
[xmlParser release];
</code></pre>
<p>I think your troubles are stemming from a misunderstanding of how memory management works in Objective-C.</p>
<p>Hope this helps.</p>
|
Fuzzy matching of product names <p>I need to automatically match product names (cameras, laptops, tv-s etc) that come from different sources to a canonical name in the database.</p>
<p>For example <strong>"Canon PowerShot a20IS"</strong>, <strong>"NEW powershot A20 IS from Canon"</strong> and <strong>"Digital Camera Canon PS A20IS"</strong>
should all match <strong>"Canon PowerShot A20 IS"</strong>. I've worked with levenshtein distance with some added heuristics (removing obvious common words, assigning higher cost to number changes etc), which works to some extent, but not well enough unfortunately.</p>
<p>The main problem is that even single-letter changes in relevant keywords can make a huge difference, but it's not easy to detect which are the relevant keywords. Consider for example three product names:<br />
<strong>Lenovo T400</strong><br />
<strong>Lenovo R400</strong><br />
<strong>New Lenovo T-400, Core 2 Duo</strong><br />
The first two are ridiculously similar strings by any standard (ok, soundex might help to disinguish the T and R in this case, but the names might as well be 400T and 400R), the first and the third are quite far from each other as strings, but are the same product.</p>
<p>Obviously, the matching algorithm cannot be a 100% precise, my goal is to automatically match around 80% of the names with a high confidence.</p>
<p>Any ideas or references is much appreciated</p>
| <p>I think this will boil down to distinguishing key words such as <strong>Lenovo</strong> from chaff such as <strong>New</strong>.</p>
<p>I would run some analysis over the database of names to identify key words. You could use code similar to that used to generate a word cloud. </p>
<p>Then I would hand-edit the list to remove anything obviously chaff, like maybe New is actually common but not key.</p>
<p>Then you will have a list of key words that can be used to help identify similarities. You would associate the "raw" name with its keywords, and use those keywords when comparing two or more raw names for similarities (literally, percentage of shared keywords).</p>
<p>Not a perfect solution by any stretch, but I don't think you are expecting one?</p>
|
Difference between generic argument constrained to an interface and just using the interface <p>What is the difference between this:</p>
<pre><code>void MyMethod(IMyInterface value)
{
//...
}
</code></pre>
<p>and this:</p>
<pre><code>void MyMethod<T>(T value) where T : IMyInterface
{
//...
}
</code></pre>
| <p>The main functional difference is that you can know the actual type of the object inside of the generic method. The T parameter will contain the actual type which can advantageous in certain scenarios. </p>
<p>In the non-generic case you cannot guarantee access to the underlying type of the object. Most of the type you could grab value.GetType() but the user could pass Null and thwart you. </p>
|
Does PyS60 has a reliable garbage collection? <p>I have heard it many times that garbage collection in PyS60 is not up to to the mark. This imposes a lot of limits on writing cleaner code. Can I at least rely that the non cyclic references are cleaned up after a function exists.</p>
| <p>PyS60 as of version 1.9.0 uses Python 2.5.1 core and has no problems with garbage collection.</p>
|
Jasper in Jetty 6 throws exception for JSTL tag <p>I'm trying to run an application in jetty that runs fine in Tomcat 5.5. The app uses servlet 2.4 and JSP 2.0.</p>
<p>Jetty/Jasper is throwing this exception:</p>
<pre><code>org.apache.jasper.JasperException: /WEB-INF/tiles/layout/main.jsp(85,55) PWC6340: According to the TLD, rtexprvalue is true, and deferred-value is specified for the attribute items of the tag handler org.apache.taglibs.standard.tag.rt.core.ForTokensTag, but the argument for the setter method is not a java.lang.Object
</code></pre>
<p>One odd thing, I can't find the TLD anywhere. It seems to be obtaining it by magic that I don't understand. Is it possibly getting a wrong TLD?</p>
<p>It's also hard to tell from where it's loading org.apache.taglibs.standard.tag.rt.core.ForTokensTag. Eclipse doesn't find it in the load path of the project.</p>
<p>Any hints welcome ...</p>
| <p>Jetty includes their own JSTL library and there is no need to include jakrta taglib's standard and core jars. </p>
<p>If you do put jakartat taglib's jars into your web application then there is a conflict in the forTokens tag that causes this error while other tags work well. I suggest either remove the jakarta taglib implementation from your web app and rely on Jetty's, or stop using forTokens.</p>
|
EXEC(query) AT linkedServer With Oracle DB <p>I am using Microsoft SQL server 2005. I need to sync data between SQL server and an Oracle db. First thing I need is to find out if the count of data on Oracle side with certain filters(here I use ID as a simple example).</p>
<pre><code>SELECT COUNT(*) FROM oracleServer..owner.table1 WHERE id = @id;
</code></pre>
<p>The problem I have is that the table on the lined server or Oracle is very big with 4M rows of data. The above query took about 2minutes to get data back. This code is just a simplied piece. Actually my SP has some other queries to update, insert data from the lined server to my SQL server. The SP took hours or 10+ hours to run with large Oracle db. Therefore T-SQL with lined server is not good for me.</p>
<p>Recently I found OPENQUERY and EXEC (...) AT linedServer. OPENQUERY() is very fast. It took about 0 time to get the same result. However, it does not support variable query or expressions. The query has to be a literal constant string.</p>
<p>EXEC() is in the same way to pass-through query to Oracle. It is fast as well. For example:</p>
<pre><code>EXEC ('SELECT COUNT(*) FROM owner.table1 WHERE id = ' + CAST(@id AS VARCHAR))
AT oracleServer
</code></pre>
<p>The problem I have is how to pass the result COUNT(*) back. I tried to google examples in web and msdn. All I can find are SQL or ExpressSQL linedServer examples like:</p>
<pre><code>EXEC ('SELECT ? = COUNT(*) FROM ...', @myCount OUTPUT) AT expressSQL
</code></pre>
<p>This query does not work for Oracle. It seems in Oracle, you can set value as output in this way:</p>
<pre><code>SELECT COUNT(*) INTO myCount ...
</code></pre>
<p>I tried this:</p>
<pre><code>EXEC ('SELECT COUNT(*) INTO ? FROM ...', @myCount OUTPUT) AT oracleServer
EXEC ('SELECT COUNT(*) INTO : FROM ...', @myCount OUTPUT) AT oracleServer
EXEC ('SELECT : = COUNT(*) FROM ...', @myCount OUTPUT) AT oracleServer
</code></pre>
<p>None of those working. I got error message saying query not executable on Oracle server. </p>
<p>I could write a .Net SQL Server project to do the job. Before that, I just wonder if there is anyway way to pass value out as oupput parameter so that I put the better performance T-SQL codes in my SP?</p>
| <p>Just a quick update on this. I think I got the solution. I found it in a discussion on a similar issue at <a href="http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic14841.aspx" rel="nofollow">Dev NewsGroup</a>. Based on the information, I tried this:</p>
<pre><code>DECLARE @myCount int;
DECLARE @sql nvarchar(max);
set @sql =
N'BEGIN
select count(*) into :myCount from DATAPARC.CTC_MANUAL_DATA;
END;'
EXEC (@sql, @myCount OUTPUT) AT oracleServer;
PRINT @myCount; -- 3393065
</code></pre>
<p>Wa! I got the result back in 3 seconds comparing T-SQL query directly on Orable DB (+2minutes). The important thing is to use "BEGIN" and "END;" to wrap the query as anonymous block and don't miss ";" after END</p>
<p>You need anonymous block for output parameters. If you only have input or no parameters, you don't need the block and the query works fine.</p>
<p>Enjoy it! By the way, this is a quick update. If you don't see me again, I would not have any trouble on this issue.</p>
|
What are the pros and cons for different methods of checking a Collection for a null before adding to a Set? <p>This is a follow up question to "<a href="http://stackoverflow.com/questions/591115/is-there-a-basic-java-set-implementation-that-does-not-permit-nulls">Is there a basic Java Set implementation that does not permit nulls?</a>". (thank you to all of those who helped with the answer) </p>
<p>It seems that the way to do this, since Sun didn't provide something simple like this OOTB, is with a wrapper / proxy. This seems nearly straight forward. What I am wondering is what are the pros/cons of the following two approaches of adding a collection, or is there another better approach?</p>
<p>Approach #1</p>
<pre><code>public boolean addAll( Collection<? extends E> c) {
if ( null == c ) {
throw new NullPointerException( "c cannot be null" );
}
/*
* This seems like a terrible abuse of exceptions when
* all I want to do is check the set for a null.
*
* However, simply running through each element of the
* Collection may provide much worse performance for large
* collections. And according to the Collection API, the
* contains method may throw NullPointerExceptions if the
* collection implementation does not allow null elements.
*/
boolean collectionContainsNull = false;
try {
collectionContainsNull = c.contains(null);
} catch (NullPointerException safeToIgnore) {
/* Safe to ignore since we do not want nulls */
}
if (collectionContainsNull) {
throw new NullPointerException("c cannot contain null elements");
}
this.wrapperSet.addAll(c);
}
</code></pre>
<p>Approach #2</p>
<pre><code>public boolean addAll( Collection<? extends E> c) {
if ( null == c ) {
throw new NullPointerException( "c cannot be null" );
}
E[] a = ( E[] )c.toArray();
/*
* We have to iterate through the entire collection to check for
* a null. This won't take advantage of any optimizations that
* c.contains may be using.
*
* We don't call add(e) here because if we hit a null midway through
* we would violate the condition that the set remains unchanged
* on error.
*/
for ( E e : a ) {
if (null == e) {
throw new NullPointerException("c cannot contain nulls");
}
}
this.wrapperSet.addAll(a);
}
</code></pre>
<p>Thanks in advance!</p>
| <p>The second approach is better. Never hide exceptions - you are relying on the assumption that c.contains(null) only throws a NullPointerException in the case that there is a null in the collection. However if the NullPointeException is thrown because of a problem with an equals method you will have a bug in your code - and you will have hidden it.</p>
<p>Edit:</p>
<p>From the JavaDoc for contains, NullPointerException is thrown - if the specified element is null and this collection does not permit null elements (optional).</p>
<p>Given that it is an optional method you may wind up with an UnsupportedOperationException being thrown instead of the NullPointerExcepion (in addition to hiding the an error in equals).</p>
|
Replacing body.onload in a user control <p>I am refactoring a page that uses <code><body onload="myJS();"></code> to a user control. I understand I can do it using server side script registration on load.</p>
<p>If I want to do it on the client side (ascx), how would I do this?</p>
| <p>Taken from <a href="http://snipplr.com/view/3116/cross-browser-add-event-listener/" rel="nofollow">http://snipplr.com/view/3116/cross-browser-add-event-listener/</a></p>
<pre><code>// Cross-browser implementation of element.addEventListener()
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
</code></pre>
<p>Use it like this: <code>addEvent(window, your_onload_handler)</code>. Or you could just use jquery for this and a lot of other things.</p>
|
Why does strcmp() return 0 when its inputs are equal? <p>When I make a call to the C string compare function like this:</p>
<p><code>strcmp("time","time")</code></p>
<p>It returns 0, which implies that the strings are not equal.</p>
<p>Can anyone tell me why C implementations seem to do this? I would think it would return a non-zero value if equal. I am curious to the reasons I am seeing this behavior.</p>
| <p>strcmp returns a lexical difference (or should i call it "short-circuit serial byte comparator" ? :-) ) of the two strings you have given as parameters.
0 means that both strings are equal</p>
<p>A positive value means that s1 would be after s2 in a dictionary.</p>
<p>A negative value means that s1 would be before s2 in a dictionary.</p>
<p>Hence your non-zero value when comparing "time" and "money" which are obviously different, even though one would say that time is money ! :-)</p>
|
Are there any open source cross platform NAT punch throughs? <p>Are there any open source cross platform NAT punch throughs?</p>
| <p>I haven't seen one, but you'll find more information than you require here:</p>
<p><a href="http://www.enchantedage.com/node/8" rel="nofollow">http://www.enchantedage.com/node/8</a></p>
<p>It's not terribly hard to implement, just a bit of work.</p>
<p>There is code on the page that demonstrates this that builds on unix and windows, including both the server portion (the introducer) and the client portions. It doesn't list a license, but the author indicates in the readme that the technique is free, and re-implementing it from the information on the page and the source code example appears to be relatively easy.</p>
<p>The author appears to be the owner of the website enchantedage, so you can probably contact them directly for more information.</p>
|
Visual Studio adds columns to DataGridView after running program <p>I have a datagridview that is linked to a three columns in the database, and it's only displaying them (no editing). When I run the program in debug, and exit, when I return to the form in Visual Studio, it has my three columns, plus all the columns in the table it's linked to. If I don't remove these, the next time I run the program, they show up on the form. If I remove them, I have to do it every time I run the program.</p>
<p>Any ideas on how to fix this?</p>
| <p>Is <code>AutoGenerateColumns</code> set to <code>True</code> ?</p>
<p>You should set it to <code>False</code> if you want to prevent the DGV from creating columns (in addition to those you created manually) from the datasource.</p>
<p>Edit: To clarify, this admittedly weird behaviour could result if the property is not set to False in design mode itself. I'm thinking of the corner case in which you set it to <code>False</code> at runtime. I would also take a look at the designer file (you might have to click the "show all files" option to view it) and see what it contains pertaining to the DGV. Might be a problem there.</p>
<p>Alternatively, have you tried deleting the control itself and creating a new DGV with the same bindings?</p>
|
Executing a Cygwin process from .NET? <p>I'm trying to launch Cygwin version of ruby.exe from a .NET application, but I'm stuck.</p>
<pre><code>c:\>"c:\cygwin\bin\ruby.exe" c:\test\ruby.rb
/usr/bin/ruby: no such file to load -- ubygems (LoadError)
</code></pre>
<p>As you see Ruby can't locate libraries because it's looking some Linux style paths. </p>
<p>Obviously when I run ruby.exe from .NET since it can't find libraries it fails like above.</p>
<p>If I don't load any library it works fine :</p>
<pre><code>c:\>"c:\cygwin\bin\ruby.exe" -v
ruby 1.8.7 (2008-08-11 patchlevel 72) [i386-cygwin]
</code></pre>
<p>Originally cygwin starts with this cygwin.bat</p>
<pre><code>chdir C:\cygwin\bin
bash --login -i
</code></pre>
<p>How can I make .NET to first go into cygwin enviroment and then execute ruby in that enviroment ?</p>
<ul>
<li>I can't use Windows Ruby, I need to cygwin ruby.</li>
<li>I'm aware of potential usage of interactively driving "bash" but that sounds dirty, unless there is nice way of doing it.</li>
</ul>
| <p>Are you using perhaps mixing native Windows rubygems and Cygwin ruby? Using Cygwin rubygems seems to work fine for me. (Why is your Cygwin ruby interpreter apparently searching a path with Windows backslashes in it?).</p>
<p>Alternatively, have you tried <code>run.exe</code>?</p>
<pre><code>C:\cygwin\bin\run.exe -p /starting/dir exe_to_run
</code></pre>
<p>Here's the man-page entry:</p>
<blockquote>
<p>NAME</p>
<p>run - start programs with hidden console window</p>
<p>SYNOPSIS</p>
<p>run [ -p path ] command [ -wait ] arguments</p>
<p>runcommand [ -p path ] [ -wait ] arguments</p>
<p>DESCRIPTION</p>
<p>Windows programs are either GUI programs or console programs. When
started console programs will either attach to an existing console
or create a new one. GUI programs can never attach to an exiting con-
sole. There is no way to attach to an existing console but hide it if
started as GUI program.</p>
<p>run will do this for you. It works as intermediate and starts a pro-
gram but makes the console window hidden.</p>
<p>With -p path you can add path to the PATH environment variable.</p>
<p>Issuing -wait as first program argument will make run wait for program
completition, otherwise it returns immediately.</p>
<p>The second variant is for creating wrappers. If the executable is
named runcommand (eg runemacs), run will try to start the program (eg
emacs).</p>
<p>EXAMPLES</p>
<p>run -p /usr/X11R6/bin xterm</p>
<p>run emacs -wait
runemacs -wait</p>
<p>run make -wait</p>
</blockquote>
|
Loading cells via nib and referencing components in them <p>I'm loading a UITableViewCell that contains two tagged labels. The user will leave the current view, containing the following code and go to another view. A name value is set there and the user comes back to this view (code below). I assign the name they set in the other view to the name label. That works but I get a new label misaligned on top of my other labels. It seems I'm keep two versions of this cell. Not quite sure. Any suggestions on what might be causing that sort of behavior?</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if(indexPath.section == 0)
{
cell = [tableView dequeueReusableCellWithIdentifier:@"CellNameIdentifier"];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"CellentName" owner:self options:nil];
cell = cellName;
//self.cellName = nil;
}
}
return cell;
}
- (void)viewDidAppear:(BOOL)animated {
UILabel *startdate = (UILabel *)[cellName viewWithTag:1];
startdate.text = aName;
[super viewDidAppear:animated];
}
</code></pre>
| <p>From the look of this code it is less likely that you are getting "a new label misaligned on top of my other labels" and more like the drawing is failing to repaint on top of things properly. To make this work, you can try calling [tableView reloadData] or using an observer, but I think there is a better way.</p>
<p>You should be able to pass the object into your other view, modify the object (instead of the label) and move the data around that way. In other words on the table view, it loads the objects, and inside of cellForRowAtIndexPath it loads the cells and sets the label names using the object data. Push in the second view and pass the object as a property. Manipulate this property all you want on that screen and when you pop the view, there is no special logic. The first table view again displays whatever is saved inside that object you were manipulating.</p>
|
Google Checkout : Best way to handle cart editing and checkout confirmation <p>I am in the process of implementing Google Checkout in an e-store. Once customers click the 'Google Checkout' button, my project requires that they are able to navigate back to the e-store to possibly edit the cart. Customers should be able to click the 'back' button, type in the URL to my cart page, or click the 'edit' link from Google.</p>
<p>At the same time, I need to clear the cart and provide customers with a blank slate as soon as they click the confirmation button on Google's side. I am already listening for a new-order-notification from Google, but this does not always arrive quickly enough to prevent customers from returning to the e-store and scratching theirs heads as to why their carts still show the items they just purchased.</p>
<p>Have any Google Checkout implementors come up with a novel solution to this problem? Any ideas are appreciated!</p>
| <p>I've done this using 2 different approaches, neither properly fulfils your requirement of handling the back button AND clearing the basket if they complete the order, but they've worked for me in practice without any complaints.</p>
<p><strong>First approach</strong>: clear the basket and provide way of reconstructing it via query string in the "EditCartUrl" Google Checkout request parameter. Then, when the customer clicks the edit basket button their basket is reconstructed. The back button, however, does not work in this situation.</p>
<p><strong>Second approach</strong>: don't clear the basket, but (optionally) make it read-only before redirecting to Google Checkout. We do this so that the basket record cannot be changed while they are within Google Checkout. If they then click back, or edit cart, a NEW basket is created on our site (cloned from the original) each time. This provides support for the back button, but will only provide the customer with a cleared basket if the order has gone through and we have processed the request before they return to the site.</p>
<p>Making the basket read-only is optional - we do it so we can preserve the basket record to match the resulting order from Google Checkout. If you don't require this, it's as simple as not clearing the basket.</p>
<p>The second approach has done me fine for the last few years without any complaints from customers. I'd rather the customer be able to click the back button than worry too much about them seeing the basket not empty itself after checking out using Google.</p>
|
VS2005: How to automatically generate a build number with date? <p>I have a .net 2.0 C# application in Visual Studio 2005 for which I'd like to automatically generate the correct version build number which should contain a number that allows me to guess the build date of the application.<br />
I tried to use the <a href="http://code.msdn.microsoft.com/AssemblyInfoTaskvers" rel="nofollow">'AssemblyInfo Task'</a> tool from Microsoft but by default this tool doesn't work. For today it would generate a build number '090227' which exceeds the maximum of 65535 and thus geneartes an error.<br /><br />
I could also live with a build number which contains the year and the day in the year, like 09001 for January 1 2009...<br />
Do you know any solution for this problem?<br />
Do I have to update the source code for this 'AssemblyInfo Task' or would this be possible to achieve in VS2008 or so?<br />
Thanks for your help.</p>
| <p>You'll want to look at <a href="http://msbuildtasks.tigris.org/" rel="nofollow">msbuildtasks</a>. It is an open source set of msbuild tasks. The module has a task to increment/modify/etc a build number. It's also super easy to use and super easy to extend.</p>
|
Disable texturing in OpenSceneGraph <p>I need to completely disable texturing in OSG. I tried <code>glDisable(GL_TEXTURE_2D)</code> and also using an osg::stateSet, but some nodes that have textures still render their textures. Is there any way to globally turn off texturing?</p>
<p>A bit of background : I need to produce an object coverage map for a scene, that is, knowing what object produced each visible pixel. I'm rendering each object with a flat color and reading back the color buffer - this is why texturing breaks what I'm trying to do. Any other ideas about how to accomplish this?</p>
| <p>Did you make sure to set the osg::StateAttribute::OVERRIDE bit when setting the Texture2D attribute? i.e. something like</p>
<pre><code>osg::Texture2D*const tex2D = new osg::Texture2D;
ss->setAttributeAndModes( tex2D, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE );
</code></pre>
<p>where <code>ss</code> is a stateset on a node high enough up in your scene graph to encompass all things that might have textures.</p>
<p>Of course if the GL_TEXTURE_2D mode or any Texture2D attributes lower down have the osg::StateAttribute::PROTECTED bit set then the OVERRIDE will be ignored but you might be in a position where you know that's not going to happen.</p>
|
Do i need to close a MySqlConnection in asp.net? <p>I've read that in PHP non-persistent open links are automatically closed at the end of the script's execution. So what's up with asp.net?</p>
| <p>Simple: PHP and ASP.NET aren't the same thing. They have different "rules". Don't try to write code in one environment as if it were the other.</p>
<p>In .NET should almost always open a connection as late as you can and close it as early as you can, letting the built-in connection pool handle the "real" connection to the database. <em>Don't</em> leave it to the GC/finalizer to tidy up connections for you.</p>
|
jquery: ajaxError always fires last <p>I am building a page that may receive <strong>LARGE</strong> amounts of html from an ajax call, which it than insert into the page.
Sometimes, instead of the html i am expecting, i will get an http 401 error.
Ideally i want to have the error handler fire first, so i can set an error flag, display a message, and <strong>NOT</strong> insert the html that comes in.</p>
<p>The problem i am having is that the error handler fires <strong>LAST</strong>, and so i have already inserted the html, which contains unexected script tags, and it makes everything blow up. </p>
<p>also, i noticed that ajaxError fires after the 'complete' handler, which blows.</p>
| <p>You should be using the <code>success</code> handler instead of <code>complete</code> to update the html because it will be triggered only if the server sends 200.</p>
|
ADO.NET Entity Framework I can't see Foreign Key Property in Model <p>I have 2 table. In first table I have a Foreign Key link to second table's primary key.</p>
<p>(second)Personel and (first)Istbl are my tables.</p>
<p>In personel table I have PersonelID , PersonelName, PersonelSurname.</p>
<p>In Istbl table I have IsID, PersonelID, xx, xx, xx, going like this.</p>
<p>I can't see PersonelID in EF Model Viewer. I also can't see it in code screen.</p>
<p>Is there any example for me?</p>
| <p>EF v1 hides foreign keys because it views them as persistence artifacts not important to the domain model. See <a href="http://www.thedatafarm.com/blog/2007/09/11/EntityDataModelAssociationsWheresMyForeignKey.aspx" rel="nofollow">here</a> for a discussion.</p>
<p>EF v2, shipping with .NET 4, will include much better support for foreign keys in the model.</p>
|
Flash Site Architecture - one swf vs many? <p>I'm about to start building a site entirely in flash (per the client's request), using AS3, and was wondering about best practices for doing so in terms of application architecture. The site isn't too large--think homepage, persistent nav, 8 subsections or so, each with their own content but similar design between subsections. In the past, I would have used multiple swfs (say, one for the nav and one each for the subsections) and loaded them dynamically; now, though, I'm considering taking a different route and using a more object-oriented design, with lots of classes and just one swf (plus a preloader to load it).</p>
<p>Are there any best-practices for determining whether it's better to dynamically load smaller swfs vs building a single large swf? In AS2 I think loading many smaller swfs made more sense, but with AS3's stronger object-oriented capabilities I'm wondering if that's still the case.</p>
<p>I know that one argument against the single-swf design would be the added weight of loading everything upon initial siteload, but I don't think there's enough heavy content that it's of real concern here.</p>
<p>Any thoughts?</p>
| <p>It depends on what you mean by "smaller."</p>
<p>Don't break it into chunks that are too small or you'll kill yourself with connection overhead. Don't pack the whole site into one mammoth wad that will takes weeks to download.</p>
<p>A good rule of thumb: if you find yourself trying to think up catchy or entertaining things to display while your users are waiting for it to download, restructure instead.</p>
<p>-- MarkusQ</p>
|
NUnit - specifying a method to be called after every test <p>Does NUnit let me invoke a method after every test method?</p>
<p>e.g.</p>
<pre><code>class SomeClass
{
[SomeNUnitAttribute]
public void CalledAfterEveryTest()
{
}
}
</code></pre>
<p>I'm aware of [SetUp] and [TearDown], but that only works for the tests in the current class. I want something like [TearDown], except it runs after <em>every</em> unit test, whether its in the current class or not. Possible?</p>
| <p>The [TearDown] Attribute marks the cleanup method.</p>
<p>If you want it for multiple classes I believe you can add the teardown method to a base class and inherit from that in every test class that needs the teardown behaviour.</p>
|
Sql Aggregate Results of a Stored Procedure <p>I currently have a stored procedure that returns a list of account numbers and associated details. The result set may contain multiple entries for the same account number. I also want to get some aggregate information such as how many distinct accounts are contained within a particular result set. Is there some way to retrieve such a view from my stored procedure results such as</p>
<pre><code>SELECT AccountNumber, Count(*)
FROM mystoredproc_sp
GROUP BY AccountNumber
</code></pre>
<p>It's fine if it needs to be contained within another stored procedure, but I'd like to be able to at least benefit from the logic that already exists in the first SP without duplicating the bulk of its code.</p>
| <pre><code>DECLARE @tt TABLE (acc INTEGER)
INSERT INTO @tt EXECUTE mystoredproc_sp
SELECT acc, COUNT(*) FROM @tt GROUP BY acc
</code></pre>
|
Software Testing against multiple versions of SQL Server <p>I'm currently working on a test plan and ran into a possible problem and I was wondering if anyone had any suggestions.</p>
<p>The application uses SQL Server and it can connect between the different versions for compatibility (2000, 2005, 2008). Well i'm trying to set up some test machines and was wondering how I should set things up. Should I do each OS against each SQL version, or are there versions/OS's I can exclude due to some reason I don't know. The way i'm seeing things now to test everything would be 9 machines or VM's (last three are preparing for Win7 in future, but not necessary now). </p>
<p>WinXP - 2k, 2k5, 2k8
WinVista - 2k, 2k5, 2k8
Win7 - 2k, 2k5, 2k8</p>
<p>Any ideas will be appreciated.</p>
<p>Thanks in advance,
Aaron Foley</p>
| <p>Your test plan makes sense, although it's probably not something you'll have to conduct more than once. Just make sure you have some type of automated test plan set up.</p>
<p>At a minimum, test XP against 2k and 2k5, and Vista/Win7 against 2k5 and 2k8.</p>
|
VB.NET List(of X).Contains Behavior <p>I have a custom class set up as a key that has two properties, X and Y</p>
<p>I have something similar to this:</p>
<pre><code>Dim test As New List(of TestClass)
Dim key as New TestData
key._a = A
key._b = B
For Each a As TestClass In SomeCollection
If Not test.Contains(key) Then
'Do Stuff
End If
Next
</code></pre>
<p>My question is this: How does the .Contains on the List(of T) behave? Does it look for an identical data structure, or does it simply match on one of the properties of my key? </p>
<p>If you can, please include a link where I can look at some documentation regarding this.</p>
<p><em>EDIT</em>
Is the Contains method Typesafe?</p>
| <p>It uses the <code>Equals</code> method to check for identity.</p>
<p>By default (if not overridden) <code>Equals</code> returns <code>true</code> if two references are identical or two structures are equal memberwise.</p>
|
How can I tell whether an element matches a selector? <p>Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as <code>p</code> or <code>.myclass</code>? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?</p>
<p>The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.</p>
<p>Will this work as intended? I can't figure out Javascript object comparisons. </p>
<pre><code>$(selector, myElement.parentNode).each({
if (this == myElement) // Found it
});
</code></pre>
<p>Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...</p>
| <p>You can use the <a href="http://docs.jquery.com/Is"><code>is()</code></a> method:</p>
<pre><code>if($(this).is("p")){
// ...
}
</code></pre>
|
PolicyException: Required permissions cannot be acquired â what does this error mean <p>Got this error when trying to load an aspx page:</p>
<pre><code>Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[PolicyException: Required permissions cannot be acquired.]
System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Boolean checkExecutionPermission) +2770052
System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Int32& securitySpecialFlags, Boolean checkExecutionPermission) +57
[FileLoadException: Could not load file or assembly 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +54
System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +211
System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +141
System.Reflection.Assembly.Load(String assemblyString) +25
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +32
[ConfigurationErrorsException: Could not load file or assembly 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +596
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +211
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +46
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +177
System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +185
System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +230
System.Web.Compilation.BuildManager.CompileGlobalAsax() +49
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +462
[HttpException (0x80004005): Could not load file or assembly 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +57
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +612
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +644
[HttpException (0x80004005): Could not load file or assembly 'SQLite.NET, Version=0.21.1869.3794, Culture=neutral, PublicKeyToken=c273bd375e695f9c' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +3465427
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +69
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +279
</code></pre>
| <p>Do you have the web app configured as Medium Trust and the SQLite.NET assembly requires Full Trust?</p>
<p>See if adding this to your web.config fixes it:</p>
<pre><code><system.web>
<securityPolicy>
<trust level="Full" />
</securityPolicy>
...
</system.web>
</code></pre>
<p>Or if you already have the trust tag, change the level to Full.</p>
|
Suitable environment for a 7 year old <p>My 7 year old would like to learn, how to program? (his idea not mine, and he does things in the outside world. So, I am not too worried from that point of view. He already went so far as to take a game programming book out of my office to read at bed time.) The other day we sat down and wrote a very simple number guessing game (you pick 8 and it is correct, anything else it is wrong). </p>
<p>It went OK but there were a number of questions he had based on the syntax of the language. (I happened to pick Java as I had the IDE opened at the time.) I teach post-secondary introductory programming courses so this was a bit of an eye opener to me (most students out of high school are reluctant to ask questions) as I really had to figure out, how to explain syntax to a 7 year old?</p>
<p>Clearly any C type language is going to have the same issues, as will most âlanguagesâ. I looked at squeak but decided not to use it yet. I looked at the Alice environment but didn't like it for this either.</p>
<p>From a physical point of view he is comfortable with a keyboard/mouse and can put together Lego sets with relative ease (so following directions with a fun outcome works for him). I have access to Lego NXT but he is still a bit young for that (it takes too long to see the results of the work, even with the supplied graphical environment). </p>
<p>Ideally I'd like the experience to help him build up confidence in math and logic (if a 7 year old has logic:-).</p>
<p>I remember using turtle graphics/logo as a child. I am leaning towards this but wondering if there are any other ideas or if anyone can recommend a good logo environment?</p>
<p>Edit 1:</p>
<p>Logo works out well. I'll need to teach him the concept of angles (90 degrees, 180 degrees). Unfortunalty they don't really do division at school yet so angles might be fun...</p>
<p>First off draw a square:</p>
<pre><code>FORWARD 50
RIGHT 90
FORWARD 50
RIGHT 90
FORWARD 50
RIGHT 90
FORWARD 50
RIGHT 90
</code></pre>
<p>At some point later I'll go into loops:</p>
<pre><code>REPEAT 4
[
FORWARD 50
RIGHT 90
]
</code></pre>
<p>And then variables:</p>
<pre><code>make "length 50
REPEAT 4
[
FORWARD :length
RIGHT 90
]
</code></pre>
<p>This works out very well. Virtually no syntax, easy for a 7 year old to remember the vocabulary, and immediate feedback.</p>
<p>Edit 2:</p>
<p>Well it was a success, in that he was able to write a simple program (no loops yet) while I was out of the room. It actually works out very well - we went out and got to graph paper and a protractor, we fugured out 90 degree angles, and he made a bunch of squares, turned a square into a rectangle, and got to see where he went wrong and how to debug it. I'd recommend this approach for anyone with a 7 year old who is interested in programming. I think I'd recommend it to my post-secondary students too (!)</p>
| <p>There is actually a browser-based Logo interpreter in Javascript.</p>
<p><a href="http://logo.twentygototen.org/">http://logo.twentygototen.org/</a></p>
|
wxPython toolbar help <p>I am new to Python. I am writing an application using wxPython and I currently my code that generates a toolbar looks like this:</p>
<pre><code>class Window(wx.Frame)
def __init__(self, parent, plot):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Name", size =(900, 600))
self.Centre()
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am trying to clean up the code a bit and I want the toolbar to have its own class so when I want to create a toolbar, I simply call it something like this:</p>
<pre><code>toolbar = Toolbar()
</code></pre>
<p>My question is how can I rewrite it so it works like that? Currently my code looks like this:</p>
<pre><code>class Toolbar():
def __init__(self):
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am not quite sure how 'self' works. Do I need to rewrite the <strong>init</strong> function? How do I fix it? Any help is greatly appreciated. Thanks</p>
| <p>Instead of a class that sets up your toolbar, use a function. The function can be a member function of your Window that subclasses wx.Frame. That way, the toolbar will get Created from the correct window, and be attached the way you would expect.</p>
<p>The class that you're writing above would work, if it knew which wx.Frame (your class called Window) to connect the toolbar to. To get it to work you would have to pass the frame object to the toolbar creator class...</p>
<pre><code>class Toolbar():
def __init__(self, frame_to_connect_to):
frame_to_connect_to.toolbar = frame_to_connect_to.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
frame_to_connect_to.toolbar.SetToolBitmapSize((32,32))
frame_to_connect_to.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
frame_to_connect_to.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
frame_to_connect_to.toolbar.AddSeparator()
frame_to_connect_to.toolbar.Realize()
</code></pre>
<p>It looks like a quick fix... but really using a class to do this is not a good use of classes. (I'd even go so far as to say it was incorrect.)</p>
<p>Really, what would clean things up a bit would be just to move the toolbar stuff to its own member function:</p>
<pre><code>class Window(wx.Frame)
def __init__(self, parent, plot):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Name", size =(900, 600))
self.Centre()
self._init_toolbar()
def _init_toolbar(self):
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>You get all the benefits.</p>
|
PHP mysqli unexpected parameter Question <p>I feel like a total n00b for not understanding what I'm doing wrong, but here goes.</p>
<p>I'm writing a simple web form that's storing information in a MySQL database. I'm getting this error:</p>
<pre><code>mysqli_stmt_init() expects parameter 1 to be mysqli, null given in /myfile.php
</code></pre>
<p>Here's my code:</p>
<pre><code>$server = 'localhost';
$username = 'myusername';
$password = 'mypassword';
$db = 'mydb';
$link = mysqli_connect($server, $username, $password, $db);
.
.
.
$stmt = mysqli_stmt_init($link); /*This line throws the error*/
</code></pre>
<p>Any ideas? Thanks in advance.</p>
| <p>Are you 100% sure you are successfully connecting to the database?</p>
<p>Add at the top of your script:</p>
<pre><code>error_reporting(E_ALL);
ini_set('display_errors', 1);
</code></pre>
<p>Also add right below your connection line:</p>
<pre><code>if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
</code></pre>
|
Objects returned from Silverlight Async calls lose their contained aggregates <p>A call from a Silverlight 2.0 control to a WebService, returned via MyWebServiceNameEventArgs is not returning contained List<> aggregates. For Example, I've got a Person class that has a List and List. When I trace the call I see that the person has the lists are populated appropriately. However, when it arrives via the MyWebServiceNameEventArgs the lists are null. the simple types like FirstName, DOB etc are correctly returned.</p>
<p>Is there something I have to do to get the enclosed aggregates to be returned?</p>
<p>Here's my code:</p>
<pre><code>private void btnGetPerson_Click(object sender, RoutedEventArgs e)
{
var proxy = new TutorWCFServicesClient();
proxy.GetPersonWithPersonKeyOfCompleted += new EventHandler<GetPersonWithPersonKeyOfCompletedEventArgs>(proxy_GetPersonWithPersonKeyOfCompleted);
var perID = 29; // testing
proxy.GetPersonWithPersonKeyOfAsync(perID);
}
void proxy_GetPersonWithPersonKeyOfCompleted(object sender, GetPersonWithPersonKeyOfCompletedEventArgs e)
{
var per = e.Result;
if (per != null)
{
FirstName.Text = per.FirstName;
LastName.Text = per.LastName;
if (per.Phones != null)
{
var hPhone = (from phone in per.Phones where phone.PhoneType.ToLower() == "home" select phone).FirstOrDefault();
var cPhone = (from phone in per.Phones where phone.PhoneType.ToLower() == "cell" select phone).FirstOrDefault();
var wPhone = (from phone in per.Phones where phone.PhoneType.ToLower() == "work" select phone).FirstOrDefault();
if (hPhone != null)
{
PhoneHome.Text = string.Format("({0}) {1}-{2}", hPhone.AreaCode, hPhone.Exchange, hPhone.Number);
}
if (cPhone != null)
{
PhoneCell.Text = string.Format("({0}) {1}-{2}", cPhone.AreaCode, cPhone.Exchange, cPhone.Number);
}
if (wPhone != null)
{
PhoneSchool.Text = string.Format("({0}) {1}-{2}", wPhone.AreaCode, wPhone.Exchange, wPhone.Number);
}
}
}
else
{
FirstName.Text = "Not Found";
}
}
</code></pre>
| <p>Dumb error, I forgot to refresh the ServiceReference in the Silverlight app.</p>
|
what is /dev/windrvr6 <p>What is /dev/windrvr6 Is this a generic driver? I have 2 card made by different vendors using /dev/windrvr6 and they seem to work fine. Will this be a problem in the future?</p>
| <p>It could be that they both used tools from <a href="http://www.jungo.com/" rel="nofollow">Jungo</a>; they have products to help people make PCI drivers, and part of their common infrastructure is <a href="http://www.jungo.com/st/windriver%5Fusb%5Fpci%5Fdriver%5Fdevelopment%5Fsoftware.html" rel="nofollow">WinDriver</a>. (Despite its name, <a href="http://www.jungo.com/st/linux.html" rel="nofollow">it's also for Linux</a>)</p>
<p>I don't expect that this should be a problem.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.