input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
how to change javascript function to ActionScript 3? <p>anybody can help me to change that javascript function to AS3?</p>
<p>thanks :)</p>
<pre><code> function parseURLtoVars(strLocation){
var rArray = new Array();
var key;
var urlString = new String(strLocation);
if (urlString.search(/\?/)>-1){
var qArray = urlString.split('?')[1].split('&');
if (qArray.length > 0){
for (key in qArray){
var arVal = qArray[key].split('=');
if (arVal.length ==2){
rArray[arVal[0]] = arVal[1];
} else {
continue;
}
}
return rArray;
} else {
return false;
}
}
return false;
}
</code></pre>
| <p>this returns params as an object, to return a boolean should be a simple edit.</p>
<pre><code>function getParams(documentRoot):Object
{
try {
var params:Object = LoaderInfo(documentRoot.loaderInfo).parameters;
var pairs:Object = {};
var key:String;
for(key in params) {
pairs.key = String(params.key);
}
} catch(e:Error) {
return {};
}
return params;
}
</code></pre>
|
Why is git-cvsimport missing one major patchset? <p>This is a followup to <a href="http://stackoverflow.com/questions/683091/how-do-i-debug-git-cvsimport-cant-see-complicated-commit">a previous question of mine</a>.</p>
<p>I can look through the output of cvsps (saved in my ~/.cvsps directory) and see a patchset for a major, complicated commit. But this commit does not show up when I do cvsimport to update my existing git repository. I know that git-cvsimport will ignore patchsets that are newer than 10 minutes, in an effort to avoid importing a CVS commit that is incomplete. I think I've also heard that it will skip patchsets for which the associated branch cannot be identified. What other reasons might be causing git-cvsimport to be ignoring my commit? How can I debug this?</p>
<p>Here is a little bit of the cvsps output:</p>
<pre><code>patchset: 50064
date: 1238445635
author: skiphoppy
tag:
tag_flags: 0
branch: HEAD
branch_add: 1
descr:
My log message
-=-END CVSPS DESCR-=-
members:
file:ordinaryChangedFile; pre_rev:1.44; post_rev:1.45; dead:0; branch_point:0
file:newFileRenamedAndModifiedFromOldFile; pre_rev:INITIAL; post_rev:1.1; dead:0; branch_point:0
file:deletedFileGoneBecauseRenamed; pre_rev:1.2; post_rev:1.3; dead:1; branch_point:0
...
</code></pre>
<p>Does that branch_add: 1 line have anything to do with it? There are only 9 such commits in the entire repository; the other 50090 commits say branch_add: 0. Other than that I don't know what the differences are from a cvsps or git-cvsimport point of view. The commit was complicated, involving renaming several files and making associated content modifications. Definitely difficult for CVS to handle. A snap for git, of course, but hard for git to handle when the real backend is CVS.</p>
<p>I've got to perform the same type of complicated commit three more times, and I can't afford to spend 4 1/2 hours each time to reimport a brand new git repository from CVS due to cvsimport not being able to see my commit.</p>
<p>More importantly, I'm frightened by the fact that my daily runs of git-cvsimport (which I intended to put into cron, or even write a daemon to run every five minutes or so) might <strong><em>miss</em></strong> commits in the future! I have found no way to git an existing repository to pick up these commits; I can only run git-cvsimport in a brand new repository and wait forever, losing the use of many of my other branches while I'm at it.</p>
| <p>Well, this may be the problem. My git-cvsimport lines look like this:</p>
<pre><code>git cvsimport -p x ...
</code></pre>
<p>The -p x is is supposed to pass the -x option to cvsps to tell it to ignore the cached output that it left lying around from previous runs. I thought the main reason to do that was so that the last few patchsets, which might be incomplete, will be thrown out and completed the next time you run. Turns out there may be more issues that it fixes, and this may be one of them.</p>
<p>I learned to run git cvsimport this way from <a href="http://issaris.blogspot.com/2005/11/cvs-to-git-and-back.html" rel="nofollow">this blog entry</a>, which is currently one of the highest hits on Google for "git cvs." It was only in the process above, where I was trying to run git-cvsimport through the Perl debugger on output from cvsps, that I had to check and see what arguments were really going to cvsps. I learned cvsps was being run like this:</p>
<pre><code>cvsps --norc x --cvs-direct ...
</code></pre>
<p>Instead of:</p>
<pre><code>cvsps --norc -x --cvs-direct ...
</code></pre>
<p>And I experimentally verified that I get different output from cvsps, with some patchsets missing (I have no idea what the pattern is), when x is passed instead of -x. Thanks to Murphy's law, cvsps doesn't seem to report that this was a problem, and git-cvsimport never sees it.</p>
<p>So anyway, git cvsimport needs to be run like this:</p>
<pre><code>git cvsimport -p -x ...
</code></pre>
<p>My previous versions of this repository are completely hosed at this point, but I have been able to force the last of the problem commits into them (some of the earlier commits are missing, though). So I get to go through the four-hour import process one more time, and I'm hoping that will be it!</p>
<p>One last tip: git-cvsimport on Windows doesn't seem to work at all. I got less than 10% of the number of commits, although I did wind up with a tree that resembles the current state of our project. It just seems to be lacking almost all the history...</p>
|
HTML divs popup to select columns <p>I have a web application(ASP.NET2.0 C#) and in it, I have a gridview that gets its data from a datasource.</p>
<p>I wanted to add the following feature: the user can click a button "select columns", and a box pops up with a list of all the columns(a checkboxlist in a div, possibly) and that way, the user can choose the columns they want to see, and click another button "show" and the list of columns goes away, and the table shows the columns that the user selected.</p>
<p>I have already implemented the column choosing part, but it is the popup part that I need help with. How can I make the div popup and then disappear? </p>
<p>The solution might require javascript, and I might not have figured it out since I don't really know javascript that well. </p>
<p>Thank you.</p>
| <p>HI,
Its better to make the display of div to be none rather than setting visibility to hidden. If visibility is set to hidden even if the div doesn't show up but it will take the rendering space which in some situation might not be that good.</p>
<p>You can dynamically create a div using createNode and then by absolute positioning and setting the top and left according to your convenience you can align the div to any portion in the page. Its better if you could disable the background when the div pops out.</p>
|
JMS Topic Creation in JBoss 5 AS <p>In Jboss 4, when I deployed an ear with an MDB for a topic that had not been specified in the deployment descriptors, the server would automatically create the topic (after posting a warning saying that topic didn't exist).</p>
<p>In Jboss 5, it doesn't seem to automatically create the topics anymore (errors out instead). Is there a configuration option somewhere that would allow automatic topic creation? </p>
| <p>From the JBoss community forums -- <a href="https://jira.jboss.org/jira/browse/JBAS-6013" rel="nofollow">This JIRA</a> was added in 5AS.</p>
<p>Unfortunately it looks like there is no way to implement createDestination globally in the standardjboss.xml descriptor -- You have to add a custom jboss.xml descriptor to the ear deploying the mdb.</p>
<pre><code><jboss xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee
http://www.jboss.org/j2ee/schema/jboss_5_0.xsd" version="3.0">
<enterprise-beans>
<message-driven>
<ejb-name>MessageDriven</ejb-name>
<create-destination>true</create-destination>
</message-driven>
</enterprise-beans>
</jboss>
</code></pre>
|
Valid email address regular expression? <p>I have done some testing but I wanted to ask if anyone sees a problem with this ruby regular expression for email validation:</p>
<pre><code>/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
</code></pre>
<p>Look good?</p>
<p>Thanks,</p>
<p>Tony</p>
| <p>You were close, have to add just a few more characters:</p>
<pre><code>(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
\t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
\t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
\t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)
</code></pre>
<p>No, I'm not joking: <a href="http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html">http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html</a></p>
|
Linq query loses order <p>I have a view in my database that produces ordered results, but when I run a Linq query over that view, the results are no longer ordered (at least, according to the foreach I use to iterate over the results, and according to the debugger). Is this a known difficulty with Linq, or am I missing something?</p>
<p><strong>Update</strong>: my view, from SQL Server 2008 (from design view):</p>
<pre><code>SELECT TOP (100) PERCENT UrlId, Title, Description, Url, Parent, ResourceKey, Published, dbo.udf_SiteMap_GetRoles(UrlId) AS Roles
FROM dbo.SiteMap
ORDER BY DisplayOrder
</code></pre>
<p>The Linq query that builds the SiteMap:</p>
<pre><code>SqlConnection connection = new SqlConnection(_connect);
DataContext dc = new DataContext(connection);
Table<NodeRoleEntity> siteMapTable = dc.GetTable<NodeRoleEntity>();
var rootQuery = from ne in siteMapTable
where ne.ParentID == null
select ne;
foreach (NodeRoleEntity rootNode in rootQuery)
{
SiteMapNode root = rootNode.AsSiteMapNode(this);
base.AddNode(root, _root);
AddChildNodes(root, siteMapTable);
}
</code></pre>
<p>This query uses the SiteMap built above to render menus in my ASP.NET application:</p>
<pre><code>StaticSiteMapProvider _provider = SiteMap.Providers["MySiteMap"] as StaticSiteMapProvider;
string cultureToken = _GetCulture().ToLower();
SiteMapNode cultureRoot =
(from SiteMapNode cr in _provider.RootNode.ChildNodes
where cr.Description == cultureToken
select cr).First();
int menuCount = 0;
foreach (SiteMapNode node in cultureRoot.ChildNodes)
{
_RenderMenu(node, menuCount.ToString(), writer);
menuCount++;
}
</code></pre>
<p>It is the nodes in <code>cultureRoot.ChildNodes</code> that are ordered improperly (but the rows from which those nodes are derived are ordered). </p>
| <p>Your linq query is:</p>
<pre><code>var rootQuery = from ne in siteMapTable
where ne.ParentID == null
select ne;
</code></pre>
<p>This will generate sql like so</p>
<pre><code>SELECT *
FROM SiteMapTable
WHERE ParentID == @P1
</code></pre>
<p>You can take this sql to the database, run it and observe that your results are un-ordered. Here's what happens:</p>
<p>In the database, the text of the view will be placed as a subquery into your query.</p>
<pre><code>SELECT *
FROM
(
SELECT top 100 percent *
FROM ...
ORDER BY ...
) as SiteMapTable
WHERE ParentID == @P1
</code></pre>
<p>The query optimizer will notice that ordering was not asked for at the outer most level, and decide that order is not needed for the results. It will strip out/ignore the ordering in the sub-query. You can view the estimated execution plan to confirm this.</p>
|
Draw Gaussian curve in Java <p>I'm coding an interactive applet with <a href="http://code.google.com/p/piccolo2d/" rel="nofollow">Piccolo</a> and I need to include a Gaussian curve (aka <a href="http://en.wikipedia.org/wiki/Normal%5Fdistribution" rel="nofollow">Normal distribution chart</a>) inside it.</p>
<p>I imagine any kind of Java implementation would be enough, but I can't find any. Ideally, I'd like to pass a set of values and have the chart drawn in a panel, an image object or anything that can be embedded in an applet.</p>
<p>Before getting my hands dirty coding it myself, does anybody know of a working piece of code to do it?</p>
<p>Implementations in other languages are welcomed, as long as they are easily portable to Java.</p>
| <p>Don't know if it works, but Google threw up <a href="http://vase.essex.ac.uk/software/JavaPlot/code/ac/essex/graphing/charts/continuous/Gaussian.java.html" rel="nofollow">this code to plot a Gaussian distribution</a>.</p>
<p>The home page for this project is <a href="http://vase.essex.ac.uk/software/JavaPlot/" rel="nofollow">here</a>. </p>
<p>If Piccolo doesn't perform the plotting for you, I would perhaps use <a href="http://www.jfree.org/jfreechart/" rel="nofollow">JFreeChart</a> for the actual plotting, since it's widely supported and very capable. (I'm not familiar with Piccolo)</p>
|
Drupal node?destination not working <p>I've troubles with Drupal 6 and (maybe) mod_rewrite:</p>
<p>if I go to <em><a href="http://127.0.0.1/drupal/node/115/edit?destination=admin%2Fcontent%2Fnode" rel="nofollow">http://127.0.0.1/drupal/node/115/edit?destination=admin%2Fcontent%2Fnode</a></em> and then I save the node, I don't get redirected to <em>admin/content/node</em>, but it directs me to node/115 :-(</p>
<p>Why??</p>
<p>In my .htaccess I uncommented: <em>RewriteBase /drupal</em> (because my drupal path is /var/www/htdocs/drupal)</p>
<p>My server is running Apache 2.2.4 on Slackware 12</p>
<p>Any help I'll be appreciated :D</p>
| <p>It does look like a configuration problem, because this normally works. You can debug it by adding some dsm() dumps in <code>includes/common.inc/drupal_goto()</code> : this is where the <code>destination</code> parameter is processed.</p>
<p>Note that if some module traps your form submission, for instance by declaring a <code>_validate</code> or <code>_submit</code> handler, it can very well change the redirection information: check whether you can reproduce this without contrib modules enabled.</p>
|
File and Directory Security with IPrincipal <p>I need to gain access to the files and directories that the current IPrincipal has access to via the Directory.GetDirectories() and Directory.GetFiles() methods, without listing the other files. The process itself is running as NETWORK SERVICE, so it must change the principal to the current user (via IPrincipal) for the duration of these calls.</p>
<p>I have attempted to change Thread.CurrentPrincipal to the new IPrincipal prior to the file access part, but it doesn't appear to make a difference.</p>
<p>Is there something else I can do, or am I missing something?</p>
| <p>Windows impersonation solves this problem by using the login details to acquire a user token. This token can then be used to obtain a WindowsIdentity, which is then used to generate an impersonation context. Within this context scope, you can then access the file system <em>as</em> the impersonated user.</p>
<p>Of course, you will need to store the user name and password for this approach to work.</p>
<p>First, define the Windows APIs required to obtain a user token from Windows:</p>
<pre><code>internal class WindowsAPI
{
public const int LOGON32_PROVIDER_DEFAULT = 0;
public const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport( "advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode )]
public static extern bool LogonUser( String lpszUsername,
String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken
);
[DllImport( "kernel32.dll", CharSet = CharSet.Auto )]
public extern static bool CloseHandle( IntPtr handle );
}
</code></pre>
<p>Then, use these APIs to aquire a WindowsIdentity:</p>
<pre><code>private WindowsIdentity GetIdentity( string userName, string password )
{
_userToken = IntPtr.Zero;
if ( !WindowsAPI.LogonUser(
userName,
AbbGrainDomain,
password,
WindowsAPI.LOGON32_LOGON_INTERACTIVE, WindowsAPI.LOGON32_PROVIDER_DEFAULT,
ref _userToken
) )
{
int errorCode = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception( errorCode );
}
return new WindowsIdentity( _userToken );
}
</code></pre>
<p>And finally, use this identity to generate an impersonation context:</p>
<pre><code>public List<string> GetDirectories( string searchPath )
{
using ( WindowsImpersonationContext wic = GetIdentity().Impersonate() )
{
var directories = new List<string>();
var di = new DirectoryInfo( searchPath );
directories.AddRange( di.GetDirectories().Select( d => d.FullName ) );
return directories;
}
}
</code></pre>
<p>Finally it is important to clean up the windows handle using the IDisposable pattern, using the stored _userToken:</p>
<pre><code>if ( _userToken != IntPtr.Zero )
WindowsAPI.CloseHandle( _userToken );
</code></pre>
|
Exception thrown when resources declaration order changed <p>I get exception when declare resources in this order:</p>
<pre><code><Window.Resources>
<sys:Object x:Key="resourceA"></sys:Object>
<x:Array x:Key="resourceB" Type="sys:String">
<sys:String>foo</sys:String>
</x:Array>
</Window.Resources>
</code></pre>
<p>and when declare this way, all works:</p>
<pre><code><Window.Resources>
<x:Array x:Key="resourceB" Type="sys:String">
<sys:String>foo</sys:String>
</x:Array>
<sys:Object x:Key="resourceA"></sys:Object>
</Window.Resources>
</code></pre>
<p>The Exception thrown is:</p>
<blockquote>
<p>Cannot convert the value in attribute
'ItemsSource' to object of type
'System.Collections.IEnumerable'.
'System.Windows.Markup.ArrayExtension'
is not a valid value for property
'ItemsSource'. Error at object
'System.Windows.Controls.ComboBox' in
markup file
'WpfResourcesBug;component/window1.xaml'
Line 18 Position 37.</p>
</blockquote>
<p>Full code:</p>
<pre><code><Window x:Class="WpfResourcesBug.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<sys:Object x:Key="resourceA"></sys:Object>
<x:Array x:Key="resourceB" Type="sys:String">
<sys:String>foo</sys:String>
</x:Array>
</Window.Resources>
<StackPanel>
<ComboBox SelectedIndex="0" ItemsSource="{StaticResource resourceB}" />
</StackPanel>
</Window>
</code></pre>
| <p>I think you might find a possible solution <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/9db5f1f5-f3a9-402c-9869-08d3624eea59/" rel="nofollow">here</a></p>
|
Python: an iteration over a non-empty list with no if-clause comes up empty. Why? <p>How can an iterator over a non-empty sequence, with no filtering and no aggregation (<code>sum()</code>, etc.), yield nothing?</p>
<p>Consider a simple example:</p>
<pre><code>sequence = ['a', 'b', 'c']
list((el, ord(el)) for el in sequence)
</code></pre>
<p>This yields <code>[('a', 97), ('b', 98), ('c', 99)]</code> as expected.</p>
<p>Now, just swap the <code>ord(el)</code> out for an expression that takes the first value out of some generator using <code>(...).next()</code> â forgive the contrived example:</p>
<pre><code>def odd_integers_up_to_length(str):
return (x for x in xrange(len(str)) if x%2==1)
list((el, odd_integers_up_to_length(el).next()) for el in sequence)
</code></pre>
<p>This yields <code>[]</code>. Yeah, empty list. No <code>('a', </code>stuff<code>)</code> tuples. Nothing.</p>
<p>But we're not filtering or aggregating or reducing. A generator expression over <code>n</code> objects without filtering or aggregation must yield <code>n</code> objects, right? What's going on?</p>
| <p><code>odd_integers_up_to_length(el).next()</code> will raise StopIteration, which isn't caught there, but is caught for the generator expression within it, stopping it without ever yielding anything.</p>
<p>look at the first iteration, when the value is 'a':</p>
<pre><code>>>> odd_integers_up_to_length('a').next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
</code></pre>
|
Prevent/stop auto anchor link from occurring <p>I need to prevent the automatic scroll-to behavior in the browser when using link.html#idX and <div id="idX"/>.</p>
<p>The problem I am trying to solve is where I'm trying to do a custom scroll-to functionality on page load by detecting the anchor in the url, but so far have not been able to prevent the automatic scrolling functionality (specifically in Firefox).</p>
<p>Any ideas? I have tried preventDefault() on the $(window).load() handler, which did not seem to work.</p>
<p>Let me reiterate this is for links that are not clicked within the page that scrolls; it is for links that scroll on page load. Think of clicking on a link from another website with an #anchor in the link. What prevents that autoscroll to the id?</p>
<p>Everyone understand I'm not looking for a workaround; I need to know if (and how) it's possible to prevent autoscrolling to #anchors on page load.</p>
<p><hr /></p>
<h2><strong>NOTE</strong></h2>
<p>This isn't <em>really</em> an answer to the question, just a simple race-condition-style kluge.</p>
<p>Use jQuery's scrollTo plugin to scroll back to the top of the page, then reanimate the scroll using something custom. If the browser/computer is quick enough, there's no "flash" on the page.</p>
<p>I feel dirty just suggesting this...</p>
<pre><code>$(document).ready(function(){
// fix the url#id scrollto "effect" (that can't be
// aborted apparently in FF), by scrolling back
// to the top of the page.
$.scrollTo('body',0);
otherAnimateStuffHappensNow();
});
</code></pre>
<p>Credit goes to <a href="http://stackoverflow.com/users/22419/wombleton">wombleton</a> for pointing it out. Thanks!</p>
| <p><a href="http://www.inmotiondesign.nl/playground/?p=20">This</a> seems the only option I can see with ids:</p>
<pre><code>$(document).ready(function() {
$.scrollTo('0px');
});
</code></pre>
<p>It doesn't automatically scroll to classes.</p>
<p>So if you identify your divs with unique classes you will lose a bit of speed with looking up elements but gain the behaviour you're after.</p>
<p>(Thanks, by the way, for pointing out the scroll-to-id feature! Never knew it existed.)</p>
<p>EDIT: </p>
|
What's the point of basis path coverage? <p>The article at <a href="http://www.onjava.com/pub/a/onjava/2007/03/02/statement-branch-and-path-coverage-testing-in-java.html?page=2" rel="nofollow">onjava</a> seems to imply that basis path coverage is a sufficient substitute for full path coverage, due to some linear-independence/cyclomatic-complexity magic.</p>
<p>Using an example similar to the article:</p>
<pre><code>public int returnInput(int x, boolean one, boolean two)
{
int y = x;
if(one)
{
y = x-1;
}
if(two)
{
x = y;
}
return x;
}
</code></pre>
<p>with the basis set {FF,TF,FT}, the bug is not exposed. Only the untested TT path would expose it.</p>
<p>So, how is basis path coverage useful? It doesn't seem much better than branch coverage.</p>
| <p>[Disclaimer: I've never heard of this technique before, it just looks interesting so I've done a few searches and here's what I think I've found out. Hopefully someone who knows what they're talking about will contribute too...]</p>
<p>I think it's supposed to be a better way of generating branch coverage tests, not a complete substitute for path coverage. There's a far longer document here which restates the goals a bit: <a href="http://www.westfallteam.com/sites/default/files/papers/Basis_Path_Testing_Paper.pdf" rel="nofollow">http://www.westfallteam.com/sites/default/files/papers/Basis_Path_Testing_Paper.pdf</a></p>
<p>The onjava article says "the goal of basis path testing is to test all decision outcomes independently of one another. Testing the four basis paths achieves this goal, making the other paths extraneous"</p>
<p>I think "extraneous" here means, "unnecessary to the goal of basis path testing", not as one might assume, "a complete waste of everyone's time".</p>
<p>I think the point of testing branches independently, is to break those accidental correlations between the paths which work, and the paths you test, that occur with terrifying frequency when I write both the code and an arbitrary set of branch coverage tests myself. There's no magic in the linear independence, it's just a systematic way of generating branch coverage, which discourages the tester from making the same assumptions as the programmer about correlation between branch choices.</p>
<p>So you're right, basis path testing misses your bug, and in general misses 2^(N-1)-N bugs, where N is the cyclomatic complexity. It just aims not to miss the 2^(N-1)-N paths <em>most likely to be buggy</em>, as letting the coder choose N paths to test typically does ;-)</p>
|
Help with regex pattern <p>I have a txt file and each line has a set of random strings, I need to select only the lines that contains only the characters: 1234567890qwertyuiopasdfghjklzxcvbnm-._~</p>
<p>I'm reading line by line and verifying char by char, I don't think it's the best way to do that, and I think a RegEx would be perfect.</p>
<p>So can anybody help with with a pattern for this?</p>
<p>thanks!</p>
| <pre><code> /^[-0-9a-z._~]*$/
^ :: matches the start of a string/start of a line
[ :: start of a character class, means match any one of the contained characters
- :: dash has a special meaning in character classes, so to avoid having it interpreted for its special meaning, list it first
0-9 :: shorthand for 0123456789 in a character class
a-z :: shorthand for abcdefghijklmnopqrstuvwxyz in a character class
._~ :: means exactly these characters in a character class
] :: end of the character class
* :: match zero or more of the previous atom (in this case, the character class)
$ :: matches the end of a string/end of a line
</code></pre>
|
Inversion of control for your Inversion of control container? <p>I've recently had to update a relatively large control library that uses Ninject 1.0 to Ninject 2.0 to help resolve some issues I had with 1.0. The update has gone well and I think Ninject 2.0 is a lot quicker.</p>
<p>However to try and avoid this problem in the future I have created my own interface for injecting fields and properties (which will essentially call methods on the IOC container I wish to use within the current web application). So now my control library is independant of any particular IOC container which will speed up any changes in that area in the future.</p>
<p>I was wondering has anyone else has done the same thing?</p>
<p>I'm happy with what it has achieved but ideally I would like to update it. In my controls I create these injected fields often as protected and set them in the constructor for that control. </p>
<pre><code>IBlogService _blogService = null;
IEmailService _emailService = null;
public Templates_BlogTemplate()
{
Inject(ref _blogService);
Inject(ref _emailService);
}
</code></pre>
<p>The problem I have with the above is that I have to use "ref" on all objects to actually set the property and I cannot use that on properties directly.</p>
<p>I would prefer to do something along these lines but I don't think it is possible.</p>
<pre><code>IBlogService _blogService = null;
IEmailService _emailService = null;
public Templates_BlogTemplate()
{
Inject(_blogService, _emailService);
}
</code></pre>
<p>Has anyone got any ideas of how to neaten the code up or make it work in a cleaner way? I also would want to avoid attributes so it forces the developer to make a decision to inject the variable at a certain point within the control.</p>
<p>All thoughts and feelings are welcome.</p>
<p>Thanks</p>
| <p>Support property injection, and inject dependencies to "this". </p>
<p>In my case, I have a base class that calls StructureMap.BuildUp(this), and the user control would have properties like:</p>
<pre><code>public IBlogService _blogService{get;set;}
public IEmailService _emailService{get;set;}
</code></pre>
<p>The only line specific to structuremap I have is in the base class. If ninject allows you to do this, then you can call your code handing it the control instance, and let it inject the properties based on its configuration.</p>
|
How can I determine all the codepoints that do not have glyphs in a font using FreeType? <p>This question is closely related to</p>
<p><a href="http://stackoverflow.com/questions/103725/is-there-a-way-to-programatically-determine-if-a-font-file-has-a-specific-unicode">http://stackoverflow.com/questions/103725/is-there-a-way-to-programatically-determine-if-a-font-file-has-a-specific-unicode</a></p>
<p>However, I am looking for a solution that does not use the Windows API. Freetype in particular looks promising, and I was wondering if anyone familiar with it could provide pointers.</p>
<p>Basically, I'd like to, given a font, calculate a mapping from character map to a sequence of codepoints without glyphs for that character map.</p>
| <p>With FreeType in particular, you may use the <a href="http://freetype.sourceforge.net/freetype2/docs/reference/ft2-base_interface.html#FT_Get_Char_Index" rel="nofollow">FT_Get_Char_Index</a> function. This function returns a glyphID of 0 to indicate an unmapped glyph.</p>
<p>In more general terms: first you'd need to select a Character Mapping table (some fonts include multiple maps for different platforms or different purposes under a single platform), then build a dictionary from the explicitly-mapped glyphs, and test against that.</p>
|
What is the name of this anti-pattern? <p>Surely some of you have dealt with this one. It tends to happen when programmers get a bit too taken by OO and forget about performance and having a database.</p>
<p>For an example, lets say we have an Email table and they need to be sent by this program. At start-up, it looks for anything that needs to be sent as follows:</p>
<pre><code>Emails = find_every_damn_email_in_the_database();
FOR Email in Emails
IF !Email.IsSent() THEN Email.Send()
</code></pre>
<p>This is a good from a do-not-repeat-yourself perspective, but sometimes it's unavoidable and it should be:</p>
<pre><code>Emails = find_unsent_emails();
FOR Email in Emails
Email.Send()
</code></pre>
<p>Is there a name of this one?</p>
| <p>I'll have a go at it and coin the name "the lazy filter (anti) pattern".</p>
|
Adobe AIR from Flash a big disaster? <p>Does anyone have any experience with building AIR apps from within Flash CS3? I inherited an AIR app that is being build from within Flash and is doing my head in to get build.</p>
<p>First of all, the AIR app doesn't run from with the Flash IDE. There is no document class and when I place a trace statement on the first frame it never actually traces (yes, Omit trace actions in the publish settings is un-ticked). I see an application window (with an AIR icon) but it's not actually doing anything. It is as if the code is never executed.</p>
<p>Second, I'm not sure what should be included in the AIR package. It currently tries to package up all my source code when I create an AIR file, including my .svn folders.</p>
<p>It seems to be impossible to use relative paths in either the dialog that Flash presents (under the Controls menu) or a separate descriptor file. From Flash's point of view, what is the relative path anyway, where the Fla is placed or where the swf is placed? (currently different folders in my project).</p>
<p>Lastly, does anyone know of any good tutorials that talk more about the inner workings of AIR? Not that marketing or "hello, world" mambo jumbo that Google constantly seems to come up with...</p>
<p>Thanks,
Luke</p>
| <p>While it is possible to compile projects created in Flash Professional using Flash Builder, and vice versa, if the project has any significant complexity, doing so becomes non-trivial.</p>
<p>If the person who created the project was using Flash Builder, I would expect that opening the project in (even a trial version of) Flash Builder will allow you to get the project up and running and compiling in order to test.</p>
<p>If it was created in Flash Builder, and you are attempting to open it in Flash Professional, there are many caveats involved. You may have to set the Document Class, and ensure that various packages/frameworks are included in your build settings. Also, there are some instances in which the Flash Professional compiler may operate differently than the Flash Builder compiler (they are not the same), resulting in odd behavior in your app, assuming it compiles.</p>
<p>It's not your fault â Adobe has conflated the term "Flash" between several of their products, so it is not clear at all what is what, and while compatibility may be indicated by the names of things (hey, AIR is AIR, right?), wrong.</p>
<p>Your best bet is to open the original project in Flash Builder and take it from there. Good luck!</p>
|
Pig Latin in MIPS Assembly <p>In my MIPs Assembly Programming class I've been tasked with writing a program that converts a string into simplified pig latin.</p>
<p>Simplified pig latin assumes all words in the string are at least 2 characters long, and every word has its first letter shifted to the end followed by "ay". Also, assume there are no punctuation marks of any kind.</p>
<p>So, "stackoverflow is great" becomes "tackoverfloway siay reatgay".</p>
<p>I've taken a stab at this program and I'm nearly completed. It works fine, except that for some reason I have a line break in the middle of the last word every time.</p>
<p>For example:</p>
<blockquote>
<p>tackoverflowsay siay reat<br />
gay</p>
</blockquote>
<p>Instead of:</p>
<blockquote>
<p>tackoverflowsay siay reatgay </p>
</blockquote>
<p>I've tried decuding what would be causing this line break in the last exit portion of my program but I don't see it. Do I have a pre-mature null terminated string? If I do, I don't see it.</p>
<p>Here is my code:</p>
<pre><code>####################################################
# Text Segment
####################################################
.text
.globl main
main:
la $t0, char
la $t1, buffer
lb $t3, space
la $a0, prompt
li $v0, 4
syscall
la $a0, buffer
li $a1, 200
li $v0, 8
syscall
lb $t2, ($t1) # Load first char
addi $t1, $t1, 1
loop:
lb $t4, ($t1) # Load next character into $t4
addi $t1, $t1, 1
beqz $t4, exit # Reached end of string, exit?
beq $t3, $t4, loop2 # If $t4 = " " char, second loop
move $a0, $t4 # else, lets keep printing chars
li $v0, 11
syscall
j loop
loop2:
move $a0, $t2
li $v0, 11
syscall
la $a0, aystr
li $v0, 4
syscall
lb $t2, ($t1)
addi $t1, $t1, 1
j loop
exit:
move $a0, $t2
li $v0, 11
syscall
la $a0, aystr
li $v0, 4
syscall
li $v0, 10
syscall # Cya...
####################################################
# Data Segment
####################################################
.data
prompt: .asciiz "Enter Phrase: "
result: .asciiz "Pig Latin: "
space: .ascii " "
aystr: .asciiz "ay "
char: .byte 1
buffer: .byte 200
</code></pre>
| <p>You almost certainly have a string of the form:</p>
<pre><code>stackoverflow is great\n
</code></pre>
<p>where <code>\n</code> is a newline character. This would translate into:</p>
<pre><code>tackoverflowsay siahy reat\ngay
</code></pre>
<p>if you simplistically detected the end of the word as either space or null-terminator.</p>
<p>I'm not going to give you the code (since this is homework) but the easiest solution, in my opinion, would be to have another loop processing the entire string, replacing all <code>"\n"</code> characters with spaces.</p>
<p>This would be done before your latinization loops.</p>
|
Setting a column's default value to be the logged in user name in Access 2007 <p>I have an Access file developed using Access 2003, and am trying to work with it using Access 2007.</p>
<p>Some tables have a "changedby" column, which has a default value of</p>
<pre><code>=Environ("username")
</code></pre>
<p>This is triggering an error</p>
<p><i>Unknown function 'Environ' in validation expression or default value on market.changedby</i></p>
<p>Is there a replacement function available in Access 2007, which can be used as a formula in a default value for a column?</p>
| <p>Check out this <a href="http://www.access-programmers.co.uk/forums/showthread.php?t=115442" rel="nofollow">thread</a>.</p>
<p>It's states that you have to wrap the environ call in a <a href="http://www.access-programmers.co.uk/forums/showthread.php?t=76173" rel="nofollow">function</a> to get around the Access "sandbox"</p>
<p>Another poster says you can set the macor security to low to fix it as well.</p>
|
Why is List<T> not thread-safe? <p>from this site:</p>
<p><a href="http://crfdesign.net/programming/top-10-differences-between-java-and-c">http://crfdesign.net/programming/top-10-differences-between-java-and-c</a></p>
<blockquote>
<p>Unfortunately, List<> is not
thread-safe (C#âs ArrayList and Javaâs
Vector are thread-safe). C# also has a
Hashtable; the generic version is:</p>
</blockquote>
<p>what makes <code>List<T></code> not thread-safe? is it implementation problem on .net framework engineer's part? or are generics not thread-safe?</p>
| <p>You really need to classify Java's Vector's type of thread safety. Javas Vector is safe to be used from multiple threads because it uses synchronization on the methods. State will not be corrupted. </p>
<p>However, Java's vector's usefulness is limited from multiple threads without additional synchronization. For example, consider the simple act of reading an element from a vector</p>
<pre><code>Vector vector = getVector();
if ( vector.size() > 0 ) {
object first = vector.get(0);
}
</code></pre>
<p>This method will not corrupt the state of the vector, but it also is not correct. There is nothing stopping another thread from mutating the vector in between the if statement an the get() call. This code can and <strong>will</strong> eventually fail because of a race condition.</p>
<p>This type of synchronization is only useful in a handfull of scenarios and it is certainly not cheap. You pay a noticable price for synchronization even if you don't use multiple threads. </p>
<p>.Net chose not to pay this price by default for a scenario of only limited usefulness. Instead it chose to implement a lock free List. Authors are responsible for adding any synchronization. It's closer to C++'s model of "pay only for what you use" </p>
<p>I recently wrote a couple of articles on the dangers of using collections with only internal synchronization such as Java's vector. </p>
<ul>
<li><a href="http://blogs.msdn.com/jaredpar/archive/2009/02/11/why-are-thread-safe-collections-so-hard.aspx">Why are thread safe collections so hard?</a></li>
<li><a href="http://blogs.msdn.com/jaredpar/archive/2009/02/16/a-more-usable-thread-safe-collection.aspx">A more usable API for a mutable thread safe collection</a></li>
</ul>
<p>Reference Vector thread safety: <a href="http://www.ibm.com/developerworks/java/library/j-jtp09263.html">http://www.ibm.com/developerworks/java/library/j-jtp09263.html</a></p>
|
What searching algorithm/concept is used in Google? <p>What searching algorithm/concept is used in Google?</p>
| <p><a href="http://infolab.stanford.edu/~backrub/google.html">The Anatomy of a Large-Scale Hypertextual Web Search Engine</a> </p>
|
Can I transpose a file in Vim? <p>I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making. </p>
<p>The original file might be</p>
<pre><code>THE DAY WAS LONG
THE WAY WAS FAST
</code></pre>
<p>and it would become</p>
<pre><code>TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
</code></pre>
<p>UPDATE: Golf rules apply to selecting correct answer.</p>
<p>UPDATE: Python fans should check out Mr. Duffy's answer below.</p>
| <p>Here is a command in Vim language. So you don't have to compile Vim with +python support.</p>
<pre><code>function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newlines = []
for col in range(0, maxcol - 1)
let newline = ''
for line in lines
let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
let newline .= line_with_extra_spaces[col]
endfor
call add(newlines, newline)
endfor
1,$"_d
call setline(1, newlines)
endfunction
command! TransposeBuffer call s:transpose()
</code></pre>
<p>Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.<br>
Execute <code>:TransposeBuffer</code> to transpose current buffer </p>
|
what is the exact difference between Closed and Stopped State in PPP State machine <p>I wanted to know what is the exact difference between Closed and Stopped State in PPP State machine.</p>
<p>It would be great full if someone explain in detail.</p>
<p>I am designing ppp stack using C++.</p>
<p>Thanks a lot in advance.</p>
| <p>"Closed" means the PPP state machine for that link, has been shut down (closed) through either some user intervention (link shutdown) or the underlying physical layer going down (alarm detection, etc). </p>
<p>"Stopped" means either 1) The PPP state machine did not succeed in the negotiation and hence stopped, and will retry after some time, or 2) The peer terminated the session, and the local side will re-initiate negotiation after some time.</p>
|
null used with logical operator <p>I have a table with name,age and address.I have totally five rows of data in the table.For some rows the age is left null.I have to display all the data where age is not null. </p>
<p>select * from sample_table where (age !=null);</p>
<p>But no output is displayed and it doesn't give an error also.Please explain this.Thanks. </p>
| <p>With NULL you have to use <code>IS</code> or <code>IS NOT</code>. The following query should work:</p>
<pre><code>SELECT * FROM sample_table WHERE (age IS NOT NULL)
</code></pre>
|
How can you tell if a trigger is enabled in PostgreSQL? <p>My googling-fu is failing me. How to know if a PostgreSQL trigger is disabled or not?</p>
| <p>It's my first day with postresql, but I think you can check the trigger state via pg_trigger system table: <a href="http://www.postgresql.org/docs/current/static/catalog-pg-trigger.html" rel="nofollow">http://www.postgresql.org/docs/current/static/catalog-pg-trigger.html</a></p>
<p>The columns you will need are <code>tgrelid</code> and <code>tgenabled</code>.</p>
|
Why can't I leverage 4GB of RAM in my computer to process less than 2GB of information in C#? <p>Scenario: over 1.5GB of text and csv files that I need to process mathematically. I tried using SQL Server Express, but loading the information, even with BULK import takes a very long time, and ideally I need to have the entire data set in memory, to reduce hard disk IO.</p>
<p>There are over 120,000,000 records, but even when I attempt to filter the information to just one column (in-memory), my C# console application is consuming ~3.5GB of memory to process just 125MB (700MB actually read-in) of text.</p>
<p>It seems that the references to the strings and string arrays are not being collected by the GC, even after setting all references to null and encapsulating IDisposables with the using keyword.</p>
<p>I think the culprit is the String.Split() method which is creating a new string for each comma separated value.</p>
<p>You may suggest that I shouldn't even read the unneeded* columns into a string array, but that misses the point: How can I place this <em>entire</em> data set in memory, so I can process it in parallel in C#?</p>
<p>I could optimize the statistical algorithms and coordinate tasks with a sophisticated scheduling algorithm, but this is something I was hoping to do before I ran into memory problems, and not because of.</p>
<p>I have included a full console application that simulates my environment and should help replicate the problem.</p>
<p>Any help is appreciated. Thanks in advance.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace InMemProcessingLeak
{
class Program
{
static void Main(string[] args)
{
//Setup Test Environment. Uncomment Once
//15000-20000 files would be more realistic
//InMemoryProcessingLeak.GenerateTestDirectoryFilesAndColumns(3000, 3);
//GC
GC.Collect();
//Demostrate Large Object Memory Allocation Problem (LOMAP)
InMemoryProcessingLeak.SelectColumnFromAllFiles(3000, 2);
}
}
class InMemoryProcessingLeak
{
public static List<string> SelectColumnFromAllFiles(int filesToSelect, int column)
{
List<string> allItems = new List<string>();
int fileCount = filesToSelect;
long fileSize, totalReadSize = 0;
for (int i = 1; i <= fileCount; i++)
{
allItems.AddRange(SelectColumn(i, column, out fileSize));
totalReadSize += fileSize;
Console.Clear();
Console.Out.WriteLine("Reading file {0:00000} of {1}", i, fileCount);
Console.Out.WriteLine("Memory = {0}MB", GC.GetTotalMemory(false) / 1048576);
Console.Out.WriteLine("Total Read = {0}MB", totalReadSize / 1048576);
}
Console.ReadLine();
return allItems;
}
//reads a csv file and returns the values for a selected column
private static List<string> SelectColumn(int fileNumber, int column, out long fileSize)
{
string fileIn;
FileInfo file = new FileInfo(string.Format(@"MemLeakTestFiles/File{0:00000}.txt", fileNumber));
fileSize = file.Length;
using (System.IO.FileStream fs = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fs))
{
fileIn = sr.ReadToEnd();
}
}
string[] lineDelimiter = { "\n" };
string[] allLines = fileIn.Split(lineDelimiter, StringSplitOptions.None);
List<string> processedColumn = new List<string>();
string current;
for (int i = 0; i < allLines.Length - 1; i++)
{
current = GetColumnFromProcessedRow(allLines[i], column);
processedColumn.Add(current);
}
for (int i = 0; i < lineDelimiter.Length; i++) //GC
{
lineDelimiter[i] = null;
}
lineDelimiter = null;
for (int i = 0; i < allLines.Length; i++) //GC
{
allLines[i] = null;
}
allLines = null;
current = null;
return processedColumn;
}
//returns a row value from the selected comma separated string and column position
private static string GetColumnFromProcessedRow(string line, int columnPosition)
{
string[] entireRow = line.Split(",".ToCharArray());
string currentColumn = entireRow[columnPosition];
//GC
for (int i = 0; i < entireRow.Length; i++)
{
entireRow[i] = null;
}
entireRow = null;
return currentColumn;
}
#region Generators
public static void GenerateTestDirectoryFilesAndColumns(int filesToGenerate, int columnsToGenerate)
{
DirectoryInfo dirInfo = new DirectoryInfo("MemLeakTestFiles");
if (!dirInfo.Exists)
{
dirInfo.Create();
}
Random seed = new Random();
string[] columns = new string[columnsToGenerate];
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= filesToGenerate; i++)
{
int rows = seed.Next(10, 8000);
for (int j = 0; j < rows; j++)
{
sb.Append(GenerateRow(seed, columnsToGenerate));
}
using (TextWriter tw = new StreamWriter(String.Format(@"{0}/File{1:00000}.txt", dirInfo, i)))
{
tw.Write(sb.ToString());
tw.Flush();
}
sb.Remove(0, sb.Length);
Console.Clear();
Console.Out.WriteLine("Generating file {0:00000} of {1}", i, filesToGenerate);
}
}
private static string GenerateString(Random seed)
{
StringBuilder sb = new StringBuilder();
int characters = seed.Next(4, 12);
for (int i = 0; i < characters; i++)
{
sb.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * seed.NextDouble() + 65))));
}
return sb.ToString();
}
private static string GenerateRow(Random seed, int columnsToGenerate)
{
StringBuilder sb = new StringBuilder();
sb.Append(seed.Next());
for (int i = 0; i < columnsToGenerate - 1; i++)
{
sb.Append(",");
sb.Append(GenerateString(seed));
}
sb.Append("\n");
return sb.ToString();
}
#endregion
}
}
</code></pre>
<p>*These other columns will be needed and accessed both sequentially and randomly through the life of the program, so reading from disk each time is a tremendously taxing overhead.</p>
<p>**Environment Notes: 4GB of DDR2 SDRAM 800, Core 2 Duo 2.5Ghz, .NET Runtime 3.5 SP1, Vista 64.</p>
| <p>Yes, String.Split creates a new String object for each "piece" - that's what it's meant to do.</p>
<p>Now, bear in mind that strings in .NET are Unicode (UTF-16 really), and with the object overhead the cost of a string in bytes is approximately <code>20 + 2*n</code> where <code>n</code> is the number of characters.</p>
<p>That means if you've got a lot of small strings, it'll take a lot of memory compared with the size of text data involved. For example, an 80 character line split into 10 x 8 character strings will take 80 bytes in the file, but 10 * (20 + 2*8) = 360 bytes in memory - a 4.5x blow-up!</p>
<p>I doubt that this is a GC problem - and I'd advise you to remove extra statements setting variables to null when it's not necessary - just a problem of having too much data.</p>
<p>What I <em>would</em> suggest is that you read the file line-by-line (using <code>TextReader.ReadLine()</code> instead of <code>TextReader.ReadToEnd()</code>). Clearly having the whole file in memory if you don't need to is wasteful.</p>
|
.Net: Retrieving data from threads <p>This is an Easy Q, but great help:</p>
<p>Under title" <em>Retrieving data from threads</em> MSDN (<a href="http://msdn.microsoft.com/en-us/library/ts553s52%28VS.71%29.aspx" rel="nofollow">Here</a>) introduces a way to get data from a child thread by using callback method which is encapsulated by a delegate passed from main thread to the child thread - who has the data.</p>
<p>You can see that clearly ( the last Example in the MSDN <a href="http://msdn.microsoft.com/en-us/library/ts553s52%28VS.71%29.aspx" rel="nofollow">page</a>)</p>
<p>My Q is, since we are taking about retrieving data (from child threads to main thread) the call back method should be executed by the main thread and not by the child thread...</p>
<p>I changed the code a bit ( to verify that) so I attached the name of the thread before each output:</p>
<pre><code> public static void ResultCallback(int lineCount) {
Console.WriteLine(Thread.CurrentThread.Name + ":Independent task printed {0} lines.", lineCount);
}
</code></pre>
<p>And I named the child thread: "Method2" while the main thread "System"...</p>
<p>I got this output: <strong>Method2</strong>: Independent task printed 1 lines. </p>
<p>where the correct output should have been : <strong>System</strong>:Independent task printed 1 lines..</p>
<p>Who is drunk here? MSDN, me or .NET?</p>
| <p>"You" ;-p</p>
<p>Callbacks are still executed on the worker thread; they provide the data back to the calling <strong>code</strong> - but they don't have an inbuilt way of interrupting the calling <strong>thread</strong>. It is your code's responsibility to push that work back to the main thread if necessary. For example, in a winforms app you might have:</p>
<pre><code>public static void ResultCallback(int lineCount) {
// runs on worker thread
Invoke((MethodInvoker)delegate {
// runs on UI thread
Console.WriteLine(Thread.CurrentThread.Name +
":Independent task printed {0} lines.", lineCount);
});
}
</code></pre>
|
How to read third party cookies works across different domains? <p>I know this question has been asked before, but many answers don't give clear samples with codes on how to do this using ASP.NET 2.0. A simple C# is preferred, but I can also accept VB.NET or F#.</p>
<p>This <a href="http://stackoverflow.com/questions/390219/why-wont-asp-net-create-cookies-in-localhost">third party cookies question</a> is a sample of a self answered question with the same topic, but it didn't give any clues about reading/getting the third party cookies.</p>
| <p>It is a security feature that one can only read cookies from the same domain that created the cookies. Trying to read "foreign" cookies is a sign of malicious intentions.</p>
|
What`s wrong with qt 4.5.0 integration with Visual Studio 2008? <p>I downloaded and installed qt evaluation for vs2008 and expect it to be integrated with VS, but it is not. It is trial 30 days commercial license. What`s wrong with it or may be I got it wrong?</p>
| <p>The Visual Studio integration is a separate download:
<a href="http://www.qtsoftware.com/downloads/visual-studio-add-in" rel="nofollow">http://www.qtsoftware.com/downloads/visual-studio-add-in</a></p>
|
Code to create Sorting for a GridView in ASP.net in Code Behind? <p>This is my code code for the Page_Load Event</p>
<pre><code> OdbcConnection myConnection;
DataSet dataSet = new DataSet();
OdbcDataAdapter adapter;
//making my connection
myConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings ["ODBC_ConnectionString"].ConnectionString);
adapter = new OdbcDataAdapter("SELECT * from Company", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
</code></pre>
<p>This is my code for the PageIndexChanging event and it all works fine.</p>
<pre><code> DataSet ds = new DataSet();
if (Session["DataSource"] != null)
ds = ((DataSet)Session["DataSource"]);
GridView1.DataSource = ds;
GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataBind();
</code></pre>
<p>Now what code do i need to create the Sorting event?</p>
<pre><code>protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
?????????????????????????
}
</code></pre>
<p>Etienne</p>
| <p>I usually do this:</p>
<pre><code> public string SortField {
get {
return (string) ViewState["_sortField"];
}
set {
ViewState["_sortField"] = value;
}
}
public string SortDir {
get {
return (string) ViewState["_sortDir"];
}
set {
ViewState["_sortDir"] = value;
}
}
</code></pre>
<p>Put your code to do databinding into another Method because you have to call it during Sort, Paging, and when your page first loads. Call it DoDataBind() for example. Then you have in DoDataBind()</p>
<pre><code>DataTable dt = yourDataSet.Tables[0];
dt.DefaultView.Sort = SortField + " " + SortDir;
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
</code></pre>
<p>Then your event looks like this:</p>
<pre><code>protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
if (e.SortExpression == SortField && SortDir != "desc") {
SortDir = "desc";
}
else {
SortDir = "asc";
}
SortField = e.SortExpression;
DoDataBind();
}
</code></pre>
<p>Then in your aspx page you'll need to specify what the SortExpression is. For example something like this:</p>
<pre><code><asp:BoundField DataField="FIRSTNAME"
HeaderText="First Name" SortExpression="FIRSTNAME" />
</code></pre>
|
Update via XML or SQLite db file if possible? <p>I'm developing an app using UITableView driven content.</p>
<p>Current testing is done with local XML of size 100kb. This info should update about once every 2 months. The flow is reading pre-sorted XML -> convert to NSDictionary -> UITableView</p>
<p>Since parsing XML will take some work during load every time, plus table index, sorting and searching seems clumsy. So I have this idea about storing such info in a sqlite DB file</p>
<p>My real question is whether it's possible to download the entire sqlite DB file via http(s) instead of XML to update the info?</p>
| <p>I don't understand the question...you have a sqlite database on a server somewhere and you want to know if it's possible to download via http? Yes, of course, just open a NSURLConnection and grab the data.</p>
<p>If you want to somehow <strong>transform</strong> XML from an http source to a sqlite database, well, then you'll have to write your own custom transformation code to get the proper SQL statements--there's no automatic way to do this in Cocoa.</p>
|
Vectorization <p>I have a problem with graphs in Excel (2003). I have several matrices :</p>
<p>a b c d
e f g h</p>
<p>i j k l
m n o p</p>
<p>q r s t
u v w x</p>
<p>I want to plot the vector z = (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t), so I pick one row at a time in "series" under graphs using Ctrl, but when the number of rows reach a certain limit, Excel cannot include them all.</p>
<p>So instead I manually stack all rows after one another (like z) into a row vector in Excel. When the number of rows gets large, it takes time.</p>
<p>Do you know of a way to solve this problem of Excel stopping without first creating a vector (like z). If not, do you know of a way to make a (row) vector nonmanually (a VBA script perhaps) ?</p>
| <p>For this kind of numerical task with a simple intent (plot a graph) and simply formatted data, you are better off using a plotting program like Gnuplot. Excel is designed for fewer values and more complex tasks, so you're running into its limitations.</p>
<p>Gnuplot in particular is scriptable, and can generate graphs from a script file, which will save effort if you're doing this more than once!</p>
|
Assign double value to label in C# <p>How do i assign double value to a string ? </p>
<p>Example : </p>
<p>double a = 5.5,b= 6.0;<br />
double sum = a + b ; </p>
<p>Lable1.Text = sum.ToString(); </p>
<p>Result :<br />
11.5 </p>
<p>but in label i am getting only 11...how do i display 11.5 in lable ? </p>
| <pre><code>Label1.Text = sum.ToString("#0.0");
</code></pre>
<p>Generally speaking, "0" is a zero placeholder and "#" is a digit placeholder. You can find more info <a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx">here</a>. You can also try</p>
<pre><code>Label1.Text = sum.ToString("F1");
</code></pre>
<p>where 1 stands for one digit after the decimal point.</p>
|
Class containing auto_ptr stored in vector <p>In an answer to <a href="http://stackoverflow.com/questions/700588/is-it-safe-to-store-objects-of-a-class-which-has-an-stdautoptr-as-its-member-v">http://stackoverflow.com/questions/700588/is-it-safe-to-store-objects-of-a-class-which-has-an-stdautoptr-as-its-member-v</a> I stated that a class that contained an auto_ptr could be stored in a vector <strong>provided the class had a user-defined copy constructor</strong>.</p>
<p>There were several comment suggesting that this was not the case, so this question is an attempt to clear the issue up. Consider the following code:</p>
<pre><code>#include <memory>
#include <vector>
using namespace std;
struct Z {};
struct A {
A( Z z )
: p( new Z(z) ) {}
A( const A & a )
: p( a.p.get() ? new Z( *a.p.get()) : 0 ) {}
// no assigment op or dtor defined by intent
auto_ptr <Z> p;
};
int main() {
vector <A> av;
Z z;
A a(z);
av.push_back( a );
av.push_back( A(z) );
av.clear();
}
</code></pre>
<p>Please examine the above & in your reply indicate where undefined
behaviour in the meaning of the C++ Standard could occur for this particular class used in this particular way. I am not interested whether the class is useful, well-behaved, sortable, or how it performs under exceptions.</p>
<p><strong>Please also note that this is not a question about the validity of creating a vector of auto_ptrs - I am well aware of the issues regarding that.</strong></p>
<blockquote>
<p>Thanks all for your inputs on what in
retrospect is probably a rather silly
question. I guess I focussed too much
on the copy ctor & forgot about
assignment. The lucky winner of my
acceptance points (and points mean
prizes!) is <strong>litb</strong> for a typically
exhaustive explanation (sorry
earwicker)</p>
</blockquote>
| <p>Objects stored in containers are required to be "CopyConstructable" as well as "Assignable" (C++2008 23.1/3).</p>
<p>Your class tries to deal with the CopyConstructable requirement (though I'd argue it still doesn't meet it - I edited that argument out since it's not required and because it's arguable I suppose), but it doesn't deal with the Assignable requirement. To be Assignable (C++2008 23.1/4), the following must be true where <code>t</code> is a value of <code>T</code> and <code>u</code> is a value of (possibly <code>const</code>) <code>T</code>:</p>
<blockquote>
<p><code>t = u</code> returns a <code>T&</code> and <code>t</code> is equivalent to <code>u</code></p>
</blockquote>
<p>The standard also says in a note (20.4.5/3): "<code>auto_ptr</code> does not meet the CopyConstructible and Assignable requirements for Standard Library container elements and thus instantiating a Standard Library container with an <code>auto_ptr</code> results in undefined behavior."</p>
<p>Since you don't declare or define an assignment operator, an implicit one will be provided that uses the <code>auto_ptr</code>'s assignment operator, which definitely makes <code>t</code> not equivalent to <code>u</code>, not to mention that it won't work at all for "<code>const T u</code>" values (which is what <a href="http://stackoverflow.com/questions/704780/class-containing-autoptr-stored-in-vector/705153#705153">Earwicker's answer</a> points out - I'm just pointing out the exact portion(s) of the standard).</p>
|
What is your experience with ARM Jazelle? <p>I'm evaluating between open source and closed source JVM for ARM. In particular, the closed source JVM can make use of Jazelle (java acceleration for newer ARMs).</p>
<p>Do you have any experice with this technology?</p>
<p>(And BTW, which OS do you use with it?)</p>
| <p>I worked for a big wireless handset maker. Our team was porting J2ME to the ARM-based handsets. We had 2 guys working on using Jazelle; no OS, just on raw ARM9 silicon. Sadly, it stayed in research because the JIT got the performance we needed without having to pay the license fees for Jazelle.</p>
<p>If you accept the rule-of-thumb that running the Hotspot JVM without JIT runs at 1/10th of compiled C. Then, JIT returns 50% of what you lost and Jazelle returns 60% of what you lost. These are very rough estimates. It all depends on the kind of code that is running. Jazelle had slightly better performance for our test cases because it handled more situations than the JIT. Whereas the JIT went compiled-C-fast in a handful of cases. </p>
<p>The previous poster seems to misunderstand Jazelle. Jazelle causes a trap-like action for a Java bytecode. The user must supply code snippets to handle each bytecode. Without such snippets and the lookup table, you are going to get the unimplemented exception.</p>
|
try-catch not working? <p>I'm using a try-catch block in the following Actionscript 3 code:</p>
<pre><code>try {
this._subtitle = new SubtitleController(subtitlePath, _framerate);
this._subtitle.addEventListener(Event.COMPLETE, subtitleLoaded);
}
catch (e:Error) {
trace('subtitle not found');
}
</code></pre>
<p>The <code>SubtitleController</code> constructor then tries to load the <code>subtitlePath</code> and throws an <code>Error #2044: Unhandled ioError</code>, but the error is not caught by the <code>try</code> statement. The error is simply thrown like no <code>try</code> statement ever existed.</p>
<p>Sure, I can replace that code with</p>
<pre><code>this._subtitle.addEventListener(IOErrorEvent.IO_ERROR, function (ev:Event) { trace('subtitle not loaded'); });
this._subtitle = new SubtitleController(subtitlePath, _framerate);
this._subtitle.addEventListener(Event.COMPLETE, subtitleLoaded);
</code></pre>
<p>and it almost works, it stops trowing that error, but throws another one instead.</p>
<p>But isn't the whole point of <code>try-catch</code> blocks to do that? Why does it not work with the <code>try-catch</code>, but it does work with a regular event listener?</p>
| <p>IOErrors/NetworkErrors are asynchronous errors. They are not thrown when the method causing them is called as normal runtime errors. Otherwise the execution would have have to stop completely until a (for example) a file is completely loaded ... </p>
|
html form within mail client <p>Ok, get this.</p>
<p>I have been assigned to write an html form to be EMAILED to clients so that they can fill it in and submit it FROM THE EMAIL CLIENT! apparently emailing a link to the existing form on our website is not good enough.</p>
<p>I am still trying to get my head around this as it seems almost void of common sense, but anyways, my guess is that I will have no way of validating data, and if actually works, how will the user know? WTF?????</p>
<p>Get this, They will be emailing both a pdf and an html doc to clients, I tried putting my case forward but apparently the marketing pro's say IT IS POSSIBLE AND MUST BE DONE, WORKING BY FRIDAY!</p>
| <p>This is not a good idea on many fronts:</p>
<ol>
<li><p>Not all email clients will support a form post from HTML
see: <a href="http://www.campaignmonitor.com/blog/post/2435/how-forms-perform-in-html-emai/" rel="nofollow">http://www.campaignmonitor.com/blog/post/2435/how-forms-perform-in-html-emai/</a></p></li>
<li><p>No clientside validation</p></li>
<li>What's exactly wrong with a link?</li>
<li><p>How are you getting data from PDF form submission? You can get expensive form tools from Adobe: <a href="http://www.adobe.com/government/forms.html" rel="nofollow">http://www.adobe.com/government/forms.html</a></p></li>
<li><p>Some spam / av checkers will dispose of form based emails.</p></li>
</ol>
|
Passing Interface's method as parameter <p>Is it possible to pass interface's method as parameters?</p>
<p>I'm trying something like this:</p>
<pre><code>interface
type
TMoveProc = procedure of object;
// also tested with TMoveProc = procedure;
// procedure of interface is not working ;)
ISomeInterface = interface
procedure Pred;
procedure Next;
end;
TSomeObject = class(TObject)
public
procedure Move(MoveProc: TMoveProc);
end;
implementation
procedure TSomeObject.Move(MoveProc: TMoveProc);
begin
while True do
begin
// Some common code that works for both procedures
MoveProc;
// More code...
end;
end;
procedure Usage;
var
o: TSomeObject;
i: ISomeInterface;
begin
o := TSomeObject.Create;
i := GetSomeInterface;
o.Move(i.Next);
// somewhere else: o.Move(i.Prev);
// tested with o.Move(@i.Next), @@... with no luck
o.Free;
end;
</code></pre>
<p>But it is not working because:</p>
<blockquote>
<p>E2010 Incompatible types: 'TMoveProc' and 'procedure, untyped pointer or untyped parameter'</p>
</blockquote>
<p>Of course I can do private method for each call, but that is ugly. Is there any better way?</p>
<p>Delphi 2006</p>
<hr>
<p>Edit:
I know that I can pass whole interface, but then I have to specify which function use. I don't want two exactly same procedures with one different call. </p>
<p>I can use second parameter, but that is ugly too.</p>
<pre><code>type
SomeInterfaceMethod = (siPred, siNext)
procedure Move(SomeInt: ISomeInterface; Direction: SomeInterfaceMethod)
begin
case Direction of:
siPred: SomeInt.Pred;
siNext: SomeInt.Next
end;
end;
</code></pre>
<hr>
<p>Thanks all for help and ideas. Clean solution (for my Delphi 2006) is Diego's Visitor. Now I'm using simple ("ugly") wrapper (my own, same solution by TOndrej and Aikislave).</p>
<p>But true answer is "there is no (direct) way to pass interface's methods as parameters without some kind of provider.</p>
| <p>If you were using Delphi 2009, you could do this with an anonymous method:</p>
<pre><code>TSomeObject = class(TObject)
public
procedure Move(MoveProc: TProc);
end;
procedure Usage;
var
o: TSomeObject;
i: ISomeInterface;
begin
o := TSomeObject.Create;
i := GetSomeInterface;
o.Move(procedure() begin i.Next end);
</code></pre>
<p>The problem with trying to pass a reference to just the interface method is that you are not passing a reference to the interface itself, so the interface cannot be reference counted. But anonymous methods are themselves reference counted, so the interface reference inside the anonymous method here can be reference counted as well. That is why this method works.</p>
|
BackgroundWorker Thread in IIS7 - FAIL! <p>Just wondering if anyone has had any trouble using a BackgroundWorker Thread in a site running under IIS 7 in Integrated Pipeline mode?</p>
<p>I am trying to use such a beast to update the database schema (admin function, obviously), and it works perfectly in Cassini, but when I deploy to IIS 7, the thread gets about one line of code in and silently ends. Is there a way to tell why a thread ended?</p>
<p>Thanks in advance.</p>
| <p>It is probably an exception. Perhaps you're running with different set of rights between the two environments. </p>
|
Should I do all the exercises in K&R? <p>This is a quick slightly subjective question I need to ask. In order to become a proficient C programmer, I felt I'd learn C from the k&r. I find the book a little easygoing, difficult to understand sometimes but easygoing on the whole.</p>
<p>My question here is, do I have to absoultely do all the exercises (even those that stumped me) to become a proficient programmer in C? Or can I skip most of them? The format and layout of the questions asked are ... difficult, at best without using the tools available to C's rich set of libraries.</p>
| <p>First, best of luck with your learning of C.</p>
<p>What to do to become a proficient programmer per se, is something very very crude. I will answer that with an analogy. You may complete all the exercises at the end of the book, but fail to complete the first practical program you are assigned to work upon. In another case, you might have failed to complete any exercise but yet you are able to complete your first assignment. Who do you think is in a better place? I would leave the discussion to interpretation.</p>
<p>Exercises at the end of the book are meant to make a person going through the text familiar with nuances of problems, code situations, programming techniques. These generally are meant to test the practical implementation of the text you might have just read. These are problems which would give you an oversight of what come in usually in daily practice. As with any exam, if you are unable to solve one particular problem, it does not mean that you are don't know anything.</p>
<p>My suggestion would be to try all the problems. Mark down which stumped you and revisit them after some time when you have a better grasp of the topic, may be after you solved some more problems, or went through another good resource.</p>
<p>Try and read more on the topic using the Internet or elsewhere.</p>
<p>As for the book, any book that makes you understand is good, if it fails, its not worth for you. </p>
<p>Have fun and Keep Walking !!!</p>
|
Sql Server time 1 hour behind <p>I have a datetime column in a table called 'createdDate' were the default value is set to getutcdate(). However when a row is added to the table the createdDate's time value is 1 hour behind the system time. So my question is how do I increase the current database system timestamp by 1 hour?</p>
<p>Thanks in advance. </p>
| <p>It sounds like your servers are aware of daylight saving (GMT, BST and so on), and your database is resolutely using UTC.</p>
<p>Use GetDate() if you want your dates in the <em>database</em> to match the database <em>server</em>'s time.</p>
<p>Alternatively, uncheck the box to "automatically adjust clock for daylight saving changes" in the Date and Time properties on your server and continue to use GetUtcDate().</p>
|
What is use of operators and alerts in SQL server management studio? <p>Can anyone explain why and where to use operators and alerts in SQL server management studio?</p>
| <p>Operators and alerts are intended to support SQL Server jobs, which in turn are managed by the SQL Server Agent.</p>
<p>Lets say you had a SQL Server instance that processed a significant number of jobs. You may want to assign a particular operator responsiblity for certain jobs and so choose to inform them of the status of these jobs i.e. a member of the Finance Team might be responsible for a job that produces invoices.</p>
<p>The following reference details how to create operators.</p>
<p><a href="http://www.mssqltips.com/tip.asp?tip=1523" rel="nofollow">http://www.mssqltips.com/tip.asp?tip=1523</a></p>
<p>Hope this makes sense but do please feel free to contact me directly if you need further assistance.</p>
<p>Cheers, John</p>
|
ChannelFactory.CreateChannel and proxy instantiation is slow in WCF <p>I have a client-server application, in which the client communicates with the server using WCF (WCF is used both in the client and the server).
My problem is, that instantiating the auto-generated proxy in the client, in the following way:
<pre><code> new Service1Client() </code></pre>takes constantly 15.xxx seconds.
I tried to solve this problem, and came to the following results:</p>
<p>1) Compiling and running the same code on other computers, ends up in the same way (always 15.xxx seconds).</p>
<p>2) Instantiating the proxy using <code>ChannelFactory.CreateChannel< IService1 >()</code>
doesn't help (it gives the same result). </p>
<p>My guess, is that whenever the channel factory creates a channel, it tries to do something with a 15 seconds timeout, and when it fails, it continues with creation.</p>
<p>By the way, I use .Net 3.5 without SP1, and cannot upgrade to SP1 :(</p>
<p>Thanks ahead</p>
| <p>Even though it is already outdated, it may be useful for somebody else searching for the same. Problem could be with DNS resolution problem, that might be solved in SP1. So you can check if it happens only when you use host name or also with specified IP address.</p>
|
Silverlight 3 - RIA Services and LINQ <p>This is a basic LINQ question.</p>
<p>In my RIA Services Application, I have a Family object with Contacts in a child list. This is a entity framework application.</p>
<p>I am wondering why when I select my fam the child list of Contacts are not loaded, well I know that it must because of lazy loading but how to I get my query to load the children.</p>
<pre><code>var fam = from f in ContextContainer.FamilyCtx.Families
where f.familyId == fID
select f;
</code></pre>
| <p>I think you should have something similar to:</p>
<p>ContextContainer.LoadFamilies(fam, null);</p>
<p>The "LoadFamilies" is autogenerated from RIA services.</p>
<p>there should then be an OnLoaded event when the async result has been completed.</p>
<p>you can then say somelistbox.ItemSource = e.LoadedEntities</p>
|
Search multiple indices at once using Lucene Search <p>I am using Zend_Search_Lucene to implement site search. I created separate indices for different data types (e.g. one for users, one for posts etc). The results are similarly divided by data type however there is an 'all' option which should show a combination of the different result types. Is it possible to search across the different indices at once? or do i have to index everything in an all index?</p>
<p>Update: The <a href="http://framework.zend.com/download/latest" rel="nofollow">readme</a> for ZF 1.8 suggests that it's now possible to do in ZF 1.8 but I've been unable to track down where this is at in the documentation. </p>
| <p>So after some research you have to use Zend_Search_Lucene_Interface_MultiSearcher. I don't see any mention of it in the documentation as of this writing but if you look at the actual class in ZF 1.8 it's straightforward t use</p>
<pre><code>$index = new Zend_Search_Lucene_Interface_MultiSearcher();
$index->addIndex(Zend_Search_Lucene::open('search/index1'));
$index->addIndex(Zend_Search_Lucene::open('search/index2'));
$index->find('someSearchQuery');
</code></pre>
<p>NB it doesn't follow PEAR syntax so won'w work with Zend_Loader::loadClass</p>
|
Is there a JQuery plugin which combines Draggable and Selectable <p>I'm looking to implement a web interface with a number of items which can be selected and dragged around to position them, <strong>either in groups or singly</strong>. Rather like the Windows Desktop, really.</p>
<p>We're using JQuery already, so additions to that would be first choice. JQuery UI Draggables and Selectables individually do much of what we want, but don't really work together to give the sort of effect we're looking for.</p>
<p>I am completely overwhelmed by the JQ plugin site (it's 'popular' algorithm doesn't seem very useful), and would welcome guidance as to the best way to avoid a lot of wheel-reinvention here, as I would guess that this metaphor has already been done.</p>
| <p>I also needed to do same thing, and i didn't want to use interface extension from eyecon.ro. After some research, I found <a href="http://www.ryancoughlin.com/2008/11/23/combining-selectables-and-draggables-using-jquery-ui/" rel="nofollow"><em>Combining Selectables And Draggables Using jQuery UI</em></a>. It is nicely told but to make the code snippets run you have to dig into it. I was able to make it work. I slightly changed it, this is my way to get it done. It needs modifications for using on production level, but i hope it helps.</p>
<pre><code>// this creates the selected variable
// we are going to store the selected objects in here
var selected = $([]), offset = {top:0, left:0};
// initiate the selectable id to be recognized by UI
$("#selectable").selectable({
filter: 'div',
});
// declare draggable UI and what we are going to be doing on start
$("#selectable div").draggable({
start: function(ev, ui) {
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
});
if( !$(this).hasClass("ui-selected")) $(this).addClass("ui-selected");
offset = $(this).offset();
},
drag: function(ev, ui) {
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
// take all the elements that are selected expect $("this"), which is the element being dragged and loop through each.
selected.not(this).each(function() {
// create the variable for we don't need to keep calling $("this")
// el = current element we are on
// off = what position was this element at when it was selected, before drag
var el = $(this), off = el.data("offset");
el.css({top: off.top + dt, left: off.left + dl});
});
}
});
</code></pre>
<p>CSS Styles to be able to see what's happening:</p>
<pre><code>#selectable { width: 100%; height: 100%;}
#selectable div {
background: #ffc;
line-height: 25px;
height: 25px;
width: 200px;
border: 1px solid #fcc;
}
#selectable div.ui-selected {
background: #fcaf3e;
}
#selectable div.ui-selecting {
background: #8ae234;
}
</code></pre>
<p>HTML Markup:</p>
<pre><code><div id="selectable">
<div>item 1</div>
<div>item 2</div>
<div>item 3</div>
<div>item 4</div>
</div>
</code></pre>
|
Mdi form ensure visible <p>I am developing a c# .NET app with MDI forms.
When the Mdi children are moved around and using the scroll bars some forms will be outside the displayed area.
I would like to do to the Mdi children something similar to TreeNode.EnsureVisible() which moves the TreeView scrollbars until the Node is fully visible.
Calling Form.Activate() doesn't do this.
I don't mind if P/Invoke is required</p>
<p>Thanks in anticipation</p>
<p>Alex</p>
| <p>You could call the method ActivateMdiChild(childForm) on the parent Window which bring the focus on the childForm.
HTH</p>
|
Spring Hibernate SQL Query <p>I have a VO class which has the getter and setter of another VO class too. For example:</p>
<pre><code>Class DocumentVO{
PrintJobVO job;
PrintRunVO run;
String id;
getters and setters..
}
</code></pre>
<p>Now I have a requirement to use the Native SQL Query using spring hibernate. When I want to map the ids I have a problem. My query is,</p>
<pre><code>select {r.*},{d.*}
from runs {r}, documents {d}
where {r}.RUN_ID as {r.id} = d.RUN_ID as {d.run.id}
</code></pre>
<p>Here <code>run</code> is of type PrintRunVO which has its id and other values. How can I map them in my SQL? I am getting an error like <code>invalid user.table.column, table.column, or column specification</code>.</p>
<p>What's the way to overcome this?</p>
| <p>Use the Result Transformer concept in your plain SQL query.</p>
<pre><code>String query = "myquery";
SQLQuery q = session.createSQLQuery(query);
q.addScalar("param1", Hibernate.STRING);
q.addScalar("param2", Hibernate.STRING);
q.setResultTransformer(Transformers.aliasToBean(MyVO.class));
q.setParameter("queryParam1", "some value");
return q.list();
</code></pre>
|
indentation of multiline string <p>I have a script that uses the cmd Python module. The cmd module uses a triple quoted multiline string as it's help text. Something like this</p>
<pre><code>def x(self, strags = None):
"""class
help text here
and some more help text here"""
</code></pre>
<p>When running the script, the command 'help x' will print the string. It will, however, print the newlines in front of the last two lines as well. I can overcome this by not indenting these lines, but that'll make my code ugl{y,ier}. </p>
<p>How to overcome this indenting problem? How do the pro Python coders handle this?</p>
| <p>Personally I try to follow <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> which refers the reader to <a href="http://www.python.org/dev/peps/pep-0257/" rel="nofollow">PEP 257</a> for Docstring Conventions. It has an entire section on multi-line docstrings.</p>
|
how do I pull a remote tracking branch while in the master branch <p>I'm in master and I do a git pull, I get a message indicating I need to pull a remote branch.</p>
<p>Typically I do a <em>git co [branch]</em> then <em>git pull/rebase</em>.</p>
<p>Is there a way to git pull/rebase of [branch] without having to do a <em>git co [branch]</em> first?</p>
| <p>If you combine Apikot and Jeremy you get:</p>
<pre><code>git pull --rebase origin branch
</code></pre>
<p>Or, if you haven't set the branch mapping up in your config:</p>
<pre><code>git pull --rebase origin <src>:<dst>
</code></pre>
|
ASP.NET MenuItem Individual Styles <p>I'm hoping to use an ASP.NET Menu Control for navigation through my site. However, I've got a requirement that each MenuItem must be styled differently (different colors, both static, and onHover). Without creating a custom class that would inherit from MenuItem, is this possible?</p>
<p>Thoughts on a better solution?</p>
| <p>Short of overriding RenderContents on Menu, your options are very limited. Most of what you'd need is private and sealed and you won't get anywhere there.</p>
<p>My solution would be to use templates. You could use MenuItem.Value or Depth and and ItemIndex to identify each item and provide necessary attributes.</p>
<p>In Page:</p>
<pre><code><asp:Menu ID="menu" runat="server" DynamicHorizontalOffset="2" StaticSubMenuIndent="10px">
<Items>
<asp:MenuItem Text="Item 1" Value="value 1">
<asp:MenuItem Text="Item 2" Value="value 2">
<asp:MenuItem Text="Item 3" Value="value 3"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Item 4" Value="value 4">
<asp:MenuItem Text="Item 5" Value="value 5"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Item 6" Value="value 6"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Item 7" Value="value 7"></asp:MenuItem>
<asp:MenuItem Text="Item 8" Value="value 8"></asp:MenuItem>
</Items>
<StaticItemTemplate>
<asp:Panel runat="server" ForeColor='<%# GetItemColor(Container) %>'>
<%# Eval("Text") %> - <%# Eval("Value") %>
</asp:Panel>
</StaticItemTemplate>
<DynamicItemTemplate>
<asp:Panel ID="Panel1" runat="server" ForeColor='<%# GetItemColor(Container) %>'>
<%# Eval("Text") %> - <%# Eval("Value") %>
</asp:Panel>
</DynamicItemTemplate>
</asp:Menu>
</code></pre>
<p>In Code (never mind silliness of this code, it is just to demonstrate the principle):</p>
<pre><code>public Color GetItemColor(MenuItemTemplateContainer container)
{
MenuItem item = (MenuItem)container.DataItem;
//identify based value
if (item.Value == "value 2")
return Color.Brown;
//identify based on depth and index
if (item.Depth == 0)
switch (container.ItemIndex)
{
case 0: return Color.Red;
case 1: return Color.Blue;
case 2: return Color.DarkGreen;
default:
return Color.Black;
}
else
switch (container.ItemIndex)
{
case 0: return Color.Purple;
case 1: return Color.Aqua;
case 2: return Color.DarkOrange;
default:
return Color.Black;
}
}
</code></pre>
|
Visual Studio 2008 Database Addon <p>I am currently trying out visual studio to access sql server databases instead of using SQL Server Management Studio.</p>
<p>It was a good surprise how easy it is to setup and use a connection do a database and for the moment it has a positive impact on my productivity.</p>
<p>My question is: Is there an addon (or something i can do) to enable intelisense on SQL Queries?</p>
| <p>Red Gate SQL Prompt integrates into VS 2008, but it costs money...</p>
<p>Edit: <a href="http://stackoverflow.com/questions/414404/are-there-free-sql-server-mgmt-studio-autocomplete-add-ins">Are there Free SQL Server Mgmt Studio Autocomplete Add-ins?</a>
This may not work in VS though...</p>
|
How can I return an instance of a dynamically-built type to a WCF service expecting an interface? <p>I want to have an operation contract that returns an interface. </p>
<p>My problems:</p>
<p>1) I want to register dynamically with the service the known type that will be returned, or to have WCF accept the type. I noticed that unless it is a known type marked by attribute or in a static method of the service, the method will fail.</p>
<p>2) I want on the client side, to be able to construct a dynamic implementor of the interface from the message. </p>
<p>I don't want to mess with messages. I just want that the implementation details to be hidden.</p>
| <p>I've run into the same situation : I think you <strong>have</strong>, by design, to use the [KnownType] attribute so the serializer know which implementation to wait for.</p>
<p>The key point is that the serializer receives some bytes with only little metadata regarding how to read them (mainly, the type's name). That's why it needs to know which type those bytes are supposed to represent, and to "know" this type.
<em>Without this information, there's absolutely no way for the serializer to figure out where it's suppose to find the few fields implementing your interface functionality.</em></p>
<p>However, you can add new KnownTypes at runtime (ie dynamically) using directly the DataContractSerializer</p>
<p>Plenty of information on that topic <a href="http://blogs.msdn.com/sowmy/archive/2006/06/06/all-about-knowntypes.aspx" rel="nofollow">here</a> </p>
|
Google App Engine database inconsistency <p>Im writing a twitter app in Google App Engine. It accepts commands as Direct Messages, so i have setup a third party cronjob service to invoke a handler that processes DMs at regular intervals. I have a Model 'Info' that has just one entry, it stores some common data which are used in many places in the App(in this case, the time when the messages were processed recently). The general pattern of my handler is like this:</p>
<pre><code>class Info(db.Model):
msg_polled = db.DateTimeProperty(auto_now_add = True)
.... More Properties ....
@classmethod
def get_info(cls):
info = cls.all().get()
if not info:
info = cls()
info.put()
return info
---------------------------------------------------------
info = Info.get_info()
msgs = api.GetDirectMessages(since = info.msg_polled)
if not msgs:
return
logging.info('Processing Messages since %s ' % str(info.msg_polled))
for msg in msgs:
...process commands...
logging.info('Processed Message :- @%s : %s' % (msg.sender_screen_name, msg.text))
info.msg_polled = datetime.datetime.now()
info.put()
</code></pre>
<p>But sometimes i get logs like this : </p>
<pre><code>I 03-30 07:50AM 10.973
Processing Messages since Sun, 29 Mar 2009 11:41:59 GMT
I 03-30 07:50AM 11.122
Processed Message :- @foo : Foo_Bar
-------------------------------------------------------
I 03-30 07:46AM 08.014
Processing Messages since Sun, 29 Mar 2009 11:41:59 GMT
I 03-30 07:46AM 08.130
Processed Message :- @foo : Foo_Bar
</code></pre>
<p>Here, it seems that info is not getting commited to the database. The message is processed multiple number of times, sometimes upto 10+ times before the msg_polled value changes. But i am not getting any Datastore exceptions. This happens only once in a while.</p>
<p>Any help is appreciated.</p>
| <p>The Google AppEngine datastore uses BigTable under the covers, which is a distributed database system. Because of this, updates might not be visible immediately since the new data has not yet reached every distributed table (Amazon calls this "eventual consistency" in their SimpleDB). You should be fine after a few minutes.</p>
|
Silverlight 3 - dataform errorsummary with RIA validation <p>I got a dataform partially working with RIA services (I can fetch and edit data).</p>
<p>The problem is that I added validation to my RIA service fields. Ex: from my metadata.cs file </p>
<p>[StringLength ( 50, ErrorMessage= "bad data dude!" , MinimumLength=4)]
public string Title;</p>
<p>In the dataform, when a user enters data violating the above rule, an exception is thrown saying "bad data dude!" which is sort of OK. The problem is that I would like the data form to show this message in the error summary?</p>
<p>What am I doing wrong?</p>
| <p>Visual Studio breaks because it sees an error it believes is not handled. If you just continue the program the error will be handled and the failed validation will show as expected.</p>
<p>You can tell VS not to stop on an user unhanded ValidationException using the Debug/Exceptions dialog in VS.</p>
|
ASP.NET MVC - Cascading Drop Down <p>I'm currently learning ASP.NET MVC and using Nhibernate.</p>
<p>I would like to use Cascading Drop-Down Boxes. Has anyone managed to get cascading drop-down boxes working in MVC?</p>
<p>Updated:
I have looked at the following website: <a href="http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx">link text</a> and used method 1.</p>
<p>Controller Code</p>
<pre><code> var makeList = new SelectList(makeRepository.ListMakes (), "Id", "make",1);
ViewData["Makes"] = makeList;
//// Create Models view data
var modelList = new CascadingSelectList(modelRepository.ListModels (Convert.ToInt32(makeList.SelectedValue.ToString())), "ModelID","Id", "Name");
ViewData["Models"] = modelList;
</code></pre>
<p>View Code</p>
<pre><code><%= Html.DropDownList("--Select Make--","Makes")%>
<label for="Makes">Car Model:</label>
<%= Html.CascadingDropDownList("Models", "Makes") %>
</code></pre>
<p>The correct list of cars is listed when a Make with id of 1 is selected, but when I select a different make the model list is empty?</p>
| <p>You may want to read this <a href="http://stephenwalther.com/blog/archive/2008/09/07/asp-net-mvc-tip-41-creating-cascading-dropdown-lists-with-ajax.aspx" rel="nofollow">TIP</a>.</p>
<p>In this tip, Stephen Walter demonstrates three methods of creating cascading dropdown lists. First, he shows you how to alter the list of options displayed by one dropdown list when an option in another dropdown list changes. Second, he shows you how to expose the data for the dropdown lists through a controller action. Next, he shows you how to grab the data for the dropdown lists from web services.</p>
|
ASP.NET URL-rewriting options <p>I've seen some .NET sites that obviously are using some sort of URL-rewriting method, but the one that intrigues me the most are ones that look like:</p>
<p><strong><a href="http://www.somesite.com/pages/an-example-page.aspx" rel="nofollow">http://www.somesite.com/pages/an-example-page.aspx</a></strong></p>
<p>I have previously used "UrlRewritingNet.UrlRewrite", but that requires that the database primary key integer be located somewhere in the requested URL.</p>
<p>Is there any other way to perform this? I am using ASP.NET 3.5</p>
<p>Thank u!</p>
| <p>There is a System.Web.Routing addition in the new MVC Framework you can use to do it in 3.5 or I believe it is included in the 3.5 SP1 install.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.routing.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.web.routing.aspx</a></p>
|
Software to test C# code <p>Consider i have a C# code, I need some tool that would perform an analysis of my code and report bugs and vulnerabilities. Are there any open source tools, something like klocwork.?</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/bb429476.aspx" rel="nofollow">FxCop</a> can perform static analysis of compiled assemblies, <a href="http://www.jetbrains.com/resharper/" rel="nofollow">ReSharper</a> can analyze your program at source code level. Certain editions of Visual Studio have Code Analysis built into them.</p>
<p>As a sidenote: get up to speed on <a href="http://en.wikipedia.org/wiki/Unit%5Ftest" rel="nofollow">unit testing</a> (think <a href="http://www.nunit.org/" rel="nofollow">NUnit</a> et al.)</p>
|
ASP.NET/IIS equivalent of Java/WAS context-root <p>In Java on WebSphere Application Server if I want my servlets, etc., to start with a certain root path, I use the context-root property in the EAR deployment descriptor (application.xml). For example, my servlet is named GetData, but I want the URL to be www.mysite.com/secure/restricted/GetData, so I set the context-root to secure/restricted.</p>
<p>How do I do that in ASP.NET on IIS? Is the some kind of configuration setting for the application?</p>
| <p>One option would be Url Rewritting - <a href="http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx</a></p>
<p>On the other hand, if you have your dynamic asp.net site separated from the rest of your content, you can add the folder secure/ and configure in there through the IIS Manager to point restricted to your asp.net site (regardless of where you have it stored).</p>
<p>That said, I don't know whether the WAS context-root give you something extra, for links to other info outside the asp.net site.</p>
|
toggle div visibility with a checkbox list <p>I have a web application(ASP.NET2.0 C#).
Within it, I have a div that contains a checkbox list and a button.</p>
<p>I want to toggle the div viewing, so I got some javascript code online to help me.</p>
<p>Heres the code:</p>
<pre><code><script language="javascript">
var state = 'hidden';
function showhide(layer_ref) {
if (state == 'visible')
{
state = 'hidden';
}
else
{
state = 'visible';
}
if (document.all)
{ //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.visibility = state");
}
if (document.layers)
{ //IS NETSCAPE 4 or below
document.layers[layer_ref].visibility = state;
}
if (document.getElementById && !document.all)
{
maxwell_smart = document.getElementById(layer_ref);
maxwell_smart.style.visibility = state;
}
}
</script>
</code></pre>
<p>I call the function this way:</p>
<pre><code><a href="javascript://" onclick="showhide('AlertDiv');">Choose Columns</a>
</code></pre>
<p>When I use this function, it shows me the div with the button, but it doesn't show me the checkboxlist....Any ideas on what's going on?</p>
<p>Thank you.</p>
| <p>Have you tried using display instead of visiblity?</p>
<p>For example, instead of:</p>
<pre><code>document.getElementById(layer_ref).style.visiblity = "hidden";
document.getElementById(layer_ref).style.visiblity = "visible";
</code></pre>
<p>Use:</p>
<pre><code>document.getElementById(layer_ref).style.display = "none";
document.getElementById(layer_ref).style.display = "block";
</code></pre>
<p>You will have to replace all your references to visiblity with display not just the getElementById version. You also may want to look into using <a href="http://docs.jquery.com/Downloading%5FjQuery" rel="nofollow">jQuery</a> which will handle your scenario with a few lines of code, plus no need for an onclick attribute to cloud you html.</p>
<pre><code><script type="text/javascript" src="jquery-1.3.2.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.toggleLink').click(function(e) {
e.preventDefault();
$('#AlertDiv').toggle();
});
});
</script>
<a href="#" class="toggleLink">Choose Columns</a>
</code></pre>
|
Best way to change clustered index (PK) in SQL 2005 <p>I have a table which has a clustered index on two columns - the primary key for the table.
It is defined as follows:</p>
<pre><code>ALTER TABLE Table ADD CONSTRAINT [PK_Table] PRIMARY KEY CLUSTERED
(
[ColA] ASC,
[ColB] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
</code></pre>
<p>I want to remove this clustered index PK and add a clustered index like follows and add a primary key constraint using a non-clustered index, also shown below.</p>
<pre><code>CREATE CLUSTERED INDEX [IX_Clustered] ON [Table]
(
[ColC] ASC,
[ColA] ASC,
[ColD] ASC,
[ColE] ASC,
[ColF] ASC,
[ColG] ASC
)WITH (PAD_INDEX = ON, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, FILLFACTOR = 90, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF) ON [PRIMARY]
ALTER TABLE Table ADD CONSTRAINT
PK_Table PRIMARY KEY NONCLUSTERED
(
ColA,
ColB
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
</code></pre>
<p>I was going to just drop the PK clustered index, then add the new clustered index and then add the non-clustered primary key index, but I learned that dropping the existing clustered index would cause the table data to be reordered (see answer here <a href="http://stackoverflow.com/questions/705504/what-happens-when-i-drop-a-clustered-primary-key-in-sql-2005">http://stackoverflow.com/questions/705504/what-happens-when-i-drop-a-clustered-primary-key-in-sql-2005</a>), which I don't think should be necessary. The table is knocking 1 TB, so I really want to avoid any unnecessary reordering.</p>
<p>My question is, what is the best way to go from the existing structure to the desired structure?</p>
<p>EDIT: Just want to clarify. The table is 1TB and I unfortunately do not have space to create a temporary table. If there is a way to do it without creating a temp table then please let me know.</p>
| <p>This isn't a complete answer to your question, but make sure that if you have any other indexes on the table that you drop those first. Otherwise SQL Server will have to rebuild them all when you remove the clustered index then rebuild them all again when you add back a new clustered index. The usual steps are:</p>
<ol>
<li>Remove all non-clustered indexes</li>
<li>Remove clustered index</li>
<li>Add new clustered index</li>
<li>Add back all non-clustered indexes</li>
</ol>
|
What is data is submitted to Google when using google maps? <p>I have been asked by a client to map data, but the client does not what any other data besides addresses for geocoding to be sent to another server. Does the Google maps API submit other data besides addresses and latitude/longitude to Google?</p>
<p>For example, I would not want the "dealerInfo" node to be submitted to Google in the following XML used for a map on [<a href="http://www.coastalbendchevydealers.com/" rel="nofollow">http://www.coastalbendchevydealers.com/</a>][1] .</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<markers>
<!-- Neessen Automotive -->
<marker lat="27.5380258" lng="-97.8547257" dealer="Neessen Automotive">
<dealerInfo><![CDATA[
<table border="0" class="infoWindow">
<tr><td rowspan="5" width="155" align="left"><img src="images/chevydealer.jpg" width="150" height="113"/></td></tr>
<tr><td align="left"><strong>Neessen Automotive</strong></td></tr>
<tr><td align="left">2007 S. US Highway 77 Bypass<br>Kingsville, Texas</td></tr>
<tr><td align="left">361-592-2668</td></tr>
<tr><td align="left"><a href="http://www.neessenautomotive.com" target="_blank">www.neessenautomotive.com</a></td></tr>
</table>
]]></dealerInfo>
</marker>
</code></pre>
| <p>It shouldn't be submitted at all, it depends on how you are paring the XML file.</p>
<pre>
GDownloadUrl("AMBest2bil50bil.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i "+name+"<br>Total Assets: "+formatCurrency(text)+"<p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
GEvent.addListener(marker, "click", function() {
map.setCenter(point,10);
});
map.addOverlay(marker);
}
</pre>
<p>That will parse my XML file and only manipulate the 'marker' tag. You already have the info geocoded since you have the lat/long and I'd presume that the CDATA is for some type of popup/mouse over display. I do not believe you will be passing any of that to Google.</p>
|
C++ socket server on Mac. Help! <p>Hey everyone.
I'm planning on writing a socket server in C++ running on a Mac. I've been searching through a great portion of the internet without any results. Anyone knows where to start? Or even got a basic source code?
Much appreciated.</p>
| <p>i think the ASIO Library is platform independent enough for that.</p>
<p>Look here:
<a href="http://www.boost.org/doc/libs/1%5F38%5F0/doc/html/boost%5Fasio.html" rel="nofollow">Boost Asio</a>
<a href="http://think-async.com/Asio/" rel="nofollow">Asio Only</a></p>
|
Cannot update document property on ItemAdded event when using Vista <p>We are trying to create a custom event handler that would fire on ItemAdded event. The event handler then updates the document with a unique ID value to a column in this document library. </p>
<p>Our solution works fine, except when a user on Vista is trying to save a new document from Office 2007. In this scenario the document is stored to document library but Unique ID column is empty, and there is no exception.</p>
<p>Vista Users can upload document(s) to library without a problem. Everything else works fine on XP and Win2k3 operating systems.</p>
<p>Has anyone seen something similar, and what might be the problem here? To demonstrate the problem we are using DateTime.Now as unique ID. </p>
<pre><code> using Microsoft.SharePoint;
public class TestReciever : SPItemEventReceiver
{
public override void ItemAdded(Microsoft.SharePoint.SPItemEventProperties properties)
{
try {
DisableEventFiring();
properties.ListItem("UniqueID Column") = DateTime.Now.ToString();
properties.ListItem.SystemUpdate();
EnableEventFiring();
}
catch (Exception ex) {
// handle exception
}
}
}
</code></pre>
| <p>We have noticed exactly the same thing happening. When the 2007 doc is added to the library, the properties from the list are added to it (blank). </p>
<p>Then the (synchronous) event handler is called, updating the list with the correct values for the UniqueID column. </p>
<p>Then the inbuilt property mapping to 2007 docs kicks in and overwrites your values with those stored in the 2007 doc (not raising an item updated event again).</p>
<p>This means that the list now has a blank for your column.</p>
<p>If you change to an asynchronous event you may see what we did and that the slight delay for asynchronous meant that the property mapping to 2007 docs happened first (we think) meaning the value was stored correctly.</p>
<p>It is possible to break the property mapping between the list and office, but that is only a workaround. </p>
<p>I cannot for the life of me find where this info is on an MS site, but it is a known problem. Perhaps you can hang in there for SP2 (may even be fixed in SP1, but am unsure).</p>
|
Service Host Resolving - C# Equivalent to RMI Registry? <p>I'm taking a Masters capstone course early and doing my project in C# while everyone else is doing theirs in Java. The project has 4 services and requires a name server that maps service names to sockets. The instructor is suggesting that the students use RMI to build this registry. Since I'm not very familiar with Java, and the instructor is not very familiar with .NET, we weren't able to come up with an equivalent in C#. Anyone out there aware of one?</p>
<p>Update:</p>
<p>I'm looking for a way to discover a WCF service without explicitly knowing its socket.</p>
<p>Update 2:</p>
<p>I will be demoing the project on my XP laptop using VS 2008/WebDev server.</p>
| <p>You can use the UDDI server that comes with Windows Server 2K3/8. This will give you discovery of your services. Other than that you would need a 3rd party package or roll your own.</p>
|
Are uninitialized struct members always set to zero? <p>Consider a C struct:</p>
<pre><code>struct T {
int x;
int y;
};
</code></pre>
<p>When this is partially initialized as in </p>
<pre><code>struct T t = {42};
</code></pre>
<p>is <em>t.y</em> guaranteed to be 0 or is this an implementation decision of the compiler?</p>
| <p>item 8.5.1.7 of standard draft:</p>
<blockquote>
<p>-7- If there are fewer initializers in the list than there are members in the
aggregate, then each member not
explicitly initialized shall be
default-initialized (dcl.init).
[Example:</p>
<pre><code>struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };
</code></pre>
<p>initializes ss.a with 1, ss.b with
"asdf", and ss.c with the value of an
expression of the form int(), that is,
0. ]</p>
</blockquote>
|
Make an option selected based on $_GET. Is this even possible? <p>I have a quick question.</p>
<p>Is it possible to do something like this?</p>
<p>The options are generated dynamically based on foreach loop. I want the loop to stop where the $_GET['t'] equals the $k and make it selected.</p>
<pre><code><option value="http://domain.com/<?php print $k; ?>/" <?php if ($k == $_GET['t']) print 'selected'; ?>><?php print $v; ?></option>
</code></pre>
<p>Basically is there a way to make the option selected/highlighted based on the provided $_GET[t'] value on the address bar.. I tried it and i get undefined index: t error.</p>
<p>am i missing something?</p>
<p>Thanks a lot.</p>
| <p>You get the undefined error because "t" is not in your <code>$_GET</code> request.</p>
<p>make sure you are calling the right url (i.e.: example.com/script.php?t=test)</p>
<p>Do make sure you are checking for the value (as others suggested) with <code>isset($_GET['t'])</code></p>
|
Eclipse keeps running my old web application <p>OMG - what is going on with Eclipse (3.3 Europa) - has anyone come accross this problem (bearing in mind I have been messing about with uninstalling different Tomat containers and installing others - but anyway thats another story)</p>
<p>When I change a line of code or remove a class within my project - when I come to debug - it actually goes to a line that is commented out and runs that line regardless!!!! e.g.</p>
<p>//System.out.println("you should not be able to read this!");</p>
<p>UPDATE: This can be solved by setting Project -> Build Automatically (see answer below).</p>
<p><hr /></p>
<p>REMAINING PROBLEM:</p>
<p>Eclipse is not keeping my hot deploy folder current with the latest changes to my project:</p>
<p>I found out to my horror that some old remenants of my project are 'hanging around' in the folder that I think Eclipse uses for hot deploys or something </p>
<p><strong>C:\myJavaCode.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\myWebApp</strong></p>
<p>basically it is not actually copying accross any changes made in the classes of my working dir!?!??</p>
<p>...anyway - in order to keep my project up to date - I have to modify this folder too - TOTALLY UNACCEPTABLE - as you can't develop in this way - it would take you eons! Anyway, if anyone can help explain to me what stupid thing I have done to get me in this mess and how I can get out of this mess - I would really appreciate it.</p>
| <p>Have a look at:</p>
<blockquote>
<p>Windows>Preferences>Server>Launching...</p>
</blockquote>
<p>and:</p>
<blockquote>
<p>Project>Build Automatically</p>
</blockquote>
<p>maybe you accidentally disabled the auto-deploy features.</p>
|
How can I change the image displayed in an UIImageView programmatically? <p>I have an <code>IBOutlet</code> to an <code>UIImageView</code>, but when I look at the <code>UIImageView</code> doc, I can't see any hint about how to programmatically change it. Do I have to fetch an <code>UIImage</code> object from that <code>UIImageView</code>?</p>
| <p>If you have an IBOutlet to a UIImageView already, then all you have to do is grab an image and call setImage on the receiver (UIImageView). Two examples of grabbing an image are below. One from the Web, and one you add to your Resources folder in Xcode.</p>
<pre><code>UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
</code></pre>
<p>or</p>
<pre><code>UIImage *image = [UIImage imageNamed: @"cell.png"];
</code></pre>
<p>Once you have an Image you can then set UIImageView:</p>
<pre><code>[imageView setImage:image];
</code></pre>
<p>The line above assumes imageView is your IBOutlet.</p>
<p>That's it! If you want to get fancy you can add the image to an UIView and then add transitions. </p>
<p>P.S. Memory management not included.</p>
|
Dynamic columns when pivoting <p>I have a table of equipment, a table of customers and a sparse table of equipment and customers. I want to produce a query that returns a 1 if the equipment/Customer table record exists and a 0 if it doesn't for each customer. There are only a small number of customers in this problem, so what I want back should look like this:</p>
<pre><code>EquipmentID Cust1 Cust2 Cust3
----------- ----- ----- -----
1234 1 0 1
1357 0 1 0
2234 1 0 0
</code></pre>
<p>I can use a <code>cross join</code> to get a master list of possible records, but that returns the information in rows. I want to see it in columns, but the <code>PIVOT</code> keyword requires that I name the columns first. What I need is for the column names (<code>Cust1</code>, <code>Cust2</code>...) to be dynamic.</p>
| <p>If you want to do that, then you have to create the query string dynamically and then pass it to the <a href="http://msdn.microsoft.com/en-us/library/ms188001.aspx" rel="nofollow"><code>sp_execute</code></a> stored procedure. AFAIK, there isn't a way to do it without constructing the query string dynamically.</p>
|
Login Control - Response.Redirect <p>I have a usercontrol on a page that has a login control in it. This controls the display of another user control (if the user is not logged in they get the login control user control). I have some authentication code (see below) that runs when the user clicks the "Login" button. Basically I want it to post back to the same page so they will be logged in and able to now see the other protected user control. This code is not working. Perhaps there is something going on in another page that is making this not work, but does this code itself seem like it should work?</p>
<p>string userName = Membership.GetUserNameByEmail(Login1.UserName);</p>
<pre><code> if (userName != null)
{
e.Authenticated = Membership.ValidateUser(userName, Login1.Password);
}
else
{
e.Authenticated = false;
}
if (e.Authenticated)
{
Login1.UserName = userName;
ImageButton loginButton = (ImageButton)Login1.FindControl("LoginButton");
if (loginButton != null)
{
//loginButton.PostBackUrl = Request.Url.ToString();
Response.Redirect(Request.Url.ToString());
}
}
</code></pre>
| <p>The issue is the login control will itself do a redirect setting a cookie or an encrypted authentication ticket in the url (cookieless).</p>
<p>I think the login control has some properties where you can tell it where it will be redirecting to (which overrides the one in the web.config).</p>
|
How can I make UIImageView change its image programmatically? <p>I have this code:</p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
landscape.image = [UIImage imageNamed:@"tenerife1.png"];
}
</code></pre>
<p>First, I created an <code>UIImageView</code> with <code>IBOutlet</code>. Landscape is pointing to that <code>UIImageView</code>. In <code>InterfaceBuilder</code> I told to show an specific image in that <code>UIImageView</code>. It never changes. I always see the image I specified in <code>InterfaceBuilder</code>. But I want to set it programmatically. How can I do this?</p>
| <p>Try calling setNeedsDisplay on the view after you change the image:</p>
<pre><code> [landscape setNeedsDisplay];
</code></pre>
|
Get schema of proc's select output <p>I'd like to put the results of a stored proc into a temp table. It seems that the temp table must be defined beforehand and an INSERT INTO will not work. </p>
<p>Anyone know how to get the schema of the recordset being returned from a select statement?</p>
<p>sp_help only gets info on parameters.</p>
| <p>You should be able to insert into a temp table without defining the schema using OPENQUERY: </p>
<pre><code>SELECT * INTO #TempTable
FROM OPENQUERY(ServerName, âEXEC DataBaseName.dbo.StoredProcedureName paramvalues1, paramvalues1â²)
</code></pre>
<p>Where ServerName is the name of your Sql Server instance. See <a href="http://munishbansal.wordpress.com/2008/04/29/inserting-results-of-a-stored-procedurefunction-into-a-temp-table/" rel="nofollow">this article</a> for more info</p>
|
Looping through DirectoryEntry or any object hierarchy - C# <p>I am currently developing an application that use the System.DirectoryServices namespace to create a DirectoryEntry object and loop through the entire hierarchy to collect information. </p>
<p>I do not know number of child entries for each DirectoryEntry object in the hierarchy, so I can not create a N number of nested loops to spiders through the Children property</p>
<p>Here is my pseudo code example:</p>
<pre><code>//root directory
DirectoryEntry root = new DirectoryEntry(path);
if(DirectoryEntry.Childern != null)
{
foreach(DirectoryEntry child in root.Children)
{
//loop through each Children property unitl I reach the last sub directory
}
}
</code></pre>
<p>My question is, what is the best way to create a loop to collect information if you so not know the number of sub directories in your object? </p>
<p>(This can be applied to any type of object that you do not know the object hierarchy) </p>
| <p>Use a recursive function if you don't know the depth of the hierarchy and need to traverse down through all levels.
Below is an example using depth-first traversal.</p>
<pre><code>var root = new DirectoryEntry(someDN);
DoSomething(root);
function DoSomething(DirectoryEntry de)
{
// Do some work here against the directory entry
if (de.Children != null)
{
foreach (var child in de.Children)
{
DoSomething(child);
}
}
}
</code></pre>
|
Classic ASP crash course <p>I'm a C# and PHP developer. At work, I just got some classic ASP stuff dumped in my lap. I only need to make edits for a few weeks so I don't want to have to learn too much about legacy stuff I'll never touch again. However, I do need to be able to do my job for this duration.</p>
<p>How can I get a good crash course in ASP? I need to get good-enough at it very quickly. What sites/books/resources would best fit this need?</p>
| <p><a href="http://www.w3schools.com">http://www.w3schools.com</a> has a really good ASP tutorial. It's actually what I used when I went into classic ASP from a PHP background in school.</p>
|
Eclipse Servlets take a long time to update <p>I'm testing running a simple Servlet from within Eclipse. When I click 'Run', the console says it is starting TomCat, and then an internal browser launches within Eclipse which shows my code.</p>
<p>However, if I make any changes in the servlet and click 'Refresh' in the browser, the changes don't show. Then, a few seconds later if i hit refresh, the changes begin to show randomly. So I'm guessing there's a cache setting somewhere that controls this.</p>
<p>How can I turn that cache setting off or otherwise make the Eclipse internal browser update instantly as soon as I hit refresh?</p>
| <p>This is caused by the way servlet developing works. When modifying your servlert, it needs to be submitted to the servlet container after compiling it. The servlet container itself needs to reload the servlet, the servlet must be instantiated (servlet lifecycle). Thats a lot of things to do, which may cause you waiing for an update visible in the browser some seconds.</p>
|
How to make MPMoviePlayerController respect the ring/silent switch? <p>I'm trying, unsuccessfully, to get the MPMoviePlayerController to play movies silently if the ring/silent switch on the iPhone is set to silent. There are no interface methods to help me out nor does the player respect the AudioSessionProperty() trick:</p>
<pre><code>UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetProperty(
kAudioSessionProperty_AudioCategory,
sizeof (sessionCategory),
&sessionCategory);
</code></pre>
<p>Has anyone had any success silencing movie playback?</p>
| <p>I spent some time trying to get this to work myself. Eventually I gave up after trying, failing and reading <a href="https://devforums.apple.com/message/142085" rel="nofollow">this post on the apple dev forums</a>.</p>
<blockquote>
<p>"The MPMoviePlayerController establishes its own audio session and there is nothing you can do to affect this"</p>
</blockquote>
|
Spring MVC form:select Tag, multiple selections not binding correctly? <p>I am trying to create a form to edit an existing database row. I am using the Spring MVC form tag to auto bind the html to a form backing object. The row has a many to many relationship with another table, which I am trying to represent with a multiple select box using the form:select tag;</p>
<pre><code><form:select path="rules">
<form:options items="${bundle.rules}" itemValue="name" itemLabel="name"/>
</form:select>
</code></pre>
<p>I am using Hibernate for persistence so the relationship is represent as a HashSet inside the Bundle pojo.</p>
<pre><code> private Set<Rule> rules = new HashSet<Rule>(0);
</code></pre>
<p>Without the selection box on the page, the object will update to the database correctly, however with the selection box the object will not update to the database and I am getting this error in my log4j log, note that this error is not causing an exception, it is only visible in the logs;</p>
<pre><code>DEBUG org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:256) - Data binding errors: 1
</code></pre>
<p>This happens regardless of wither I deselect items inside the select box, the entire form refuses to submit correctly. Can anyone help me?</p>
<p>I am aware of <a href="http://stackoverflow.com/questions/284368/how-do-i-bind-collection-attributes-to-a-form-in-spring-mvc">http://stackoverflow.com/questions/284368/how-do-i-bind-collection-attributes-to-a-form-in-spring-mvc</a>, which is similar to this question, unfortunately none of the suggestions seemed useful to my problem.</p>
| <p>The problem is with the submission of your form. Spring isn't able to bind an object of the command, so it doesn't submit the form, but redirects you to the formView instead.</p>
<p>When the binding is successfully performed, you will see this message instead:</p>
<pre><code>No errors -> processing submit
</code></pre>
<p>To solve your problem, you will need to register a CustomCollectionEditor with your controller. (See this <a href="http://sirinsevinc.wordpress.com/tag/customcollectioneditor/">link</a>). It would be something like this:</p>
<pre><code>protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
{
binder.registerCustomEditor(Set.class, "rules", new CustomCollectionEditor(Set.class)
{
protected Object convertElement(Object element)
{
String name = "";
if (element instanceof String)
name = (String) element;
return name != null ? new Rule(name) : null;
}
});
}
</code></pre>
|
Ensuring method is called <p>I have this class:</p>
<pre><code>public abstract class AbstractIncomingCall {
/*
class properties
*/
public void changeStatus(/*some parameters*/){
//store parameters in class properties
isValid();
}
protected abstract boolean isValid();
}
</code></pre>
<p>...which is extended by this class:</p>
<pre><code>public class IncomingCallImpl extends AbstractIncomingCall{
//I override the parent's method
public void changeStatus(/*same parameters as parent's method*/) {
super.changeStatus(/*same parameters as parent's method*/);
//do something interesting
}
protected boolean isValid() throws StatusChangeNotOccurredException {
//implement my validation algorithm
}
</code></pre>
<p>What I would like to achieve is ensuring that whenever changeStatus(/*some parameters*/) gets called the isValid() method is called; note that the isValid() method is implemented only in the concrete class, also it uses class properties inheritated from the parent class.
Is there a way I can follow to ensure that isValid() is called other than calling super?
I dislike very much the fact that I have to pass parameters all around, I think I'm going totally in the wrong direction and there is a cleaner way to achieve this.
What I would like to keep in my code is the "isValid() calling logic" in the abstract class, because every call needs to be validated and I can't rely on me remembering this in the future :P</p>
<p>Thanks in advance :]</p>
| <p>It sounds like you want changeStatus() to follow the Template Method pattern. In this pattern, you define changeStatus() in the abstract class (making it final if you don't trust people to extend properly), and have it call the required methods:</p>
<pre><code>public final void changeStatus()
{
doSomethingSubclassSpecific();
isValid()
}
protected abstract doSomethingSubclassSpecific();
</code></pre>
|
ItemsSource + Converter + Treeview wont update <p>This one is fairly complex, hopefully I can make this clear enough for somebody to help me out. I have an object lets call it a Manager, the Manager has a collection of people that he manages, the people all implement IPerson, but different types of people have different properties. I want to display this manager in a tree, and under the manager node I want to show all the projects he is managing which can be determined from the people he manages. </p>
<p>So the plan is to use a converter to convert a person into a List of projects. Here is the XAML:</p>
<pre><code><HierarchicalDataTemplate DataType="{x:Type ui:Manager}">
<TextBlock Text="{Binding Path=Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate.ItemsSource>
<Binding Path="People">
<Binding.Converter>
<configUtil:ProjectListConverter/>
</Binding.Converter>
</Binding>
</HierarchicalDataTemplate.ItemsSource>
</HierarchicalDataTemplate>
</code></pre>
<p>My Person class implements INotifyPropertyChanged, and the list holding the people implements INotifyCollectionChanged.This code works great when I set the treeview ItemsSource, the Managers are displayed with their list of projects.</p>
<p>However, when I add a new person to the list of people, the TreeView is not updated. When I debug, I can see that the CollectionChanged is firing with the Add action and the added item. Also the CollectionChanged event is not null so I know the UI is watching it. But the Converter does not execute when the item is added. </p>
<p>here is the Add method for the List holding the IPerson objects:</p>
<pre><code>public void Add(T item)
{
list.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
}
</code></pre>
<p>Am I somehow breaking the databinding?</p>
<p>What other things can I check for?</p>
<p>The Converter just looks at each item in the People list and figures out what projects they are working on and adds the project name to an output List.</p>
| <p>The converter is applied to the property that stores the collection. Therefore, it will only be called if the collection instance itself changes (not if items in the collection are changed). One way around this would be to invalidate the collection when you want it to refresh.</p>
<p>The simplest way to invalidate the collection property and cause the converter code to run again would be to <code>null</code> out the collection and reassign it. Another way is to get the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.aspx" rel="nofollow"><code>BindingExpression</code></a> (via <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.aspx" rel="nofollow"><code>BindingOperations</code></a>) and call <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpression.updatetarget.aspx" rel="nofollow"><code>UpdateTarget</code></a>. Finally, you could instead bind to a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx" rel="nofollow"><code>CollectionView</code></a> (or subclass thereof) and call <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.refresh.aspx" rel="nofollow"><code>Refresh</code></a> on it.</p>
<p>And if you <em>really</em> want to fix the problem cleanly, you could bind to your own implementation of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.aspx" rel="nofollow"><code>ICollectionView</code></a> which does the filtering and raises events as necessary.</p>
|
Asp.Net Gridview Buttonfield get Row Data <p>I have a Gridview which is binded to a datatable that I created. The data in the table is ever changing.</p>
<p>I added a buttonfield to the Gridview. When clicked I want to send a specific columns value in that row through a link or sent through a function.</p>
<p>How do you go about doing this?</p>
| <p>I found out how to do it. You set the commandName property to whatever you want to call it inside the properties.</p>
<p>Then if you double click on the button after creating it in design view, it should pop up a function in the code behind page. You can then access the row by doing the following. </p>
<p>protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{</p>
<pre><code> int rowNum = int.Parse(e.CommandArgument.ToString());
</code></pre>
<p>}</p>
<p>from there you can use the row number to access specific column data. </p>
|
Load WPF styles or other Static Resources from an external file or assembly <p>I have a few WPF applications and I want all my styles to be in a shared assembly instead of declaring them in each application separately.</p>
<p>I am looking for a way so I don't have to change all my <code>Style="{StaticResource BlahBlah}"</code> in the existing applications; I just want to add the reference to this style assembly, and delete it from the current application, so it's taken from the assembly.</p>
<p>Is there any way?</p>
| <p>Referencing an external ResourceDictionary (XAML File):</p>
<pre><code><Application.Resources>
<ResourceDictionary Source="MyResources.xaml" />
</Application.Resources>
</code></pre>
<p>Referencing an external ResourceDictionary (DLL):</p>
<pre><code><Application.Resources>
<ResourceDictionary Source="/MyExternalAssembly;component/MyResources.xaml" />
</Application.Resources>
</code></pre>
|
ASP.Net Problem in Prod/Dev <p>I am facing strange problem,
Whenever I commented second <strong>if</strong> condition, it works in Production, but fail in development.</p>
<p>And when I dont comments second if condtion of code, it works for development and fail for production.</p>
<pre><code> protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lblDocument.Text = "Document :" + this.Request.QueryString["A_No"].ToString();
//if (!frmViewer.Action.Contains("?"))
//{
// frmViewer.Action = String.Format("{0}?A_No={1}&A_Format={2}",
// frmViewer.Action,
//this.Request.QueryString["A_No"].ToString(),
// //this.Request.QueryString["A_Format"].ToString());
// }
}
}
</code></pre>
<p>Here is Error message:</p>
<p><strong>CS0117: 'System.Web.UI.HtmlControls.HtmlForm' does not contain a definition for 'Action'</strong></p>
| <p>Did you verify that your ASPX file was migrated up to production with the latest changes?</p>
<p>It looks to me that the Action control was added in development, and the DLL file migrated up to production, but not the corresponding ASPX file.</p>
|
How to use ROW_NUMBER in the following procedure? <p>I have the following stored procedure which returns A, B, and the count in descending order. I am trying to use ROW_NUMBER, so I can page the records, but I want the first row number 1 to be the record with the highest count, so basically, if I return a table with 3 records and the count is 30, 20, 10, then row number 1 should correspond with count 30, row number 2 should correspond with count 20, and row number 3 should correspond with count 10. dbo.f_GetCount is a function that returns a count.</p>
<pre><code>CREATE PROCEDURE dbo.Test
AS
@A nvarchar(300) = NULL,
@B nvarchar(10) = NULL
AS
SELECT @A = NULLIF(@A,''), @B = NULLIF(@B,'')
SELECT h.A, hrl.B,
dbo.f_GetCount(hrl.A,h.B) as cnt
FROM dbo.hrl
INNER JOIN dbo.h on h.C = hrl.C
WHERE (@A IS NULL OR h.A like '%' + @A + '%')
AND (@B IS NULL OR hrl.B = @B)
GROUP BY hrl.B, h.A
ORDER BY cnt desc
</code></pre>
| <pre><code>WITH q AS
(
SELECT h.A, hrl.B,
dbo.f_GetCount(hrl.A,h.B) as cnt
FROM dbo.hrl
INNER JOIN dbo.h on h.C = hrl.C
WHERE (@A IS NULL OR h.A like '%' + @A + '%')
AND (@B IS NULL OR hrl.B = @B)
GROUP BY hrl.B, h.A
)
SELECT q.*, ROW_NUMBER() OVER (ORDER BY cnt DESC) AS rn
FROM q
ORDER BY rn DESC
</code></pre>
<p>To retrieve first <code>10</code> rows, use:</p>
<pre><code>WITH q AS
(
SELECT h.A, hrl.B,
dbo.f_GetCount(hrl.A,h.B) as cnt
FROM dbo.hrl
INNER JOIN dbo.h on h.C = hrl.C
WHERE (@A IS NULL OR h.A like '%' + @A + '%')
AND (@B IS NULL OR hrl.B = @B)
GROUP BY hrl.B, h.A
)
SELECT TOP 10 q.*,
ROW_NUMBER() OVER (ORDER BY cnt DESC, A, B) AS rn
FROM q
ORDER BY cnt DESC, A, B
</code></pre>
<p>To retrieve rows between <code>11</code> and <code>20</code>, use:</p>
<pre><code>SELECT *
FROM (
WITH q AS
(
SELECT h.A, hrl.B,
dbo.f_GetCount(hrl.A,h.B) as cnt
FROM dbo.hrl
INNER JOIN dbo.h on h.C = hrl.C
WHERE (@A IS NULL OR h.A like '%' + @A + '%')
AND (@B IS NULL OR hrl.B = @B)
GROUP BY hrl.B, h.A
)
SELECT q.*,
ROW_NUMBER() OVER (ORDER BY cnt DESC, A, B) AS rn
FROM q
) qq
WHERE rn BETWEEN 11 AND 20
ORDER BY cnt DESC, A, B
</code></pre>
|
Why is this bash prompt acting strangely/disappearing, and how do I fix it (OS X)? <p>I admit that I use a somewhat long-winded bash prompt:</p>
<pre><code>--(username)-(Wed April 01|12:00:00)--(~ $</code></pre>
<p>Recently, I got the bright idea to change it so that depending on the exit value from the previous command, if success, the interior elements of the ()'s would be green, and if failure, they would be red. I got it working for the most part (some odd exit statuses will change the color to something else, but I'm ok with it), but when typing a command which is more than one line, and causes the terminal to scroll, the prompt disappears! My prompt worked fine when there was no color, so I'm guessing it is related to my color escaping, and particularly my unclosed ['s, but I can't pin it down.</p>
<pre><code>#.profile
export PS1='--(\e[$((32-${?}))m\u\e[0m)-(\e[$((32-${?}))m\d\e[0m|\e[$((32-${?}))m\T\e[0m)--(\e[$((32-${?}))m\w\e[0m \$ '</code></pre>
<p>Thanks in advance!</p>
| <p>It sounds like <a href="http://forums.macosxhints.com/archive/index.php/t-17068.html">this</a> should solve your problem.</p>
<p>This seems to work for me<code>*</code>:</p>
<pre><code>export PS1='--(\[\e[$((32-${?}))m\]\u\[\e[0m\])-(\[\e[$((32-${?}))m\]\d\[\e[0m\]|\[\e[$((32-${?}))m\]\T\[\e[0m\])--(\[\e[$((32-${?}))m\]\w\[\e[0m\] \$ '
</code></pre>
<p><code>*</code> well, really <code>export PS1='\u@\h:\w\$ '</code> works for me</p>
<p>To quote the linked post, the answer lies in adding <strong>\[ and \]</strong> around all of your color sequences in your PS1 declaration:</p>
<blockquote>
<p>Before I had the following value for PS1:</p>
<p>'\e[0;34m\h:\w [!]\$\e[0m '</p>
<p>which gave me a nice blue prompt of the following form</p>
<p>hostname:working-directory [command-number]$</p>
<p>However, I had the same line-wrapping problem you did. The fix was to insert \[ and \] around the ANSI escapes so that the shell knows not to include them in the line wrapping calculation. This results in the following value for PS1:</p>
<p>'\[\e[0;34m\]\h:\w [!]\$\[\e[m\] '</p>
</blockquote>
|
Can I use a dll written in C with PHP? <p>We are interfacing with a piece of hardware developed here, and allowing access via the web. The firmware for this device is written in C, and part of that firmware is about 5000 lines of code that parses huge binary files for config data, compiled to a .dll.</p>
<p>Is there any way under heaven that I can access a .dll, written in C, from PHP? </p>
<p>I'm betting it's a no, but before starting a quest to duplicate 5000 lines of C in PHP, I thought I'd give the experts here a shot.</p>
<p>Thanks all.</p>
<p>JH</p>
| <p>yes, you can use it as a php extension (which are written in C), but you might need some modifications .. etc</p>
<p><a href="http://devzone.zend.com/node/view/id/1021" rel="nofollow">http://devzone.zend.com/node/view/id/1021</a></p>
<p>I think <a href="http://stackoverflow.com/questions/705443">this question</a> is related to yours.</p>
|
Tools to compare two sites structures <p>Does anyone knows about any tools allowing to compare two almost exactly same websites?</p>
<p>Simply, I have a sandbox site and production site, and would like to find out the difference between them, to know what content to move to production site.</p>
<p>Thanks!</p>
<p>Edit:</p>
<p>Ok, I see I missed a critical piece of information (sorry!). The both sites are online and based on CMS (Drupal), hence I need some crawling tool which would run over the two sites, and show what pages present in sandbox, but not on production.</p>
<p>Thanks for everyone who answered regardless!</p>
| <p>Use <a href="http://www.httrack.com/">httrack</a> to pull down a copy of the sites, and then your favourite file comparing tool to review the differences. (I prefer <a href="http://winmerge.org/">WinMerge</a>, which can recursively run though two folders of files, has options to ignore whitespace differences and blank lines, and even runs well under Linux using WINE.)</p>
<p>P.S. You might even want to run your downloaded HTML files through <a href="http://tidy.sourceforge.net/">HTML Tidy</a> to normalise/pretty format them before doing the comparison.</p>
<p><hr /></p>
<p>The other way to do it would be a <a href="http://stackoverflow.com/questions/225772/compare-two-mysql-databases">database comparison</a>. You would still do the file comparison of the raw website files (not the spidered version) too though. From memory, the schema for a Drupal database isn't too hard to follow, particularly if you are just primarily interested in node content.</p>
|
Decorators and in class <p>Is there any way to write decorators within a class structure that nest well? For example, this works fine without classes:</p>
<pre><code>def wrap1(func):
def loc(*args,**kwargs):
print 1
return func(*args,**kwargs)
return loc
def wrap2(func):
def loc(*args,**kwargs):
print 2
return func(*args,**kwargs)
return loc
def wrap3(func):
def loc(*args,**kwargs):
print 3
return func(*args,**kwargs)
return loc
def merger(func):
return wrap1(wrap2(wrap3(func)))
@merger
def merged():
print "merged"
@wrap1
@wrap2
@wrap3
def individually_wrapped():
print "individually wrapped"
merged()
individually_wrapped()
</code></pre>
<p>The output is:</p>
<pre><code>1
2
3
merged
1
2
3
individually wrapped
</code></pre>
<p>which is what I want. But now let's say that I want to make <code>merged</code> and <code>individually_wrapped</code> as static or class methods. This will also work, so long as the decorators are kept out of the class namespace. Is there any good way to put the decorators within the namespace? I'd rather not enumerate all the ways that won't work, but the main problem is that if <code>merger</code> is a method, it can't access the <code>wrapX</code> methods. Maybe this is a stupid thing to want to do, but has anyone gotten something like this to work, with all the decorators and decorated methods in the same class?</p>
| <p>"Is there any good way to put the decorators within the namespace?"</p>
<p>There's no compelling reason for this. You have module files. Those are a tidy container for a class and some decorators. </p>
<p>You don't ever need decorators as methods of the class -- you can just call one method from another. </p>
|
How to prevent, counter or compensate for, an empty/NULL field (MySQL) returning an empty set <p>I'm learning PHP and MySQL to get a hang of server-side scripting and for personal interest/development. The first 'program,' beyond 'hello world' seems to be writing ones' own blog.</p>
<p>This is a little beyond me yet and so thought I'd start with a contacts-database type. So far so good, but (and there's always the but!) I'm trying to format a presentation in the form that the contact's name is formatted as a mailto: link.</p>
<pre><code>$query = mysql_query("
SELECT CONCAT(fname,', ',sname) AS name, email.address AS email
FROM contacts, emails
WHERE contacts.contactID=email.contactID");
while ($row = mysql_fetch_array($query)) {
echo "<li><a href=\"mailto" . $row['email'] . "\"> . $row['name'] . "</a></li>";
}
</code></pre>
<p>This is fine until I dare to enter a contact that has no email address in the Db, at which point the obvious lack of an email.contactID to equal the contacts.contactID rears its head.</p>
<p>I realise that I should be able to deal with this but...I can't think of how (yay to insomnia! @.@ ). Any suggestions would be appreciated.</p>
| <p>You want a left (aka left outer) join.</p>
<pre><code>select concat(c.fname, ' ', c.sname) as name, e.address as email
from contacts c
left join emails e
on (c.contactID = e.contactID)
</code></pre>
|
Clean, efficient algorithm for wrapping integers in C++ <pre><code>/**
* Returns a number between kLowerBound and kUpperBound
* e.g.: Wrap(-1, 0, 4); // Returns 4
* e.g.: Wrap(5, 0, 4); // Returns 0
*/
int Wrap(int const kX, int const kLowerBound, int const kUpperBound)
{
// Suggest an implementation?
}
</code></pre>
| <p>The sign of <code>a % b</code> is only defined if <code>a</code> and <code>b</code> are both non-negative.</p>
<pre><code>int Wrap(int kX, int const kLowerBound, int const kUpperBound)
{
int range_size = kUpperBound - kLowerBound + 1;
if (kX < kLowerBound)
kX += range_size * ((kLowerBound - kX) / range_size + 1);
return kLowerBound + (kX - kLowerBound) % range_size;
}
</code></pre>
|
In Python how can I access "static" class variables within class methods <p>If I have the following python code:</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
</code></pre>
<p>It complains </p>
<pre><code>NameError: global name 'bar' is not defined
</code></pre>
<p>How can I access class/static variable 'bar' within method 'bah'?</p>
| <p>Instead of <code>bar</code> use <code>self.bar</code> or <code>Foo.bar</code>. Assigning to <code>Foo.bar</code> will create a static variable, and assigning to <code>self.bar</code> will create an instance variable.</p>
|
static BOOL in Objective C <p>In the following code, I'm creating a category on UIColor to create a random color. However, from this code, I would have thought that the 'if' conditional would be true every time the method is run, instead of just the first time. </p>
<p>I think I'm not really understanding static variables correctly. Does a static variable only get set once, and then the second time the method is run, that line is just ignored? (so seeded would forever be YES after the first run)?</p>
<pre><code>@interface UIColor(Random)
+(UIColor *)randomColor
{
static BOOL seeded = NO;
if (!seeded)
{
seeded = YES;
srandom(time(NULL));
}
CGFloat red = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat green = (CGFloat)random()/(CGFloat)RAND_MAX;
CGFloat blue = (CGFloat)random()/(CGFloat)RAND_MAX;
return [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
}
</code></pre>
| <p>You are correct that the static variable only is set once.</p>
<p>the code </p>
<pre><code>static BOOL seeded = NO;
</code></pre>
<p>is <strong>not</strong> equivalent to</p>
<pre><code>static BOOL seeded;
seeded = NO;
</code></pre>
<p>the second one would always evaluate to NO, while the first one will evaluate to NO until set differently.</p>
|
In scons, how can I inject a target to be built? <p>I want to inject a "Cleanup" target which depends on a number of other targets finishing before it goes off and gzip's some log files. It's important that I not gzip early as this can cause some of the tools to fail.</p>
<p>How can I inject a cleanup target for Scons to execute?</p>
<p>e.g. I have targets foo and bar. I want to inject a new custom target called 'cleanup' that depends on foo and bar and runs after they're both done, without the user having to specify</p>
<pre><code>% scons foo cleanup
</code></pre>
<p>I want them to type:</p>
<pre><code>% scons foo
</code></pre>
<p>but have scons execute as though the user had typed </p>
<pre><code>% scons foo cleanup
</code></pre>
<p>I've tried creating the cleanup target and appending to sys.argv, but it seems that scons has already processed sys.argv by the time it gets to my code so it doesn't process the 'cleanup' target that I manually append to sys.argv.</p>
| <p>you shouldn't use <code>_Add_Targets</code> or undocumented features, you can just add your cleanup target to <code>BUILD_TARGETS</code>:</p>
<pre><code>from SCons.Script import BUILD_TARGETS
BUILD_TARGETS.append('cleanup')
</code></pre>
<p>if you use this documented list of targets instead of undocumented functions, scons won't be confused when doing its bookkeeping. This comment block can be found in <code>SCons/Script/__init__.py</code>:</p>
<pre><code># BUILD_TARGETS can be modified in the SConscript files. If so, we
# want to treat the modified BUILD_TARGETS list as if they specified
# targets on the command line. To do that, though, we need to know if
# BUILD_TARGETS was modified through "official" APIs or by hand. We do
# this by updating two lists in parallel, the documented BUILD_TARGETS
# list, above, and this internal _build_plus_default targets list which
# should only have "official" API changes. Then Script/Main.py can
# compare these two afterwards to figure out if the user added their
# own targets to BUILD_TARGETS.
</code></pre>
<p>so I guess it is intended to change <code>BUILD_TARGETS</code> instead of calling internal helper functions</p>
|
Extract the first word of a string in a SQL Server query <p>What's the best way to extract the first word of a string in sql server query?</p>
| <pre><code>SELECT CASE CHARINDEX(' ', @Foo, 1)
WHEN 0 THEN @Foo -- empty or single word
ELSE SUBSTRING(@Foo, 1, CHARINDEX(' ', @Foo, 1) - 1) -- multi-word
END
</code></pre>
<p>You could perhaps use this in a UDF:</p>
<pre><code>CREATE FUNCTION [dbo].[FirstWord] (@value varchar(max))
RETURNS varchar(max)
AS
BEGIN
RETURN CASE CHARINDEX(' ', @value, 1)
WHEN 0 THEN @value
ELSE SUBSTRING(@value, 1, CHARINDEX(' ', @value, 1) - 1) END
END
GO -- test:
SELECT dbo.FirstWord(NULL)
SELECT dbo.FirstWord('')
SELECT dbo.FirstWord('abc')
SELECT dbo.FirstWord('abc def')
SELECT dbo.FirstWord('abc def ghi')
</code></pre>
|
Generate Complex Object from LINQ to XML in VB .NET <p>I have an XML File that I am processing using LINQ. I want to basically serialize the XML data into custom objects but don't know how.</p>
<p>Simplified XML</p>
<pre><code><Data>
<Group id="1">
<Child id="1"/>
<Child id="2"/>
<Child id="3"/>
</Group>
<Group id="2">
<Child id="1"/>
<Child id="2"/>
<Child id="3"/>
</Group>
</Data>
</code></pre>
<p>I have a class called Group with a property called Children that is a list of (Child).</p>
<p>I can do the following in linq to generate the Enurable( of Group):</p>
<pre><code> dim g = From item In _
XElement.Load("XMLFile.xml", LoadOptions.None)...<Group> _
Select New nABLE4ConfigInfo.Group(item.@id)
</code></pre>
<p>How can I finish the above LINQ query to populate the Children property of the Group object?</p>
| <p>I think this class, paired with <code>System.Xml.Serialization.XmlSerializer</code>, will do the trick:</p>
<pre><code><Serializable> _
Public Class Data
<Serializable> _
Public Class Group
<Serializable> _
Public Class Child
<XmlAttribute> _
Public id As Integer
End Class
<XmlArray> _
Public Child() As Child
<XmlAttribute> _
Public id As Integer
End Class
<XmlArray> _
Public Group() As Group
End Class
</code></pre>
<p>The class may need some work yet: getting the arrays right can be tricky.</p>
|
WPF exception running animation in another class <p>I can run an animation from the main window class but if I try to run the same code from another class in the same namespace I receive an exception in the storyboard begin function<br>
this is the exception:<br><br>
No applicable name scope exists to resolve the name 'DefaultGroup'.<br></p>
<p>this is how I set the storyboard target and property</p>
<pre><code>Storyboard.SetTargetName(r3d,"DefaultGroup");
Storyboard.SetTargetProperty(r3d, new PropertyPath("(Visual3D.Transform).(Transform3DGroup.Children)[2].(RotateTransform3D.Rotation)"));
</code></pre>
<p>How can I fix this?
<br>
Thanks<br>
Walther</p>
| <p>--otherUserControl.cs</p>
<pre><code>StackPanel defaultGroup;
</code></pre>
<p>--MainWindow.cs</p>
<pre><code>this.RegisterName(otherUserControl.defaultGroup.Name, otherUserControl.defaultGroup); // RegisterName
Storyboard.SetTargetName(r3d,"defaultGroup");
Storyboard.SetTargetProperty(r3d, new PropertyPath("(Visual3D.Transform).(Transform3DGroup.Children)[2].(RotateTransform3D.Rotation)"));
</code></pre>
|
C#: How do you disable a key from being pressed indefinetly in textbox's keydown event? <p>C#: How do you disable a key from being pressed indefinetly in textbox's keydown event?</p>
| <p>The standard way to handle that is to create an event handler for the <code>Textbox.KeyDown</code> event and then set <code>KeyEventArgs.SuppressKeyPress</code> to true if the key pressed matches the key you want to disable. Here is an example:</p>
<pre><code>yourTextBox.KeyDown += delegate(Object sender, KeyEventArgs e)
{
e.SuppressKeyPress = (e.KeyCode == YOUR_KEY);
}
</code></pre>
|
Is there a reasonable approach to "default" type parameters in C# Generics? <p>In C++ templates, one can specify that a certain type parameter is a default. I.e. unless explicitly specified, it will use type T. </p>
<p>Can this be done or approximated in C#?</p>
<p>I'm looking for something like:</p>
<pre><code>public class MyTemplate<T1, T2=string> {}
</code></pre>
<p>So that an instance of the type that doesn't explicitly specify <code>T2</code>:</p>
<pre><code>MyTemplate<int> t = new MyTemplate<int>();
</code></pre>
<p>Would be essentially:</p>
<pre><code>MyTemplate<int, string> t = new MyTemplate<int, string>();
</code></pre>
<p>Ultimately I am looking at a case wherein there is a template that is fairly widely used, but I am considering expanding with an additional type parameter. I could subclass, I guess, but I was curious if there were other options in this vein. </p>
| <p>Subclassing is the best option.</p>
<p>I would subclass your main generic class: </p>
<p><code>class BaseGeneric<T,U></code> </p>
<p>with a specific class </p>
<p><code>class MyGeneric<T> : BaseGeneric<T, string></code></p>
<p>This makes it easy to keep your logic in one place (the base class), but also easy to provide both usage options. Depending on the class, there is probably very little extra work needed to make this happen.</p>
|
Excel VBA copy XL-2007 Macro-Enabled Workbook as excel-2003 file with no macros <p>I''m looking for a vba macro that will make a copy of the current Excel 2007 macro-enabled workbook with the name I specify as an Excel 2003 macro-free document. It should also keep the current workbook open and in the Excel 2007 format (so save-as wouldn't work).</p>
<p>I can't figure out how to do the copy operation...</p>
| <p>It's much, much easier to do a save as.</p>
<p>Why does it have to stay open? - you can simulate it by: </p>
<ul>
<li>Doing a Save As to a new file </li>
<li>Close the copy </li>
<li>Re-open the original</li>
</ul>
<p>As far as removing the code look at these questions: </p>
<p><a href="http://stackoverflow.com/questions/704759/how-to-remove-excel-vba-code-modules-when-spreadsheet-opened-closed">http://stackoverflow.com/questions/704759/how-to-remove-excel-vba-code-modules-when-spreadsheet-opened-closed</a></p>
<p><a href="http://stackoverflow.com/questions/680875/macro-to-save-active-sheet-as-new-workbook-ask-user-for-location-and-remove-macr">http://stackoverflow.com/questions/680875/macro-to-save-active-sheet-as-new-workbook-ask-user-for-location-and-remove-macr</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.