input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
rotate text from a horizontal to a vertical position <p>Is it possible to rotate text from a horizontal position to a vertical on a single point without using something like flash? So I would read the same text normally by tilting my head.</p>
<p>I was thinking you can do this in jquery but couldn't find a plug in.</p>
| <p>i used pure CSS and it worked very fine for me,here is the code:</p>
<pre><code><div style="-webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); z-index:inherit; float:left">Not at all</div>
</code></pre>
|
Why does my jQuery alert show twice? <p>I am using jQuery. I have a problem when alerts the IDs of a list shows two times, instead of once.</p>
<p>The list:</p>
<pre><code><ul id="testnav">
<li> <a href="#">Page 1</a></li>
<li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>
</ul>
</code></pre>
<p>The code:</p>
<pre><code>$("li").click(function(){
var current_id = $(this).attr('id');
alert(current_id);
// These alert two times, one is empty and another one is content_1
});
</code></pre>
<p>Why dopes the code alert two times? How do I make it execute a single time?</p>
| <p>$("li").click() is applying the click event to all LIs on the page.</p>
<p>When you click</p>
<pre><code><li> <a href="#">Page2..</a>
<ul id="subnav">
<li id="content_1"><a href="#"> Page3</a></li>
</ul>
</li>
</code></pre>
<p>You're actually clicking the outer LI, and the inner-most LI, which would cause the event to fire twice. The outer LI has no ID, so it's empty, and the inner LI has an ID of "content_1", so that displays.</p>
<p>Does that make sense?</p>
|
What's a good way to get started integrating ADFS with AzMan? <p>Does anyone know of any good screenscasts or documentation covering the integration Active Directory Federation Services (ADFS) with Authorization Manager (AzMan)?</p>
| <p>There are many links I would recommend, screencasts are always a good way to get started:</p>
<p><strong><em>Channel 9 Screencasts</em></strong>:</p>
<p><em>AzMan</em></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-Getting-Started-with-AzMan/" rel="nofollow">Demystified Series: Getting Started with AzMan</a></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-Programming-AzMan/" rel="nofollow">Demystified Series: Programming AzMan</a></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-AzMan-in-the-Enterprise/" rel="nofollow">Demystified Series: AzMan in the Enterprise</a></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-AzMan-on-Windows-Server-Code-Name-Longhorn-and-Windows-Vista/" rel="nofollow">Demystified Series: AzMan on Windows Server Code Name âLonghornâ and Windows Vista</a></p>
<p><em>ADFS</em></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-Active-Directory-Federation-Services-AD-FS-Part-1/" rel="nofollow">Active Directory Federation Services (AD FS) Part 1 by Keith Brown</a></p>
<p><a href="http://channel9.msdn.com/posts/donovanf/Demystified-Series-Active-Directory-Federation-Services-AD-FS-Part-2/" rel="nofollow">Active Directory Federation Services (AD FS) Part 2 by Keith Brown</a></p>
<p><strong><em>Documentation / Articles</em></strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa480244.aspx" rel="nofollow">Whitepaper on Developing Applications Using Windows Authorization Manager</a></p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc300469.aspx" rel="nofollow">MSDN Article on using Role-Based Security in Your Middle Tier .NET Apps</a></p>
<p><a href="http://technet.microsoft.com/en-us/library/cc780256.aspx" rel="nofollow">Role-Based Access Control for Multi-tier Applications Using Authorization Manager</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms952386.aspx" rel="nofollow">Role-Based Access Control Using Windows Server 2003 Authorization Manager</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa480465.aspx" rel="nofollow">Security Application Block</a></p>
<p><strong><em>Blogs</em></strong></p>
<p><a href="http://blogs.technet.com/adfs_documentation/default.aspx" rel="nofollow">ADFS Documentation Blog</a></p>
<p><a href="http://blogs.technet.com/adfs/" rel="nofollow">ADFS Product Support Blog</a></p>
<p><a href="http://blogs.msdn.com/donovanf/default.aspx" rel="nofollow">Identity and Access Blog (A .NET Developer's Resource)</a></p>
<p><a href="http://www.pluralsight.com/community/blogs/keith/default.aspx" rel="nofollow">Security Briefs (Keith Brown's Blog)</a></p>
<p><a href="http://blogs.msdn.com/azman/" rel="nofollow">Authorization Manager Team Blog</a></p>
<p><a href="http://identity-des.com/" rel="nofollow">Federated Identify Blog</a></p>
<p><a href="http://www.olegsych.com/2008/12/t4-toolbox-strongly-typed-azman-wrapper-generator/" rel="nofollow">T4 Toolbox: Strongly-typed AzMan wrapper generator</a></p>
<p>That's probably more than enough for now, hopefully some of these links will be useful in helping you understand AzMan and how it's role-based access control (RBAC) capabilities can be employed in the claims-based programming model that ADFS uses.</p>
|
Add a link stylesheet dynamically in the <head> <p>How to add a link stylesheet reference to the head of a document ?</p>
<p>I've found this code but it's not working with all browsers, it crashes my IE7 :</p>
<pre><code>var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "style.css";
document.getElementsByTagName("head")[0].appendChild(ss);
</code></pre>
<p>Thanks</p>
| <p>Internet explorer will support innerHTML, though it adds reflow this would work:</p>
<pre><code>var headHTML = document.getElementsByTagName('head')[0].innerHTML;
headHTML += '<link type="text/css" rel="stylesheet" href="style.css">';
document.getElementsByTagName('head')[0].innerHTML = headHTML;
</code></pre>
|
ASP.net: weird url parameter when implment meta refresh on header <p>I was trying to implement Rick's adding meta refresh via header on this <a href="http://www.west-wind.com/Weblog/posts/6841.aspx" rel="nofollow">article</a></p>
<p>For some reason my url look like this </p>
<p><a href="http://localhost/pickweb/" rel="nofollow">http://localhost/pickweb/</a>(S(hp5mypqznxgquf45vzz4fi55))/Login.aspx</p>
<p>What is this "(S(hp5mypqznxgquf45vzz4fi55))" in my url? Even if i remove the code in Rick's blog it still have that weird parameter.</p>
<p>I implement Rick's code </p>
<pre><code>Response.AppendHeader("Refresh", "4; url=profile.aspx");
</code></pre>
<p>in my Master page.</p>
<p>Jack</p>
| <p>Looks like you are using cookieless sessions:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa479314.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa479314.aspx</a></p>
|
PHP landmines in general <p>What surprises have other people found with writing PHP web applications? There's the well known and to be fixed issue with compile time class inheritance but I know of a couple others and wanted to try and build a list of the top gotcha's of the language.</p>
<p>Note: </p>
<p>I've held several positions as a Sr. PHP5 developer so PHP work pays my bills, this question is not meant to bust on PHP as a language as every single language I've worked with has some well known or not so well known surprises.</p>
| <p>I'm not sure if this counts, but the need to compile PHP scripts is a huge performance issue. In any serious PHP project you need some kind of compiler cache like <a href="http://de.php.net/apc" rel="nofollow">APC</a>, <a href="http://eaccelerator.net/" rel="nofollow">eAccelerator</a>, <a href="http://www.php-accelerator.co.uk/" rel="nofollow">PHP Accelerator</a>, or the (commercial) <a href="http://www.zend.com/" rel="nofollow">Zend Platform</a>.</p>
|
Database as fileformat <p>A niave beginners question about database design.<br />
I have an app managing some logger data eg. 1000s of sequential measurements of time, voltage, current, temperature. In addition each sequence run has meta data (date, location, etc).<br />
So I need a table for each set of measurements and a master table listing these tables and the meta data for each. </p>
<p>A couple of questions:<br />
This doesn't really use the fact that all the data tables are the same format - there is no 'array of tables' concept, does this mean anything?</p>
<p>Would I just give each data table a unique name, put that in the main table as a column, then simply substitute it into the SQL select statement - or is there a better way?</p>
<p>edit: The reason for many tables, one per run, is that there might be 10-100 runs each with many 1000s of measurements. If I want to display/query/delete just one run it seemed more natural to have each in it's own table.<br />
It looks like this is a programmer mindset (everything should be collections of separate objects) the database approach seems to prefer - store everything together and use index/cross-references.</p>
| <p>You'd have one table (Run) that stores date/time/location and an integer primary key (auto increment).</p>
<p>You'd have another table (Measurements) that stores time/voltage/current/temp, an integer primary key (auto increment), and a FK to Run (just a not-null integer column called RunID).</p>
<p>So 2 tables total.</p>
|
C++ CLI cryptic function call <p>So I'm trying to call a function that is a manged wrapper around an OCX object. Having great difficulty. Function is;</p>
<pre><code>foo(System::Object ^% theBuffer)
</code></pre>
<p>where 'theBuffer' is an array of bytes. The template for the unmanaged OCX which 'foo' wraps is</p>
<pre><code>goo(VARIANT* theBuffer);
</code></pre>
<p>So I've tried;</p>
<pre><code>System::Int32 buf[10];
foo(buf);
</code></pre>
<p>which fails. And</p>
<pre><code>Bitmap ^b;
foo(b);
</code></pre>
<p>which compiles but obviously the called function is not going to create a .NET bitmap for me. </p>
<p>So I guess the question is how do I pass this function a block of memory it can write to and then get access to it back in .NET world.</p>
<p>Thanks</p>
| <p>You can't convert a <code>VARIANT</code> to the buffer directly.</p>
<p>First you need to check what kind of object is stored in it by checking <code>theBuffer->vt</code>. The returned value will be of the type <code>VARTYPE </code>.</p>
|
What coding tricks have you used to avoid writing more sql? <p>This question was suggested by <a href="http://stackoverflow.com/users/5486/kyralessa">Kyralessa</a> in the <a href="http://stackoverflow.com/questions/488020/what-is-your-most-useful-sql-trick-to-avoid-writing-more-code">What is your most useful sql trick to avoid writing more sql?.</a> I got so many good ideas to try from the last question, that I am interested to see what comes up with this question.</p>
<p>Once again, I am not keeping the reputation from this question. I am waiting 7 days, for answers, then marking it wiki. The reputation that the question has earned, goes into a bounty for the question. </p>
<p>Ground Rules:</p>
<ul>
<li><p>While it is certainly reasonable to write code, to move processing from SQL into the code to address performance issues, that is really not the point of the question. The question is not limited to performance issues. The goal is less simply less sql to get the job done.</p></li>
<li><p>Communicate the concept, so that other users say "Oh Wow, I didn't know you could do that."</p></li>
<li><p>Example code is very useful, to help people that are primarily visual learners.</p></li>
<li><p>Explicitly state what Language you are using, and which dialect of SQL you are using.</p></li>
<li><p>Put yourself in your readers shoes. What would they need to see right there on the screen in front of them, that will cause an epiphany. Your answer is there to benefit the reader. Write it for them.</p></li>
<li><p>Offsite links are ok, if they appear after the example. Offsite links as a substitute for a real answer are not.</p></li>
</ul>
<p>There are probably other things to make it nicer for the reader that I haven't thought of. Get Creative. Share knowledge. Have fun showing off.</p>
<p>[EDIT] - It looks like there hasen't been any activity in a while. 5 votes = 50, so there is the bounty, and it has been wikified.</p>
| <p>If you want to avoid writting SQL use an ORM such as nHibernate, or one of the Microsoft offerings Linq to SQL / Entity Framework</p>
<p>This is even better then using a generator since you won't need to rerun the generators, and if you use Fluent nHibernate you can enable Configuration via Convention and not even maintain a mapping file / class. </p>
|
SmartPhone with a good SDK on Sprint PCS? <p>For as long as mobile phones have been running third-party applications, I've wanted to try my hand at writing some.</p>
<p>Now that it's coming time to replace my PalmOS-powered Treo 530, I'm looking to acquire a new phone that has a robust platform for third-party development. For contractual reasons, it must work on the Spring PCS network.</p>
<p>Ideally, such a phone would have a well-documented API, a well-supported OS, and an emulator that will run under Windows XP or Fedora Core.</p>
<p>Does anybody know of such a phone?</p>
| <p>For Sprint network, you are probably better off with BlackBerry or Windows Mobile device. Only these two have pretty robust SDKs. If this is not for personal/hobby project work and you intend to develop commercial apps for them then you should go for Sprint 3.3.2 SDK. It works for most sprint handsets including touch screen, Qwerty keypad and flip/slider screen handsets.</p>
<p>As you probably wont be aiming for multiple handset support (like my day job) this will be a lot easier.</p>
|
Specify default filegroup for indices? <p>This is puzzling me - in SQL Server 2005/2008, I can specify the default file group which is then used for all data tables. I can also specify another filegroup for all BLOB type fields.</p>
<p>But I cannot figure out if and how I can specify a default filegroup for indices.....</p>
<p>My setup usually is:
* primary filegroup - nothing but the system catalog - bare minimum
* DATA filegroup - which I make the default for my database
* INDEX filegroup for all indices
* BLOB filegroup (optional) for all BLOB data
* LOG (obviuosly)</p>
<p>Now if I create all by tables and indices manually by script, of course I can specify the appropriate file group for each. But is there a way / trick / hack to make it possible to specify where to put the indices? When I use SQL Server Mgmt Studio to e.g. designate a column as primary key on a table, it creates a PK_(tablename) index - but unfortunately, it sticks that into the DATA filegroup, and once it's there, it seems I cannot change it anymore (in the visual designer).</p>
<p>Am I missing something? Or has Microsoft just not provided such a setting??</p>
<p>Thanks for any hints, pointers, leads!</p>
<p>Marc</p>
| <p>If there is a clustered index on a table, the data and the clustered index always reside in the same filegroup. You cannot place the base table and clustered index on separate Filegroups. This is because the clustered index is the actual table data.</p>
<p>You can of course place non-clustered indexes in a different Filegroup from the table they reference.</p>
<p>You cannot specify two default Filegroups i.e. one for data and one for indexes.</p>
<p>Hope this clears things up for you but please feel free to pose further questions.</p>
|
Is there an equivalent to the iSeries OVRDBF command in SQL? <p>I have a requirement in a SQL environment that under specific circumstances, all references to table (or view) A in a procedure actually use table (or view) B. On the iSeries I would have used the OVRDBF command to override references to table A with table B: OVRDBF FILE(A) TOFILE(B). What would be the equivalent to this in SQL? Is there one? </p>
<p>My goal is to end up with a procedure that is ignorant of the override. I don't want conditional logic inside the procedure that directs processing at table B when certain conditions are met. The vision:</p>
<p>Under typical circumstances: Just invoke the procedure</p>
<p>Under specific alternative circumstances: Perform the OVRDBF equivalent and then Invoke the procedure</p>
| <p>Not sure which SQL environment support which options:</p>
<p>I believe DB2 has a CREATE ALIAS statement. Write the SQL over the alias. </p>
<p>Another possibility: run your queries over views: where you would do the OVRDBF, drop the view and rebuild it over the desired table.</p>
|
How do you return more than one DataTable from a method? <p>I have class which has a method that needs to return three DataTables. I thought I could use Generics but honestly I've never used them, so I'm trying figure it out. It may not be the right thing here.</p>
<p>I have in my class Employee:</p>
<pre><code>public List<Employee> GetEmployees()
{
//calls to other methods in my class;
//psuedocode
GetDataTable1;
GetDataTable2;
GetDataTable3;
return all three datatables;
}
</code></pre>
<p>On my presentation side I have three gridviews:</p>
<p>I create my class Employee and call GetEmployees and get back my list of DataTable, then</p>
<pre><code>gridview1.datasource = datatable1;
gridview2.datasource = datatable2;
gridview3.datasource = datatable3;
</code></pre>
<p>I'm not sure how to proceed. I have tried the class method definition above but I'm not getting it right.</p>
<p>Hoping for advice. I do not wish to use three methods. I am using C# and asp.net 2.0.</p>
<p>Thank you.</p>
| <p>You can add them all to a <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx" rel="nofollow">DataSet</a> and return that</p>
|
Language detection in PHP ( UTF-8 ) <p>What code snippets are out there for detecting the language of a chunk of UTF-8 text? I basically need to filter a large amount of spam that happens to be in Chinese and Arabic. There's a PECL extension for that, but I want to do this purely in PHP code. I guess I need to loop through a Unicode string with a unicode version of ord() and then create some kind of a range table for different languages. </p>
| <p>Pipe your text through <a href="http://www.google.com/uds/samples/language/detect.html" rel="nofollow">Google's language detection</a>. You can do this via AJAX. Here is the <a href="http://code.google.com/apis/ajaxlanguage/documentation/" rel="nofollow">documentation/developer's guide</a>. For example:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("language", "1");
function initialize() {
var text = document.getElementById("text").innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en",
function(result) {
var translated = document.getElementById("translation");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="text">ä½ å¥½ï¼å¾é«èè¦å°ä½ ã</div>
<div id="translation"></div>
</body>
</html>
</code></pre>
|
Computing the statistical mode <p>I'm currently trying to verify whether or not, given an unsorted array A of length N and an integer k, whether there exists some element that occurs n/k times or more.</p>
<p>My thinking for this problem was to compute the mode and then compare this to n/k. However, I don't know how to compute this mode quickly. My final result needs to be n*log(k), but I have no idea really on how to do this. The quickest I could find was n*k...</p>
| <p>Use a hash table to count the frequency of each value:</p>
<pre><code>uint[int] counts;
foreach(num; myArray) {
counts[num]++;
}
int mostFrequent;
uint maxCount = 0;
foreach(num, count; counts) {
if(count > maxCount) {
mostFrequent = num;
maxCount = count;
}
}
</code></pre>
|
gedit plugin development in python <p>Does anyone know where information about writing gedit plugins can be found ? I'm interested in writing them in Python. I know of <a href="http://live.gnome.org/Gedit/PythonPluginHowTo">Gedit/PythonPluginHowTo</a>
, but it isn't very good . Besides the code of writing a plugin that does nothing , I can't seem to find more information . I started to look at other people's code , but I think this shouldn't be the natural way of writing plugins . Can someone help ?</p>
| <p>When I started working on my gedit plugin, I used the howto you gave a link to, also startign with <a href="http://www.russellbeattie.com/blog/my-first-gedit-plugin">this URL</a>. Then it was looking at other plugins code... I'm sorry to say that, but for me this topic is poorly documented and best and fastest way is to get a pluging done that actually does something.</p>
|
How can I "subtract" one table from another? <p>I have a master table <code>A</code>, with ~9 million rows. Another table <code>B</code> (same structure) has ~28K rows from table <code>A</code>. What would be the best way to remove all contents of <code>B</code> from table <code>A</code>?</p>
<p>The combination of all columns (~10) are unique. Nothing more in the form a of a unique key.</p>
| <p>If you have sufficient rights you can create a new table and rename that one to A. To create the new table you can use the following script:</p>
<pre><code>CREATE TABLE TEMP_A AS
SELECT *
FROM A
MINUS
SELECT *
FROM B
</code></pre>
<p>This should perform pretty good.</p>
|
Programmatic MSIL injection <p>Let's say I have a buggy application like this:</p>
<pre><code>using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("2 + 1 = {0}", Add(2, 1));
}
static int Add(int x, int y)
{
return x + x; // <-- oops!
}
}
}
</code></pre>
<p>The application is already compiled and deployed into the wild. Someone has found the bug, and now they are requesting a fix for it. While I could re-deploy this application with the fix, its an extreme hassle for reasons outside of my control -- I just want to write a patch for the bug instead.</p>
<p>Specifically, I want to insert my own MSIL into the offending assmembly source file. I've never done anything like this before, and googling hasn't turned up any useful information. If I could just see a sample of how to do this on the code above, it would help me out tremendously :)</p>
<p><strong>How do I programmatically inject my own MSIL into a compiled .NET assembly?</strong></p>
<p>[Edit to add:] To those who asked: I don't need runtime hotswapping. Its perfectly fine for me to have the app closed, manipulate the assembly, then restart the program again.</p>
<p>[Edit one more time:] It looks like the general consensus is "manipulating the assembly is a <strong>bad</strong> way to patch a program". I won't go down that road if its a <a href="http://weblogs.asp.net/alex_papadimoulis/archive/2005/05/25/408925.aspx" rel="nofollow">bad idea</a>.</p>
<p>I'll leave the question open because MSIL injection might still be useful for other purposes :)</p>
| <p>I guess the question I would ask is "how would you deploy the patch"? Somewhere, you have to deploy something to fix a bug that is already out in the wild. Why would recompiling the dll and releasing the fixed version really be an issue? My guess is that figuring out how to programatically inject MSIL is going to be more trouble than simply redeploying a fixed assembly. </p>
|
Is there a CSS parser for C#? <p>My program need to parse css files into an in-memory object format. Any advice on how this should be done ?</p>
| <p>ExCSS (supports CSS2.1 and CSS3) on GitHub: <a href="https://github.com/TylerBrinks/ExCSS">https://github.com/TylerBrinks/ExCSS</a>.</p>
<p>Which is a newer version of the code project article: <a href="http://www.codeproject.com/KB/recipes/CSSParser.aspx">http://www.codeproject.com/KB/recipes/CSSParser.aspx</a></p>
|
Interesting API Design/Pattern <p>I am re-designing part of our internal ORM tool, and I want to expose Field (a class that represents a field in the database, like CustomerFirstName) directly to the end-developer.</p>
<p>So that was easy enough to accomplish, however the API got a little ugly because this Field class was previously used internally and is too open. For instance, and this is just one small example: the IsDirty property was not read-only, and that's something end-developers shouldn't be able to tamper with.</p>
<p>I thought about maybe creating two interfaces, IPublicField and IPrivateField, and trying to get the field class to implement both of them. However, continuing with the IsDirty example, I didn't want something like this:</p>
<pre><code>Public ReadOnly Property PrivateIsDirty Implements IPrivateField.IsDirty
...
End Property
Public Property IsDirty Implements IPublicField.IsDirty
...
End Property
</code></pre>
<p>...It's just a little ugly, plus you could still cast back to the Field class and get into the non-readonly method. I also didn't want to introduce a seperate setter method because it would be another breaking change that I don't want to think about, and it also would create an inconsistency with other parts of the API.</p>
<p>I ended up renaming the Field class to InnerField, and creating a facade/wrapper style structure around it like this:</p>
<pre><code>Public Class Field
Implements BusinessObjects.IField
Private InnerField As BusinessObjects.IInnerField
Public Sub New(ByVal field As IInnerField)
InnerField = field
End Sub
...
Public ReadOnly Property IsDirty() As Boolean Implements BusinessObjects.IField.IsDirty
Get
Return InnerField.IsDirty
End Get
End Property
...
End Class
</code></pre>
<p>This seems to be working out pretty well. Internally, the InnerField is suitably open and we have the freedom to make it more open in the future without impacting end-developers, and externally the Field class provides the simplified, locked down tool that end-developers need.</p>
<p>So, assuming that was coherent, I was wondering how you might have proceeded in this situation, and whether my solution seems reasonable from the outside.</p>
<p>Thanks!</p>
| <p>In the specific case of the isDirty property, you could just restrict the scope of the setters:</p>
<pre><code>public bool IsDirty
{
get
{
// logic here that the end-devs can use safely.
}
private set
{
// logic here that is only exposed to other members of your private
// ORM assembly.
}
}
</code></pre>
|
Custom validation summary <p>I'm using the UpdateModel method for validation. How do I specify the text for the error messages as they appear in the validation summary?</p>
<p><hr /></p>
<p>Sorry, I wasn't entirely clear. When I call UpdateModel(), if there is parsing error, for example if a string value is specified for a double field, a "SomeProperty is invalid" error message is automatically added to the ModelState.</p>
<p>How do I specify the text for said <em>automatically</em> generated error message?</p>
<p>If I implement IDataErrorInfo as suggested, it's error message property gets called for <em>every</em> column, regardless of whether the default binder deems it valid or not.</p>
<p>I'd have to reimplement the parse error catching functionality that I get for free with the default binder.</p>
<p>Incidentally, the default "SomeProperty is invalid" error messages seem to have mysteriously dissappeared in the RC. A validation summary appears and the relevant fields are highlighted but the text is missing! Any idea why this is?</p>
<p>Thanks again and I hope all this waffle makes sense!</p>
| <p><a href="http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/" rel="nofollow">This tutorial</a> is a good example of the <code>IDataErrorInfo</code> technique - it makes adding validation parameters easy by adding them as attributes directly to the properties of the model classes.</p>
<p><a href="http://www.asp.net/learn/mvc/tutorial-29-cs.aspx" rel="nofollow">These</a> <a href="http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx" rel="nofollow">examples</a> also may help - slightly different approaches to validating.</p>
<p>Additionally, <a href="http://stackoverflow.com/questions/1721327/validate-object-based-on-external-factors-ie-data-store-uniqueness/1741831#1741831">this creative idea (which also implements <code>IDataErrorInfo</code>)</a> may be a help to you.</p>
|
2-D (concurrent) HashMap: 2-property key type? hashmap of hashmaps? [update] <p>So I need a 2-dimensional <code>ConcurrentHashMap</code>.</p>
<p>It has to be as blazing fast as possible, as I'm going to be adding to and updating its values extremely frequently. It's in a multithreaded application, hence the choice to use ConcurrentHashMap instead of just HashMap.</p>
<p>Both the "x" and "y" indices are integers with a known range (0 through 40,000,000).</p>
<p>What I need to know is: What's the most efficient way to implement this so it'll be as speedy as possible? The most obvious route is to do a literal 2-D hashmap:</p>
<p><code>ConcurrentHashMap<Integer, ConcurrentHashMap<Integer, ValueObj>> foo;</code></p>
<p>Or I could make a private class "IntPair" with two properties x and y, and use that as a key... though if I do that, what's the most efficient way to do <code>equals()</code> and <code>hashcode()</code>? and will I wind up allocating too many new <code>IntPair</code>s? Could I keep a set of <code>IntPair</code>s for each x/y I've assigned, and then use a purely reflexive equals() such that I'm just checking for the exact same object instance?</p>
<p><hr /></p>
<h2>Update:</h2>
<p>Now that I've taken a closer look at Integer.valueOf(int), the specific caching model it uses wouldn't make sense here, since I'm dealing with a very sparse matrix with unpredictable entries. I really need to be caching all those IntPairs which are used, not a prespecified subset.</p>
<p>Intuitively, it seems to me that looking up an IntPair in a big map to see if I've already created it would, in fact, be more-or-less the same as just looking it up in the big "2-D" ConcurrentHashMap anyway, wouldn't it? So it seems the solution here is really to just use <code>new IntPair(x,y)</code> each time I look up a key. Yes?</p>
| <p><code>ConcurrentHashMap</code> is quite large, so you probably don't want a collection of them.</p>
<p>Short lived objects are actually very fast to allocate. Are you going to have to create the <code>Integers</code> anyway?</p>
<p>You could intern the coordinate objects, but the cost for just a lookup would probably be comparable to creating them anyway. The real win with <code>Integer</code> is that the same instances are shared when you keep around lots of them for some time.</p>
<p>If performance is really a huge issue, you could write (or use) a map-type object that maps longs to references. I wouldn't be surprised to see custom maps out there which also have functionality associated with coordinate systems (like finding nearest or within a range).</p>
|
How to effectively use DTO objects (Data Transfer Objects)? <p>What is the best way to implement DTOs?</p>
<p>My understanding is that they are one way to transfer data between objects. For example, in an ASP.Net app, you might use a DTO to send data from the code-behind to the business logic layer component.</p>
<p>What about other options, like just sending the data as method parameters? (Would this be easiest in asces wher there is less data to send?)</p>
<p>What about a static class that just holds data, that can be referenced by other objects (a kind of global asembly data storage class)? (Does this break encapsulation too much?)</p>
<p>What about a single generic DTO used for every transfer? It may be a bit more trouble to use, but reduces the number of classes needed to work with (reduces object clutter).</p>
<p>Thanks for sharing your thoughts.</p>
| <p>I've used DTO's to:</p>
<ul>
<li>Pass data between the UI and service tier's of a standard 3-tier app.</li>
<li>Pass data as method parameters to encapsulate a large number (5+) of parameters.</li>
</ul>
<p>The 'one DTO to rule them all' approach could get messy, best bet is to go with specific DTO's for each feature/feature group, taking care to name them so they're easy to match between the features they're used in.</p>
<p>I've never seen static DTO's in the way you mention and would hesitate at creating DTO singletons like you describe.</p>
|
What's a good profiler for a CLI based multi-threaded PHP application? <p>I've written a batch processor that runs multiple threads (pcntl_fork) and I'm getting some weird results when child processes go defunct and don't seem to let go of their resources.</p>
<p>Is there a good code profiler, trace utility I can use to 'watch' the parent process and children to see what is going on?</p>
| <p>The only profiler I know of is <a href="http://www.xdebug.org/" rel="nofollow">XDebug</a>. You can process the results with <a href="http://code.google.com/p/webgrind/" rel="nofollow">Webgrind</a> or KCachegrind.</p>
<p>It gives performance statistics about your written PHP code, so you should be able to figure out if the problems are due to your code or some PHP/OS bug.</p>
|
How can you detect when the user clicks on the notification icon in Windows Mobile (.NET CF 3.5) <p>Surfing the net, I came across this:</p>
<p><a href="http://groups.google.com/group/microsoft.public.dotnet.framework.compactframework/msg/d202f6a36c5c4295?dmode=source&hl=en" rel="nofollow">this code</a> that shows how to display a notification at the bottom of the screen on a Windows Mobile device. My question is, is there a way to either specify which options are displayed beneath the notification (on the taskbar) or is there a way to detect when the user clicks on the notification itself, so that I can react to that programmatic ally.</p>
| <p>With this specific API, the key is in the SHNOTIFICATIONDATA's hwndSink member. When the notification is clicked, the hwnd you pass in here will get the click message. For this it's simplest to pass in a <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsce.forms.messagewindow(VS.80).aspx" rel="nofollow">MessageWindow</a>'s handle.</p>
<p>You might also look at the <a href="http://msdn.microsoft.com/en-us/library/ms908104.aspx" rel="nofollow">CeSetUserNotification</a> API instead. It's actually quite a bit more robust in what it allows you to do and how you can get notifications back at the app.</p>
|
PHP XML Parsing <p>Which is the best way to parse an XML file in PHP ?</p>
<p><strong>First</strong><br/>
Using the DOM object </p>
<pre><code>//code
$dom = new DOMDocument();
$dom->load("xml.xml");
$root = $dom->getElementsByTagName("tag");
foreach($root as $tag)
{
$subChild = $root->getElementsByTagName("child");
// extract values and loop again if needed
}
</code></pre>
<p><strong>Second</strong><br/>
Using the simplexml_load Method</p>
<pre><code>// code
$xml = simplexml_load_string("xml.xml");
$root = $xml->root;
foreach($root as $tag)
{
$subChild = $tag->child;
// extract values and loop again if needed
}
</code></pre>
<p>Note :
These are the two I am aware of. If there are more fill in.</p>
<p>Wanted to know which method is the best for parsing huge XML files, also which method is the <strong>fastest</strong> irrespective of the way the method needs to be implemented</p>
<p>Size will be varying from 500KB to 2MB. The parser should be able to parse small as well as large files in the least amount of time with good memory usage if possible.</p>
| <p>It depends on the document you're passing, but XMLReader is usually the faster than both simplexml and DOM (<a href="http://blog.liip.ch/archive/2004/05/10/processing_large_xml_documents_with_php.html" rel="nofollow">http://blog.liip.ch/archive/2004/05/10/processing_large_xml_documents_with_php.html</a>). Personally though I've never used XMLReader and usually decided which to use depending on whether or not I need to edit it:</p>
<ul>
<li>simplexml if I'm just reading a document</li>
<li>DOM if I'm modifying the DOM and saving it back</li>
</ul>
<p>You can also convert objects between simplexml and DOM.</p>
|
Special mouse events in a browser: wheel, right-click? <p>Google maps is an impressive display of what you can do with javascript and Ajaxy-goodness. Even my mouse scroll wheel and right-click works to provide specific functionality.</p>
<p>In the standard HTML spec, I don't see an "onmouserightclick" event or similar basic javascript handling for the mouse wheel. Maybe I am looking in the wrong places.</p>
<p>I presume these events are browser and platform specific (or "sensitive" instead of specific). And am wondering what the basic, plain HTML and Javascript is needed to exploit these events, in ALL browsers.</p>
<p>Naturally, when designing a site these features have to be extra, since some people still use the one-button mouse.</p>
<p>How to I use events with the mouse wheel and right-click? I'm looking for sample code.</p>
<p><strong>EDIT:</strong> Thanks for the jQuery code guys! The system-developer in me still has questions and doubts though. Mainly I'm concerned about platform-limitations that would seem to apply here. Is there a browser that some of these features don't work in? Does the mouse wheel up and down events also allow for mouse wheel click events? I would just expect there to be some limitation out there and am wondering if it's officially documented. I want to know how it works at the low level. I am glad to see it is easy in jQuery, another reason for me to get into it.</p>
| <p><strong><em>Mouse Wheel</em></strong>: <br> ol' no-jquery-or-prototype-library method: <a href="http://adomas.org/javascript-mouse-wheel/" rel="nofollow">here</a></p>
<p>Prototype method: <a href="http://www.ogonek.net/mousewheel/demo.html" rel="nofollow">Here</a></p>
<p>JQuery method: <a href="http://www.ogonek.net/mousewheel/jquery-demo.html" rel="nofollow">Here</a></p>
|
What is the best way of formally expressing usability requirements? <p>I am writing a system requirements document and need to include non-functional requirements relating to the usability of the system, but am not sure of the best way to express this.</p>
<p>"The system shall be easy to use" seems a bit vague to me, and not testable. Are there any 'official' standards/guidelines that can be adhered to relating to the usability of a program?</p>
| <p>Usually, we try to hash out an application-specific definition of 'easy to use'. For example, for our current project, easy to use means:</p>
<p>-All delays in the system longer than .5 seconds will produce a dialog box that says "Please wait."</p>
<p>-It is possible to reach any given system function from the main window in less than 3 clicks.</p>
<p>-It is possible to accomplish any given task with just the keyboard, without the mouse.</p>
<p>-All buttons in the system will adhere to established button convention (link to established button convention regarding size, naming, position, etc.)</p>
<p>-All screens will have a help button. Each help button on a given screen must provide at least one 'topic' for each control on the screen.</p>
<p>-etc.</p>
<p>These sorts of things are testable, and taken together, constitute a 'pretty good' usability standard. That said, nothing substitutes for actual users trying it out.</p>
|
How to open a file for non-exclusive write access using .NET <p>Is it possible to open a file in .NET with non exclusive write access? If so, how? My hope is to have two or more processes write to the same file at the same time.</p>
<p><strong>Edit:</strong> Here is the context of this question: I am writing a simple logging HTTPModule for IIS. Since applications running in different app pools run as distinct processes, I need a way to share the log file between processes. I could write a complex file locking routine, or a lazy writer, but this is a throw away project so its not important.</p>
<p>This is the test code I used to figure out the process.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
namespace FileOpenTest
{
class Program
{
private static bool keepGoing = true;
static void Main(string[] args)
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
Console.Write("Enter name: ");
string name = Console.ReadLine();
//Open the file in a shared write mode
FileStream fs = new FileStream("file.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
while (keepGoing)
{
AlmostGuaranteedAppend(name, fs);
Console.WriteLine(name);
Thread.Sleep(1000);
}
fs.Close();
fs.Dispose();
}
private static void AlmostGuaranteedAppend(string stringToWrite, FileStream fs)
{
StreamWriter sw = new StreamWriter(fs);
//Force the file pointer to re-seek the end of the file.
//THIS IS THE KEY TO KEEPING MULTIPLE PROCESSES FROM STOMPING
//EACH OTHER WHEN WRITING TO A SHARED FILE.
fs.Position = fs.Length;
//Note: there is a possible race condition between the above
//and below lines of code. If a context switch happens right
//here and the next process writes to the end of the common
//file, then fs.Position will no longer point to the end of
//the file and the next write will overwrite existing data.
//For writing periodic logs where the chance of collision is
//small, this should work.
sw.WriteLine(stringToWrite);
sw.Flush();
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
keepGoing = false;
}
}
}
</code></pre>
| <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx">FileShare</a> enumeration when opening the file using File.Open. Specifically, use FileShare.ReadWrite. </p>
|
How would a php or java client authenticate if I'm using WCF w/ forms auth? <p>I have a generic proof of concept WCF service that is using forms authentication to secure access. All works great when my client is .NET (vb code below)</p>
<pre><code>Dim client As SupplierServiceClient = New SupplierServiceClient()
client.ClientCredentials.UserName.UserName = "xxxx@xxx.xx.xx"
client.ClientCredentials.UserName.Password = "password"
Dim SupplierList As List(Of Supplier) = client.GetSuppliers()
</code></pre>
<p>but as I want this to interop w/ anyone who can do SOAP 1.1/1.2 - how would a PHP or Java client connect?</p>
<p>My WCF web.config is listed below (fyi)</p>
<pre><code><system.serviceModel>
<services>
<service name="SampleApplicationWCF.Library.SupplierService" behaviorConfiguration="NorthwindBehavior">
<endpoint address="" name="wsHttpSupplierService" contract="SampleApplicationWCF.Library.ISupplierService" binding="wsHttpBinding" bindingConfiguration="wsHttp"/>
<endpoint address="https://server/SampleApplicationWCF/SupplierService.svc/Basic" name="basicHttpSupplierService" contract="SampleApplicationWCF.Library.ISupplierService" binding="basicHttpBinding" bindingConfiguration="basicHttp"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="basicHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</code></pre>
| <p>I managed to authenticate a PHP client, but not without some effort.
At first, I tried the following:</p>
<pre><code>$header = new stdClass;
$credentials = new stdClass;
$credentials->Username="myuser";
$credentials->Password="mypass";
$header->UsernameToken = $credentials;
$securityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
$client->__setSoapHeaders($securityNamespace, 'Security', $header);
</code></pre>
<p>It didn't work. It seems that PHP5 (v5.3.5 in my case) has a bug preventing the namespace prefix from appearing inside nested header tags.
<a href="http://bugs.php.net/bug.php?id=48966">http://bugs.php.net/bug.php?id=48966</a><br>
I ended up with:</p>
<pre><code><UsernameToken><Username>myuser</Username><Password>myuser</Password></UsernameToken>
</code></pre>
<p>instead of:</p>
<pre><code><o:UsernameToken><o:Username>myuser</o:Username><o:Password>myuser</o:Password></o:UsernameToken>
</code></pre>
<p>So, what I had to do was hardcoding the necessary XML in a variable. This is ugly but working:</p>
<pre><code>$securityNamespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
$headerContent = "<o:Security xmlns:o=\"$securityNamespace\">
<o:UsernameToken>
<o:Username>myuser</o:Username>
<o:Password>mypass</o:Password>
</o:UsernameToken>
</o:Security>";
$headerVar = new SoapVar($headerContent, XSD_ANYXML, null, null, null);
$header = new SoapHeader($securityNamespace, 'o:Security', $headerVar);
$client->__setSoapHeaders(array($header));
</code></pre>
<p>I hope it will be helpful to someone.
Bye!</p>
|
How to compile the generated AS <p>hope you can help me with this question.</p>
<p>So, I've been working for a while with Flex, and had the crazy idea to create pure AS project.</p>
<p>If I compile a Flex app with the -keep flag, the generated actionscript gets generated.</p>
<p>Do you guys know of a way to make it compile, without going trough the code and gluing it all together? </p>
<p>Thanks.</p>
| <p>Generated ActionScript is really only provided for reference; it's not really intended to be repurposed in that sense. Indeed, if you even have any, you've most likely compiled your project already anyway (unless you got it from somewhere else), so one might ask why you'd want to compile the generated stuff rather than your own source -- but nonetheless, although I haven't actually tried it, you should be able to point the Flex compiler <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_13.html" rel="nofollow">mxmlc</a> at your generated source to compile it, provided you're able to get all your dependencies to line up (which may be what you mean by "gluing it all together"). </p>
<p>Just a thought, although again, I haven't actually tried it, so your results may vary. What is it you're trying to do, though? Just curious. :)</p>
|
EXCEL VBA CSV Date formatting issue <p>I am an Excel VBA newbie. My apologies if I am asking what seems to be an obvious question.
I have a CSV text file I am opening in an Excel worksheet. One row of the file contains date information formatted as "YY-MMM', (ie: 9-FEB, or 10-MAY). When the Excel spreadsheet opens the file the date information is changed to "mm/dd/yyyy" format and reads as 02/09/2009 or 05/10/2009 where the YY-MMM is now MM/YY/2009, (ie: the 9-FEB becomes 02/09/2009, and the 10-MAY becomes 05/10/2009). </p>
<p>I would like to know if it is possible to reformat the field from YY-MMM to mm/01/yyyy.</p>
<p>I have tried to parse the date field after converting it to text with </p>
<pre><code>Range("B11", "IV11").NumberFormat = "text"
</code></pre>
<p>However, then the value is a serial date and non-parsable.</p>
<p>I have been unsuccessfully looking for a list of the NumberFormat options.</p>
<p>If you can point me in a direction it will be much appreciated.</p>
| <p>Just to answer a part of your question, here is the list of date formatting options (excluding time):</p>
<pre><code>d = day of month, e.g. 7
dd = zero-padded day of month, e.g. 07
ddd = abbreviated day name, e.g. Thu
dddd = full day name, e.g. Thursday
</code></pre>
<p>pretty much the same for month...</p>
<pre><code>m = month number, e.g. 7
mm = zero padded month number, e.g. 07
mmm = abbreviated month name, e.g. Jul
mmmm = full month name, e.g. July
</code></pre>
<p>years are simpler...</p>
<pre><code>yy = 2 digit year number, e.g. 09
yyyy = 4 digit year number, e.g. 2009
</code></pre>
<p>you can combine them and put whatever separators you like in them</p>
<p>e.g. </p>
<pre><code>YY-MMM, 09-FEB
DDDD-DD-MMM-YY, Wednesday-04-Feb-09
dd/mm/yyyy, 04/02/2009
mm/dd/yyyy, 02/04/2009
</code></pre>
<p>I've just been trying a few things out and I think your best bet is to change the format in the text file to conform to a more standard date arrangement. If you can reverse them (e.g. MMM-YY) you'll be fine, or split them into separate columns (what if when you import you define - as a separator as well as comma?). This is one case where Excel trying to be clever is a pain.</p>
<p>HTH</p>
|
Open web.config from console application? <p>I have a console capplication that runs on the same computer that hosts a bunch of web.config files. I need the console application to open each web.config file and decrypt the connection string and then test if the connection string works.</p>
<p>The problem I am running into is that OpenExeConfiguration is expecting a winforms application configuration file (app.dll.config) and OpenWebConfiguration needs to be run through IIS. Since this is my local machine, I'm not running IIS (I use Visual Studio's built-in server).</p>
<p>Is there a way I can open the web.config files while still getting the robustness of .NET's capabilities to decrypt the connectionstrings?</p>
<p>Thanks</p>
<p><strong>Update</strong>
The OpenWebConfiguration works if you are querying IIS directly or are the website in question that you want to look up the web.config for. What I am looking to accomplish is the same sort of functionality, but from a console application opening up the web.config file of a website on my same machine not using an IIS query because IIS isn't running on my machine.</p>
| <p>Ok I got it... compiled and accessed this so i know it works... </p>
<pre><code> VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(@"C:\test", true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
// Get the Web application configuration object.
Configuration config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
ProtectSection(config, @"connectionStrings", "DataProtectionConfigurationProvider");
</code></pre>
<p>This is assuming you have a file called web.config in a directory called C:\Test.</p>
<p>I adjusted @Dillie-O's methods to take a Configuration as a parameter.</p>
<p>You must also reference System.Web and System.configuration and any dlls containing configuration handlers that are set up in your web.config.</p>
|
How do I limit a user's permission in Sharepoint to a single survey <p>I have a user group set up in Sharepoint that has permission to access to a single site. I would like to restrict this groups access futher to a single survey within that site. Is there any way to set Sharepoint permissions to a more granular level?</p>
| <p>You can give access to only specific lists, views or pages using the Limited Access Permission Level</p>
<p>Go into the list or view that you want to give people access to, go to Settings --> List Settings --> Permissions for this List</p>
<p>You can then give direct rights to users that do not have access to any objects higher up in the hierarchy. </p>
|
Parsing XML from the National Weather Service SOAP Service in C# LINQ to XML <p>I'm a junior C# programmer that's trying to develop a library that will allow me to encapsulate the nasty details of parsing the XML returned from the NWS, and returning a collection representing the data.</p>
<p>My SOAP request would return an XML document in this form:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<dwml version="1.0" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.nws.noaa.gov/forecasts/xml/DWMLgen/schema/DWML.xsd">
<head>
<product srsName="WGS 1984" concise-name="time-series" operational-mode="official">
<title>NOAA's National Weather Service Forecast Data</title>
<field>meteorological</field>
<category>forecast</category>
<creation-date refresh-frequency="PT1H">2009-02-04T20:01:00Z</creation-date>
</product>
<source>
<more-information>http://www.nws.noaa.gov/forecasts/xml/</more-information>
<production-center>Meteorological Development Laboratory<sub-center>Product Generation Branch</sub-center></production-center>
<disclaimer>http://www.nws.noaa.gov/disclaimer.html</disclaimer>
<credit>http://www.weather.gov/</credit>
<credit-logo>http://www.weather.gov/images/xml_logo.gif</credit-logo>
<feedback>http://www.weather.gov/feedback.php</feedback>
</source>
</head>
<data>
<location>
<location-key>point1</location-key>
<point latitude="42.23" longitude="-83.27"/>
</location>
<moreWeatherInformation applicable-location="point1">http://forecast.weather.gov/MapClick.php?textField1=42.23&amp;textField2=-83.27</moreWeatherInformation>
<time-layout time-coordinate="local" summarization="none">
<layout-key>k-p24h-n7-1</layout-key>
<start-valid-time>2009-02-04T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-04T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-05T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-05T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-06T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-06T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-07T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-07T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-08T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-08T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-09T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-09T19:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-10T07:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-10T19:00:00-05:00</end-valid-time>
</time-layout>
<time-layout time-coordinate="local" summarization="none">
<layout-key>k-p24h-n6-2</layout-key>
<start-valid-time>2009-02-04T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-05T08:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-05T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-06T08:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-06T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-07T08:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-07T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-08T08:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-08T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-09T08:00:00-05:00</end-valid-time>
<start-valid-time>2009-02-09T19:00:00-05:00</start-valid-time>
<end-valid-time>2009-02-10T08:00:00-05:00</end-valid-time>
</time-layout>
<parameters applicable-location="point1">
<temperature type="maximum" units="Fahrenheit" time-layout="k-p24h-n7-1">
<name>Daily Maximum Temperature</name>
<value>15</value>
<value>19</value>
<value>33</value>
<value>46</value>
<value>41</value>
<value>43</value>
<value>44</value>
</temperature>
<temperature type="minimum" units="Fahrenheit" time-layout="k-p24h-n6-2">
<name>Daily Minimum Temperature</name>
<value>-2</value>
<value>16</value>
<value>29</value>
<value>32</value>
<value>27</value>
<value>32</value>
</temperature>
</parameters>
</data>
</dwml>
</code></pre>
<p>I'm trying to put the maximum and minimum temps that are inside this XML in separate collections of strings while ignoring the "name" elements using LINQ.</p>
<p>Edit:
This is the code I use to get the XML from the Web Reference:</p>
<pre><code> WeatherNWS.ndfdXML client = new TestNWS.WeatherNWS.ndfdXML();
string XMLZip = client.LatLonListZipCode("48180");
XElement myElement = XElement.Parse(XMLZip);
string[] myString = myElement.Value.Split(',');
decimal lat = Convert.ToDecimal(myString[0]);
decimal lon = Convert.ToDecimal(myString[1]);
weatherParametersType parameters = new weatherParametersType();
parameters.maxt = true;
parameters.mint = true;
string XML = client.NDFDgen(lat, lon, productType.timeseries, DateTime.Now, DateTime.Now.AddDays(7), parameters);
</code></pre>
| <p>This should be able to get the maximum temperatures for you, you would just have to change the where filter to get the minimums</p>
<pre><code> using System.Xml.Linq;
\\...
XDocument xmlDoc = XDocument.Load("YourXml.xml");
var maximums = from tempvalue in xmlDoc.Descendants("temperature").Elements("value")
where tempvalue.Parent.Attribute("type").Value == "maximum"
select (string)tempvalue;
List<string> returnme = maximums.ToList<string>();
return returnme;
</code></pre>
<p>Hope this help.</p>
<p>Note: I'm a bit rusty with my Linq to Xml in C# so it may not be the most elegant solution.</p>
|
objective-c: determining if a regex matches a string <p>What's wrong with the following code?</p>
<pre><code>-(IBAction)numFieldDoneEditing{
NSPredicate * regexTest = [NSPredicate predicateWithFormat: @"SELF MATCHES '^\\d*\\.\\d{2}$'"];
NSString *text = [[NSString alloc] initWithFormat: @"%@", numberField.text];
if ([regexTest evaluateWithObject: text] == YES) {
//do something
}
else{
//do something else
}
[text release];
[regexTest release];
}
</code></pre>
| <p>For some reason, you have to escape your backslashes <em>twice</em> for the <code>\d</code> sequence in the regex specification:</p>
<pre><code>NSPredicate * regexTest = [NSPredicate predicateWithFormat: @"SELF MATCHES '^\\\\d*\\.\\\\d{2}$'"];
</code></pre>
<p>Some other problems with your code:</p>
<ul>
<li>You shouldn't be releasing the <code>regexText</code> object because you're not an owner. It wasn't created with a method named <code>init</code> or <code>copy</code>. See the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html" rel="nofollow">Memory Management Programming Guide for Cocoa</a></li>
<li><p>This is more of a style issue, but if you have a boolean variable, don't compare it for equality with YES or NO, it just makes the code harder to understand. Just test it or its inverse directly. For example:</p>
<pre><code>// Positive test:
if([regexTest evaluateWithObject: text])
; // do stuff
// Negative test
if(![regexTest evaluateWithObject: text])
; // do stuff
</code></pre></li>
</ul>
|
How do I enumerate and load resources in an iPhone app? <p>I'm trying to populate an NSArray with a collection of images in Resources. However, for maximum flexibility, I'm trying to avoid hard-coding the filenames or even how many files there are.</p>
<p>Normally, I'd do something like this example from the sample code at apple:</p>
<pre><code>kNumImages = 5; //or whatever
NSMutableArray *images;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:@"image%d.jpg", i];
[images addObject:[UIImage imageNamed:imageName];
}
</code></pre>
<p>However, I'm trying to avoid kNumImages entirely. Is there a way to run a regex or something on resources?</p>
| <p>Here's a snippet that does just that from my iPhone app</p>
<pre><code>// Load item icons
paths = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:nil];
for (NSString *filename in paths) {
filename = [[filename componentsSeparatedByString:@"/"] lastObject];
if ([filename hasPrefix:@"ItemIcon"]) {
[UIImage imageNamed:filename];
}
}
</code></pre>
<p>It loops through all resources that have a png extension, and it the filename begins with "ItemIcon" then it loads into UIImage's built in cache.</p>
<p>If you have them in a specific directory, you will need to specify the indirectory: argument.</p>
|
print.css is printing very small text <p>My print.css pages are printing out very small, super reduced and the text is like 6 pt.:</p>
<pre><code>@charset "UTF-8";
/* CSS Document */
body {
background: white;
font-size: 12pt;
/* Change text colour to black (useful for light text on a dark background) */
.lighttext
color: #000
}
/* Remove unwanted elements */
#menu, #header, #nav, #prod, #home, #our, #work, #whole, #contact, #circle, #logo, #flower, #navblank, #bottom, .noprint
{
display: none;
}
#wrapper, #content {
width: auto;
margin: 0 5%;
padding: 0;
border: 0;
float: none !important;
color: black;
background: transparent none;
}
div#content {
margin-left: 10%;
padding-top: 1em;
border-top: 1px solid #930;
}
div#mast {
margin-bottom: -8px;
}
div#mast img {
vertical-align: bottom;
}
a:link, a:visited {
color: #520;
background: transparent;
font-weight: bold;
text-decoration: underline;
}
#content a:link:after, #content a:visited:after {
content: " (" attr(href) ") ";
font-size: 90%;
}
#content a[href^="/"]:after {
content: " (http://www.alistapart.com" attr(href) ") ";
}
</code></pre>
<p>Do not understand why - does anyone have any suggestions to correct the output of this print.css?</p>
| <p>As pt stands for points being 1/72th of an inch I would hazard a guess that it may be down to screen size, although in reality it could be any number of things. We'd really need more information.</p>
<p>Have you tried using em's instead? They're the best way of dealing with font sizes.</p>
|
Should I use Java's String.format() if performance is important? <p>We have to build Strings all the time for log output and so on. Over the JDK versions we have learned when to use <code>StringBuffer</code> (many appends, thread safe) and <code>StringBuilder</code> (many appends, non-thread-safe).</p>
<p>What's the advice on using <code>String.format()</code>? Is it efficient, or are we forced to stick with concatenation for one-liners where performance is important?</p>
<p>e.g. ugly old style,</p>
<pre><code>String s = "What do you get if you multiply " + varSix + " by " + varNine + "?");
</code></pre>
<p>vs. tidy new style (and possibly slow),</p>
<pre><code>String s = String.format("What do you get if you multiply %d by %d?", varSix, varNine);
</code></pre>
<p>Note: my specific use case is the hundreds of 'one-liner' log strings throughout my code. They don't involve a loop, so <code>StringBuilder</code> is too heavyweight. I'm interested in <code>String.format()</code> specifically.</p>
| <p>I took <a href="http://stackoverflow.com/a/513705/1845976">hhafez</a> code and added a <strong>memory test</strong>:</p>
<pre><code>private static void test() {
Runtime runtime = Runtime.getRuntime();
long memory;
...
memory = runtime.freeMemory();
// for loop code
memory = memory-runtime.freeMemory();
</code></pre>
<p>I run this separately for each approach, the '+' operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches.
I added more concatenations, making the string as "Blah" + i + "Blah"+ i +"Blah" + i + "Blah".</p>
<p>The result are as follow (average of 5 runs each):<br/>
<strong>Approach Time(ms) Memory allocated (long)<br/>
'+' operator 747 320,504<br/>
String.format 16484 373,312<br/>
StringBuilder 769 57,344<br/></strong></p>
<p>We can see that String '+' and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use.
This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won't get to clean the many string instances resulting of the '+' operator.</p>
<p>And a note, BTW, don't forget to check the logging <strong>level</strong> before constructing the message.</p>
<p>Conclusions:</p>
<ol>
<li>I'll keep on using StringBuilder.</li>
<li>I have too much time or too little life.</li>
</ol>
|
Non-working alpha in Flash Player 6 [Given Up On] <p>I've got a flash project that due to requirements has to be backward compatible with flash 6. Everything works, except the first 6 (of 17) jpeg images that are loaded by <MovieClip>.loadMovie don't respond to changes to their alpha setting.</p>
<p>If I rearrange the order of the images in the XML file that is used to provide the image urls to the flash movie, the new first six images fail to respond to alpha and the old six will respond to alpha.</p>
<p>Any ideas as to what might be the cause?</p>
<p>Edit:
I had added code to try and wait for the images to load completely first using onClipEvent(data). The images appear to pre-load before the animation starts but the alpha property still doesn't work.</p>
<p>Edit 2:
I justed used a wipe type transition instead of a fade. I hope to never have to use flash 6 again.</p>
| <p>Are you waiting for all the images to load properly before you change their alpha?
You need to listen for the INIT event (not sure of the exact name in as2) for them to be available to your code.</p>
|
Offscreen rendering to a texture in a win32 service <p>I'm trying to write a C++ windows service that can render to a texture. I've got the code working as a regular console app, but when run as a service <code>wglGetProcAddress()</code> returns NULL.</p>
<p>Can anyone tell me if this is possible, and if so, what do I need to do to make OpenGL work inside a service process? </p>
<p><hr /></p>
<h3>Edit:</h3>
<p>I still haven't got this to work under Vista, but it does work under XP.</p>
| <p>You can get a fully capable software renderer by using Mesa3D.
Simply build Mesa3D and put the opengl32.dll built there alongside your application.
This should enable you to use OpenGL 2.1 and extensions.
We use this for testing Opengl applications in a Windows service.</p>
|
vbscript: test for existence of a column in a recordset <p>Bah, vbscript. </p>
<p>I'm trying to figure out how to get this statement to work: </p>
<pre><code>if (not rsObject("columnNameThatDoesntExist") is nothing) then
' do some stuff
end if
' else do nothin
</code></pre>
<p>Where rsObject is a RecordSet and columnNameThatDoesntExist is ... well you know. I'm looking for something like rsObject.Columns.Contains(string). But of course can't find it. </p>
<p>Edit: Looks like looping rsObject.Fields is an option, is that the only way to do this? </p>
| <p>I am sure you have your reasons, but if you don't know what fields you are calling back from your database, you could always use On Error Resume Next and On Error Goto 0 to ignore the tossed error. Seems like a bad way to me, but it would work</p>
<pre><code>blnItWasntThere = True
On Error Resume Next
If (rsObject("columnNameThatDoesntExist") <> "") Then
blnItWasntThere = False
...
...
...
End If
On Error Goto 0
If blnItWasntThere Then
'handle this error'
End If
</code></pre>
<p>But with that said, I think you would be more worried about the mystery recordset you are getting back.</p>
<p>Or make your own function</p>
<pre><code>Function ColumnExists(objRS, Column)
Dim blnOutput, x
blnOutput = True
On Error Resume Next
x = objRS(Column)
If err.Number <> 0 Then blnOutput = False
On Error Goto 0
ColumnExists = blnOutput
End Function
</code></pre>
|
Is there a way to access an iframe's window object from the canvas in FBJS? (facebook) <p>From the facebook canvas, I need to be able to access an iframe window. Normally you could do this with window.frames, but FJBS doesn't seem to allow access to the window object.</p>
<p>Has anyone figured out how to access window objects?</p>
| <p>you could try this. Let me know how it works. </p>
<pre><code>var myIframe = document.getElementById('myIframeId');
// could retrieve window or document depending on the browser
// (if FBJS allows it!?)
var myIframeWin = myIframe.contentWindow || myIframe.contentDocument;
if( !myIframeWin.document ) { //we've found the document
myIframeWin = myIframeWin.getParentNode(); //FBJS version of parentNode
}
</code></pre>
|
Delphi Prism / VS 2008: Switching from code to design with one key? <p>I've used several Versions of the Delphi IDE for many years. When I'm using Delphi Prism, I have to deal with Visual Studio - in my case especially VS 2008. </p>
<p>One of the most annoying things to me is that I have to right-click on my form to switch to the code editor and vice versa. In Delphi, one could simply press the <kbd>F12</kbd> key to switch between code and form designer. </p>
<p>Is there a way to let this shortcut work in Visual Studio? It seems to me that I at least need 2 shortcuts when I take a look at the Keyboard options.</p>
| <p>You can use default keys:</p>
<ul>
<li>From "Form Designer" - <kbd>F7</kbd></li>
<li>From Code To "Form Designer" - <kbd>Shift</kbd> + <kbd>F7</kbd></li>
</ul>
|
Some data changes in the database. How can I trigger some C# code doing some work upon these changes? <p>Suppose I have some application A with a database. Now I want to add another application B, which should keep track of the database changes of application A. Application B should do some calculations, when data has changed. There is no direct communication between both applications. Both can only see the database.</p>
<p>The basic problem is: Some data changes in the database. How can I trigger some C# code doing some work upon these changes?</p>
<p><hr /></p>
<p>To give some stimulus for answers, I mention some approaches, which I am currently considering:</p>
<ol>
<li>Make application B polling for
changes in the tables of interest.
Advantage: Simple approach.
Disadvantage: Lots of traffic,
especially when many tables are
involved.</li>
<li>Introduce triggers, which will fire
on certain events. When they fire
they should write some entry into an
âevent tableâ. Application B only
needs to poll that âevent tableâ.
Advantage: Less traffic.
Disadvantage: Logic is placed into
the database in the form of triggers.
(Itâs not a question of the
âevilnessâ of triggers. Itâs a design
question, which makes it a
disadvantage.)</li>
<li>Get rid of the polling approach and
use SqlDependency class to get
notified for changes. Advantage:
(Maybe?) Less traffic than polling
approach. Disadvantage: Not database
independent. (I am aware of
OracleDependency in ODP.NET, but what
about the other databases?)</li>
</ol>
<p>What approach is more favorable? Maybe I have missed some major (dis)advantage in the mentioned approaches? Maybe there are some other approaches I havenât think of?</p>
<p><hr /></p>
<p>Edit 1: Database independency is a factor for the ... let's call them ... "sales people". I can use SqlDependency or OracleDependency. For DB2 or other databases I can fall back to the polling approach. It's just a question of cost and benefit, which I want to at least to think about so I can discuss it.</p>
| <p>I would go with solution #1 (polling), because avoiding dependencies and direct connections between separate apps can help reduce complexity and problems.</p>
|
How can you work around the re-sending of the http referrer data on refresh in php? <p>I have a IN/OUT ratio hit counting system on my site. When a user is sent to my site, I grab the referrer, strip the domain, look up the domain and +1 to hits_in. Very simple. What I discovered thou is, if a user refreshes the page, the referrer is resent to the site, and it counts it as another +1. Whats even worse is that if user clicks on some link on the site, and then hits BACK to go to the original page, the referrer is resent, and it counts as another +1. So if a foreign site sends me 1 user, who clicks on a video link, views the video, hits BACK in his browser, and then does this 3 times, it will count as if a site sent me 4 users when in fact its just 1.</p>
<p>Any way I could prevent the 2 examples from happening without actually logging all IPs and checking access times for each IP before doing the +1. </p>
| <p>I am not expert in this, but can't you just use sessions. temporarily store referred url into session, so if user clicks back than check if users session contains referral site. if it contains don't count.</p>
|
Do I understand Ajax correctly? <p>I'm been reading up on Ajax and would like to see from the stackoverflow community if I'm understanding everything correctly.</p>
<p>So the normal client server interaction is a user pulls up a web browser types in a url and a HTTP request is sent to the server requesting the page and resources( css, pics ) from the web server. The web server responds to the client via HTTP the page/resources requested and the browser renders the html/JavaScript for the user to view the page.</p>
<p>1) So would it be safe to say that XMLHttpRequest( XHR ) object is doing the same process as the browser except your not requesting html from the server, your requesting text in some type of format?</p>
<p>2) Is it true that a XHR object is much like a regular object that can be manipulated by the program creating the object( like a normal object ), but also sends and receives data with another program( web server ) via HTTP? </p>
<p>3) So in my mind when a XHR is created it is loaded into memory and we setup some of the objects arguments when we do the request.open(âGETâ, url, true). Once we do a request.send(null) the object basically attempts to âGETâ the url via HTTP and once we get the data back from the server it is put in the responseText argument. Am I understanding this correctly?</p>
<p>4) Also synchronous vs asynchronous. When I think of synchronous I think of steps having to be followed in order. For example, I push a button, data gets sent to server, and I have to wait for data to come back before I can do anything else. With asynchronous connections I would push button, data gets sent to server, I do what ever I want while data gets sent back. Is this a good analogy?</p>
| <p>1) Nope. The XMLHttpRequest object does exactly what its name implies -- it initiates an HTTP request. This request can be in XML, or HTML, or PHP. At the end of the day, the browser doesn't care, because in an AJAX request, it doesn't parse the request -- you have to do it yourself. So it doesn't automatically render the HTML from an AJAX request.</p>
<p>2) <s>I'm not sure about manipulation (the XHR object may be immutable) but possibly. Would you ever need to extend it or manipulate it? </s>
Yes, you can change properties of the object and so on. I apologize. I didn't understand you at first :)</p>
<p>3) Yep.</p>
<p>4) That's a great analogy. It's exactly what happens. Another analogy is a 4 lane highway is to asynchronous as a one-way street is to synchronous. If one car breaks down on the 4 lane highway, the rest can keep moving at their normal speed -- but if one breaks down on the one-way road, everything freezes. :)</p>
|
How can I avoid the bluish border when clicking a HyperlinkButton in Silverlight? <p>I have a Silverlight menu for my application with an image as the background. I use some empty HyperlinkButton at a specific position and size to simulate a real button on the image (think as a HTML image-map):</p>
<pre><code><HyperlinkButton x:Name="Portfolio" Width="86" Height="40" Canvas.Top="50" NavigateUri="/portfolio"/>
<HyperlinkButton x:Name="Analysis" Width="79" Height="40" Canvas.Top="50" Canvas.Left="124" NavigateUri="/analysis" BorderThickness="0"/>
<HyperlinkButton x:Name="News" Width="77" Height="40" Canvas.Top="50" Canvas.Left="240" NavigateUri="/news"/>
<HyperlinkButton x:Name="Questions" Width="80" Height="40" Canvas.Top="50" Canvas.Left="357" NavigateUri="/questions"/>
<HyperlinkButton x:Name="Companies" Width="80" Height="40" Canvas.Top="50" Canvas.Left="477" NavigateUri="/companies"/>
</code></pre>
<p>The problem is when I click these buttons it shows a bluish border corresponding to the hyperlink button area during the click event. There is a way I can avoid showing that?</p>
| <p>I found the answer in other blog, just set IsTabStop="False" in the HyperLinkButton instance.</p>
|
Webforms App Layout Opinions? <p>I have a very simple webforms app that will allow field techs to order parts from the warehouse.<br />
Essentially it work like so:<br /></p>
<ol>
<li>User selects a category from a filter dropdown, which then binds items of that category to a gridview control<br />
<li>User finds an item in the gridview and inputs a desired quantity (in a text box in a template field in each row)<br />
<li>User repeats 1 & 2 as needed<br />
<li>User sees a summary of the complete requisition<br />
<li>User confirms items and submits the requisition for processing
</ol>
<p>My no-brainer UI design so far is the generic dropdown-above-a-gridview where there's a category drop-down list that filters a gridview, like in the eye-catching asp.net ado tutorials:</p>
<p>Â Â Â Â <img src="http://static.asp.net/asp.net/images/dataaccess/15fig01vb.png" width="500" height="350"></p>
<p>Each gridview row (in my app, not in the image above) lists an item's details and can accept a quantity input in the template textbox if the user wants to requisition that item.</p>
<p>Given that a user will want items from different categories during a single usage session, I'm trying to figure out a good, user-friendly way to allow users to input a quantity for an item, have a warm fuzzy feeling that their input has been accepted/stored, then change the category filter (thus binding the gridview to a different set of data) and select other items from the gridview as many times as necessary before summing up their order and submitting it.</p>
<p>I've thought about putting another grid below the first and adding items to it dynamically as the user selects each item. But that seems awkward. Ditto with an unordered list or similar simple structure under the grid.</p>
<p>I've also thought about just storing the user's picks in view state or session state and displaying a summary on another page, kind of like a shopping cart sort of functionality. Maybe do that and use some sort of ajaxy goodness on the main page to display something warm and fuzzy when a quantity is input?</p>
<p>WWYD? What Would You Do?</p>
<p>TIA.</p>
| <p>Probably because both your choices are fine - it comes down to personal preference. The shopping cart idea is well known. But sometimes it gets old if you have to keep going back and forth between the cart and the item selection.</p>
<p>What's wrong with the separate grid? -That way you keep the selection list separate from the ordered items list?</p>
|
HTML document to PDF? <p>I've got an ASP.NET web page that is a dynamically generated report. For business reasons, this exact report needs to be produced as a PDF. What's the best way to do this? Setting the selected printer to Adobe PDF is not an option.</p>
<p>Learn to programmatically create PDFs from scratch? Is there a way to render it in some browser control, then save the ouput?</p>
| <p><a href="http://code.google.com/p/wkhtmltopdf/" rel="nofollow">wkhtmltopdf</a> - I compiled it in Windows and it works great. It uses WebKit (Safari, Chrome, etc.) to render an HTML page into PDF, and it is free!</p>
|
Web server config - shttpd/Mongoose <p><a href="http://code.google.com/p/mongoose/" rel="nofollow">http://code.google.com/p/mongoose/</a><br />
<a href="http://shttpd.sourceforge.net/shttpd.1.txt" rel="nofollow">http://shttpd.sourceforge.net/shttpd.1.txt</a></p>
<p>Trying to configure the lightweight web server shttpd now called mongoose to execute CGI scripts in C. </p>
<p>Does it need a seperate CGI interpreter for C? </p>
<p>A download of shttpd on source forge had separate interpreter exe for perl and php cgi but not sure if that means I need one in C... </p>
| <p>Actually, with tiny C compiler (http://bellard.org/tcc/) it is very possible to run .c files as scripts. Just add <code>#!/usr/local/bin/tcc -run</code> at the first line of your C source.</p>
|
Parse filter expression using RegEx <p>I have a query filter written in human readable language. I need to parse it and convert to the SQL where clause. Examples are:</p>
<pre><code>CustomerName Starts With 'J'
</code></pre>
<p>becomes</p>
<pre><code>CustomerName LIKE 'J%'
</code></pre>
<p>and </p>
<pre><code>CustomerName Includes 'Smi'
</code></pre>
<p>becomes</p>
<pre><code>CustomerName LIKE '%Smi%'
</code></pre>
<p>The full expression to be parsed may be much more complicated such as</p>
<pre><code>CustomerName Starts With 'J' AND State = 'CA'
</code></pre>
<p>should become</p>
<pre><code>CustomerName LIKE 'J%' AND State = 'CA'
</code></pre>
<p>What is the best way to go about this? Can it be done easily with RegEx (I am not a regex expert).</p>
| <p>In the absence of other answers I'll chuck in my 2 cents:</p>
<p>It seems to me that you're actually creating a new language, albeit one that's very similar to an existing one. So I suspect there are many techniques from the field of computer language interpretation that could make this a simpler task.</p>
<p>The other thing to be cautious of are accidental (or intentional) SQL injection problems.</p>
<p>I've not tackled a task like this, but if I were approaching this using Regex I'd be tempted to have a separate method for each new syntax and then pass that input to each of the methods. For example here's how I might handle the 'Start With' syntax.</p>
<pre><code> public void Main()
{
string input = @"CustomerName Starts With 'J' AND State = 'CA'";
ReplaceStartsWith(ref input);
//...
//ReplaceIncludes(ref input);
Console.WriteLine(input);
//Returns: CustomerName LIKE 'J%' AND State = 'CA'
}
void ReplaceStartsWith(ref string input)
{
input = startsWithRegex.Replace(input, match =>
string.Format("LIKE '{0}%'", match.Groups["literal"]));
}
&nbsp;
static RegexOptions commonOptions =
RegexOptions.Compiled |
RegexOptions.ExplicitCapture |
RegexOptions.IgnoreCase |
RegexOptions.IgnorePatternWhitespace |
RegexOptions.Singleline;
&nbsp;
static Regex startsWithRegex = new Regex(
@"\bstarts\s+with\s+'(?<literal>[^']*)'"
, commonOptions);
</code></pre>
|
In an Atom feed is it ok to change the "updated" field when an entry has its content changed? <p>If an Entry represents some file/resource that has changed - is it enough to change the updated field? I note that most feed readers won't show it as "new" as it has the same UUID? </p>
<p>rfc4287 says that I can change it, but feed readers seem to ignore it. </p>
| <p>Well from looking at this, rf4287 says its fine to update a resource and its updated field. However, if you want feed readers to pick it up as a fresh item - you need to think of an Entry representing a change, not so much 1 to 1 with an underlying resource. </p>
|
How to validate numeric input C++ <p>I'd like to know how to limit an input value to signed decimals using <code>std::cin</code>.</p>
| <p>If the backing variable of the <code>cin</code> is a number, and the string provided is not a number, the return value is false, so you need a loop:</p>
<pre><code>int someVal;
while(!(cin >> someVal)) {
cin.reset();
cout << "Invalid value, try again.";
}
</code></pre>
|
How to leave URL parameters unescaped in ASP.NET MVC? <p>I've noticed the returnurl URL parameter on the Stackoverflow login/logout links are not escaped but when I try to add path as a parameter to a route it gets escaped.</p>
<p>So /login?returnurl=/questions/ask shows /login?returnurl=%2fquestions%2fask and it's kind of ugly. How do I get it to not escape the returnurl value?</p>
<p>Here's what I'm doing in the code:</p>
<pre><code>Html.ActionLink("Login", "Login", "Account", new { returnurl=Request.Path }, null)
</code></pre>
| <blockquote>
<p>How do I get it to not escape the
returnurl value</p>
</blockquote>
<p>How's about this?</p>
<pre><code>var url = Url.Action("Login", "Account", new {returnurl = Request.Path});
var unEncodedUrl = HttpUtility.UrlDecode(url);
Response.Write("<a href='" + unEncodedUrl + "'>...</a>");
</code></pre>
<p>Be sure that's what you want though, <a href="http://en.wikipedia.org/wiki/Percent-encoding">URL encoding has its purpose.</a></p>
|
RegEx: HTML whitelist <p>Being weak on regular expressions, I've been working with them to improve. One concept I've been trying to do is to remove all HTML elements except for a list of allowed ones.</p>
<p>I've managed to do the reverse -- remove a specified list of elements:</p>
<pre><code><\/?(strong|em|a)[^>]*>
</code></pre>
<p>However I want the opposite, and remove every element but.</p>
| <p><a href="http://kore-nordmann.de/blog/do_NOT_parse_using_regexp.html" rel="nofollow">Do NOT try parsing with regular expressions</a></p>
<p>Instead use a <a href="http://grom.zeminvaders.net/html-sanitizer" rel="nofollow">real parser</a></p>
|
struts2 problem in action <p>I've started an application using struts 2.0.14 and web server is apache tomcat 6.0.
I am getting an error, please help me to solve this.</p>
<p>Application name: <strong>strutsTest</strong></p>
<p>Welcome page: <strong>EmpDetails.jsp</strong> in a package named â<strong>validTest</strong>â having action like:</p>
<pre><code><s:form action="takeAction" method="post>
</code></pre>
<p>Action class: Employee.java and also I wrote Employee-validation.xml.</p>
<p>Now when I run my application it opens with following url: <code>http://localhost:8080/strutsTest/validTest/empDetails.jsp</code></p>
<p>There is only textbox in empDetails.jsp named email and I am validating this textbox using employee-validation.xml
To test this I entered an invalid email and got an error message on the top of same welcome page (empDetails.jsp). But this url changed to:
<code>http://localhost:8080/strutsTest/validTest/takeAction.action</code></p>
<p>Not an issue. Now, I entered valid email and submit but got an error message instead of next page i.e thanks.jsp and url has changed to - </p>
<p><code>http://localhost:8080/strutsTest/takeAction.action</code></p>
<p>Error is:</p>
<pre>
HTTP Status 404 - /strutsTest/thanks.jsp
type Status report
message /strutsTest/thanks.jsp
description The requested resource (/simpleStruts2.0.14/thanks.jsp) is not available.
</pre>
| <p>From your description, the validation part is excluded for your problem. In your struts.xml file, you may have configure the result as:</p>
<pre><code><action name="takeAction" ...>
<result>/simpleStruts2.0.14/thanks.jsp</result>
</action>
</code></pre>
<p>The result page: /simpleStruts2.0.14/thanks.jsp is not available(so HTTP 404 response), you may changed to something like this:</p>
<pre><code><result>/validTest/thanks.jsp</result>
</code></pre>
|
Is there any way to determine how many characters will be written by sprintf? <p>I'm working in C++.</p>
<p>I want to write a potentially very long formatted string using sprintf (specifically a secure counted version like _snprintf_s, but the idea is the same). The approximate length is unknown at compile time so I'll have to use some dynamically allocated memory rather than relying on a big static buffer. Is there any way to determine how many characters will be needed for a particular sprintf call so I can always be sure I've got a big enough buffer?</p>
<p>My fallback is I'll just take the length of the format string, double it, and try that. If it works, great, if it doesn't I'll just double the size of the buffer and try again. Repeat until it fits. Not exactly the cleverest solution.</p>
<p>It looks like C99 supports passing NULL to snprintf to get the length. I suppose I could create a module to wrap that functionality if nothing else, but I'm not crazy about that idea.</p>
<p>Maybe an fprintf to "/dev/null"/"nul" might work instead? Any other ideas?</p>
<p>EDIT: Alternatively, is there any way to "chunk" the sprintf so it picks up mid-write? If that's possible it could fill the buffer, process it, then start refilling from where it left off.</p>
| <p>The man page for <code>snprintf</code> says:</p>
<pre>
Return value
Upon successful return, these functions return the number of
characters printed (not including the trailing '\0' used to end
output to strings). The functions snprintf and vsnprintf do not
write more than size bytes (including the trailing '\0'). If
the output was truncated due to this limit then the return value
is the number of characters (not including the trailing '\0')
which would have been written to the final string if enough
space had been available. Thus, a return value of size or more
means that the output was truncated. (See also below under
NOTES.) If an output error is encountered, a negative value is
returned.
</pre>
<p>What this means is that you can call <code>snprintf</code> with a size of 0. Nothing will get written, and the return value will tell you how much space you need to allocate to your string:</p>
<pre><code>int how_much_space = snprintf(NULL, 0, fmt_string, param0, param1, ...);
</code></pre>
|
Is there a way to generate a DLL file from Visual Studio Express without explicitly creating a DLL project? <p>Is there a way to generate a DLL file from Visual Studio Express without explicitly creating a DLL project?</p>
<p>EDIT:
Maybe my thinking process has gone astray on me, but I am trying to setup NUnit, and thought is needed a dll to run it... Please correct me if I am wrong.</p>
| <p>Yes, you can change the Project Properties|Application|Output Type to either Windows Application, Console Application or Class Library, thus by selecting Class Library you will output a DLL.</p>
<p>I struggle to think why you'd want to do this though?</p>
|
Are Concurrent SQL inserts into the same table transactionally safe? <p>I have a simple table in MySql whose raison-d'être is to store logs.
The table has an autoincremented sequence and all the other columns has zero referential integrity to other tables. There are no unique keys or indexes on any columns. The column with autoincrement is the primary key.</p>
<p>Will concurrent INSERTs ever interfere with each other ? I define <strong>interference</strong> to mean losing data.</p>
<p>I am using autocommit=true for this insert.</p>
| <p>You'll never lose data just because you do simultaneous inserts. If you use transactions you might "lose" some IDs - but no actual data. (Imagine that you start a transaction, insert a few rows and then do a rollback. InnoDB will have allocated the auto_increment IDs , but there are no rows with those IDs because you did the rollback).</p>
<p>Since you don't need indexes, you should have a look at the ARCHIVE table engine. It's amazingly insanely fast -- and your tables gets much smaller which in turn makes the table scans when you read the table later MUCH faster.</p>
|
What copy protection technique do you use? <p>I'm thinking about adding some kind of copy protection to one of my tools. </p>
<ul>
<li>Do you have any experience with that?</li>
<li>Have you developed your own protection techniques or did you buy 3rd party software?</li>
<li>Do you think it is a viable method to increase sales? (In a private and/or corporate environment)</li>
<li>What do you do to prevent hassling your paying customers? In most cases it's the <em>paying</em> customers who suffer from a bad copy protection, and I don't want this to happen to my customers. (Even if that means accepting some freeloaders)</li>
</ul>
<p>I'm especially interested in techniques which allow a trial or freeware version of your software for private use but limit the usefulness in a corporate environment.</p>
<p><hr /></p>
<p><strong>Related Question</strong>: <a href="http://stackoverflow.com/questions/109997/how-do-you-protect-your-software-from-illegal-distribution">How do you protect your software from illegal distribution</a><br />
<strong>Related Question</strong>: <a href="http://stackoverflow.com/questions/506282/protect-net-code-from-reverse-engineering/">Protect .NET code from reverse engineering.</a><br />
<strong>Related Question</strong>: <a href="http://stackoverflow.com/questions/203229/preventing-the-circumvention-of-copy-protection">Prevent the circumvention of copy protection.</a> </p>
| <p>Whatever technique you use, your software will be copied. The actual aim of copy protection is to prevent honest customers from being tempted to be unfair.</p>
<p>The minimum copy protection technique is enough. The maximum is not worth the time spent.</p>
<p>Moreover, I've heard that some developers provide user support to any user who asks, customer or not. The idea is that happy users may become faithful customers.</p>
|
DAM Solutions for full-length movies <p>Are there any DAM (Digital Asset Management) solutions in the market that can handle storage & classification of full length movies (10 GB and greater).
Have heard of solutions from EMC Documentum, Artesia, Oracle UCM and the like but not sure if they handle file sizes this large ? Any open-source systems ?</p>
| <p>I am going to go out on a a limb and say 'No'. There may be some custom ones around, but I have not seen anything that could handle videos of that size.</p>
<p>Personally, I have implemented the image portion of Oracle's DAM (still owned by Stellent at the time). I remember the tech being optimized for short streaming videos. </p>
<p>In Aust, ABC recently launched a streaming service;
<a href="http://www.abc.net.au/iview/" rel="nofollow">http://www.abc.net.au/iview/</a>
This, like other I have seen that are similar, seem to be limited to episodes or shows limited to 1/2 or single hour blocks.</p>
<p>Actually, 10gb seems like a crazy size to be entered into a CM system. As CM implies the files will be shared/ available remotely.
Are the videos uncompressed?
Do you want to stream/provide them across the network?
I would be interested to know some more details on the system you are after.</p>
|
Why does GCC look at private constructors when matching functions? <p>I'm very busy write now debugging some code, so I can't cookup a complete example, but this basically describes my problem </p>
<pre><code>class Base{};
class MyX:public Base
{
...
};
class Derived:Base
{
...
};
template<class X>
class MyClass:Derived
{
private:
MyClass(const MyClass& )
:x()
{}
public:
MyClass(const X& value)
:x(value)
{}
};
....
MyX x;
MyClass<MyX>(x);
</code></pre>
<p>This gives me an error like this:</p>
<pre><code>error: there are two possible constrcutors MyClass<X>(const MyClass<X>&) and MyClass<X>(const X&)
</code></pre>
| <pre><code>MyClass<MyX>(x);
</code></pre>
<p>is parsed as </p>
<pre><code>MyClass<MyX> x;
</code></pre>
<p>But <code>MyClass<MyX></code> does not have a default constructor. Try giving it a name:</p>
<pre><code>MyClass<MyX> p(x);
</code></pre>
|
Selenium Grid + Maven 2 <p>Is there a good tutorial or does anyone have experience with setting this up ?
I have a Testsuite.html which launches my tests in one browser atm. This is done in the integration-test lifecycle by the maven selenium plugin. I want to run my tests on multiple browsers. I couldn't find any documentation about selenium grid + maven. I hope somebody can help me.</p>
<p>Thanks in advance, kukudas</p>
| <p>Selenium Grid and maven are really not much different than Selenium and maven.</p>
<p>Grid is basically a drop-in replacement for selenium-rc. In our current setup we let the automated build system use Grid. It does this by simply changing the selenium-rc url (which is normally localhost:4444) to the grid's url.</p>
<p>Additionally we specify the browser string (*firefox, *iexplore, *opera or whatever) as a system property on the mvn command line, which we pick up when we initialize the selenium client libraries in our code.</p>
<p>So the way we've done it we basically set up 4 different build projects with different browser strings.</p>
|
Open Source license that requires giving credit in user's web site <p>I have this small code library that I'm considering releasing into Open Source. I want to release it under something similar to MIT License, i.e. no significant restrictions, however I would like to require that if you use my library on your servers, you have to give me credit on your website.</p>
<p>Basically, I want a license which is to MIT License as AGPL is to GPL.</p>
<p>Does something like this exist, or do I have to write my own?</p>
<p>Or is this just a Really Bad Idea?</p>
<p><strong>EDIT</strong>: I guess I should have left out the "write my own" part. I'm not a lawyer, and I don't want to pay one. I just thought it would be nice to be able to tell if someone's using my lib with a simple Google search.</p>
| <p>Look here :</p>
<p><a href="http://www.opensource.org/licenses/category" rel="nofollow">http://www.opensource.org/licenses/category</a></p>
<p>and pleeeeeeeeeeease don't write your own!</p>
<p>From Aaron Digulla comment (Thank you Aaron):</p>
<p><em>It takes a lawyer a long time to write a license that will actually hold in court (and why would you want a license that doesn't?) Hundreds of people all over the world worked several MONTHS on GPL v3! â Aaron Digulla</em> </p>
<p>On the other side :</p>
<p>When you work in a company and you will use opensource, you normally can choose
among the licenses that are "approved" in the company :-).</p>
<p>a new license is normally a NO GO :-(</p>
<p><strong>ATTENTION</strong> to Kodisha: From the cc-site:</p>
<p><em>Creative Commons licenses should not be used for software. We strongly encourage you to use one of the very good software licenses which are already available.</em></p>
<p>PS : <a href="http://stackoverflow.com/questions/236699/what-open-source-license-to-choose">see What Open Source License to choose?</a></p>
|
AJAX.NET request handlers - set hidden field <p>I'm trying to set the value of a hiddenfield control in an AJAX initialize request handler. However on the server the hidden field control always contains the value for the previous postback. I presume the viewstate is being prepared / send before I set the hidden field in the initialize request handler.
Is there any way to set the hidden field so that is passes the new value through or perhaps pass a value to the server via another mechanism.</p>
<p>This is the code I'm using:</p>
<pre><code>var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(MyPage_initializeRequestHandler);
function MyPage_initializeRequestHandler(sender, args)
{
var hiddenField1= $get('hiddenField1');
if (hiddenField1 != null)
{
hiddenField1.value = 'test';
}
}
</code></pre>
<p>Many thanks.</p>
| <p>Are you using update panels?</p>
<p>If you are then you need to make sure that the hidden field is inside the update panel that is being refreshed, otherwise the new value will not be sent to the browser.</p>
<p>Also, how are you creating the hidden field, if it's part of an update panel post back you should be using ScriptManager.RegisterHiddenField.</p>
<p>HTH's</p>
|
How do you deploy a website to your webservers? <p>At my company we have a group of 8 web developers for our business web site (entirely written in PHP, but that shouldn't matter). Everyone in the group is working on different projects at the same time and whenever they're done with their task, they immediately deploy it (cause business is moving fast these days). </p>
<p>Currently the development happens on one shared server with all developers working on the same code base (using RCS to "lock" files away from others). When deployment is due, the changed files are copied over to a "staging" server and then a sync script uploads the files to our main webserver from where it is distributed over to the other 9 servers.</p>
<p>Quite happily, the web dev team asked us for help in order to improve the process (after us complaining for a while) and now our idea for setting up their dev environment is as follows:</p>
<ul>
<li>A dev server with virtual directories, so that everybody has their own codebase, </li>
<li>SVN (or any other VCS) to keep track of changes</li>
<li>a central server for testing holding the latest checked in code</li>
</ul>
<p>The question is now: How do we manage to deploy the changed files on to the server without accidentaly uploading bugs from other projects? My first idea was to simply export the latest revision from the repository, but that would not give full control over the files.</p>
<p>How do you manage such a situation? What kind of deployment scripts do you have in action? </p>
<p>(As a special challenge: the website has organically grown over the last 10 years, so the projects are not split up in small chunks, but files for one specific feature are spread all over the directory tree.)</p>
| <p>Cassy - you obviously have a long way to go before you'll get your source code management entirely in order, but it sounds like you are on your way!</p>
<p>Having individual sandboxes will definitely help on things. Next then make sure that the website is ALWAYS just a clean checkout of a particular revision, tag or branch from subversion.</p>
<p>We use git, but we have a similar setup. We tag a particular version with a version number (in git we also get to add a description to the tag; good for release notes!) and then we have a script that anyone with access to "do a release" can run that takes two parameters -- which system is going to be updated (the datacenter and if we're updating the test or the production server) and then the version number (the tag).</p>
<p>The script uses sudo to then run the release script in a shared account. It does a checkout of the relevant version, minimizes javascript and CSS[1], pushes the code to the relevant servers for the environment and then restarts what needs to be restarted. The last line of the release script connects to one of the webservers and tails the error log.</p>
<p>On <a href="http://www.yellowbot.com/">our</a> <a href="http://www.weblocal.ca/">websites</a> we include an html comment at the bottom of each page with the current server name and the version -- makes it easy to see "What's running right now?"</p>
<p>[1] and a bunch of other housekeeping tasks like that...</p>
|
DependancyProperty attach to a property of a property <p>I have a workflow with a property in it, declared like this:</p>
<pre><code>public Person userAccount {get;set;}
</code></pre>
<p>Person is a class with it's own properties (like Person.Name) and with WF I can bind to the userAccount property fine yet I can't seem to bind to the userAccount.Name.</p>
<p>Is it possible to do this? If so what do I need to change? </p>
| <p>No</p>
<p>i don't think that its possible to driectly bind to Memebers of Variables in Workflow</p>
<p>you will have to bind to entier class i.e. userAccount</p>
|
Does The Same Stylesheet Get Loaded Multiple Times On Different Pages? <p>I work on a large Intranet system - as it is an evolved system which started over ten years ago unfortunately the design of it isn't great and needs to be completely rewritten as it currently works by using frames.</p>
<p>The problem with the frame-based layout is that there's a "main" section which does the includes for the stylesheets. This is quite a simple question, but I've never found any evidence of it. Does that same stylesheet get loaded multiple times because it's on separate web pages? Or does the browser cache it and do a comparison check against same-named stylesheets. Is this the same for JavaScript libraries?</p>
| <p>Yes, browsers will load external scripts and stylesheets from cache for each frame, unless you deliberately break it by sending no-cache headers with those files.</p>
|
How to set up headers and libraries for Linux development <p>I recently set up, for a learning exercise, an Ubuntu desktop PC with KDE 4.2, installed Eclipse and started to look for information on how to develop for KDE. I know there's KDevelop and will probably have a look at that at some time in the future. Right now, however, I don't have the correct headers and libraries for creating KDE applications in C/C++ using Eclipse. If I have the following:</p>
<pre><code>#include <kapplication.h>
</code></pre>
<p>it fails to compile since there are dependancies on other header files that are not present on my hard disk or reference classes that aren't declared anywhere.</p>
<p>So, the question is, what packages do I need to install in order to have the correct set of headers to allow me to write applications for KDE 4.2? Are there any packages I shouldn't have? Alternatively, if there are no packages then where can I get the appropriate files?</p>
<p>As a corollary, are there any good tutorials on KDE development, something like the Petzold Windows book?</p>
<p>EDIT: Clarifying what I'm really after: where can I download the correct set of header files / libraries in order to build a KDE application? IDEs to compile code aren't a real problem and are easy to get, as is setting up compiler options for include search paths and so on. Does the KDevelop package have all the correct include and library files or are they separate? I guess they are separate as KDevelop is an IDE that can do other languages as well, but I'm probably wrong. So, the KDE/Qt header files I have don't work, where do I get the right ones?</p>
<p>Skizz</p>
| <p>make sure you have installed build-essential package. For more documentation available from the command line, install glibc-doc, manpages-dev, gcc-*-doc, libstdc++*-doc (replace '*' with suitable version numbers for your system)</p>
<p>EDIT:
I'm going to accept this one, but with a few extra bits.</p>
<p>Firstly, <a href="https://techbase.kde.org/Getting_Started/Build/KDE4/Kubuntu_and_Debian">this page</a> had a pair of 'sudo aptitude install' which I commands which I used to get some required packages. I also got the KDevelop and QDevelop applications although I'm not sure they are required. There was also another package I needed: 'kdelibs5-dev' and this one appears to be the key package. Everything eventually worked after getting that one. Eclipse and KDevelop were both happy building a simple application once the compiler settings were set up - just search paths and library file names for Eclipse.</p>
<p>From first impressions, Eclipse appears better than KDevelop for the single reason that the tool windows in Eclipse can be detached from the main window and float - useful on a dual monitor setup. I couldn't see anyway to do that in KDevelop (I'm sure someone will comment on how to do this).</p>
|
Backup/Restore Shared Services Provider on SharePoint MOSS <p>I'm having serious issues with backing up and restoring a shared services provider.</p>
<p>Using the Central Administration backup I run the backup to s:\</p>
<p>This completes fine.</p>
<p>I then from another SharePoint Server choose to restore a backup and point it to the UNC path \machineipaddress\s$\spbr00DF</p>
<p>I have given everyone full access to s:\ on the source server.</p>
<p>All I get back from SharePoint is this:</p>
<p>Directory \machineipaddress\s$\spbr00DF does not exist or the SQL Server service account and the BI_WEB\Administrator service account do not have permission to read or write to the backup folder. Specify a different directory.</p>
<p>Would appreciate anyones thoughts on this.</p>
<p>reference: <a href="http://technet.microsoft.com/en-us/library/cc896556.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/cc896556.aspx</a></p>
<p>All the best</p>
| <p>Hey I'm new here but just wanted to add my two cents.</p>
<p>I was having the same issue and found one of the above users was correct, the error was generated because a system account did not have access to the share.</p>
<p>On our server we got the same error. When we created our Sharepoint sites we selected the Network Service account to run the site. I went to the share and added the Network Service account with Full Control and now the restore works.</p>
<p>Hope this helps someone.</p>
|
How do I align textPosition for a label? <p>I wonder if it is possible to set <code>textPosition()</code> for a <code>Label</code> that includes an <code>Image</code> and a text part so that the text is both TOP and LEFT. The problem I have now is that I need the text to be TOP but when that is selected the text is centered over the image. My wish is that the text is over the image but to the left and not centered. I wonder if there is a way to do this?</p>
<p>I have tried to add the text to one <code>Label</code> and the image to another <code>Label</code> and then contain them in a container but the problem is then that the alignment will be the same for all the items(text over image) and item over item. So it will not be possible to see if the text over the second image is part of the first image or the second. </p>
<p>Thanks.</p>
<hr>
<p>Ok so this is what I mean. This is the current behaviour:</p>
<pre><code>Label item = new Label();
item.setIcon(icon);
item.setText("House:");
item.setTextPosition(TOP);
</code></pre>
<p>Result:</p>
<pre><code>House:
/\
</code></pre>
<p>The wanted behaviour is:</p>
<pre><code>Label item = new Label();
item.setIcon(icon);
item.setText("House:");
item.setTextPosition(TOP);
item.setTextPosition(LEFT);
</code></pre>
<p>House:</p>
<pre><code>/\
</code></pre>
<p>I need to set TextPosition to both Top and left, is that possible? Or is there any otherway I can get this behaviour. If I use a container the result will be:</p>
<p>House:</p>
<pre><code>/\
</code></pre>
<p>House:</p>
<pre><code>/\
</code></pre>
<p>What I want is that the alignment between "House:" and /\ is separate from "House:" and the /\ above.</p>
<p>I hope this makes any sense. Hard to explain it in a good way. Thanks for any help you can give me.</p>
| <p>Use two labels within a container to achieve that, one for the icon and another for the text. There are infinite number of configurations for things like that, the more support we add the more complex and slow label rendering becomes and its API becomes more convoluted. </p>
|
Use something else than JDBC over firewall <p><p>
I have simple server-client application that uses JDBC to connect to database and things works ok. Application does few simple things with JDBC connection (get data, insert new line and few others). <p>
Now, I would like to keep the same application but use it outside of firewall - so, I would put something else on some host:port (and open that port to outside world) - instead of JDBC opening database access directly. <p>
I guess that this problem is faced many many times and sure there are a lot approches.
<br>
One way can be doing servlet on one side, accessing it on client side. <br>
I guess, I haven't touched Spring yet, maybe another would be to do POJO Java Class and using Spring configure it as http service.
I have heard also "rumors" that Jetty has something that can help in this case (to minimaze coding on server and client side)
<p>
I would prefer something that:<br>
- is not complicate (easy learning path)<br>
- reuse something that is already done.
<p></p>
<p>What approach would you recommend ? </p>
<p>Thank you and regards,<br>
Igor</p>
| <p>The normal approach would be to implement a web service, which can be pretty easy these days with Axis etc.</p>
<p>You really don't want to open direct JDBC to clients outside a firewall by tunnelling over HTTP... the server should <em>strictly</em> control what kind of interaction takes place with the database.</p>
|
Preferred way of #! in shell scripts <p>I searched google but couldn't find an answer to this rather simple question. I have a python script that has the hash-bang (#!) on the first line:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>However, what if this is run on a computer with python in /bin/python or /usr/local/bin/python, or some other place? There has to be a better way to set the interpreter for a shell script. It should be possible to set it via $PATH, as that will know where to find python if it's installed on the system.</p>
| <p>Use env.</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>It's not bulletproof, but it covers more cases than /usr/bin/python.</p>
|
SQL query to select unreferenced rows <p>I'm having a brain-dead moment... I have two tables described by:</p>
<pre><code>CREATE TABLE table_a (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL
UNIQUE (name))
CREATE TABLE table_b (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
a_key INTEGER NOT NULL,
other_stuff VARCHAR(255) NOT NULL,
FOREIGN KEY(a_key) REFERENCES table_a(id)
ON DELETE CASCADE)
</code></pre>
<p>How can I select all rows from table_a that do not have an entry in table_b.a_key?</p>
| <pre><code>SELECT table_a.*
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_key
WHERE table_b.id IS NULL
</code></pre>
|
Getting the most out of Resharper - good tutorials/screencasts <p>I've just installed Resharper, and I really don't know how to use it "correctly".
I noticed that there are some demos and documents at their website, but I'm wondering..</p>
<p>..how did you learn to use it efficiently? Are there any other good resources(demos/tutorials)?</p>
| <p>There is a <a href="http://dimecasts.net/Casts/ByTag/ReSharper">series of screencasts</a> on the <a href="http://dimecasts.net/">Dime Casts</a> website which are quite good as an introduction.</p>
<p>There is also the <a href="http://blog.excastle.com/2007/01/31/blog-event-the-31-days-of-resharper/">31 days of Resharper</a> and the <a href="http://www.jetbrains.com/resharper/documentation/index.html">official demos</a> give you an idea of what's possible so you know to dive into the menu.</p>
|
Silverlight: Getting image (from OpenFileDialog) width/height <p>I've been using the BitmapImage.DownloadProgress event to wait until the image is loaded when creating a bitmap from a URI. That was I can use an event handler to check the Image.ActualWidth/ActualHeight after the download is complete. This works fine.</p>
<p>But when I am loading an image that the user has selected from their computer, the DownloadProgress is useless.</p>
<p>This works for URI bitmaps:</p>
<pre><code>private void LoadImage(Uri uri)
{
this.ResetProgressImage();
BitmapImage image = new BitmapImage();
image.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(LoadImageDownloadProgress);
image.UriSource = uri;
this.ImageFull.Source = image;
}
private void LoadImageDownloadProgress(object sender, DownloadProgressEventArgs e)
{
this.Dispatcher.BeginInvoke(delegate
{
this.ProgressImage.Value = e.Progress;
if (e.Progress == 100)
{
ImageHelper.Current.Width = Math.Round(this.ImageFull.ActualWidth);
ImageHelper.Current.Height = Math.Round(this.ImageFull.ActualHeight);
}
});
}
</code></pre>
<p>But this doesn't work when getting a BitmapImage from a stream:</p>
<pre><code>private void LoadImage(Stream stream)
{
this.ResetProgressImage();
BitmapImage image = new BitmapImage();
image.DownloadProgress += new EventHandler<DownloadProgressEventArgs>(LoadImageDownloadProgress);
image.SetSource(stream);
this.ImageFull.Source = image;
}
</code></pre>
<p>Does anyone know an alternative to DownloadProgress, when using SetSource(stream)?</p>
| <p>There is no event in BitmapImage to monitor the loading progress using a stream.</p>
<p>However, if you just need the image dimensions, you can add the image to the hierarchy and wait for the "Loaded" or "LayoutUpdated" event.</p>
|
How to escape phpdoc comment in phpdoc comment? <p>I would like to know how to escape phpdoc comments within a phpdoc comment.</p>
<p>For example, how would I have to write this:</p>
<pre><code>/**
* Some documentation...
*
* <code>
* /**
* * Example example phpdoc.
* */
* </code>
*/
</code></pre>
<p>Obviously above example won't work.</p>
<p>I tried replacing the asterisk's with &#x2A;, but it will just nicely print "&#x2A;"...</p>
| <p>According to <a href="http://manual.phpdoc.org/HTMLframesConverter/default/phpDocumentor/tutorial%5FphpDocumentor.howto.pkg.html#basics.desc">DocBlock Description details</a>, you can, as of 1.2.0rc1, write {@*} to write */.</p>
<p>For example:</p>
<pre><code>/**
* Simple DocBlock with a code example containing a docblock
*
* <code>
* /**
* * My sample DocBlock in code
* {@*}
* </code>
*/
</code></pre>
|
Places you can ask for quick code review? <p>Learning how to unit test in my own time though is providing me with further insight, I'd often would of liked to have someone there saying that I'm indeed going in the right direction with my tests.</p>
<p>Doing this by myself (and being the only developer at my company actively looking into unit testing) I get no privilege nor do I have contacts that can do this for me. I was wondering if there are any sites out there that contain a community of developers that would be happy to help review how I'm approaching my unit testing, discuss with me what I could be doing better or how my approach could be improved / changed / complete revised from scratch.</p>
<p>Such a site probably doesn't exist, and for a personal play project I'm not really willing to spend money on a code review (at what is currently not very much code at all) unless this really becomes a barrier to my progression.</p>
<p>I just thought that perhaps I'd missed something out there in interdev world :P</p>
| <p>As long as you don't post it like.</p>
<p><em>Is this okay?</em></p>
<pre><code>... 200 lines of code....
</code></pre>
<p>I think StackOverflow members would be happy to answer your unit-testing related questions.</p>
<p>Simply ask about your general setup and architecture, and maybe some small specific questions with small bits of code and you can earn rep and get some good answers.</p>
|
Problem with C# serialization extension methods <p>I really like the extension method that TWith2Sugars posted <a href="http://stackoverflow.com/questions/271398/post-your-extension-goodies-for-c-net-codeplexcomextensionoverflow#271423">here</a>. I ran into an odd problem though. When I put this into a shared class library and call the serialization function, I get the following error:</p>
<blockquote>
<p>The type MyType was not expected. Use
the XmlInclude or SoapInclude
attribute to specify types that are
not known statically.</p>
</blockquote>
<p>I looked around a bit and found that the XmlSerializer can only serialize types that it is aware of. I interpret this to mean classes that are in the class library, not the project that I build based off that libary.</p>
<p>Is there a way around this? Can this function be placed into a class library or does it need to be in each project that uses it?</p>
<p><strong>Update:</strong></p>
<p>I figured out what was causing the problem. I had the following code:</p>
<pre><code>object o = new MyClass();
o.Serialize();
</code></pre>
<p>This was causing the error. When I changed the code to:</p>
<pre><code>MyClass c = new MyClass();
c.Serialize();
</code></pre>
<p>Everything ran fine. So, lesson learned - don't try to (de)serialize generic objects. The thing I liked the most about the link I referenced was that I did not have to put any XML attribute tags on my classes. The extension method just worked.</p>
<p>For purposes of closing out the question, I will award the answer to whoever expands on <a href="http://stackoverflow.com/questions/515940/problem-with-c-serialization-extension-methods/515986#515986">Marc's answer</a> (including Marc) with a code sample illustrating the use of [XmlInclude].</p>
| <p>Your understanding is wrong. What this error means is basically as follows: XML serializer cannot operate on class hierarchies unless you explicitly tell it what classes are there in the said hierarchy. Just add <code>XmlInclude</code> attribute for the type of each derived class to your base class and you're done.</p>
|
Why does Visual Studio want to check-out a File when opened? <p>Why does Visual Studio want to check-out a File when opened?</p>
<p>I just double click the file to open it and Visual Studio wants to check it out.
I did not make any changes to it. I just opened it. </p>
<p>i.e. In Solution Explorer I double click ctlEmployeeEdit.vb and the first thing Visual Studio wants to do is check-out that file. I got VS set up to prompt me on check-out so I normally say no to the check-out and then the control will display.</p>
<p>We are using Visual Studion 2005 and Visual Source Safe 2005.</p>
<p>We have a solution of over a hundred files and it is only happening on a hand full of them but that hand full seems to be getting larger, almost a mouth full now. (Humm I wonder if a hand full is larger than a mouth full? But that question is for another posting.)</p>
<p>Also how can this be fixed?</p>
<p>Should I delete my local copy of the solution and do another "Get Latest" from Visual Source Safe when this happens?</p>
<p>I have the feeling some of you are going to say the way to fix this is to upgrade to a <strong>REAL</strong> Source Control producted. :)</p>
<p><strong>Edited:</strong> </p>
<p>Some of the Third Party controls are:</p>
<ol>
<li>DevExpress User Controls v8.3</li>
<li>IdeaBlade DevForce control</li>
</ol>
| <p>This is not the default VS behavior. It's almost certainly a 3rd party plugin that is doing something on file open that is ending up in a check out request. What plugin's do you have installed?</p>
<p>There's also some designers that end up checking out files on accident when they are open. Do you have any designers open?</p>
|
extending jquery on the main element object <p>I've seen some jquery code where people extend the main object like:</p>
<pre><code> $('someId').myCustomObject();
</code></pre>
<p>Is this possible or am I mistaken? (if yes, how?)</p>
| <p>Yes it's easily possible. The standard pattern for building extensions is:</p>
<pre><code>(function($) {
$.fn.myCustomObject = function(options) {
var defaults = { ... };
var opts = $.extend(defaults, options);
this.each(function(i) {
... // Act on each item, $(this).
... // Use opts.blah to read merged options.
});
};
})(jQuery);
</code></pre>
<p>This allows you to use '$' in the plug-in, yet allows compatibility mode.</p>
|
Planning for efficiency early vs Premature optimization <p>I seem to notice two schools of thought emerging in regards to optimization:</p>
<ol>
<li><strong>Premature optimization is the root of all evil</strong>. You should only optimize when you've written the most readable and simplest thing possible. If after profiling you determine that the software is too slow, you should optimize.</li>
<li><strong>Optimizations should be done early in a project's lifecycle</strong>. Optimizations need to be planned for, but should be done reasonably.</li>
</ol>
<p>On the face of things, they seem to be fairly opposed viewpoints. The thing is, I see the merit in both schools of thought. I can also think of times when both of these ways of thinking have helped me write better and faster software.</p>
<p>Is there any way to reconcile these two ideas? Is there a middle ground? Is there a time when one idea is the best tool for the job? Or am I presenting a false dichotomy and both views can co-exist peacefully?</p>
| <p>Optimise at the design and architecture level early on. Micro-optimise at the implementation level later.</p>
<p>You need to be aware of the performance costs of design decisions you make which will be hard to change later. Implementation can often be tuned later on, which is why it's not worth doing it until you know that it's a problem.</p>
|
Relative Paths Not Working in Xcode C++ <p>There are numerous post over the net that detail how relative paths don't work in Xcode. I do have an Xcode template that I downloaded where the relative paths DO work, however I have not been able to figure out why nor replicate it in other projects.</p>
<p>Firstly, I am using C++ in Xcode 3.1. I am not using Objective-C, nor any Cocoa/Carbon frameworks, just pure C++.</p>
<p>Here is the code that works in my other Xcode template:</p>
<pre><code>sound->LoadMusic( (std::string) "Resources/Audio/Pop.wav" );
</code></pre>
<p>This relative path works for me also in Windows. Running the following command gives me an absolute path to the application's full path:</p>
<pre><code>std::cout << "Current directory is: " << getcwd( buffer, 1000) << "\n";
</code></pre>
<p>/Applications/myApp</p>
<p>How can we get relative paths to work in an Xcode .app bundle?</p>
| <p>Took me about 5 hours of Google and trying different things to FINALLY find the answer!</p>
<pre><code>#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
std::cout << "Current Path: " << path << std::endl;
#endif
// ----------------------------------------------------------------------------
</code></pre>
<p>I've thrown some extra include guards because this makes it compile Apple only (I develop cross platform) and makes the code nicer.</p>
<p>I thank the other 2 guys for your answers, your help ultimately got me on the right track to find this answer so i've voted you both up. Thanks guys!!!!</p>
|
How do I make Binding respect DependencyProperty value coercion? <p>I have a control with a DependencyProperty with a CoerceValueCallback.
This property is bound to a property on a model object.</p>
<p>When setting the control property to a value that causes coercion the Binding pushes the <strong>uncoerced</strong> value to the model object. The property value on the control is coerced correctly.</p>
<p>How do I get the Binding to push the <strong>coerced</strong> value to the model object?</p>
<pre><code>void Initialize()
{
UIObject ui = new UIObject();
ModelObject m = new ModelObject();
m.P = 4;
Binding b = new Binding("P");
b.Source = m;
b.Mode = BindingMode.TwoWay;
Debug.WriteLine("SetBinding");
// setting the binding will push the model value to the UI
ui.SetBinding(UIObject.PProperty, b);
// Setting the UI value will result in coercion but only in the UI.
// The value pushed to the model through the binding is not coerced.
Debug.WriteLine("Set to -4");
ui.P = -4;
Debug.Assert(ui.P == 0);
// The binding is TwoWay, the DP value is coerced to 0.
Debug.Assert(m.P == 0); // Not true. This will be -4. Why???
}
class UIObject : FrameworkElement
{
public static readonly DependencyProperty PProperty =
DependencyProperty.Register("P", typeof(int), typeof(UIObject),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnPChanged),
new CoerceValueCallback(CoerceP)));
public int P
{
get { return (int)GetValue(PProperty); }
set { SetValue(PProperty, value); }
}
private static void OnPChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine(typeof(UIObject) + ".P changed from " + e.OldValue + " to " + e.NewValue);
}
private static object CoerceP(DependencyObject sender, object value)
{
int p = (int)value;
if (p < 0)
{
Debug.WriteLine(typeof(UIObject) + ".P coerced from " + p + " to 0");
p = 0;
}
return p;
}
}
class ModelObject
{
private int p;
public int P
{
get
{
Debug.WriteLine(this + ".P returned " + this.p);
return this.p;
}
set
{
Debug.WriteLine(this + ".P changed from +" + this.p + " to " + value);
this.p = value;
}
}
}
</code></pre>
| <p>I think that that's the whole idea of the coercion - correct value on the fly without triggering modification of any other dependencies. You can use the code below instead of native coercion mechanisms:</p>
<pre><code>OnPChanged(/* ... */)
{
// ...
var coercedP = CoerceP(P);
if (P != coercedP)
P = coercedP;
// ...
}
</code></pre>
<p>HTH.</p>
|
ASP.NET - AJAX - Partial followed by full postback problem <p>I've a page that has a series of web controls. One of these is a textbox with AutoPostBack turned off.</p>
<p>The way the page operates is that a button is clicked to save the form data. This button sits outside of the updatepanel.</p>
<p>So when I hit the save button the partial postback happens for the dropdownlist and after this postback has completed a full postback fires for the save button. However when the full postback fires the form data is returned to the state before the save button was clicked - i.e. my changes are removed.</p>
<p>I believe this could be to do with the viewstate being returned from the partial update and that viewstate not updating in the page before the full postback fires - or it getting corrupted.</p>
<p>Does anyone have any ideas?</p>
<p>Thanks.</p>
| <p>Don't mean to sound negative but these scenarios are what made me give up "by the book" ASP.net AJAX. Learning jQuery /w simplistic ASP.net forms /w NO postbacks has lead me to build more useful and cooler UI experiences than what I had to battle to get working with update panels etc.</p>
|
Is there a "canonical" name for a function combining min() and max()? <p>I find that I frequently end up writing a function that I always call "<code>clamp()</code>", that is kind of a combination of <code>min()</code> and <code>max()</code>. Is there a standard, "canonical" name for this function?</p>
<p>It always looks something like this:</p>
<pre><code>function clamp($val, $lower, $upper)
{
if ($val < $lower)
return $lower;
else if ($val > $upper)
return $upper;
else
return $val;
}
</code></pre>
<p>Or simply using built-in <code>min()</code> and <code>max()</code> functions:</p>
<pre><code>function clamp($val, $lower, $upper)
{
return max($lower, min($upper, $val));
}
</code></pre>
<p>Variations exist: You can also check for invalid input, where <code>lower > upper</code>, and either throw an exception or reverse the inputs. Or you can ignore order of the inputs and call it a median-of-three function, but that can be confusing.</p>
| <p><strong>clamp</strong> is a good name.</p>
<p>Let us make it the standard.</p>
|
Best practice for running SQL Server reporting services. Should I run on the database or web server? <p>I am configuring a new environment to run several intranet web applications. I have 2 servers, one will be the SQL Server 2008 server, and the other will be the IIS server. I also need to install SQL Server Reporting Services. I am not sure whether it would be better to run reporting services on the database server, or web server. Is there a best practice for this situation?</p>
| <p>Depends...</p>
<p>The reporting services rendering is fairly processor intensive so you need to keep that in mind. Typically if I'm designing a system with heavy load or throughput requirements I place the reporting services instance on its own server. The best practice is really dependent on the complexity of your system. </p>
<p>If a third server is not an option and the two servers you already have are similarly speced I would probably place it on the one with the lowest processor load. If you place the reporting server on the web server make sure that Reporting services uses your dedicated database server for the reporting services meta-data so that you don't have to install the RDBMS on both machines. </p>
<p>You need to keep in mind that if you don't place the reporting server on the same box as SQL server you will need another SQL Server license. The product is only "free" if it is installed on the same machine as SQL. </p>
|
How to delete object(s) from project when using deploy method? <p>When you delete an obsolete object from a project/solution, what's the best way to transfer this change into production? Does deploying have an option for this?</p>
<p>EDIT: This is a database project in Visual Studio 2008, deploying to SQL Server 2005.</p>
<p>Thanks</p>
| <p>I don't know of any automated way of deleting obsolete objects. We use a database diff and then write delete statements manually here. </p>
<p>If someone has a better solution I would love to hear it (we're on VS 2005, not 2008, but I imagine that wouldn't make too much difference)</p>
|
Spring - binding to an object rather than a String or primitive <p>Let's say I have the following command object:</p>
<pre><code>class BreakfastSelectCommand{
List<Breakfast> possibleBreakfasts;
Breakfast selectedBreakfast;
}
</code></pre>
<p>How can I have spring populate "selectedBreakfast" with a breakfast from the list?</p>
<p>I was figuring I'd do something like this in my jsp:</p>
<pre><code><form:radiobuttons items="${possibleBreakfasts}" path="selectedBreakfast" />
</code></pre>
<p>But this doesn't seem to work. Any ideas?</p>
<p>thanks,</p>
<p>-Morgan</p>
| <p>The key to it all of this is the PropertyEditor.</p>
<p>You need to define a PropertyEditor for your Breakfast class and then configure the ServletDataBinder using registerCustomEditor in the initBinder method of your controller.</p>
<p>example:</p>
<pre><code>public class BreakfastPropertyEditor extends PropertyEditorSupport{
public void setAsText(String incomming){
Breakfast b = yourDao.findById( Integer.parseInt(incomming));
setValue(b);
}
public String getAsText(){
return ((Breakfast)getValue()).getId();
}
}
</code></pre>
<p>note you'll be needing some null checking etc, but you get the idea. In your controller:</p>
<pre><code>public BreakfastFooBarController extends SimpleFormController {
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Breakfast.class, new BreakfastPropertyEditor(yourDao));
}
}
</code></pre>
<p>things to watch out for:</p>
<ul>
<li>PropertyEditor's are not thread safe</li>
<li>if you need spring beans, either manually inject them or define them in spring as prototype scope and use method injection into your controller</li>
<li>throw IllegalArgumentException if the inbound parameter is not valid/not found, spring will convert this into a binding error correctly</li>
</ul>
<p>hope this helps.</p>
<p>Edit (in response to the comment):
It looks a little strange in the given example because BreakfastSelectCommand doesn't look like an entity, I'm not sure what the actual scenario you have is. Say it is an entity, for example like <code>Person</code> with a <code>breakfast</code> property then the <code>formBackingObject()</code> method would load the Person object from the the <code>PersonDao</code> and return it as the command. The binding phase would then change the breakfast property depending on the selected value, such that the command that arrives in <code>onSubmit</code> has the breakfast property all set up.</p>
<p>Depending on the implementation of your DAO objects calling them twice or attempting to load the same entity twice doesn't actually mean that you will get two SQL statements being run. This applies particularly to Hibernate, where it guarantees that it will return the same object that is in it's session for a given identifier, thus running letting the binding attempt to load the <code>Breakfast</code> selection even through it hasn't changed shouldn't result in any undue overhead.</p>
|
What does the Visual Studio "Any CPU" target mean? <p>I have some confusion related to the .NET platform build options in Visual Studio 2008.</p>
<p>What is the "Any CPU" compilation target, and what sort of files does it generate? I examined the output executable of this "Any CPU" build and found that they are the x86 executables (who would not see that coming!). So, is there any the difference between targeting executable to x86 vs "Any CPU"?</p>
<p>Another thing that I noticed, is that managed C++ projects do not have this platform as an option. Why is that? Does that mean that my suspicion about "Any CPU" executables being plain 32-bit ones is right?</p>
| <p>An AnyCPU assembly will JIT to 64 bit code when loaded into 64 bit process and 32 bit when loaded into a 32 bit process.</p>
<p>By limiting the CPU you would be saying there is something being used by the assembly (something likely unmanaged) that requires 32 bits or 64 bits.</p>
|
What is the difference between shelve and check in in TFS? <p>What is the concept of each?</p>
<p>When is it ok to shelve your changes instead of checking in?</p>
| <p>Shelved means the changes are set aside for <em>you</em> to work on later. </p>
<p>Checked in means that the changes are made available to the rest of the team, will be in the build and will eventually ship.</p>
<p>Very different. Think of shelving as a tool for context switching when you're not done with a task. Checking in means you're done (at least a part of it).</p>
|
PHP File Validation using If statements uploads <p>Hi I am quite new to php but i have been following some tutorials but they don't seem to work so I have tried to adapt them.
I have tested this code and it works to a point but theres something else I can't get my head around, the php file is not uploading (fine) but the details are still being writen to the datbase although the $ok is spose to be set to 0 (not fine). It might be easier if explain what is ment to happen here: </p>
<p>-The User can upload gif or jpeg files. Details added to the db.
-The User can upload no file as a default will be used. Details added to the db.
-The User <strong>should not</strong> be able to upload any other file. No record should be on the db, user should have to try again. </p>
<p>My Code so far: </p>
<pre><code><?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
$ok=0;
//This gets all the other information from the form
$name= mysql_real_escape_string ($_POST['nameMember']);
$bandMember= mysql_real_escape_string ($_POST['bandMember']);
$pic= mysql_real_escape_string ($_FILES['photo']['name']);
$about= mysql_real_escape_string ($_POST['aboutMember']);
$bands= mysql_real_escape_string ($_POST['otherBands']);
$uploaded_size=$_FILES['photo']['file_size'];
if ($uploaded_size > 350000)
{
echo "Your file is too large, 35Kb is the largest file you can upload.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
if ($uploaded_type =="image/gif")
{
echo "GIf<br>";$ok=1;
}
if (empty($pic)){
echo "You haven't uploaded a photo, a default will be used instead.<br/>";$ok=1;}
if ($ok==0)
{
Echo "Sorry your file was not uploaded, please try again with the correct format.";
}
//If everything is ok we try to upload it
else
{
// Connects to your Database
mysql_connect("localhost", "*******", "******") or die(mysql_error()) ;
mysql_select_db("project") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO dbProfile (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory<br/>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
else {
//Gives and error if its not
echo "<p>If you have uploaded a picture there may have been a problem uploading your file.</p>";
print "<a class=\"blue\" href=\"createMember.php\">Add Another Record</a> | <a class=\"blue\" href=\"listMember.php\">Band Member Profiles and Affiliates Menu</a>";
}
}
?>
</code></pre>
<p>Cheers in advance. CHL</p>
| <p>The error probably is this if statement:</p>
<pre><code> if (!($uploaded_type =="image/jpeg"))
{
echo "JPEG<br>";$ok=1;
}
</code></pre>
<p>Because every time you upload an image that does not have a content type that equals "image/jpeg", $ok evaluates to 1, so everything gets written to the database.</p>
<p>But also notice, that just checking the MIME type like this can get you into trouble, since the user is able to fake the MIME type of a file.</p>
<p>You could use Imagick to get the correct image MIME type, for example. See more details here: <a href="http://de2.php.net/manual/en/function.imagick-identifyimage.php" rel="nofollow">http://de2.php.net/manual/en/function.imagick-identifyimage.php</a></p>
<p>Edit: Just noticed, that $uploaded_type does not get initialized anywhere in your script. As I said, you can do a rough estimation of the MIME type by using $_FILES['photo']['type'].</p>
|
How do I get a reference to the underlying object in a bound DataGridViewComboBoxCell? <p>I don't know if my mind is not working today or if this is actually harder than I think it should be.</p>
<p>I've got a DataGridView with a DataGridViewComboBoxColumn bound to a generic IList of CustomObjects. Here's a rough code sample of how I setup the column.</p>
<pre><code>DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn()
{
Name = "Location",
DataSource = new BindingSource(GetMyLocations(), null),
DisplayMember = "Name",
ValueMember = "ID"
};
</code></pre>
<p>Then when I want to return the value of a cell:</p>
<pre><code>string id = (string)row.Cells["Location"].Value;
</code></pre>
<p>But I don't want a reference to the ID property, I want a reference to the actual Location object! I've tried not specifying a ValueMember but that appears to just use the DisplayMember.</p>
<p>I could iterate through all of the Location objects in the column DataSource and check for the matching ID property, however, it seems like the ComboBoxCell ought to be able to return that directly.</p>
<p>Also, I can't use a Dictionary in this case.</p>
<p>Any ideas as to the best way to accomplish that?</p>
| <p>You could use an <code>IList</code> of <code>KeyValuePair</code>s of "Name" and your custom object. The idea is you need <code>ValueMember</code> to point to a reference of your object. I remember having similar issues for a while with <code>ComboBox</code>es.</p>
<p>Something like the following ought to do the trick (off the top of my head and untested):</p>
<pre><code>IList<KeyValuePair<String,MyObject>> comboData =
new IList<KeyValuePair<String,MyObject>>();
foreach(var o in GetMyLocations())
comboData.Add(new KeyValuePair<String,MyObject>(o.Name, o));
DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn()
{
Name = "Location",
DataSource = comboData,
DisplayMember = "Key",
ValueMember = "Value"
};
</code></pre>
<p>You might want to change <code>GetMyLocations()</code> to return the <code>KeyValuePair</code> list instead, so you're not populating two lists for no reason.</p>
|
Java: Image as toggle button <p>How can I create in a Swing interface a toggle image button?
I have two images, imageon.jpg and imageoff.jpg,and I basically want a clickable element that toggles the images and fires an event.</p>
<p>Update: Is there a way to override the usual 'chrome' around the image? I would prefer a simple image to a button with an image inside.</p>
| <p>Load the images with <code>ImageIcon</code>. Create a <code>JToggleButton</code>. Then apply the icons with <code>AbstractButton.setIcon/setPressedIcon/setSelectedIcon</code>. Remove the border with <code>AbstractButton.setBorderPainted(false)</code>.</p>
|
MySql Union not getting executed in a view <p>I am trying to create a view for a UNION of 2 select statements that I have created.</p>
<p>The UNION is working fine when executed individually </p>
<p>But the problem is only the 1st part of the UNION is getting executed when I am executing it as a view.</p>
<p>The query I am using is as below</p>
<pre><code>SELECT DISTINCT products.pid AS id,
products.pname AS name,
products.p_desc AS description,
products.p_loc AS location,
products.p_uid AS userid,
products.isaproduct AS whatisit
FROM products
UNION
SELECT DISTINCT services.s_id AS id,
services.s_name AS name,
services.s_desc AS description,
services.s_uid AS userid,
services.s_location AS location,
services.isaservice AS whatisit
FROM services
WHERE services.s_name
</code></pre>
<p>The above works fine when i execute it separately.
But when I use it as a view, it does not give me the results of the services part.</p>
<p>Could someone please help me with this?</p>
| <p>From <a href="http://dev.mysql.com/doc/refman/5.1/en/union.html" rel="nofollow">the union description:</a></p>
<blockquote>
<p>The column names from the first SELECT statement are used as the column names for the results returned. Selected columns listed in corresponding positions of each SELECT statement should have the same data type. (For example, the first column selected by the first statement should have the same type as the first column selected by the other statements.)</p>
</blockquote>
<p>This means, that userid and location are mixed up inside the second select statement.</p>
|
Can multiple CPUs simultaneously write to the same RAM location? <p>Are machine word size (or smaller) writes serialized? Only one native opcode is needed to copy register content to RAM. </p>
| <p>Writing data to RAM is atomic. If two CPUs try to write to the same location at the same time, the memory controller will decide on some order for the writes. While one CPU is writing to memory, the other CPU will stall for as many cycles as necessary until the first write is completed; then it will overwrite its value. This is what's known as a <a href="http://en.wikipedia.org/wiki/Race_condition" rel="nofollow">race condition</a>.</p>
<p>Writes that are smaller than the native word size are not atomic -- in that case, the CPU must read the old memory value into a register, write the new bytes into the register, and then write that new value back to memory.</p>
<p>You should never have code that depends on this -- if you have multiple CPUs that are trying to simultaneously write to the same memory location, you're doing something wrong.</p>
<p>Another important consideration is the <a href="http://en.wikipedia.org/wiki/Cache_coherency" rel="nofollow">cache coherency</a> problem. Each CPU has its own cache. If a CPU writes data to its cache, the other CPUs need to be made aware of the change to that data value if they want to read it.</p>
|
Show changesets since last "get latest version"? <p>Using Team Foundation Server and Visual Studio 2008, is there a way to highlight the submissions since my last "get latest version"? This would allow me to quickly identify what has been submitted since my last "pull" without having to remember which changeset I last synced with.</p>
<p>Thanks.</p>
<p>Eric</p>
| <p>If you right-click the file in the <code>Solution Explorer</code> and select the <code>Compare</code> option, in the pop-up window set the <code>Target Version</code> as <code>Type</code>: <code>Latest Version</code>. </p>
<p>Click <code>OK</code> and your comparer tool will open up showing the differences beteween your local file and the latest version in the server.</p>
|
How to print every element of an ARRAY in PL/SQL? <p>This is a pretty basic question, but here goes:</p>
<p>I have an array of VARCHAR2 strings in PL/SQL.</p>
<p>How can I print every element in that array?</p>
| <pre><code>for i in my_array.first..my_array.last loop
--print me
end loop;
</code></pre>
|
Find the classname of a UI control <p>I need a tool which tells the classname of the UI control on which my mouse pointer is. My GUI is in Swing. Does such a tool exist? </p>
| <p>You can get the current location of the mouse pointer by doing:</p>
<pre><code>Point location = MousePointer.getPointerInfo().getLocation();
</code></pre>
<p>Once you have the location, you can convert it to your parent containers coordinate system by doing:</p>
<pre><code>Point relativeLocation = SwingUtilities.convertPointFromScreen(location, parentComponent);
</code></pre>
<p>Finally, you can lookup a component at a location by doing:</p>
<pre><code>Component myComponent = parentComponent.getComponentAt(relativeLocation);
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.