input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
SAP .NET Connector: System exception thrown while marshaling .NET type <p>My app sends lots and lots of data to SAP. To di this, it builds up an SAP table object and sends it over. I get this error somewhat regularly, but not reliably:</p>
<pre><code>System exception thrown while marshaling .NET type 20081219 to RFCTYPE_BCD
at SAP.Connector.Rfc.RfcMarshal.NetFieldToRfcField(Object src, RFCTYPE type, Encoding encoding, Byte[] dest, Int32 offset, Int32 len, Int32 charSize, Int32 decimals)
at SAP.Connector.Rfc.RfcStructureUtil.ToRfcStructure(Object obj, Byte[] dest, Type t, Encoding encoding, Boolean isUnicode, PropertyInfo[] propinfos, RfcStructInfo structInfo)
at SAP.Connector.Rfc.RfcStructureUtil.GetITabFromList(SAPConnection conn, Object list, Type t, RfcStructInfo structInfo, Int32 itab)
at SAP.Connector.Rfc.RfcClient.PrepareClientParameters(Type classType, MethodInfo m, Boolean isTQRfc, Object[] MethodParamsIn, RFC_PARAMETER[]& paramsIn, RFC_PARAMETER[]& paramsOut, RFC_TABLE[]& tables, ParameterMap[]& paramMaps)
at SAP.Connector.Rfc.RfcClient.RfcInvoke(SAPClient proxy, String method, Object[] methodParamsIn)
at SAP.Connector.SAPClient.SAPInvoke(String method, Object[] methodParamsIn)
</code></pre>
<p>What's weird is that this doesn't happen every time. Also, the .NET type it complains about, "20081219" is the <em>data</em> I'm passing (a date)--not a type. I think the type of that field is <code>RFCTYPE.RFCTYPE_TIME</code>.</p>
<p>Any suggestions on how to troubleshoot this intermittent error? Is there some kind of state I should be clearing between calls to the SAP RFCs?</p>
<p><hr /></p>
<p><strong>Update:</strong></p>
<p>As requested, here's the code that calls SAP:</p>
<pre><code>Using sapConnection As New MySapProxy(ConnectionString)
sapConnection.Connection.Open()
sapConnection.TheSapRfcICall(SapOpCode, Nothing, Nothing, sapTable, ResultTable)
End Using
</code></pre>
<p>I'm thinking maybe multiple threads are using the same connection some how. Using <code>SAP.Connector.GetNewConnection</code> instead didn't change anything. </p>
<p><hr /></p>
<p><strong>Update:</strong></p>
<p>It seems this problem occurs even when I run a single thread! What's the deal??</p>
<p>Is there a way to disable the connection pool to see if that fixes it?</p>
<p><hr /></p>
<p><strong>Update:</strong></p>
<p>@Igal Serban's <a href="#382242" rel="nofollow">answer</a> seems to be working for me. I'll check the logs tomorrow morning and (hopefully) award the bounty! Thanks so much.</p>
<p><hr /></p>
<p><strong>Update:</strong></p>
<p>As requested, my version of librfc32.dll is 6403.3.78.4732.</p>
| <p><strong>Update 4:</strong> In second thought, I don't think that the librfc version is important. The exception seems to come from the managed code. The options that I can think of are:</p>
<ul>
<li>Try to use debugger on the single threaded version.</li>
<li>The magical way. Even without finding the bug ( That is on sap or your code). Just changing the way you do business can make it go away. Its ugly, but sometimes practical. Anyway the recommended way for your scenario seems to be to use connection pool, and not to create new proxy object for each request. So something like this (untested) code can be used:</li>
</ul>
<p><hr /></p>
<pre><code>MySapProxy proxy = new MySapProxy(); // do this only once.
// and in you main loop:
using (proxy.Connection = Connection.GetConnection(connectionString))
{
proxy.TheSapRfcICall(SapOpCode, Nothing, Nothing, sapTable, ResultTable)
}
</code></pre>
<p><hr /></p>
<p>This sample is using implicitly the connection pool. The use of can be controlled from the config file. </p>
<p><strong>Update 3:</strong> Can you please check your librfc32.dll version and date? its should be in system32 directory or in your application directory or somewhere in your %path%.</p>
<p><strong>Update 2:</strong> Sap notes are just like kb articles. I don't know if there is free access to the note in the sdn.sap.com so I have send it to your mail.</p>
<p><strong>Update 1:</strong> SAP Note 1000057 states:</p>
<blockquote>
<p>Under multithreaded heavy load, exceptions of type RfcMarshalException with reference to System.Xml.Xsl.XsltException as inner exception may occur.</p>
</blockquote>
<p>While not exactly the exception you receive. Its worth a try.</p>
<p>Patch is available as attachment to this note.</p>
<p><strong>Update 0:</strong>Only a guess. But I would suggest to look at threading issues. Is this all the stack? Can you post the part off the code where you call the sap code?</p>
|
Securly download file inside browser with correct filename <p>I am doing some work on a web site that has a secure area which is available to users only after they have logged in. In this area there is a page with links to pdf documents which can be downloaded. The physical documents are outside of the web site's root directory. The links to the pdf documents look something like this:</p>
<p>index.php?page=secure-area/download&file=protected.pdf</p>
<p>Which executes the following (note: I know this is the way to force a download rather than open the file <em>inside</em> the browser):</p>
<pre><code>// check security, get filename from request, prefix document download directory and check for file existance then...
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Connection: Close');
set_time_limit(0);
readfile($file);
</code></pre>
<p>This works well but in Firefox 3 and Internet Explorer 7 (I haven't tested with any other browser) won't open this file inside the browser, they both show the download dialog box (as expected). If I select Open rather than Save, the document is downloaded and Adobe Reader is started outside of the browser to render the document.</p>
<p><strong>The problem I have is downloading the file inside the browser and having the correct default file name if saved.</strong></p>
<p>I would like the document to open in the browser. One way of doing this is using the header "Content-Disposition: inline;" but this means that I can't specify a filename (because is seems to be ignored by the browser). The problem with doing that is when I save the document, the default name is that of the URL, not the filename of the pdf document:</p>
<pre><code>http___example.com_index.php_page=secure_area_download&file=protected.pdf
</code></pre>
<p>How can I get Firefox and Internet Explorer to open the document inside the browser and provide the correct default filename to save?</p>
| <p>I've finally come up with a work around for this problem.</p>
<p>Although the RFC 2183 shows that a filename parameter can be used for both attachment and inline for the Content-Disposition header field, it seems that browsers ignore the filename parameter when inline is used but rather try to work out what the filename should be based on the URL. If the URL has no query string then the part of the URL that follows the last / seems to be used as the filename.</p>
<p>I have changed the links that download the protected PDF documents to use nice URLs that don't contain a query string and use mod_rewrite with a .htaccess file to convert those nice URLs to execute the correct script with the correct parameters:</p>
<p>Old link:</p>
<pre><code>index.php?page=secure-area/download&file=document.pdf
</code></pre>
<p>New Link:</p>
<pre><code>file/secure-area/download/document.pdf
</code></pre>
<p>.htaccess:</p>
<pre><code>RewriteEngine On
RewriteRule ^file/secure-area/download/(.*)$ index.php?page=secure-area/download&file=$1 [L]
</code></pre>
<p>The script used to actually send the file is the same as I used before (note the example in the question uses Content-Disposition: attachment rather then Content-Disposition: inline to demonstrate browsers saving the document with the correct filename when <strong>not</strong> inline). </p>
<pre><code>// check security, get filename from request, prefix document download directory and check for file existance then...
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($file) . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Connection: Close');
set_time_limit(0);
readfile($file);
</code></pre>
<p>Now the PDF document opens inside the browser and when saved the default filename is</p>
<pre><code>document.pdf
</code></pre>
<p>and not</p>
<pre><code>http___example.com_index.php_page=secure_area_download&file=document.pdf
</code></pre>
<p>IE 7 converts spaces in the filename to +'s and single quotes to %27's when saved (Firefox doesn't), I would like to stop that from happening but for the meantime I'm happy with what I've got.</p>
|
How do I redirect output to stderr in groovy? <p>I'm looking for a way to redirect output in a groovy script to stderr:</p>
<pre><code>catch(Exception e) {
println "Want this to go to stderr"
}
</code></pre>
| <p>Just off the top of my head couldn't you do a bit of self-wiring:</p>
<pre><code>def printErr = System.err.&println
printErr("AHHH")
</code></pre>
<p>but that is a bit manual</p>
|
Help with ActiveRecord exception "Failed to lazily initialize a collection - no session" <p>I am writing a web app using Castle ActiveRecord, and I keep getting this exception whenever I try to access a lazy loaded list of related objects. Here is my code:</p>
<pre><code> using(new SessionScope())
{
foreach (var field in eventObj.RegistrationFields)
{
//Do something with the field here...
}
}
</code></pre>
<p>The RegistrationFields property looks like this:</p>
<pre><code> [HasMany(Inverse = true, Lazy = true)]
public IList<EventRegistrationField> RegistrationFields { get; set; }
</code></pre>
<p>The exception happens when the "eventObj.RegistrationFields" is accessed for the foreach loop. I also made sure to set the isweb="true" attribute in my activeRecord config settings. Does anyone know why this would happen? Here is my config:</p>
<pre><code><connectionStrings>
<add name="main" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=EventScheduler;Integrated Security=SSPI"/>
</connectionStrings>
<activerecord isWeb="true">
<config>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2005Dialect"/>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.connection.connection_string_name" value="main"/>
</config>
</activerecord>
</code></pre>
| <p>I think you're getting confused about sessions. <code>RegistrationFields</code> is a lazy property of <code>eventObj</code>. It is the session that loaded <code>eventObj</code> that would be responsible for loading <code>RegistrationFields</code>. You're explicitly opening a new session by using <code>new SessionScope()</code>, which creates a new session to which <code>eventObj</code> is not bound; therefore there is no owning session for it to get the data from. Even if the originating session is still alive, calling <code>new SessionScope()</code> nests a new session and hides the old one where it can't be seen until <code>Dispose()</code> is called on the current scope. Objects will not automatically attach themselves to the current session. This is the expected NHibernate behaviour.</p>
<p>It looks like you're trying to do session-per-unit-of-work, which is fine, but then the loading of objects <em>and</em> the resolution of all those objects' lazy collections must happen within that unit of work.</p>
<p>You could try moving to session-per-request (see the Castle docs for how to make this happen) and dropping the SessionScope creation. This will keep your objects live for the duration of a page request (which is as far as any lazy collection should live in a Web app). You must be aware, though, that in this scenario any change you make to a persistent object will be written to the DB on session flush (in effect, you should treat a change to the state of a persistent object as a change to the underlying data as if they were the same operation - then you can't go wrong).</p>
|
Should we always favor polymorphism over enums? <p>After watching: <a href="http://www.youtube.com/watch?v=4F72VULWFvc">The Clean Code Talks -- Inheritance, Polymorphism, & Testing</a></p>
<p>I checked my code and noticed a few switch statements can be refactored into polymorphism, but I also noticed I only used switch statements with enums. Does this mean enums are "evil" in OO-design and should be eliminated with polymorphism?</p>
| <p>First of all, Java actually has great enums that can be used polymorphically. I'm no Java programmer so someone else can certainly give a good example (I can't). Also, consider that polymorphism is often just overkill. I've also just seen the talk, and it's great, but it only provides guidelines, no silver bullet.</p>
<p>It's especially <em>not</em> true that all <code>switch</code> statements can be replaced. State machines is actually one case where enums make a lot of sense. I use state machines a lot in parsing. Sure, this can be done with a design pattern and class polymorphism. But it's much (<em>much</em>) more code, it performs the same job, only slower, it's not a jot more readable and it's a solution that's only needed in one single place, without any code recycling. Using subclassing here simply has no advantage.</p>
<p>Then again, this is an exception. In general, subclassing is often the better solution in languages that support it well.</p>
<p>EDIT: I notice that this might raise controversy. Of course there are a lot of good solutions that encapsulate parsing, from regular expressions to parser generator frameworks such as Antlr. Nothing wrong with them and in all but the trivial cases these are the better solution. However, I work a lot with low-level code (not in Java, obviously), where regular expressions aren't supported and parser generators also incur an overhead.</p>
|
What is a good design pattern to implement a dynamic data importer tool? <p>We are planning to build a dynamic data import tool. Basically taking information on one end in a specified format (access, excel, csv) and upload it into an web service. </p>
<p><strong>The situation is that we do not know the export field names, so the application will need to be able to see the wsdl definition and map to the valid entries in the other end.</strong></p>
<p>In the import section we can define most of the fields, but usually they have a few that are custom. Which I see no problem with that. </p>
<p>I just wonder if there is a design pattern that will fit this type of application or help with the development of it.</p>
| <p>I am not sure where the complexity is in your application, so I will just give an example of how I have used patterns for importing data of different formats. I created a factory which takes file format as argument and returns a parser for particular file format. Then I use the builder pattern. The parser is provided with a builder which the parser calls as it is parsing the file to construct desired data objects in application.</p>
<pre><code>// In this example file format describes a house (complex data object)
AbstractReader reader = factory.createReader("name of file format");
AbstractBuilder builder = new HouseBuilder(list_of_houses);
reader.import(text_stream, builder);
// now the list_of_houses should contain an extra house
// as defined in the text_stream
</code></pre>
|
Browser Add-On/Extension and Browser Form data <p>Can someone point me to an article (or discuss here) that explains how an add-on/extension can read what a user has completed in a form in a browser so you can present data to them based on the search parameters?</p>
<p>An example would be the Sidestep extension that opens a sidebar when a user searches on an airline/travel site and presents them a Sidestep meta search based on the parameters used on the original airline/travel site.</p>
| <p>extension to what? your body?:)</p>
<p>If you're talking about a browser extension, then i'm pretty sure you are on the wrong way.
You could just search for forms in the current page, and based on the field names try to figure out what did the user searched for...
A js file, and an AJAX-call is all you need, and you could basically skip the ajax call also... but i generally prefer server-side processing, as the source code is more hidden this way.</p>
|
How Pass some parameter to MVC User Control that is not in ViewData <p>I want to pass some parameters to my MVC UserControl like ShowTitle(bool) and the ViewData.Model.Row . How I define my usercontrol and pass them to it?
Tanx</p>
| <p>You can use the RenderAction HtmlHelper, found in the MVC futures dll available at <a href="http://www.codeplex.com/aspnet">codeplex</a>. In your main page
...
<% Html.RenderAction("actionName", "controllerName", new {showTitle=true, row=ViewData.Model.Row}); %></p>
<p>You need an action method on the controller with the parameters. The action then creates a ViewData for the usercontrol. The usercontrol is returned as a view with</p>
<pre><code>return View("usercontrolname", model);
</code></pre>
<p>The .ascx file then uses the model for just the user control. The resulting HTML is rendered into the calling page.</p>
|
Getting back on track after disruptions <p>Over the past few weeks it seems like I've been interrupted by maintenance tasks from old projects quite a bit in addition to a taking a training class. I feel like I've lost all forward momentum on my current project. It's difficult to even start coding because I'm not sure what I was doing and what I was thinking before the interruption.</p>
<p>What tips or techniques do you have to help make it easier to get restarted after an interruption that takes you away from your current project for a couple of hours or days? </p>
| <ul>
<li><p>Take a minute to write notes to yourself (on paper right in front of you) about the project you're putting down before you go and pick another up</p></li>
<li><p>Still messed up? Headphones on, music on, loud enough to drown out your surroundings and no lyrics</p></li>
<li><p>Really messed up? Go for lunch, take a walk, get out in the air and don't come back til the interruption has faded</p></li>
<li><p>Really really messed up? Don't accept interruptions any more. Be really firm about this with colleagues and managers. If you need to ringfence yourself to get stuff done they should be able to appreciate that, at the end of the day what's efficient for you is efficient for them.</p></li>
</ul>
|
C++ experts: is the offset of a member variable to its class constant under these conditions? <p>Given a variable <code>foo</code> of type <code>FooClass*</code> and a member variable in that class named <code>bar</code>, is the distance between <code>foo</code> and <code>&(foo->bar)</code> the same in any situation with some constraints:</p>
<ol>
<li><p><code>FooClass</code> is a non-POD type.</p></li>
<li><p>We know that <code>foo</code> will always point to an instance of <code>FooClass</code>, and not some subtype of it.</p></li>
<li><p>We only care about behaviour under a single compiler and a single compilation; that is, the value this may result in under gcc is never used in code compiled with MSVC, and it is never saved to be re-used between compilations. It is computed in the binary and used in the binary, and that is it.</p></li>
<li><p>We don't use a custom <code>new</code>, although some instances of the class may be stack-allocated and some heap-allocated.</p></li>
<li><p>There is no explicit <code>ctor</code> for <code>FooClass</code>; it relies upon the compiler-generated one (and each of the fields in <code>FooClass</code> is either POD or default-constructable).</p></li>
</ol>
<p>I can't find a guarantee either way on this in the standard (nor did I expect to), but my rudimentary testing with gcc leads me to believe that it will always be the case there. I also know that this guarantee is made for POD-types, but let us assume this type can't be POD.</p>
<p><strong>An update/clarification:</strong> this is just for a single compilation of a single binary; the calculated offsets will never leave that single execution. Basically, I want to be able to uniquely identify the fields of a class in a static map and then be able to lookup into that map for some macro/template/EVIL trickery. It is merely for my own amusement, and no life support machines will rely on this code.</p>
| <p>After you have compiled your program, <strong>Yes*</strong>.</p>
<p>The offset will remain constant.</p>
<p>There is one very important restriction, however: <strong>foo must be pointing specifically to a FooClass object</strong>. Not a class derived from FooClass, or anything else for that matter.</p>
<p>The reason that C++ makes the POD distinction regarding member offsets is because both multiple inheritance and the location (or lack of) a vtable pointer can create situations where the address of an object is not the same as the address of that object's base.</p>
|
Latex using eps images builds slowly <p>Working with a latex document with eps images as in the example below...</p>
<pre><code>\documentclass[11pt]{paper}
\usepackage[dvips]{graphicx}
\usepackage{fullpage}
\usepackage{hyperref}
\usepackage{amsmath}
\DeclareMathSizes{8}{8}{8}{8}
\author{Matt Miller}
\title{my paper}
\begin{document}
\begin{figure}[!ht]
\begin{center}
\includegraphics[width=2in] {Figuer.eps}
\end{center}
\caption{Figure\label{fig:myFig}}
\end{figure}
\end{document}
</code></pre>
<p>When I got to build my latex document the time it takes to build the document increases with time. Are there any tips or tricks to help speed up this process?</p>
<pre><code>latex paper.tex; dvipdf paper.dvi
</code></pre>
| <p>Some additional ideas:</p>
<ul>
<li>try making a simpler figure (e.g. if it's a bitmapped figure, make a lower-resolution one or one with a low-resolution preview)</li>
<li>use pdflatex and have the figure be a .jpg, .png, or .pdf source. </li>
</ul>
<p>I generally take the latter approach (pdflatex).</p>
|
How does the syndication part of RSS work? <p>I understand how to make an RSS file. The XML for it is simple enough. But do I have to anything special for updates to get distributed or do I just need to update the file periodically and the rest will take care of itself? All of the stuff I've found on rss talk about what it does but not so much how.</p>
| <p>Clients periodically or occasionally re-download your RSS resource, based in part on the update schedule you can suggest in the RSS data itself. If the clients retained what they downloaded before, then they can notice what's new from last time.</p>
|
How to import word documents into wiki? <p>Anyone knows? Because i think one of the stumbling blocks for people to embrace wiki is of the fact that they need to separately upload the images to the wiki instead of just doing simple copy/paste to the word document</p>
| <p><a href="http://www.openoffice.org">OpenOffice</a> can save as a Mediawiki text file, ready to be pasted into the edit box online.</p>
|
What is the easiest approach to synchronize and duplicate oracle db schema? <p>I find it hard to generate the dbscripts from TOAD. I get errors when executing the scripts things like looping chain of synonyms or certain statement not abel to exceute etc.</p>
<p>Is there any seamless way in said like connecting a remote oracle schema and just duplicate to my local environment?</p>
<p>And also do synchronization along the way?</p>
| <p>Syncing an entire schema, data and all, is fairly easily done with exp and imp:</p>
<pre><code>$ exp username/password@source-sid CONSISTENT=Y DIRECT=Y OWNER=schema FILE=schema.exp
$ â® # some command(s) to nuke objects, see below
$ imp username/password@dest-sid FROMUSER=schema FILE=schema.exp
</code></pre>
<p>You can import into a different schema if you want by using TOUSER in the imp command. </p>
<p>You'll need to get rid of all the objects if they already exist before running imp. You can either write a quick script to drop them all (look at the user_objects view), or just drop the user with cascade and re-create the user.</p>
<p>There is probably a better way to do this, but this is quick to implement and it works.</p>
|
ADO.NET Entity : limiting data selection based on View <p>Consider following example:</p>
<p>SQL Table Customer:</p>
<pre><code>ID: Primary Key
Name: Name
</code></pre>
<p>SQL View ViewCustomerSelection:</p>
<pre><code>ID: Link to Customer ID
SomeOption: Not important
</code></pre>
<p>I'd like to create ADO.NET an entity that only selects customers that have corresponding values in ViewCustomerSelection</p>
<p>Following does NOT work:</p>
<ul>
<li>Create entity that maps to Customer and to ViewCustomerSelection without using any conditions and any fields from ViewCustomerSelection : ViewCustomerSelection is not included in SQL and all customers are returned.</li>
<li>Include a field from ViewCustomerSelection : Correct selection is returned but now Customer object is not updateable </li>
<li>Specify "not null" condition on SomeOption field : error - "Property ViewCustomerSelection.SomeOption with 'IsNull=false' condition must be mapped.</li>
<li>Specify "not null" condition on ViewCustomerSelection.ID field : error - "Entity type contains a condition on its primary key. Please remove the condition from the mapping.</li>
</ul>
<p>Clarification </p>
<p>Database definition:</p>
<pre><code>create table Customer {
ID [int] IDENTITY(1,1) NOT NULL,
Name [varchar](50) NOT NULL
} CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
create table ViewCustomerSelection
as select customer.id, ToUpper(customer.name) as SomeOption where customer.name like 'A%'
</code></pre>
<p>I'd like to have entity Customer with ID and name, that only has records for records present in ViewCustomerSelection (note - in actuality the view is more complicated and can not be expressed using simple conditions)</p>
| <p>With my understandings you need create new entities inherited from ViewCustomerSelection. </p>
<p>I hope this <a href="http://mosesofegypt.net/post/Inheritance-and-Associations-with-Entity-Framework-Part-1.aspx" rel="nofollow">article</a> might help.</p>
|
How can I convince skeptical colleagues about proper namespaces in .Net? <p>My team is working on a conversion project to convert one product (but with many facets) from VB6 to .Net (we have over ~300k LOC). Before I got on board, the decision was made that regardless of the location of the assembly, or folder structure, all classes / structs will be in one namespace:</p>
<p>.</p>
<p>They even go as far as changing auto-generated application settings designer code, resource designer code, and such to force uniformity. How do I convince them that namespace use is good? What is the proper use of namespace and what are the pros and cons? I guess I am having a tough time understanding why my colleagues would go through so much hassle to save a few using lines. Any external, reputable references to support your argument would be much appreciated. Please help!</p>
| <h1>Good answers, already</h1>
<p>I read a lot of good answers (the drive folder's image is a good one, for example, as is the object/concept separation/organization).</p>
<p>Still, some other, less "technical" arguments could help, not to explain why namespaces are better than the alternative, but to unearth the bad reasons namespaces are not used.</p>
<h1><a href="http://en.wikipedia.org/wiki/Appeal_to_authority" rel="nofollow">Argument by Authority</a></h1>
<p>Every C#, VB.NET, Java, C++, whatever developer worth its salt on this planet acknowledge namespaces/packages are a good thing. Hey, <a href="https://www.mozilla.org/fr/js/simple-packages.html" rel="nofollow">they are even considering it in Mozilla's JavaScript</a>.</p>
<p>I guess that your question on Stack Overflow has the "Authority Argument" touch...
^_^</p>
<h1>Old Habits die hard</h1>
<p>I believe you are falling in a case of "Old habits".</p>
<p>While I have no direct experience about VB.NET against VB6 old habits, I do for C++ against stripped-down C-like, C++.</p>
<h2><i>Half the work...</i></h2>
<p>When dealing with legacy habits, half the work is discovering they already use namespaces, without acknowledging it.</p>
<p>For example (this is most true for C++ devs colliding with "old fashion", C-like code, but it is viable everywhere, I guess), do they use prefixes for their symbols.</p>
<p>Do they have:</p>
<ul>
<li><i>Account</i>User</li>
<li><i>Account</i>Price</li>
<li><i>Account</i>Id</li>
<li><i>Login</i>User</li>
<li><i>Login</i>Password</li>
</ul>
<p>classes/symbols, and explain that the "User" of Account is not the same than the "User" of login, and thus, the prefix to differentiate them?</p>
<p>The "pattern" go right through the ceiling when they prefix their symbols by module (which is certainly the case for your code, if it is large enough):</p>
<p>Do you have a MyUtil DLL, as well as MyKernel DLL and a MyGui DLL ?
Thus, do you have:</p>
<ul>
<li><i>MyUtil_</i>Something</li>
<li><i>MyUtil_</i>SomethingElse</li>
<li><i>MyKernel_</i>YetAnotherObject</li>
<li><i>MyKernel_</i>AnotherThing</li>
<li><i>MyGui_</i>SomeGui</li>
</ul>
<p>classes/symbols?</p>
<p><b>If yes, then they should acknowledge they are already using namespaces.</b></p>
<p>If not, then either your codebase is too small (but your "9 projects" tell me it's not), or they are regularly problems of name collision... Which can be resolved either by the prefixing explained above, or even better, by namespaces.</p>
<h2><i>The other half...</i></h2>
<p>The other half of the work is making them explain why their "namespaces" are better than the one built-in in the language (<i>this is the moment you should keep from banging your head against the walls in frustration because of lethal exposure braindead reasoning</i>).</p>
<p>Again, you can use the Argument by Authority thing (<i>What? You do believe know better than the Top Gun engineers from Microsoft?</i>), but in this case, you should give examples of why the .NET (or whatever) namespaces are better than the one they use (or don't use).</p>
<p>For VB.NET/.NET, there already more than enough good arguments, and I won't go on the ones behind C++ namespaces because it would be out of topic.</p>
<p>But at the very least, using built-in namespaces makes the prefix mentioned above optional. Quoting an example from internet (I'm not very knowledgeable of VB.NET):</p>
<pre><code>Imports MyWholeProject
Class HelloWorld
Public Sub Main()
Dim o As MyModuleAAA_MyObject = New MyModuleAAA_MyObject
Dim t As MyModuleBBB_MyThing = New MyModuleBBB_MyThing
Dim g As MyModuleCCC_MyGizmo = New MyModuleCCC_MyGizmo
REM etc.
End Sub
End Class
</code></pre>
<p>Is quite more verbose than the namespace enabled:</p>
<pre><code>Imports MyWholeProject.MyModuleAAA
Imports MyWholeProject.MyModuleBBB
Imports MyWholeProject.MyModuleCCC
Class HelloWorld
Public Sub Main()
Dim o As MyObject = New MyObject
Dim t As MyThing = New MyThing
Dim g As MyGizmo = New MyGizmo
REM etc.
End Sub
End Class
</code></pre>
<p>And verbosity lead to more obscure code, and thus bugs. Of course, you could replace MyModuleAAA by something less long, like MMAAA... But then, it leads to more obscure code, etc. etc..</p>
<p>More uses of namespaces on .NET can be found by Googling, like: <a href="http://www.vbdotnetheaven.com/UploadFile/ggaganesh/NamespacesInVbDotNet04202005005133AM/NamespacesInVbDotNet.aspx" rel="nofollow">http://www.vbdotnetheaven.com/UploadFile/ggaganesh/NamespacesInVbDotNet04202005005133AM/NamespacesInVbDotNet.aspx</a></p>
<h1>Project/Career related reasons</h1>
<p>Those reasons are more relatived to project/career management...</p>
<h2><i>Maintenance is not optional</i></h2>
<p>If your application is an old dying cow, where changing a label or the content of a combo is worth 2 days of work (it <i>does</i> happen) then there is no point, perhaps, to an extra-work of refactoring. In the other hand, if the refactoring is automated, then you should do it anyway.</p>
<p>But if your application is supposed to be used in the future, then sabotaging it to keep it in the past is a bad idea. You'll pay for it, someday. Each hour supposed to be won by avoiding maintenance will be paid twice or tenfold the day it will become unavoidable (you know, the day when you won't have time to do it properly because it is urgent...)</p>
<h2><i>Keeping oneself up-to-date is not optional</i></h2>
<p>This argument is for engineers, who have a career, and must keep their job: Like applications, software engineers can become obsolete.</p>
<p>And it means that the obsolete developer, when applying to another job, will lose, too. Because, hey, who wants to pay for someone who just don't get something as simple as namespaces?</p>
<p>Experience is a good thing when it is coupled with knowledge of current state-of-the-art. If not, then it's only dinosaur-old cynical and useless rambling about "<i>how it was better</i>(read: simpler)<i>, in my time, when we did not need all those gizmos like objects</i>".</p>
<h2><i>Keeping oneself up-to-date is not optional (manager side)</i></h2>
<p>By refusing to adapt to new features of the language (usually because "<i>we know better, you know?</i>"), engineers are just putting on concrete shoes while the competition is probably putting running shoes. This mean the application produced by an obsolete team will eventually lose. Period.</p>
<p>In a similar fashion, the team will hire new engineers, who probably know about the features, and who will become surprised, and then frustrated about the fact they are just programing like their grand-mothers did decades ago. The obsolete team won't keep new engineers very long (at least, the ones worth their pay).</p>
<p>Note that working on an obsolete product make it easier for top-level managers to decide it would get easier to rewrite it from scratch... And possibly somewhere else, with less-paid engineers and managers...</p>
|
Keyup Event After a Time Interval <p>I have this jQuery code that queries an API on a keyup event (via keyterms.php). It works as it is, but I'm trying to figure out how to implement a "pause" so to speak such that it will only do a query after a certain amount of time (say 2sec.) after the last keyup. Any help will be much appreciated. Thanks!</p>
<pre><code>$(document).ready(function() {
$('#loading').hide();
$('#q').keyup(function(){
$('#loading').show();
$.post("keyterms.php", {
q: $('#q').val()
}, function(response){
$('#qResult').fadeOut();
setTimeout("finishAjax('qResult', '"+escape(response)+"')", 400);
});
return false;
});
});
</code></pre>
| <p>You can use the jQuery plugin that StackOverflow uses for its <a href="http://stackoverflow.com/users">Users Page</a>; it's called <a href="https://github.com/medihack/typewatch" rel="nofollow">TypeWatch</a></p>
<p>It can be applied like such:</p>
<pre><code><input type="text" id="tb" />
<script>
$("#tb").typeWatch({ highlight: true, wait: 500, captureLength: -1, callback: finished });
</script>
</code></pre>
<p>Where in this case, <code>finished</code> is a callback function (a reference) that will be invoked when the amount of inputted time (in this case, 500ms) pass from the last keyUp event.</p>
<p>Here is a short description of the parameters it takes (<em>it actually takes one parameter, an object, and the properties of it are used as input parameters</em>) : </p>
<ul>
<li><em>highlight</em>: Aesthetics, determines if the text should be highlighted when the textbox receives focus. Default <strong>true</strong></li>
<li><em>wait</em>: The number of milliseconds to wait before the plugin considers that typing has finished. Default <strong>750</strong>.</li>
<li><em>captureLength</em>: The minimum amount of characters necessary before allowing the event to fire. Default <strong>2</strong>.</li>
<li><em>callback:</em> The function to callback after the user has "finished" typing. Default <strong>void</strong></li>
</ul>
<p>For a live <em>demo</em> of this plugin, check out the <a href="http://stackoverflow.com/users">Users Page</a></p>
|
In Mac OS X, is there a programmatic way to get the machine to go to sleep/hibernate? <p>Is there some command line or AppleScript that I can write/run to make the machine go to sleep automatically or even better, into hibernate mode? </p>
<p>I can run the program as root.</p>
| <pre><code>osascript -e 'tell application "Finder" to sleep'
</code></pre>
|
Using Python's ctypes to pass/read a parameter declared as "struct_name *** param_name"? <p>I am trying to use Python's ctypes library to access some methods in the scanning library <a href="http://www.sane-project.org/" rel="nofollow">SANE</a>. This is my first experience with ctypes and the first time I have had to deal with C datatypes in over a year so there is a fair learning curve here, but I think even without that this particular declaration would be troublesome:</p>
<pre><code>extern SANE_Status sane_get_devices (const SANE_Device *** device_list, SANE_Bool local_only);
</code></pre>
<p>First of all, I've successfully dealt with <code>SANE_Status</code> (an enum) and <code>SANE_Bool</code> (a typedef to <code>c_int</code>). Those were both simple. That first parameter, on the other hand, is causing me all sorts of grief. I'm unfamiliar with the "<code>***</code>" notation to begin with and my tracer bullets so far have yielded nothing more than garbage data. How do I format the input to this function such that I can read back a list of my Python structure-objects? For reference, the C structure being referenced is:</p>
<pre><code>typedef struct
{
SANE_String_Const name; /* unique device name */
SANE_String_Const vendor; /* device vendor string */
SANE_String_Const model; /* device model name */
SANE_String_Const type; /* device type (e.g., "flatbed scanner") */
}
SANE_Device;
</code></pre>
<p>Where <code>SANE_String_Const</code> is defined as a <code>c_char_p</code>.</p>
<p>My Python/ctypes version of this object is:</p>
<pre><code>class SANE_Device(Structure):
_fields_ = [
("name", c_char_p),
("vendor", c_char_p),
("model", c_char_p),
("type", c_char_p)]
</code></pre>
<p>Suggestions on what I should pass in such that I can get the expected behavior (a list of structure-objects) out of this? All responses appreciated.</p>
<p><strong>Update 1:</strong></p>
<p>Using the following, I was able to retrieve a correct SANE_Device Python structure:</p>
<pre><code>devices = pointer(pointer(pointer(SANE_Device())))
status = libsane.sane_get_devices(devices, c_int(0))
print status, devices, devices.contents.contents.contents.name
</code></pre>
<p>However, 1) yuck and 2) that seems like it would only work if there is a single result. I can't len() on <code>devices.contents.contents</code> or <code>devices.contents.contents.contents</code>. How am I to determine the number of results? The SANE docs specify that "If the function executes successfully, it stores a pointer to a NULL terminated array of pointers to SANE_Device structures in *device_list". Suggestions?</p>
<p><strong>Update 2:</strong></p>
<p>I was able to pass an ten-item array and then access the first element using:</p>
<pre><code>devices = pointer(pointer(pointer((SANE_Device * 10)())))
status = libsane.sane_get_devices(devices, c_int(0))
print status, devices, devices.contents.contents.contents[0].name
</code></pre>
<p>However, ten is obviously an arbitrary number and I have no way of determining the actual number of results. Trying to access <code>devices.contents.contents.contents[1].name</code> when only one device is connected causes a segmentation fault. There must be a proper way of dealing with variable-length constructs like these in ctypes.</p>
| <p>A <code>const SANE_Device ***</code> is a three-level pointer: it's a pointer to a pointer to a pointer to a constant SANE_Device. You can use the program <a href="http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html">cdecl</a> to decipher complicated C/C++ type definitions.</p>
<p>According to the <a href="http://www.sane-project.org/html/doc012.html">SANE documentation</a>, <code>SANE_get_devices()</code> will store a pointer to a NULL-terminated list of pointers to SANE devices if successful. Thus, the proper way to call it is to declare a variable of type <code>const SANE_Device **</code> (i.e. a pointer to a pointer to a constant `SANE_Device), and pass in the address of that pointer:</p>
<pre><code>const SANE_Device **device_list;
SANE_get_devices(&device_list, local_only); // check return value
// Now, device_list[0] points to the first device,
// device_list[1] points to the second device, etc.
// Once you hit a NULL pointer, that's the end of the list:
int num_devices = 0;
while(device_list[num_devices] != NULL)
num_devices++;
// num_devices now stores the total number of devices
</code></pre>
<p>Now, this is how you would call it from C code. I've skimmed the documentation on ctypes, and it appears that you want to use the <code>byref</code> function to pass the argument by reference, and that the value you pass should be a POINTER to a POINTER to a SANE_Device. Note the distinction between <code>pointer</code> and <code>POINTER</code>: the former creates a pointer to an <em>instance</em>, whereas the latter creates a pointer to a <em>type</em>. Thus, I'm guessing the following code will work:</p>
<pre><code>// SANE_Device declared as you had it
devices = POINTER(POINTER(SANE_Device))() // devices is a NULL pointer to a pointer to a SANE_Device
status = libsane.sane_get_devices(byref(devices), c_int(0))
if status != successful: // replace this by whatever success is
print error
else:
num_devices = 0
// Convert NULL-terminated C list into Python list
device_list = []
while devices[num_devices]:
device_list.append(devices[num_devices].contents) // use .contents here since each entry in the C list is itself a pointer
num_devices += 1
print device_list
</code></pre>
<p>[Edit] I've tested the above code using a very simple placeholder for <code>SANE_get_devices</code>, and it works.</p>
|
Processing CSV files from the Web using embedded Java database <p>Short version: assuming I don't want to keep the data for long, how do I create a database programmaticly in HSQLDB and load some CSV data into it to? My schema will match the files exactly and the files do have adequate column names.</p>
<p>This is an unattended process.</p>
<p>Details:</p>
<p>I need to apply some simple SQL techniques to three CSV files downloaded via the web, then create some DTOs which I can then use with some existing code to process them some more, and save them via REST. I don't really want to mess around with databases but the CSV files are linked by foreign keys, so I was thinking of using an in-memory embedded database to do the work, then throw the whole lot away.</p>
<p>I had in mind a command line app working like this:</p>
<ol>
<li>Create a fresh database in HSQLDB.</li>
<li>Start three HTTP GETs in three
threads using Apache HttpClient.</li>
<li>Import the CSVs into three HSQLDB
MEMORY tables.</li>
<li>Run some SQL.</li>
<li>Parse the results into my existing
DTOs.</li>
<li>Etc...</li>
</ol>
<p>I could use pointers to code and utilities helpful for items 1, and 3. Also is there an alternative to HSQLDB I should consider?</p>
| <p>Check <a href="http://opencsv.sourceforge.net/" rel="nofollow">opencvs</a>. It helps you to parse CSV files.</p>
|
ActionLinks doesn't always work in FireFox and Safari <p>I've been learning the new ASP.NET MVC framwork lately and I've developed a test site for a friend who runs a "light café" in Sweden. The plan is to release it within a week or so after performing some final adjustments and fixing some security issues. </p>
<p>Yesterday I published the site to a webhost running IIS 6, so the first thing I had to do was to fix the issue of the extensionless URLs. I did this with the help from Phil Haack's blog post <a href="http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx" rel="nofollow">ASP.NET MVC on IIS 6 Walkthrough</a> </p>
<p>Now I have run into another issue that works well in IE7 but not in Firefox 3 and Safari.</p>
<p>On the site I use a master page containing a "left content" with a menu. The menu consists of ActionLinks. The problem is that only the first (topmost) link works as a link, the others only look like links but they're unclickable. When I view the source everything looks good.</p>
<p>Has anyone come across a solution that fixes this, or do you maybe know what can cause this behavior? The link to the demo site is <a href="http://www.tarsius.se" rel="nofollow">Demo site</a></p>
<p>Help would be greatly appreciated since I want this to work on all browsers.</p>
| <p>Your "main" div is being placed on top of the "links" div so they can't be clicked.</p>
<p>Adding a:</p>
<p>float: right;</p>
<p>To the CSS for #main allows the links to be clicked.</p>
|
Create local user with PowerShell (Windows Vista) <p>I've installed PowerShell recently and one of the first things I started looking for was how to create a new user. After looking for some time I still haven't found this.
I have a little experience in bash on linux and find it very effective. Creating users there is trivial.
Is there an easy\built-in way to create a local user with PowerShell?</p>
<p>Thank you.</p>
| <p>You can use the localhost's <a href="http://msdn.microsoft.com/en-us/library/aa772170.aspx">ADSI</a>:</p>
<pre><code>function create-account ([string]$accountName = "testuser") {
$hostname = hostname
$comp = [adsi] "WinNT://$hostname"
$user = $comp.Create("User", $accountName)
$user.SetPassword("Password1")
$user.SetInfo()
}
</code></pre>
|
using (Fluent) NHibernate with StructureMap (or any IoCC) <p>On my quest to learn NHibernate I have reached the next hurdle; how should I go about integrating it with StructureMap?</p>
<p>Although code examples are very welcome, I'm more interested in the general procedure.</p>
<p>What I was planning on doing was...</p>
<ul>
<li>Use Fluent NHibernate to create my class mappings for use in NHibs Configuration</li>
<li>Implement ISession and ISessionFactory</li>
<li>Bootstrap an instance of my ISessionFactory into StructureMap as a singleton</li>
<li>Register ISession with StructureMap, with per-HttpRequest caching</li>
</ul>
<p>However, don't I need to call various tidy-up methods on my session instance at the end of the HttpRequest (because thats the end of its life)?</p>
<p>If i do the tidy-up in Dispose(), will structuremap take care of this for me?</p>
<p>If not, what am I supposed to do?</p>
<p>Thanks</p>
<p>Andrew</p>
| <p>I use StructureMap with fluent-nhibernate (and NH Validator) in 3 of my current projects. 2 of those are ASP MVC apps and the third is a WCF web service.</p>
<p>Your general strategy sounds about right (except you won't be making your own Session or SessionFactory, as was already pointed out in comments). For details, snag my configuration code from here:</p>
<p><a href="http://brendanjerwin.github.com/development/dotnet/2009/03/11/using-nhibernate-validator-with-fluent-nhibernate.html" rel="nofollow">http://brendanjerwin.github.com/development/dotnet/2009/03/11/using-nhibernate-validator-with-fluent-nhibernate.html</a></p>
<p>The post is really about integrating NH Validator and Fluent-NHibernate but you can see exactly how I register the session factory and ISession with StructureMap in the "Bonus" section of the post.</p>
<p>RE: Tidy up: You should try and always work within a transaction and either commit or roll-back the transaction at the end of your unit of work. NH only utilizes SQL Connections when it needs them and will take care of the cleanup of that limited resource for you. Normal garbage collection will take care of your sessions themselves. </p>
<p>The Session Factory is a very expensive object that you will want to only initialize once and keep around for the life of your app.</p>
|
Intersection of two lines defined in (rho/theta ) parameterization <p>Have created a c++ implementation of the Hough transform for detecting lines in images. Found lines are represented using rho, theta, as described on wikipedia:</p>
<blockquote>
<p>"The parameter r represents the distance between the line and the origin, while θ is the angle of the vector from the origin to this closest point "</p>
</blockquote>
<p>How can i find the intersection point in x, y space for two lines described using r, θ?</p>
<p>For reference here are my current functions for converting in and out of hough space:</p>
<pre><code>//get 'r' (length of a line from pole (corner, 0,0, distance from center) perpendicular to a line intersecting point x,y at a given angle) given the point and the angle (in radians)
inline float point2Hough(int x, int y, float theta) {
return((((float)x)*cosf(theta))+((float)y)*sinf(theta));
}
//get point y for a line at angle theta with a distance from the pole of r intersecting x? bad explanation! >_<
inline float hough2Point(int x, int r, float theta) {
float y;
if(theta!=0) {
y=(-cosf(theta)/sinf(theta))*x+((float)r/sinf(theta));
} else {
y=(float)r; //wth theta may == 0?!
}
return(y);
}
</code></pre>
<p>sorry in advance if this is something obvious..</p>
| <p>Looking at the <a href="http://en.wikipedia.org/wiki/Hough_transform">Wikipedia page</a>, I see that the equation of a straight line corresponding to a given given r, θ pair is</p>
<pre>r = x cosθ + y sinθ </pre>
Thus, if I understand, given two pairs r1, θ1 and r2, θ2, to find the intersection you must solve for the unknowns x,y the following linear 2x2 system:
<pre>x cos θ1 + y sin θ1 = r1
x cos θ2 + y sin θ2 = r2
</pre>
<p>that is AX = b, where</p>
<pre>A = [cos θ1 sin θ1] b = |r1| X = |x|
[cos θ2 sin θ2] |r2| |y|
</pre>
|
Is there any plugin framework for Java Applets? <p>We have a large Java application that run as applet or Java Web Start. And it grow more and more. Typical a user need only a small part of the classes. Because Java does not know which class can it found in which jar file that it load all jar files until it find the class. If it will load a class that not exist (for example a resource bundle) then it load all jar files. This reduce the start time on a small bandwidth very large.</p>
<p>Is there a small framework with which we can load the plugins only if needed? Or better if needed and on background?</p>
<p>Of course the framework should not delay the start time self with it large size.</p>
<p>I think it should use a URLClassLoader for downloading.</p>
| <p>I've heard that you can implement custom class loaders and I've seen tutorials on this subject. With this you should be able to control what gets downloaded more precisely. Sorry, I haven't tried this myself.</p>
|
flex 3 and acessing remote java objects <p>im just starting to learn flex and im trying to understand how Flex does remoting? From what i have read it looks like Flex provides a LifeCycle data services war which sits on your server and intercepts your remote calls , is this close?</p>
<p>Im concerned that if i use this option that 1. Ill have to add an extra war to my server - the lifecycle data service war and 2. That i will have to pay for a license for each instance i use on each cpu.</p>
<p>Is there an easier [free] option out there which i can use to call my remote java objects from within my flex mxml?</p>
| <p>Blaze DS is based off the same APIs / code base as LiveCycle Data Services and is completely free and open source:</p>
<p><a href="http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/" rel="nofollow">http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/</a></p>
<p>There are a number of other options available including:</p>
<ul>
<li>Granite DS</li>
<li>WebOrb</li>
<li>FluorineFX (for .NET)</li>
</ul>
<p>There are also solutions for PHP, Python and Ruby, although I can't recall their names right now.</p>
|
Silverlight button style how to prevent the focused state when the button is pressed? <p>In my custom button I need to show that it had focus(provides some tactile feel to tabbing to the button) and show that its pressed but what I have found is my focused state is displaying rather then my pressed state. How can I correct this. I would like to have mouse over to pressed not mouse over then focused(when the button is clicked )</p>
<p>Here is a sample of my control template.</p>
<pre><code><UserControl.Resources>
<Style x:Key="GavelButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#FF000000" x:Name="grid">
<vsm:VisualStateManager.VisualStateGroups>
<vsm:VisualStateGroup x:Name="FocusStates">
<vsm:VisualState x:Name="Unfocused"/>
<vsm:VisualState x:Name="Focused">
<Storyboard>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.OpacityMask).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFFFFFF"/>
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="grid" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
<SplineColorKeyFrame KeyTime="00:00:00" Value="#FF2844B9"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
</vsm:VisualStateGroup>
<vsm:VisualStateGroup x:Name="CommonStates">
<vsm:VisualStateGroup.Transitions>
<vsm:VisualTransition GeneratedDuration="00:00:00.2000000"/>
</vsm:VisualStateGroup.Transitions>
<vsm:VisualState x:Name="MouseOver">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1.5"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="1.5"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
<vsm:VisualState x:Name="Normal"/>
<vsm:VisualState x:Name="Pressed">
<Storyboard>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.5"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="image" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)">
<SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.5"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</vsm:VisualState>
<vsm:VisualState x:Name="Disabled"/>
</vsm:VisualStateGroup>
</vsm:VisualStateManager.VisualStateGroups>
<Image Cursor="Hand" x:Name="image" RenderTransformOrigin="0.5,0.5" Source="11_64x64.png" Stretch="Fill" OpacityMask="#FF000000">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>;
</code></pre>
| <p>When you press it is becomes focused, can't do anything about that...you can clear the Visual State Manager's Focus content and then it won't <em>look</em> focused, but it get focus from the mouse interaction no matter what you do.</p>
|
Mapping of strings to integers <p>What is the easiest way in Java to map strings (Java <code>String</code>) to (positive) integers (Java <code>int</code>), so that</p>
<ul>
<li>equal strings map to equal integers, and</li>
<li>different strings map to different integers?</li>
</ul>
<p>So, similar to <code>hashCode()</code> but different strings are required to produce different integers. So, in a sense, it would be a hasCode() without the collision possibility.</p>
<p>An obvious solution would maintain a mapping table from strings to integers,
and a counter to guarantee that new strings are assigned a new integer. I'm just wondering
how is this problem usually solved.
Would also be interesting to extend it to other objects than strings.</p>
| <p>Have a look at <a href="http://en.wikipedia.org/wiki/Perfect_hash_function">perfect hashing</a>.</p>
|
Converting MySql DateTime type into something more friendly <p>I have a Java web app that reads a MySql db and returns DateTime fields. What is the best way to convert the DateTime fields returned in the resultset into something more readable?</p>
<p>Currently the DateTime fields print as:</p>
<p>2008-12-14 16:30:00</p>
<p>but I would like something more user friendly like:</p>
<p>14 Dec 2008 at 16:30</p>
<p>I am populating an ArrayList with these dateTimes from a pojo. I would like to format them before adding to the arrayList, so then I can just print the contents of the arrayList in the JSP.</p>
| <p>Another option is to use the JSTL. The formatting library makes it easy to display a date in any format and it is i18n aware. The advantage is that you can leave the date as a Date object and manipulate it as such but only convert it when you need to display. The format tag will look like this:</p>
<pre><code><fmt:formatDate value="${myDate}" dateStyle="MEDIUM"/>
</code></pre>
<p>Like I said above, one big advantage is that it is i18n aware so you can display the date in a localized format.</p>
<p>The full syntax is:</p>
<pre><code> <fmt:formatDate value="expression"
timeZone="expression"
type="field" dateStyle="style"
timeStyle="style"
pattern="expression"
var="name" scope="scope"/>
</code></pre>
|
consume a asp.net web service that returns json from an stand alone html page <p>I've developed a web service in asp.net and am able to test it from an in-project aspx page and can readily display the information that was returned in JSON format.</p>
<p>I now need to consume the web service from a stand-alone html page.</p>
<p>Does someone have experience with this? I'm puzzled by the part that would replace this</p>
<pre><code><asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~\MyService.asmx" />
</Services>
</asp:ScriptManager>
</code></pre>
<p>If this is not possible with straight html and javascript, can someone show me a stand-alone php page that would do it?</p>
| <p>See this link:</p>
<p><a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" rel="nofollow">http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/</a></p>
<p>Use JQuery</p>
<p>www.jquery.org</p>
<p>Essentially, you make your Web Service script callable, just an attribute in your Web Service definition and you do:</p>
<pre><code> $.ajax({
type: "POST",
url: "~/MyService.asmx/MyMethod",
data: "{parameterName:'" aStringArgument + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = msg.d
// Now var is an object with properties just like your object
}
});
</code></pre>
|
Django objects.filter, how "expensive" would this be? <p>I am trying to make a search view in Django. It is a search form with freetext input + some options to select, so that you can filter on years and so on. This is some of the code I have in the view so far, the part that does the filtering. And I would like some input on how expensive this would be on the database server.</p>
<p><code>
soknad_list = Soknad.objects.all()</p>
<pre><code>if var1:
soknad_list = soknad_list.filter(pub_date__year=var1)
if var2:
soknad_list = soknad_list.filter(muncipality__name__exact=var2)
if var3:
soknad_list = soknad_list.filter(genre__name__exact=var3)
# TEXT SEARCH
stop_word_list = re.compile(STOP_WORDS, re.IGNORECASE)
search_term = '%s' % request.GET['q']
cleaned_search_term = stop_word_list.sub('', search_term)
cleaned_search_term = cleaned_search_term.strip()
if len(cleaned_search_term) != 0:
soknad_list = soknad_list.filter(Q(dream__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term) | Q(name__icontains=cleaned_search_term) | Q(school__name__icontains=cleaned_search_term))
</code></pre>
<p></code></p>
<p>So what I do is, first make a list of all objects, then I check which variables exists (I fetch these with GET on an earlier point) and then I filter the results if they exists. But this doesn't seem too elegant, it probably does a lot of queries to achieve the result, so is there a better way to this?</p>
<p>It does exactly what I want, but I guess there is a better/smarter way to do this. Any ideas?</p>
| <p>filter itself doesn't execute a query, no query is executed until you explicitly fetch items from query (e.g. get), and list( query ) also executes it.</p>
|
Need to re-format phone number entries in a PHP Formmail script <p>I have a simple text field for "Phone Number" in a contact form on a client's website. The formmail script returns whatever the user types into the field. For example, they'll receive "000-000-0000", "0000000000", (000) 000-000, etc. The client would like to receive all phone numbers in this form: 000-000-0000. Can someone provide a simple script that would strip out all extraneous punctuation, then re-insert the dashes?</p>
<p>I'm not a programmer, just a designer so I can't provide any existing code for anyone to evaluate, though I'll be happy to email the formmail script to anyone who can help.</p>
<p>Thanks.
A. Grant</p>
| <pre><code><?php
function formatPhone($number)
{
$number = preg_replace('/[^\d]/', '', $number); //Remove anything that is not a number
if(strlen($number) < 10)
{
return false;
}
return substr($number, 0, 3) . '-' . substr($number, 3, 3) . '-' . substr($number, 6);
}
foreach(array('(858)5551212', '(858)555-1212', '8585551212','858-555-1212', '123') as $number)
{
$number = formatPhone($number);
if($number)
{
echo $number . "\n";
}
}
?>
</code></pre>
<p>the above returns:</p>
<pre><code>858-555-1212
858-555-1212
858-555-1212
858-555-1212
</code></pre>
|
Private method naming convention <p>Is there a convention for naming the private method that I have called "<code>_Add</code>" here? I am not a fan of the leading underscore but it is what one of my teammates suggests.</p>
<pre><code>public Vector Add(Vector vector) {
// check vector for null, and compare Length to vector.Length
return _Add(vector);
}
public static Vector Add(Vector vector1, Vector vector2) {
// check parameters for null, and compare Lengths
Vector returnVector = vector1.Clone()
return returnVector._Add(vector2);
}
private Vector _Add(Vector vector) {
for (int index = 0; index < Length; index++) {
this[index] += vector[index];
}
return this;
}
</code></pre>
| <p>I usually see and use either "AddCore" or "InnerAdd"</p>
|
Database Abstraction in a Reporting Application <p>In a reporting application, Is it possible to abstract reporting logic and the database schema details? </p>
<p>I have a Reporting Services application with a reasonably complex reporting logic, I am trying to migrate the application to some other databases. (Databases that are built for the same purpose but developed by different software-houses. ) </p>
<p>Is it a wise decision to use a web services / WCF layer in the middle? What else options can be considered?</p>
| <p>It would be hard to do this sort of thing in a one-size-fits-all way in the general case but you could try one of these:</p>
<ul>
<li><p>Build some views over the database schema and
write the reporting sprocs against
those. This means that you have some flexibility in the underlying database schema and can use the views as an abstraction layer.</p></li>
<li><p>Build some sort of data warehouse
platform and write an ETL process to
populate it from the various data sources. This is more flexible but more effort to build and it will only work from a periodic refresh. If that degree of latency is acceptable for your application then I would suggest that the data warehouse system is the better approach. </p>
<p>The key advantage of a data warehouse is that it is optimised for reporting and has a consistent interface across all the data sources - you consolidate them into a single database with one schema. The reports are developed against that schema. Adding new systems is achieved by writing an ETL process to populate the warehouse; the reports continue to work regardless of the data source.</p></li>
</ul>
<p>WCF is a network communication system. You will find that it difficult to make this sort of architecture handle large volumes of data on a transaction by transaction basis - a batch loading ETL process would be much more efficient. However, if you need a real-time feed (perhaps for a trading floor system) you might be able to do it with something like this.</p>
<p>If you nead a low latency feed another approach would be to investigate a genre of tooling called <a href="http://en.wikipedia.org/wiki/Enterprise_Information_Integration" rel="nofollow">Enterprise Information Integration</a>. Perhaps the most widely available tool that can do this is a <a href="http://msdn.microsoft.com/en-us/library/ms140311.aspx" rel="nofollow">Data Source View</a> in <a href="http://msdn.microsoft.com/en-us/library/ms141026.aspx" rel="nofollow">SSIS</a> which does give you some flexibility in mapping arbitrary data sources to a consistent schema. It isn't as sophisticated as the best of breed EII tools but you can put SSIS packages on top of it and use those as a data source for your reports if you need to further transform the data.</p>
<p>However, I've never built a system structured like this so I can't really vouch for how well it works in practice. I would guess that it would be quite fragile and difficult to break down into parts that can be unit tested, so development and maintenance will be quite time-consuming for a system of non-trivial complexity.</p>
<p>If you want to investigate other EII systems on the market <a href="http://www.dmoz.org/Computers/Software/Enterprise_Information_Integration/" rel="nofollow">This link</a> is a directory of various articles about EII and some other EII tooling vendors.</p>
|
What is the best library for Java to grid/cluster-enable your application? <p>This is the ability to run your application on a cluster of servers with the intent to distribute the load and also provide additional redundancy.</p>
<p>I've seen a presentation for <a href="http://www.gridgain.com/">GridGain</a> and I was very impressed with it.</p>
<p>Know of any others?</p>
| <p>There are several:</p>
<ul>
<li><a href="http://www.terracotta.org/">Terracotta</a> (<a href="http://www.terracotta.org/confluence/display/wiki/FAQ#FAQ-Q%3AWhat%27syourlicense%3F">open source, based on Mozilla Public License</a>);</li>
<li><a href="http://www.oracle.com/technology/products/coherence/index.html">Oracle Coherence</a> (formerly Tangosol Coherence; commercial; based on <a href="http://jcp.org/en/jsr/detail?id=107">JSR 107</a>, which was never adopted officially);</li>
<li><a href="http://www.gigaspaces.com/">GigaSpaces</a> (commercial; based on <a href="http://www.jini.org/wiki/JavaSpaces_Specification">JavaSpaces API</a>, part of <a href="http://www.jini.org/wiki/Main_Page">Jini</a>);</li>
<li><a href="http://www.gridgain.com/">GridGain</a>, which you mentioned (open source: <a href="http://en.wikipedia.org/wiki/LGPL">LGPL</a>);</li>
<li><a href="http://www.danga.com/memcached/">memcached</a> with a <a href="http://www.whalin.com/memcached/">Java client library</a> (open source: <a href="http://en.wikipedia.org/wiki/BSD_License">BSD License</a>;</li>
<li><a href="http://ehcache.sourceforge.net/">EHCache</a> (open source: <a href="http://ehcache.sourceforge.net/license.html">Apache Software License</a>;</li>
<li><a href="http://www.opensymphony.com/oscache/">OSCache</a> (open source: <a href="http://www.opensymphony.com/oscache/license.action">modified Apache License</a>; and</li>
<li>no doubt several others.</li>
</ul>
<p>Now I haven't used all of these but I've used or investigated the majority of them.</p>
<p>GridGain and GigaSpaces are more centred around <a href="http://en.wikipedia.org/wiki/Grid_computing">grid computing</a> than caching and (imho) best suited to compute grids than data grids (see <a href="http://java.dzone.com/articles/compute-grids-vs-data-grids">this explanation of compute vs data grids</a>). I find GigaSpaces to be a really interesting technology and it has several licensing options, including a free version and a free full version for startups.</p>
<p>Coherence and Terracotta try to treat caches as <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html">Maps</a>, which is a fairly natural abstraction. I've used Coherence a lot and it's an excellent high-performance product but not cheap. Terracotta I'm less familiar with. The documentation for Coherence I find a bit lacking at times but it really is a powerful product.</p>
<p>OSCache I've primarily used as a means of reducing memory usage and fragmentation in Java Web applications as it has a fairly neat JSP tag. If you've ever looked at compiled JSPs, you'll see they do a lot of String concatenations. This tag allows you to effectively cache the results of a segment of JSP code and HTML into a single String, which can hugely improve performance in some cases.</p>
<p>EHCache is an easy caching solution that I've also used in Web applications. Never as a distributed cache though but it can do that. I tend to view it as a quick and dirty solution but that's perhaps my bias.</p>
<p>memcached is particularly prevelent in the PHP world (and used by such sites as Facebook). It's a really light and easy solution and has the advantage that it doesn't run in the same process and you'll have arguably better interoperability options with other technology stacks, if this is important to you.</p>
|
Add references manually <p>Is there anyway I can make the process of adding references to C# projects less painful?</p>
<p>Every time I create a new C# class library project. I have to use the Add Reference dialog for 5 times at least.</p>
| <p>Install the <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow">PowerCommands for Visual Studio</a>. You can then simply copy and paste a bunch of references between projects (plus lots of other useful commands). Some of the other useful commands are:</p>
<ul>
<li>Collapse Projects (my favourite)</li>
<li>Copy References and Paste References</li>
<li>Remove and Sort Usings </li>
<li>Open Containing Folder</li>
<li>Open Command Prompt</li>
</ul>
|
Smart pointers for Windows Mobile 6 SDK <p>I cannot get std::tr1::shared_ptr for my WinMobile project since the STL for WinCE is maintained by a different team at Microsoft :( aarrgh...</p>
<p>Anyone worked with another thread-safe, reference counting smart pointers? I'm actually using yasper which seems to be good. </p>
<p>Thank you very much.</p>
| <p>I'd also recommend boost::shared_ptr. You can do what I did for a library, and use a #define to switch between std::tr1::shared_ptr and boost::shared_ptr, depending on the capabilities of the compiler. That way your code doesn't need to be modified [much] if/when the CE team add tr1 support. Just my 2c.</p>
|
C++ Operator Ambiguity <p>Forgive me, for I am fairly new to C++, but I am having some trouble regarding operator ambiguity. I think it is compiler-specific, for the code compiled on my desktop. However, it fails to compile on my laptop. I think I know what's going wrong, but I don't see an elegant way around it. Please let me know if I am making an obvious mistake. Anyhow, here's what I'm trying to do:</p>
<p>I have made my own vector class called Vector4 which looks something like this:</p>
<pre><code>class Vector4
{
private:
GLfloat vector[4];
...
}
</code></pre>
<p>Then I have these operators, which are causing the problem:</p>
<pre><code>operator GLfloat* () { return vector; }
operator const GLfloat* () const { return vector; }
GLfloat& operator [] (const size_t i) { return vector[i]; }
const GLfloat& operator [] (const size_t i) const { return vector[i]; }
</code></pre>
<p>I have the conversion operator so that I can pass an instance of my Vector4 class to glVertex3fv, and I have subscripting for obvious reasons. However, calls that involve subscripting the Vector4 become ambiguous to the compiler:</p>
<pre><code>enum {x, y, z, w}
Vector4 v(1.0, 2.0, 3.0, 4.0);
glTranslatef(v[x], v[y], v[z]);
</code></pre>
<p>Here are the candidates:</p>
<pre><code>candidate 1: const GLfloat& Vector4:: operator[](size_t) const
candidate 2: operator[](const GLfloat*, int) <built-in>
</code></pre>
<p>Why would it try to convert my Vector4 to a GLfloat* first when the subscript operator is already defined on Vector4? Is there a simple way around this that doesn't involve typecasting? Am I just making a silly mistake? Thanks for any help in advance.</p>
| <p>This is explained in the book "C++ Templates - The Complete Guide". It's because your operator[] takes size_t, but you pass a different type which first has to undergo an implicit conversion to size_t. On the other side, the conversion operator can be chosen too, and then the returned pointer can be subscript. So there is the ambiguity. Solution is to drop the conversion operator. They should generally be avoided as they just introduce problems, as you see.</p>
<p>Provide a <code>begin</code> and <code>end</code> member function that returns <code>vector</code> and <code>vector + 4</code> respectively. Then you can use <code>v.begin()</code> if you want to pass to native openGL functions.</p>
<p>There is a bit confusion in the comments. I think i will update this answer now to reflect the most recent concept of this.</p>
<pre><code>struct Vector4 {
// some of container requirements
typedef GLfloat value_type;
typedef GLfloat& reference;
typedef GLfloat const& const_reference;
typedef GLfloat * iterator;
typedef GLfloat const * const_iterator;
typedef std::ptrdiff_t difference_type;
typedef std::size_t size_type;
static const size_type static_size = 4;
// returns iterators to the begin and end
iterator begin() { return vector; }
iterator end() { return vector + size(); }
const_iterator begin() const { return vector; }
const_iterator end() const { return vector + size(); }
size_type size() const { return static_size; }
size_type max_size() const { return static_size; }
void swap(Vector4 & that) {
std::swap(*this, that);
}
// some of sequences
reference operator[](size_type t) { return vector[t]; }
const_reference operator[](size_type t) const { return vector[t]; }
// specific for us. returns a pointer to the begin of our buffer.
// compatible with std::vector, std::array and std::string of c++1x
value_type * data() { return vector; }
value_type const* data() const { return vector; }
// comparison stuff for containers
friend bool operator==(Vector4 const&a, Vector4 const&b) {
return std::equal(a.begin(), a.end(), b.begin());
}
friend bool operator!=(Vector4 const&a, Vector4 const&b) { return !(a == b); }
friend bool operator<(Vector4 const&a, Vector4 const&b) {
return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end());
}
friend bool operator> (Vector4 const&a, Vector4 const&b) { return b < a; }
friend bool operator<=(Vector4 const&a, Vector4 const&b) { return !(b < a); }
friend bool operator>=(Vector4 const&a, Vector4 const&b) { return !(a < b); }
private:
GLfloat vector[4];
}
</code></pre>
|
CSS "see-through" background - crazy navigation menu problem <p>I have a crazy navigation menu that I have to code. It's kind of tough. Please see the screenshot of the design here:</p>
<p></p>
<p><a href="http://i41.tinypic.com/307xfo9.png" rel="nofollow">navigation menu screenshot</a></p>
<p>As you can see, the background of the "Home" menu item is quite tough! I can't figure out how to make its background "see-through", meaning it cuts through the dark background and shows the patterned green background.</p>
<p>Do you know how to do this using css?</p>
<p>Thanks in advance.</p>
| <p>You can use either:</p>
<pre><code>background: transparent;
background: inherit;
</code></pre>
<p>But, you'll need to structure your HTML so that the <strong><em>Home</em></strong>, <strong><em>Journal</em></strong>, etc. links are embedded in the box with the background.</p>
<p><hr /></p>
<p>For rounded corners, <a href="http://stackoverflow.com/questions/7089/what-is-the-best-way-to-create-rounded-corners-using-css">check this out</a>.</p>
<p>Or you can use images with shaped transparency as the background.</p>
<p><hr /></p>
<p>@Gary [comment]: <code>inherit</code> grabs the first settings it finds going up the hierarchy. So if you have a middle layer, it's gonna pick up on its settings instead.</p>
<p>Something you might try then is to use:</p>
<pre><code>background-image: url('greencheckers'); /* outer */
background-color: black; /* middle */
background-image: inherit; /* link */
</code></pre>
<p>In theory, it should look for the first <code>background-image</code> setting, then. But, I've never used this, so no guarantees.</p>
|
What is the best method for paging with datagrid performance? <p>On a site with a high number of users, should paging be handled in code, or with a stored procedure. If you have employed caching, please include your success factors.</p>
| <p>Personally, I never page stuff outside SQL Server. I do this at database level as if you have a million records to be paged, if you retrieve it in application layer and page it there, you are already paying a <b>huge</b> cost.</p>
|
Why .NET strips off one <form> tag from the page if there is already a form with runat server attribute? <p>It doesn't remove everything inside the 2nd form tag but just hides the and tags from the page</p>
<p>Any ideas and workaround?</p>
| <p>Nesting of forms is not allowed in html. So you cant add another form inside the server-form.</p>
<p>But it is perfectly legal in ASP.NET to add get-forms outside of the server form.</p>
|
jQuery, ThickBox with Ajax content for beginner <p>Here is the scenario: </p>
<p>ThickBox is opened from parent window (when button is pressed) with Ajax content (div based form) that contains the set of inputs with autocomplete support. Once ThickBox(form) is closed the input values should be passed to parent window.</p>
<p>Question:
the content of ThickBox is loaded dynamically, so what's the correct way to have an initial callback to manipulate ThickBox content with jQuery (kind of $(ThickBox).ready.. )?</p>
| <p>My prefered option is to investigate other modal plugin options such as <a href="http://dev.iceburg.net/jquery/jqModal/#how" rel="nofollow">jqModal</a>. This does expose onShow and onHide event hooks that you can utilise.</p>
<p>Thickbox is showing its age, it does not expose any 'show' events that you can observe.
If you are hell bent on using thickbox then you have a few options.</p>
<p>One option would be to use the global ajax events that jQuery exposes e.g <a href="http://docs.jquery.com/Ajax/ajaxSuccess#callback" rel="nofollow">$.ajaxSuccess event</a>. This will fire when thickbox has successfully requested the data to show. However at this point thickbox may not have added the data to the modal, you will have to try this out. </p>
<p>E.g</p>
<pre><code>$.ajaxSuccess( function(evt, request, settings){
//ajax method has completed
});
</code></pre>
<p>Be aware that this event will fire on completion of <strong>every</strong> ajax event that happens within your page therefore you may want some extra checks</p>
<p>Another option is to change the thickbox script and add your own callback code that allows you to pass in a function which will be raised when the modal is shown.</p>
|
Singleton with a public (single-instance) constructor <p>As an exercise, I'm translating parts of our large and battle-hardened Delphi-framework to C#. </p>
<p>Included in this framework is a generic singleton parent class. Of course, implementing a singleton in C# is fairly easy (there is even a Jon Skeet article, so what more could I wish for), but our Delphi singleton has a slightly different take on the pattern: as opposed to publishing an 'instance' property/method, it has a "fake" constructor that always returns the same instance. The essential characteristic of this approach is that the <i>user of the singleton class doesn't know that he is dealing with a singleton</i>:
as far as they know, they just construct any old class and request some information from it.</p>
<p>I want to accomplish the same thing in C# (as an exercise, so it doesn't have to be production-quality code, evil hackery is fine), but so far I've failed. </p>
<p>Any suggestion to make a simple <code>myInstance = new MyClass();</code> always return the same instance is most welcome! </p>
<p><hr /></p>
<h2>Additional info</h2>
<ul>
<li><p>We are talking a convenience-implementation of the singleton pattern, as offered by the framework. It doesn't necessarely have to be a parent-class, but it does have to assist the developers in creating their own singletons as well. Requiring them to manually redirect all their method calls to the single-instance will not make them overflow with joy. :-)</p></li>
<li><p>I'm not really interested in debating whether or not this is the right way to deal with singletons, for now I'm just interested in the finer art of c#-tweaking.</p></li>
</ul>
| <p>You would do a Proxy (Edit: As Tom points out below, the proper design pattern is Monostate):</p>
<pre><code>public class MyClass {
MyActualClass _actual;
public MyClass() {
_actual = MyActualClass. Instance;
}
public DoStuff() {
_actual.DoStuff();
}
}
internal class MyActualClass {
private MyActualClass {
}
public DoStuff() {
...
}
MyActualClass _instance;
public static Instance {
get {
if(_instance == null)
_instance = new MyActualClass()
return _instance;
}
}
}
</code></pre>
<p>....</p>
<pre><code>public static void Main() {
var my1 = new MyClass();
var my2 = new MyClass();
}
</code></pre>
<p>my1 != my2 but my1.DoStuff() calls the same instance of the method as my2.DoStuff()
This would be simplified even further if you programmed of an interface only.</p>
<p>Edit: The equality problem could partially be solved by making _actual protected internal and overwriting MyClass.Equals(object obj) to check whether this._actual == obj._actual</p>
|
How do I make a generic object list work from a specific base class? <pre><code> TMyDataList<T: TBaseDatafile, constructor> = class(TObjectList<TBaseDatafile>)
public
constructor Create;
procedure upload(db: TDataSet);
end;
</code></pre>
<p>I read in a blog post (I don't remember where now) that this is the way to declare a generic-based class with a specific base type for the generic object. And the compiler will accept it just fine. But when I try to use it, it decides not to cooperate.</p>
<pre><code>type
TDescendantList = TMyDataList<TDescendantDatafile>;
</code></pre>
<p>This gives me a compiler error.</p>
<p>[DCC Error] my_database.pas(1145): E2010 Incompatible types: 'TDescendantDatafile' and 'TBaseDatafile'</p>
<p>Thing is, 1145 isn't even a valid line. The file in question ends at #1142, and the type declaration that it's complaining about is on line #20. This makes me wonder if it's a compiler glitch. Or do I just not quite have the syntax right? Does anyone know a way to make this work?</p>
<p>EDIT: Jim pointed out that it compiles fine when he tried it. A bit more information: I have the base datafile type and the generic list declared in the same unit, while TDescendantDatafile is in a second unit and TDescendantList is defined in a third one. I've already found and reported one bug in D2009's compiler involving generics screwing up types across multiple units. This may be related. Can anyone confirm this?</p>
| <p>The definition of TObjectList<> is:</p>
<pre><code>TObjectList<T: class> = class(TList<T>)
</code></pre>
<p>So you like to do something like:</p>
<pre><code>TMyDataList<T: TBaseDatafile> = class(TObjectList<T>)
</code></pre>
<p>Unfortunately, that won't work. Luckily: </p>
<pre><code>TMyDataList<T: class> = class(TObjectList<T>)
</code></pre>
<p>Works, but that is probably not what you want. Because it will not take advantage of the class type. I really think the class specifier is a bit strange here. (TObject should have avoided the problems). But that's no help for you.</p>
<p>Then again, the following works:</p>
<pre><code> TBaseDataFile = class
end;
TDescendantDatafile = class (TBaseDataFile)
end;
TMyDataList<T: TBaseDataFile> = class(TObjectList<TBaseDataFile>)
public
constructor Create;
end;
</code></pre>
<p>Are you sure TDescendantDataFile inherits from TBaseDataFile?</p>
<p>In the old days, (read turbo pascal) sometimes the line numbers where wrong because of invisible characters. But I don't think that is still valid.</p>
|
How-To: Copy dependent assembly in case it is not in GAC? <p>I am building a Setup Package using VS2008. This is a regular setup package installing a COM Add-In app for Outlook. It works Ok, so far. However I need to improve it a little...</p>
<p>The story is that installation package copies all dependent assemblies into the installation folder of the add-in. </p>
<p>For example, the COM Add-In depends on Microsoft.Office.Interop.Outlook.dll assembly. So installation package copies it to its' folder :)</p>
<p>Of course, I can switch Exclude property of the Microsoft.Office.Interop.Outlook.dll dependency to True which will prevent the assembly from being copied. However, I need to achieve the following behavior:</p>
<ul>
<li>In case Microsoft.Office.Interop.Outlook.dll is not in GAC, we simply copy it to the installation folder of the Add-In </li>
<li>Otherwise, use the one which is in GAC</li>
</ul>
<p>Please suggest the way ti can be done in .Net2.0?
A step by step guide will be really appreciated.</p>
| <p>Just always copy it to the folder. If it's already in the GAC, the GAC'd assembly will be used first anyway.</p>
<p>In other words the runtime checks the GAC first. Then, checks application base, etc.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/yx7xezcf(VS.71).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/yx7xezcf(VS.71).aspx</a></p>
|
Drupal How to see document attached to Node for anonymous users <p>I am finishing up a Drupal site and I have attached a word document on one of my page nodes. I want anonymous people to be able to download it, but they don't even see the document. I do as a logged in user.</p>
<p>Any Ideas?</p>
| <p>You need to give anonymous users permission to view uploaded files.
I'm guessing that you used the upload module.
The permissions page is at /admin/user/permissions and under the group "upload module" you are looking for "view uploaded files".</p>
<p>-Ed</p>
|
Adding javascript to the OnBlur property of an ASP.NET text box control <p>Is there a way to specify some JavaScript to execute on the OnBlur event of an ASP.NET text box? It seems to me like if I add any event handlers to the TextBox object they will just cause postbacks to the server isntead of doing what I want. Basically, I just want to be able to have the textbox be rendered in this HTML:</p>
<pre><code><INPUT type="text" onblur="alert('1234')" />
</code></pre>
<p>Thanks!</p>
| <p>In your codebehind, add this:</p>
<pre><code>myTextBox.Attributes.Add("onblur","alert('1234');");
</code></pre>
|
is SFig language syntax efficient and clear (and better than Spring-Framework's XML DSL)? <p><strong>ADDENDUM EDIT:</strong></p>
<blockquote>
<p>Have not accepted an answer to this as
there has not been any feedback from
experienced Spring Framework
developers.</p>
</blockquote>
<p>I've been working on a replacement DSL to use for Spring-Framework applicationContext.xml files (where bean initialization and dependency relationships are described for loading up into the Spring bean factory).</p>
<p>My motivation is that I just flat out don't like Spring's use of XML for this purpose nor do I really like any of the alternatives that have been devised so far. For various reasons that I won't go into, I want to stay with a declarative language and not some imperative scripting language such as Groovy.</p>
<p>So I grabbed the ANTLR parser tool and have been devising a new bean factory DSL that I've dubbed SFig. Here's a link that talks more about that:</p>
<p><a href="http://dobbscodetalk.com/index.php?option=com_content&task=view&id=922&Itemid=85" rel="nofollow">SFig⢠- alternative metadata config language for Spring-Framework</a></p>
<p>And here is the source code repository site:</p>
<p><a href="http://code.google.com/p/sfig/" rel="nofollow">http://code.google.com/p/sfig/</a></p>
<p>I'm interested to know how I'm doing on the language syntax so far. Do you think SFig is both efficient and clear to understand? (I'm particularly concerned right now with the mulit-line text string):</p>
<pre><code>properties_include "classpath:application.properties";
org.apache.commons.dbcp.BasicDataSource dataSource {
@scope = singleton;
@destroy-method = close;
driverClassName = "${jdbc.driverClassName}";
url = "${jdbc.url}";
username = "${jdbc.username}";
password = "${jdbc.password}";
defaultAutoCommit = true;
}
org.springframework.orm.ibatis.SqlMapClientFactoryBean sqlMapClient {
@scope = singleton;
@init-method = afterPropertiesSet;
@factory-method = getObject;
configLocation = "classpath:sqlmap-config.xml";
dataSource = $dataSource;
}
/* this string will have Java unescape encoding applied */
STRING str = "\tA test\u0020string with \\ escaped character encodings\r\n";
/* this string will remain literal - with escape characters remaining in place */
STRING regexp = @"(\$\{([a-zA-Z][a-zA-Z0-9._]*)\})";
/* multi-line text block - equates to a java.lang.String instance */
TEXT my_multi_line_text = ///
Here is a line of text.
This is yet another. Here is a blank line:
Now picks up again.
///;
/* forward use of 'props' bean */
java.util.HashMap map {
this( $props );
}
/* equates to a java.util.Propertis instance */
PROPERTIES props {
"James Ward" = "Adobe Flex evangelist";
"Stu Stern" = "Gorilla Logic - Flex Monkey test automation";
Dilbert = "character in popular comic strip of same title";
"App Title Display" = "Application: ${app.name}";
"${app.desc}" = "JFig processes text-format Java configuration data";
}
/* equates to a java.util.ArrayList instance */
LIST list {
this( ["dusty", "moldy", "${app.version}", $str] );
[234, 9798.76, -98, .05, "numbers", $props, ["red", "green", "blue"]];
}
</code></pre>
| <p>I haven't much experience with the Spring XML you refer, so you should take the following feedback with a pinch of salt. </p>
<p>As a second and third caveat: </p>
<ul>
<li>providing a snippet of code will give a <em>flavour</em> of what the language and its semantics are. It is difficult to completely understand some of the choices you have already made (and with good reason), so any feedback here may be completely contradictory or impossible in the light of those choices.</li>
<li>language design is as much an art as a science, and so at this stage, any feedback you may get is likely to be quite subjective. </li>
</ul>
<p>A larger, meta-, question: as a DSL are you trying to do configuration of Spring, or as a more general class of frameworks?</p>
<p>There: caveat emptor. Now my subjective and incomplete feedback ;)</p>
<ul>
<li><p>I'm not sure I understand the reason why you have the <strong><code>@</code> prefix</strong> for <code>scope</code> and <code>destroy-method</code>, but not <code>driverClassName</code>. Also the mix of <strong>both xml-case and camelCase</strong> isn't completely apparent to start with. Is the <code>@</code> prefix a type modifier, or are these keywords in the language?</p></li>
<li><p>I'm not completely sure of your intentions about the block header format. You have class name, then a function of that class; is the intention to specify what class your are going to use for a particular function? </p></li>
</ul>
<p>e.g.</p>
<pre><code> sqlMapClient: org.springframework.orm.ibatis.SqlMapClientFactoryBean {
# body.
}
</code></pre>
<p>or even:</p>
<pre><code> sqlMapClient {
@class = org.springframework.orm.ibatis.SqlMapClientFactoryBean;
# is there a sensible (perhaps built-in) default if this is missing?
}
</code></pre>
<ul>
<li><p>I like the <strong>variable substitution</strong>; I presume the values will come from System properties?</p></li>
<li><p>I like being able to specify <strong>string literals</strong> (without escaping), especially for the regular expressions you've shown. However, having multi-character quote or quote modifier seems a little alien. I guess you considered the single-quote (shell and Perl use single-quotes for literal strings). </p></li>
<li><p>On the other hand, I think the triple forward slash for <strong>multi-line <code>TEXT</code></strong> is the right approach, but two reminiscent of comments in C-style languages. Python uses a triple <code>"</code> for this purpose. Some shell idioms have a multi-line text convention I would not copy.</p></li>
<li><p>I very much like the look of properties and config location, using what looks like a <strong>URI notion of addressing</strong>. If this is a URI, <code>classpath://file.xml</code> may be clearer. I may have the wrong end of the stick here, however.</p></li>
<li><p>I also very much like the notion of list and map literals you have, though I'm not sure where: </p>
<ul>
<li><code>this</code> comes into it (I guess a call to a Java constructor)</li>
<li>why some types are capitalized, and others are not. Do I take it that there is a default <code>MAP</code> type, which you can be more specific type if you wish to?</li>
<li>is Dilbert an unquoted string literal?</li>
</ul></li>
</ul>
<p>Finally, I'd point you to another configuration DSL, though perhaps more for sysadmin usage: <a href="http://reductivelabs.com/projects/puppet/" rel="nofollow">Puppet</a>.</p>
<p>Go well.</p>
|
Streaming audio from server to iPhone <p>I'm looking to stream some audio files I have on my server to an iPhone-client application I'm writing. Some of the audio files can be rather large in size, even after compression. My question is, is there a Cocoa framework that helps me with buffering the audio so it becomes available to the user while the rest is being brought down the pipes? If not, can anyone point me in the right direction to learn more about the technologies required to make such a thing happen using Objective-C/Cocoa?</p>
<p>A definitive resource on buffering and compression of audio from a server<->client infrastructure would be ideal.</p>
| <p>Brad mentioned a post that I wrote to stream audio via HTTP. That was this one: <a href="http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html">Streaming and playing an MP3</a>. I don't mean to be the person that links to his own blog but it does kind of address your question.</p>
<p>In regards to how hard the problem is to solve, you'll notice I've made 4 updates to that post (way more than I've done for anything else), fixing threading errors, memory leaks and network buffering issues. There is a lot to get precisely correct.</p>
|
How do I do lots of processing without gobbling cpu? <p>I know the question title isn't the best. Let me explain.</p>
<p>I do a TON of text processing which converts natural language to xml. These text files get uploaded fairly fast and thrown into a queue. From there they are pulled one-by-one into a background worker that calls our parser (using boost spirit) to transform the text into xml and load relevant portions into our db.</p>
<p>The parser can do about 100 of these at a time. I have rate-limiters on the background worker to only poll our queue every so often right now so it doesn't perform as fast. I can't throw up more than one background worker right now because my http requests start to drop -- the background worker and the webserver exist on the same machine and I <em>believe</em> it is because of cpu usage hitting 80-95%, although we could use more ram on it as well.</p>
<p>I need to scale this better. How would you go about doing it?</p>
<p>In answers to several questions:</p>
<ul>
<li><p>we use amazon web services so buying cheap extra hardware is a bit different from spawning a new amazon instance -- maybe somebody has done some code that autospawns instances on amount of load?</p></li>
<li><p>we do have a http server that just stuffs our files into a queue so the only reason it would be affected is because the cpu is busy dealing with tons of parsing related stuff</p></li>
<li><p>I already rate-limit our background workers, although we don't utilize that in the parser itself</p></li>
<li><p>I haven't tried nice yet but I've used it in the past -- I need to write down some benchmarks on that</p></li>
<li><p>the parser is completely seperate from the web server -- we have nginx/merb as our web/application server and a rake task calling c++ as our background worker -- yet they do exist on the same machine </p></li>
</ul>
| <p>Perhaps just placing the background worker at a lower scheduling priority (e.g. using <a href="http://en.wikipedia.org/wiki/Nice_(Unix)">nice</a>) would help. This means that your server can handle requests when it needs to, but when it's not busy you can go full blast with the text processing.</p>
<p>Methinks it will give you much more benefit than staggering the background worker arbitrarily.</p>
|
A piece of PHP code I'm not so sure about <p>I have here a piece of PHP code that deletes a directory and all files in it if present.
However, I'm not too sure about it, it looks to me like it'll delete all sub-maps too and then files in those and so on...</p>
<p>I basically want to give and optional true/false parameter to select wheter or not to delete sub directories. Or would it be better practice to make 2 functions? The first to completely empty the folder and the seconds the delete both the folder and everything in it.</p>
<p>Here's the code:</p>
<pre><code>function delete_directory($dirname) {
if (is_dir($dirname)) {
$dir_handle = opendir($dirname);
if (!$dir_handle) return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file)){
@unlink($dirname."/".$file);
}else {
delete_directory($dirname.'/'.$file);
}
}
}
closedir($dir_handle);
}
@rmdir($dirname) or die("Could not remove directory.");
return true;
}
</code></pre>
<p>And what I'm basically wondering is: what can go wrong here?
Is there a situation where this piece of code can seriously screw up?
I've been debugging it with Netbeans for a few hours now, and tried a lot of different scenarios. Now I'm kinda stuck and wondering if the guys at StackoverFlow can find a flaw in the code?</p>
| <blockquote>
<p>And what I'm basically wondering is: what can go wrong here? Is there a situation where this piece of code can seriously screw up?</p>
</blockquote>
<p>If the dir contains a symlink to somewhere else, it would be followed (unless I'm mistaken - You should check this). That could lead to a wildfire, where you basically wipe out your entire file system. You would probably want to safeguard against this, using <a href="http://www.php.net/realpath" rel="nofollow"><code>realpath</code></a></p>
|
Windows Gadgets & Jquery <p>I am creating a Vista Gadget and I haven't been able to get JQuery to work. I have tried a few very simple calls like this:</p>
<pre><code>$(function() {
$('a').click(function() {
$('#box').html("test");
});
});
</code></pre>
<p>I know you can use JavaScript so it doesn't make much sense to me why you wouldn't be able to use a library.</p>
<p>Does anyone know if any examples?</p>
| <p><a href="http://arsecandle.org/twadget/" rel="nofollow">Here</a> is a widget for vista done with jquery.
Might help you.</p>
<p>Above link is dead - here is another <a href="https://code.google.com/archive/p/timetablegadget/source/default/source" rel="nofollow">https://code.google.com/archive/p/timetablegadget/source/default/source</a></p>
|
How to do a custom asp.net routing (hardcoding the controller) <p>I'm trying to create a route for the following urls:
www.mysite.com/user/username
www.mysite.com/user/username/pictures</p>
<p>I tried doing that with the following code:</p>
<pre><code>routes.MapRoute(
"UserProfile",
"user/{sn}/{action}",
new { controller = "User", action = "Index", sn = "" }
);
</code></pre>
<p>So if an action is not specified, you go to the index action.</p>
<p>However, it's not working and I'm not sure what I'm doing wrong. </p>
<p>Thanks for any help. </p>
| <p>Looks like your code is correct.</p>
<p>The order of the rules is important. Try to place this above all other rules.
And if it will intefere with other rules, you should provide some constraints for the best matches.</p>
|
User Breakpoint from nowhere <p>I have some code in MS VC++ 6.0 that I am debugging. For some reason, at this certain point where I am trying to delete some dynamically allocated memory, it breaks and I get a pop up message box saying "User Breakpoint called from code at blah blah".. then the Disassembly window pops up and I see</p>
<pre><code>*memory address* int 3
</code></pre>
<p>The odd thing is, there is NOWHERE in the code that I am calling an assembly instruction like this (I think asm int 3 is a hardware break command for x86?).. </p>
<p>what could be causing this?</p>
<p>EDIT: ANSWER: My code was "walking off the end" of an array, but only in the locations marked by Visual Studio debug with 0xFDFDFDFD, which is called a NoMan'sLand fence.. I think its also called an Off-by-one error.. This array was unrelated to the point where i was freeing the memory when the error was occuring. Which made it harder to spot.. :(</p>
| <p>You're probably hitting code in the debug heap routines that have found heap corruption.</p>
<p>What does the call stack look like when you've hit the Int 3?</p>
<p>Edit: Based on the stack trace in your comments, the routine <code>_CrtIsValidHeapPointer()</code> is saying that the pointer being freed is bad. Here's the snippet of code from MSVC's DBGHEAP.C source:</p>
<pre><code> /*
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPointer(pUserData));
</code></pre>
<p><code>pUserData</code> would be the value of the pointer you're deleteing.</p>
|
Variable watch in PHP <p>Does PHP have the ability to watch a variable (or object property) and run a function when its value changes, similar to <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Object/Watch" rel="nofollow">Gecko's Javascript <code>watch</code> function</a>?</p>
| <p><a href="http://www.xdebug.org/" rel="nofollow">XDebug</a> <em>might</em> have this, but I don't know for sure.</p>
<p>If you're trying to debug a member variable on an object, you can use overloading:</p>
<pre><code>public function __set($var, $val)
{
if ($var == 'interesting') {
echo "$var set to: ";
var_dump($val);
}
$this->$var = $val;
}
</code></pre>
|
Missing AVFoundation.framework <p><code>AVFoundation.framework</code> is not where the documentation says it should be. I have iPhone SDK 2.2 installed (never had previous sdk versions installed) and I can't find that folder under <code>/System/Library/Frameworks</code></p>
<p>I did find it under</p>
<pre><code> /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.2.sdk/System/Library/Frameworks/
</code></pre>
<p>folder but if I add it from that location, then the compiler can't find the header files. I tried copying the entire <code>AVFoundation.framework</code> folder to <code>/System/Library/Framework</code>, but it still can't find the header files.</p>
<p>How can I use <code>AVFoundation</code> classes?</p>
<p>Thanks,
Alex</p>
| <p>I've used the AVFoundation classes in my code, and added it the same way you did. You cannot browse the headers for some unknown reason, but putting this in your classes header file compiles just fine:</p>
<pre><code>#import <AVFoundation/AVAudioPlayer.h>
</code></pre>
<p>I've submitted my app and had it approved, so I don't think there's anything wrong with this approach. The AVFoundation reference remains red in XCode, but it seems to work fine. Deleting the framework reference causes compile errors, so it definitely needs to be there.</p>
|
Asp.Net MVC - Best approach for "dynamic" routing <p>I am trying to come up with an approach to create "dynamic" routing. What I mean, exactly, is that I want to be able to assign the controller and action of a route for each hit rather than having it mapped directly.</p>
<p>For example, a route may look like this "path/{object}" and when that path is hit, a lookup is performed providing the appropriate controller / action to call. </p>
<p>I've tried discovering the mechanisms for creating a custom route handler, but the documentation / discoverability is a bit shady at the moment (I know, its beta - I wouldn't expect any more). Although, I'm not sure if thats even the best approach and perhaps a controller factory or even a default controller/action that performs all of the mappings may be the best route (no pun intended) to go.</p>
<p>Any advice would be appreciated. </p>
| <p>You can always use a catch all syntax ( I have no idea if the name is proper).</p>
<p>Route:
<code>
routeTable.MapRoute(
"Path",
"{*path}",
new { controller = "Pages", action = "Path" });</code></p>
<p>Controller action is defined as:
<code>public ActionResult Path(string path)</code></p>
<p>In the action for controller you will have a path, so just have to spilt it and analyse.</p>
<p>To call another controller you can use a RedirectToAction ( I think this is more proper way). With redirection you can set up a permanent redirectionfor it.
Or use a something like that:</p>
<pre><code> internal class MVCTransferResult : RedirectResult
{
public MVCTransferResult(string url) : base(url)
{
}
public MVCTransferResult(object routeValues)
: base(GetRouteURL(routeValues))
{
}
private static string GetRouteURL(object routeValues)
{
UrlHelper url = new UrlHelper(
new RequestContext(
new HttpContextWrapper(HttpContext.Current),
new RouteData()),
RouteTable.Routes);
return url.RouteUrl(routeValues);
}
public override void ExecuteResult(ControllerContext context)
{
var httpContext = HttpContext.Current;
// ASP.NET MVC 3.0
if (context.Controller.TempData != null &&
context.Controller.TempData.Count() > 0)
{
throw new ApplicationException(
"TempData won't work with Server.TransferRequest!");
}
// change to false to pass query string parameters
// if you have already processed them
httpContext.Server.TransferRequest(Url, true);
// ASP.NET MVC 2.0
//httpContext.RewritePath(Url, false);
//IHttpHandler httpHandler = new MvcHttpHandler();
//httpHandler.ProcessRequest(HttpContext.Current);
}
}
</code></pre>
<p>However this method require to run on IIS or a IIS Expres Casinni is not supporting a Server.Transfer method</p>
|
How can I use PHP to obfuscate email addresses so they are not easily harvested by spammers? <p>I'm programming in PHP and would like to create web pages which have email addresses that are easily read by humans but not easily harvested by spammers. The email addresses are coming from user input, and I think I can identify an address by using a regular expression, but I'm not clear exactly how I should replace the email addresses or with what, in order to keep most automated spam bots from harvesting them.</p>
<p>Here's one idea: (pseudo code)</p>
<pre><code>(email)@(domain.com) $1<span class="remove">DELETE</span>$2
.remove {
display: none;
}
</code></pre>
<p>Hopefully the bot will trip up on the span tag.</p>
<p>Finally, I'm looking for a solution that will not disturb email addresses that are inside of <code>mailto:</code> tags.</p>
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/311555/how-can-i-prevent-prevent-bots-from-collecting-e-mail-addresses#311629" rel="nofollow" title="How can I prevent prevent bots from collecting e-mail addresses?">How can I prevent prevent bots from collecting e-mail addresses?</a> which is duplicate of <a href="http://stackoverflow.com/questions/308772/what-are-some-ways-to-protect-emails-on-websites-from-spambots#309147" rel="nofollow" title="What are some ways to protect emails on websites from spambots?">What are some ways to protect emails on websites from spambots?</a> and maybe some others...</p>
| <h2>Use <a href="http://in2.php.net/gd" rel="nofollow">GD</a> and create image of your Email ID</h2>
<p>You can use the <a href="http://in2.php.net/gd" rel="nofollow">PHP GD library</a> to easily create an image of any given text.</p>
<p>A sample code will look like,</p>
<pre><code><?php
header("Content-type: image/png");
$im = @imagecreate(110, 20)or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 1, 5, 5, "anything@domain.com", $text_color);
imagepng($im);
imagedestroy($im);
?>
</code></pre>
<p><strong>Advantages:</strong></p>
<ul>
<li>Spammers can't just capture it, unless they use an OCR :p</li>
<li>Very low overhead, using PNG/GIF format</li>
<li>Can be created on the fly for any text</li>
</ul>
<p><strong>Disadvantages:</strong></p>
<ul>
<li>Cannot click on the mail, as a link</li>
<li>Won't work with TTS engines, a -ve for the visually challenged.</li>
</ul>
|
How do I setup a callback mechanism for RichEdit in win32 <p><strong>In win32, how do I setup a callback mechanism for RichEdit I have not created myself?</strong></p>
<p><strong>PART 1</strong></p>
<p><a href="http://stackoverflow.com/questions/352236/reading-from-a-text-field-in-another-applications-window">I'm reading from a textedit field in another application's GUI</a>. This works just fine now, except after the first read I'd like to fetch only new or modified lines. In GTK+ or Qt I'd just install a callback on some signal the field edits when its changed, but how does it work on Win32? </p>
<p>My MSDN searches result with nothing useful, probably because I don't know the exact term to search for. The class of the textedit is <a href="http://msdn.microsoft.com/en-us/netframework/bb787877(VS.85).aspx" rel="nofollow">RichText20W</a>, and it has some <a href="http://msdn.microsoft.com/en-us/netframework/bb774366(VS.85).aspx" rel="nofollow">messages</a> that are probably used somehow, though that article just discusses using them for the parent of the class.</p>
<p><strong>PART 2</strong></p>
<p>Also, <em>if</em> there is no such "text changed, here is the newly inserted text" callback which returns the new content immediately, I need some way to easily detect what is new. From top-of-my-head:</p>
<ol>
<li>Have a marker at the end of the text block we've read, and only read between that and the end.</li>
<li>Store what we've read previously, and after a second read, remove the duplicate part from the latter to have the newly inserted stuff.</li>
</ol>
<p>Option 2 might not be viable, since the textedit can contain any amount of text. The marker part sounds doable, but yet again, my feeble Win32 skills and horrible Win32 function names prevent me from finding the right way to do it.</p>
<p><em>Note that all these must be doable for a textedit I <strong>do not</strong> own and have not created, they belong to a third party process.</em></p>
<p><strong>Code samples in C++ highly appreciated.</strong></p>
<p><em>Disclaimer</em></p>
<p>Obviously, if there is some better way of doing it, let me know. I only assumed callback would be the way to go based on my previous experience with GTK+/Qt. Feel free to show me the path :)</p>
| <p>Win32 controls don't work on message-specific callbacks that you can subscribe to. They just send messages to their parent window when something happens, in this case EN_UPDATE, EN_CHANGE and all that. Even these events don't tell you what text changed. They only tell you that it <em>did</em> change.</p>
<p>You could subclass the parent, but the documentation for SetWindowLongPtr explicitly says you "should not subclass a window class created by another process." Something like this is probably possible with hooks, but I haven't used them enough to say for certain how you'd actually do it.</p>
|
How do you deal with failing Unit Tests? <p>I have a number of projects in a solution file that have unit tests written for them and I am wanting to set them up to be run by our continuous integration server. However, because many of the tests have been written poorly and have not been run regularly there are many that are failing.</p>
<p>I don't have the time at the moment to fix all of the tests but I do believe there is value in having the existing tests run. What is the best way do deal with the failing Unit Tests?</p>
<p>What I am currently doing is marking each failing test as Explicit and leaving a TODO comment. </p>
<pre><code>[Test, Explicit] //TODO: Rewrite this test because it fails
</code></pre>
<p>Is there a better way of doing this? Or should I fix all the tests before including them in the tests that are run by the CIS?</p>
| <p>Since you have a running automated build (with test failure notification!), this sounds like it's time for 5-a-day (freely from ubuntu community):</p>
<p>In each test method that's failing insert the following (pseudocode):</p>
<pre><code>if ( DateTime.now < new DateTime(2008, 12, 24, 11, 00, 00)) return;
</code></pre>
<p>For every 5 times you insert this statement you advance tha date by one working day. Set the time-of-day at some time when you're likely to have time to fix the test.</p>
<p>When the working day arrives, you fix it or delete it.</p>
|
Timed Subscription Schedule in SSRS sends out duplicate emails <p>I have created a one-time subscription in SSRS report manager 2008. However I keep getting duplicate emails sent out by the subscription. The interval between each email is about 30 minutes. </p>
<p>I have checked SQL agent job and it looks the SQL agent job is created correctly. It just runs once and after that the next run time is cleared. </p>
<p>I also checked SMTP service on local machine by testing code. SMTP works fine for test email without duplicate. So I guess probably it is something wrong in SSRS. Any advice on where I can look into? </p>
| <p>Update on this problem. </p>
<p>When I enable the reporting service log, the problem never happens again. </p>
<p>To the configuration file, the following is added.</p>
<pre><code><system.diagnostics>
<switches>
<add name="DefaultTraceSwitch" value="3" />
</switches> </system.diagnostics>
<RStrace>
<add name="FileName" value="ReportServerService_" />
<add name="FileSizeLimitMb" value="32" />
<add name="KeepFilesForDays" value="5" />
<add name="Prefix" value="tid, time" />
<add name="TraceListeners" value="debugwindow, file" />
<add name="TraceFileMode" value="unique" />
<add name="HttpTraceFileName" value="ReportServerService_HTTP_" />
<add name="HttpTraceSwitches" value="date,time, clientip,username,serverip,serverport,host,method,uristem,uriquery,protocolstatus,bytesreceived,timetaken,protocolversion,useragent,cookiereceived,cookiesent,referrer" />
<add name="Components" value="all:3,http:4" />
</RStrace>
</code></pre>
<p>However we are not sure if the problem is gone as well if we remove the configuration section. We don't want to keep the log as it grows quite fast. </p>
|
Silverlight WebPart in Sharepoint <p>I am new to Silverlight 2.0 and I am actually trying to deploy the Silverlight as webpart in Sharepoint 2007.</p>
<p>I have done the following Installations:</p>
<ol>
<li>VS 2008 with SP1</li>
<li>Silverlight 2.0 SDK and exe</li>
<li>Silverlight Tools for VS 2008</li>
<li>MOSS 2007</li>
</ol>
<p>I have created the sample Silverlight application and got the xap file from the bin directory of the solution.</p>
<p>Then I wrote a standard Sharepoint webpart with a reference to both <code>Web.Extensions</code> and <code>Microsoft.Silverlight</code> dll's:</p>
<pre><code>using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.SilverlightControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace SLWeb_Part1
{
[Guid("c890f832-05d2-4724-ae25-5f34c827c6c2")]
public class SLWeb_Part1 : System.Web.UI.WebControls.WebParts.WebPart
{
public SLWeb_Part1()
{
}
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Location of the Silverlight XAP package"),
WebDisplayName("XAP Location")]
public string XAPSource { get; set; }
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Silverlight Controld ID "),
WebDisplayName("Control ID")]
public string ControlID { get; set; }
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager = new ScriptManager();
this.Controls.Add(scriptManager);
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
Silverlight sl = new Silverlight();
sl.Source = XAPSource;
sl.ID = ControlID;
sl.Width = new Unit(400);
sl.Height = new Unit(400);
this.Controls.Add(sl);
}
}
</code></pre>
<p>I also deployed the same to the Sharepoint site, then I made an entry to the Sharepoint site's <code>web.config</code> file to include the Silverlight and Web.Extension assembly's like:</p>
<pre><code><add assembly="System.Web.Silverlight, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</code></pre>
<p>Then I included <code>application/x-silverlight-app</code> as MIME type for the web application in IIS.</p>
<p>After doing all this... I was able to browse the site as usual, but I couldnt see the Silverlight component running.... and it is not throwing any error also...</p>
<p>Can anybody help me to solve this problem at the earliest?
Do I miss any steps in the configuration?</p>
<p>Thanks in advance.</p>
| <p>I was able to resolve my issue by ensuring that my SharePoint web.config was properly configured for ASP.NET AJAX. It is not set up properly by default. See this site for details on how to do that:</p>
<p><a href="http://aspalliance.com/1719_Integrating_ASPNET_Ajax_WebPart_with_SharePoint_30.5" rel="nofollow">Integrating ASP.NET AJAX with SharePoint</a></p>
<p>Good luck!</p>
|
JavaScript - Identify whether a property is defined and set to 'undefined', or undefined <p>Say I have the following code:</p>
<pre><code>function One() {}
One.prototype.x = undefined;
function Two() {}
var o = new One();
var t = new Two();
</code></pre>
<p><code>o.x</code> and <code>t.x</code> will both evaluate to <code>undefined</code>. <code>o.hasOwnProperty('x')</code> and <code>t.hasOwnProperty('x')</code> will both return false; the same goes for <code>propertyIsEnumerable</code>. Two questions:</p>
<ul>
<li>Is there any way to tell that o.x is defined and set to <code>undefined</code>?</li>
<li>Is there ever any reason to? (should the two be semantically equivalent?)</li>
</ul>
<p>A small caveat: doing (for propName in o) loop will yield 'x' as one of the strings, while doing it in t will not - so there IS a difference in how they're represented internally (at least in Chrome).</p>
| <p>A slightly simpler way than your method is to use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator">Javascript in operator</a></p>
<pre><code>alert('x' in o); // true
alert('x' in t); // false
</code></pre>
|
Problem with an expect script <p>I'm trying to create a script to update a password in a
non-interactive way. It's working on my laptop but fails on my server.
Both are running the same configuration, using Etch.</p>
<p>This is the script:</p>
<pre><code>#!/usr/bin/expect -f
# Change user passwd
set timeout 30
strace 4
set password [lindex $argv 1]
set old_password [lindex $argv 2]
spawn passwd [lindex $argv 0]
sleep 1
expect "(current) UNIX password: $"
send "$old_password\r"
expect "Enter new UNIX password: $"
send "$password\r"
expect "Retype new UNIX password: $"
send "$password\r"
expect eof
</code></pre>
<p>On the server the output looks like this:</p>
<pre><code>myuser@server:~$ /home/myuser/adm/chpasswd myuser NewPasswd OldPasswd
2 lindex $argv 0
1 set username [lindex $argv 0]
2 lindex $argv 1
1 set password [lindex $argv 1]
2 lindex $argv 2
1 set old_password [lindex $argv 2]
1 spawn passwd $username
spawn passwd myuser
1 sleep 1
1 expect "(current) UNIX password: $"
Changing password for myuser
(current) UNIX password: 1 send "$old_password\r"
1 expect "Enter new UNIX password: $"
OldPasswd
Enter new UNIX password: 1 send "$password\r"
1 expect "Retype new UNIX password: $"
NewPasswd
1 send "$password\r"
1 expect eof
Retype new UNIX password: 1 exit 0
</code></pre>
<p>So is not working, as the couple expect-send seems unsync.</p>
<p>But strangely enough, on my laptop it works:</p>
<pre><code>test@mars:/home/test/adm$ ./chpasswd test NewPasswd OldPasswd
2 lindex $argv 1
1 set password [lindex $argv 1]
2 lindex $argv 2
1 set old_password [lindex $argv 2]
2 lindex $argv 0
1 spawn passwd [lindex $argv 0]
spawn passwd test
1 sleep 1
1 expect "(current) UNIX password: $"
Changing password for test
(current) UNIX password: 1 send "$old_password\r"
1 expect "Enter new UNIX password: $"
OldPasswd
Enter new UNIX password: 1 send "$password\r"
1 expect "Retype new UNIX password: $"
NewPasswd
Retype new UNIX password: 1 send "$password\r"
1 expect eof
NewPasswd
passwd: password updated successfully
1 exit 0
</code></pre>
<p>Any ideas why it's going wrong on the server ?
Thanks</p>
| <p>Maybe the password policy is different on the server?</p>
|
What's wrong with nullable columns in composite primary keys? <p>ORACLE does not permit NULL values in any of the columns that comprise a primary key. It appears that the same is true of most other "enterprise-level" systems.</p>
<p>At the same time, most systems also allow <em>unique</em> contraints on nullable columns.</p>
<p>Why is it that unique constraints can have NULLs but primary keys can not? Is there a fundamental logical reason for this, or is this more of a technical limitation?</p>
| <p>Primary keys are for uniquely identifying rows. This is done by comparing all parts of a key to the input. Per definition, NULL cannot be part of a comparison - the result of such a comparison would always be NULL again.</p>
<p>Additonally, NULL is allowed in a foreign key, to mark an optional relationship.<sup>(*)</sup> Allowing it in the PK as well would break this.</p>
<hr>
<p><sup>(*)</sup>A word of caution: Having nullable foreign keys is not clean relational database design.</p>
<p>If there are two entities <code>A</code> and <code>B</code> where <code>A</code> can optionally be related to <code>B</code>, the clean solution is to create a resolution table (let's say <code>AB</code>). That table would link <code>A</code> with <code>B</code>: If there <em>is</em> a relationship then it would contain a record, if there <em>isn't</em> then it would not.</p>
|
Drupal Aggregator input format <p>Drupal Aggregator core module is a useful one but suffers many problems. There are many talking about improving it in Drupal 7.</p>
<p>Right now I'm using Aggregator module which comes with Drupal 6. I'm building an aggregation site, and there is one BIG problem. Sometimes feeds contain HTML tags attributes (e.g. style, dir, title), but Aggregator's input format filter ignores SOME attributes (e.g. style and dir) and allows others (class and href). Without some attributes feeds look very missy. Aggregator contains it's own input format, it doesn't use other inputs formats (and this makes the problem harder!).</p>
<p>The question is how can I allow some HTML tags' attributes to appear in feeds.</p>
<p>P.S. last thing to do is modifying Aggregator's core files</p>
| <p>You might want to consider moving to one of the newer solutions built on top of FeedAPI </p>
<p><a href="http://drupal.org/node/326601" rel="nofollow">http://drupal.org/node/326601</a> </p>
<p>As you can see starting from there, this is where the action is, aggregation-wise.</p>
|
Possible to search multiple tables with a single query? [MSAccess/SQL Server] <p>So my goal here is to have a single search field in an application that will be able to search multiple tables and return results.</p>
<p>For example, two of these tables are "performers" and "venues" and there are the following performers: "John Andrews","Andrew Smith","John Doe" and the following venues: "St. Andrew's Church","City Hall". Is there a way to somehow return the first two performers and the first venue for a search of "Andrew"?</p>
<p>My first thought was to somehow get all the tables aggregated into a single table with three columns; "SearchableText","ResultType","ResultID". The first column would contain whatever I want searched (e.g. Performer name), the second would say what is being shown (e.g. Performer) and the third would say the item's ID (note: all my tables have auto-incrementing primary keys for ease). The question for this idea is it possible to somehow do this dynamically or do I have to add code to have a table that automatically fills whenever a new row is updated/added/deleted from the performers and venues table (perhaps via trigger?).</p>
<p>My application is written in MSAccess (I know, I know, but I have no choice) on top of a SQL Server backend. I'd prefer this happen through MSAccess so I don't have to have a "searchme" table sitting on my SQL Server but any good result is acceptable :)</p>
| <p>I think you are looking for the "union" sql keyword</p>
|
How can I hide "defined but not used" warnings in GCC? <p>I have a bunch of compile time asserts, such as:</p>
<pre><code>CASSERT(isTrue) or CASSERT2(isTrue, prefix_)
</code></pre>
<p>When compiling with GCC I get many warnings like <code>'prefix_LineNumber' defined but not used</code>. Is there a way I can hide warnings for compile time asserts? I had no luck searching the GCC documentation. I thought I might have the var automatically used globally inside the same macro but I couldn't think of any way to do it.</p>
<p>Does anyone know of a way to hide that warning in GCC?</p>
| <p>Just saw this thread while searching for solutions to this problem. I post here for completeness the solution I found...</p>
<p>The GCC compiler flags that control unused <a href="http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html">warnings</a> include:</p>
<pre><code>-Wunused-function
-Wunused-label
-Wunused-parameter
-Wunused-value
-Wunused-variable
-Wunused (=all of the above)
</code></pre>
<p>Each of these has a corresponding negative form with "no-" inserted after the W which turns off the warning (in case it was turned on by -Wall, for example). Thus, in your case you should use</p>
<pre><code>-Wno-unused-function
</code></pre>
<p>Of course this works for the whole code, not just compile-time asserts. For function-specific behaviour, have a look at <a href="http://gcc.gnu.org/onlinedocs/gcc-3.4.1/gcc/Function-Attributes.html#Function%20Attributes">Function attributes</a>.</p>
|
What fields should be indexed on a given table? <p>I've a table with a lot of registers (more than 2 million). It's a transaction table but I need a report with a lot of joins. Whats the best practice to index that table because it's consuming too much time.</p>
<p>I'm paging the table using the storedprocedure paging method but I need an index because when I want to export the report I need to get the entire query without pagination and to get the total records I need a select all.</p>
<p>Any help?</p>
| <p>The SQL Server 2008 Management Studio query tool, if you turn on "Include Actual Execution Plan", will tell you what indexes a given query needs to run fast. (Assuming there's an obvious missing index that is making the query run unusually slow, that is.)</p>
<p><img src="http://img208.imageshack.us/img208/4108/image4sy8.png" alt="SQL Server 2008 Management Studio Query Screenshot" /></p>
<p>We use this all the time on Stack Overflow.. one of the best features of SQL 2008. It works against older SQL instances as well, just install the SQL 2008 tools and point them at a SQL 2005 instance. Not sure if it works on anything earlier, though.</p>
<p>As others have noted, you can also do this manually, but it takes a bit of trial and error. You'll want indexes on fields that are used in ORDER BY and WHERE clauses. </p>
|
resize images with canvas - css overflow issue <p>I'm working on a JavaScript image resizing feature which rely on the IE only DXImageTransform addon.</p>
<p>Wanting to address modern browsers as well, I gave a shot to canvas, with pretty good results.</p>
<p>However, I face an issue in my resize function, which is the following:</p>
<pre>
function Resize(oObj, flMultiplier)
{
var canvas = document.getElementById('canvas');
var canvasContext = canvas.getContext('2d');
oObj.style.visibility = 'hidden';
canvasContext.clearRect(0,0,canvas.width,canvas.height); // clear canvas
canvasContext.fillStyle = 'rgba(0,0,0,0.4)';
canvasContext.scale(flMultiplier,flMultiplier);
canvasContext.drawImage(oObj, 0, 0);
}
</pre>
<p>If my image becomes bigger than the canvas item, then one will see only a portion of the image, which is bad.</p>
<p>I tried to tweak the canvas size at runtime, but if affects the display of the resized image. </p>
<p>So I ended up declaring a <em>big</em> canvas element, which is pretty OK, except that the css overflow of my web page is adjusted on my biggest element, and not on my resized image, which is a pain.</p>
<p>So I guess there are two ways to solve my problem:</p>
<ol>
<li>Try to exclude the big canvas element from the overflow scheme</li>
<li>Try to update the canvas element size when resizing (I may have missed something there)</li>
</ol>
| <p>I haven't tried that myself, but perhaps you can create a canvas element out of the Dom, with <code>document.createElement</code>. It could be of arbitrary size without disturbing the display.</p>
<p>Now, I lack context (why do you resize images this way instead of using width and height attributes, among other questions) so maybe I am missing the point.</p>
|
Initialize generic object with unknown type <p>How can I initialize a list containing generic objects whose types can be different?</p>
<p>For example, I have the following:</p>
<pre><code>this.Wheres = new List<Where<>>();
</code></pre>
<p>As you know, <> is not valid syntax. However, sometimes the type passed to Where will be a string and sometimes it will be DateTime, etc. I tried using object as the initialized type, but that doesn't work either.</p>
| <p>Well, you haven't really given enough context (what's SqlWhere?) but normally you'd use a type parameter:</p>
<pre><code>public class Foo<T>
{
private IList<T> wheres;
public Foo()
{
wheres = new List<T>();
}
}
</code></pre>
<p>If you want a single collection to contain multiple unrelated types of values, however, you will have to use <code>List<object></code></p>
|
What are the IDE advantages of recorded macros? <p>Just as the title says, I see a lot of editors touting macro recording as a feature but cannot find a way to take advantage of these functions myself. So what can you use it for? The type where you can record mouse movement and/or keystrokes? Is it really that helpful to people out there? Specifically, I deal with Eclipse which has a number of built in "fill in" functions, so I really don't see what the advantages could be.</p>
| <p>I use them all the time. Say, for example, I want to go down a list, indenting by 4 and adding a "|* ". In EMACS, I hit <code>C-x (</code> to start recording, do one example line to see that it's what I want, ending with <code>C-n C-a</code> to move to the next line, and end the macro with <code>C-x )</code>. Then <code>C-x e</code> repeats it line by line, and <code>C-u</code> <em>number</em> <code>C-x e</code> does it many times.</p>
|
best compression algorithm with the following features <p>What is the best compression algorithm with the following features:</p>
<ul>
<li>should take less time to decompress (can take reasonably more time compress)</li>
<li>should be able to compress sorted data (approx list of 3,000,000 strings/integers ...)</li>
</ul>
<p>Please suggest along with metrics: compression ratio, algorithmic complexity for compression and decompression (if possible)?</p>
| <p>Entire site devoted to compression benchmarking <a href="http://www.maximumcompression.com" rel="nofollow">here</a></p>
|
Getting Started with IronRuby on Rails <p>Can somebody point me to a tutorial and/or Getting Started document to get IronRuby running Rails? I'm particularly interested in a detailed, step-by-step reference, <em>not</em> general guidelines.</p>
| <p>IronRuby already 'runs' Rails today. We demo'd it running Rails back at RailsConf 08. That said, we have a lot of fit and finish work to do on IronRuby to get it to a state where it can run Rails <em>well</em>. </p>
<p>Where we're lacking right now is:</p>
<p><LI> Startup speed - this is critical for a decent experience when working with Rails - especially if you're running unit tests. Right now it takes 26s to startup Rails.
<LI> Working set - we're currently at 100MB for a 'hello world' Rails app vs. 30MB for MRI.</p>
<p>We're actually doing fine on throughput - once we're compiled things run reasonably well. </p>
<p>We're moving towards an adaptive compilation strategy where we interpret by default and compile the hot spots that we find. This will make the developer experience <em>much</em> better. We will also have an ahead-of-time compilation mode (perhaps in conjunction with NGEN and intelligent caching) down the road which may be better than the adaptive compilation strategy.</p>
|
console output formatting <p>Are there any conventions for formatting console output from a command line app for readability and consistency? For instance, do you indent sub-information, when do you print a blank line, if ever, how should you accent important statements.</p>
<p>I've found output can quickly degenerate into a chaotic blur. I'm interested in hearing about what other people do.</p>
<p><B>Update:</B> Really this is for embedded software which spits debug status out a terminal, but it's pretty much like a console app, and I figured everyone would be more familiar with that. Thanks so far.</p>
| <p>I'd differentiate two kinds of programs:</p>
<p>Do you print information that <em>might</em> be used by a script (i.e. it should be parseable)? Then define a pretty strict format and use only that (for example fixed field separators).</p>
<p>Do you print information that need not be parsed by a script (or is there an alternative script-parseable format already)? Then write what comes natural:</p>
<p>My suggestions:</p>
<ul>
<li>write it so that you would like to read it</li>
<li>indent sub-information 2 or 4 spaces, definitely not more</li>
<li>separate blocks of information by one empty line at most</li>
<li>respect the <code>COLUMN</code> environment variable (and possible <code>ROWS</code> if it applies to your output).</li>
</ul>
|
Is it possible for a Asp.Net developer on 64-bit windows to work with a team that has 32-bit? <p>Are there any compatibility issues that would prevent this from working? Do I need to have a 32-bit VM to use when working on projects for this team?</p>
| <p>No. Should work perfectly well.</p>
<p>Read a little here: <a href="http://msdn.microsoft.com/en-us/library/ms973190.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms973190.aspx</a></p>
|
Which is the best import / export LaTeX tool? <p>Working in academia publishing CS/math, you sooner or later find yourself trying to publish in a journal that will only accept .doc/.rtf. This means tedious, boring hours of translating line after line, especially equations, from LaTeX to an inferior format. Over the years I have tried a number of export tools for LaTeX, but none, at least of the free ones, that I have been very satisfied with. I'd like this page to collect and monitor the best import/export tools for LaTeX, to .doc/.rtf, or to other useful (e.g. HTML, MATHML) formats.</p>
<p>Thus, what is your one favorite import or export LaTeX tool?</p>
| <p>AFAIK there isn't really a convenient and effective way to achieve what you're trying to do. What I usually do in those rare occasions is that I export to pdf, then select all the text, and paste into word. It's horrible and messes things up and of course doesn't adjust your citations. </p>
<p>To this day I don't understand how people writing in scientific fields can write and publish in Word. It is common in some human-computer interaction literature but I have not seen it in other conferences and journals. May I ask which one it is? </p>
<p>Also, some places, once you've already been accepted, will be willing to accept a PDF if you push it with them. You may have to make little adjustment yourself. Negotiations sometimes work on this. </p>
|
Removing images with Greasemonkey? <p>I would like to stop images from loading, as in not even get a chance to download, using greasemonkey. Right now I have </p>
<pre><code>var images = document.getElementsByTagName('img');
for (var i=0; i<images.length; i++){
images[i].src = "";
}
</code></pre>
<p>but I don't think this actually stops the images from downloading. Anyone know how to stop the images from loading?</p>
<p>Thanks for your time and help :)</p>
| <p>If you want to disable images downloading for all websites (which I guess you might not be doing) and are using firefox, why not just disable them in preferences? Go to the content tab and switch off "Load images automatically".</p>
|
Java command-line launchers <p>I am working on a .jar file library to implement a bunch of helper classes to interface a PC to a piece of external hardware. I'll also add some simple applications, either command-line or GUI, to handle common tasks using the library.</p>
<p>My question is, is there a recommended way to simplify the command-line instantiation of a JVM in a certain specific way?</p>
<p>e.g. instead of requiring a user to type a cryptic error-prone command like:</p>
<pre><code>java -cp TurboBlenderLib.jar -jar TurboBlenderApp.jar -DFoo=Bar arg1 arg2
</code></pre>
<p>instead I do</p>
<pre><code>TurboBlenderApp arg1 arg2
</code></pre>
<p>?</p>
<p>I suppose I could use shell scripts (incl. win32 Batch Files... gacckkk), it's just that I'm not good at those + I was wondering if there was a more straightforward platform-independent way of running a Java app from the commandline.</p>
| <ol>
<li>When you use <code>-jar</code>, then<code>-cp</code> (and the <code>CLASSPATH</code> variable) will be ignored</li>
<li>Just provide a executable jar. "<code>java -jar TheApp <whateverargumentsyouwant></code>" shouldn't be too hard (you can have a <a href="http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html#Main%20Attributes" rel="nofollow">Class-Path attribute</a> in your <code>jar</code> files manifest, however).</li>
<li>if it is too hard write a GUI</li>
<li>or provide those shell scripts/batch files. Writing those isn't too hard either.</li>
</ol>
|
MyGeneration command line input <p>I have looked all over the internet, mygenteration's forum, and mygenteration's website and I cannot figure out how to pass parameters into a template through the command line using the xmldatapath switch. Does anyone know how to do this?</p>
<p>--edit--</p>
<p>I did a little research and <a href="http://williamsmash.com/blog/show/mygeneration-xml-input-format" rel="nofollow">here is a summary of the format of xml input for MyGeneration</a>.</p>
| <p>Have you seen <a href="http://community.entityspaces.net/forums/thread/10816.aspx" rel="nofollow">this post</a>, which indicates that the <code>-i xmldatapath</code> works with a saved output file created by MyGeneration itself. You don't detail what your exact issue is, have you tried using -c to create the file that you then use with -i? If you're still having issues add some more detail and I'll run up MyGeneration from the source and see what's going on.</p>
|
Rhino Mocks: AAA test syntax without static MockRepository methods? <p>I have been using (and liking) the new Rhino Mocks AAA syntax. However, one thing that puzzles me is that I have to create my stubs and mocks like this:</p>
<pre><code>var v1 = MockRepository.GenerateStub<MyClass>();
</code></pre>
<p>instead of with an instantiated MockRepository:</p>
<pre><code>var mr = new MockRepository();
var v1 = mr.GenerateStub<MyClass>();
</code></pre>
<p>This syntax would make transitioning my unit tests easier.</p>
<p>From reading Ayende's wiki it seems like the second syntax should work, but I just can't get it to function correctly. If I do it that way then I have to use Record/Playback blocks. I also can't find any examples online of anyone using the new syntax without the static methods.</p>
<p>So my question is, has anyone else managed to get the AAA syntax working without using the static methods and without having to resort to Record/Playback? If so, what am I missing?</p>
| <p>I checked rhino mocks with reflector.</p>
<p>MockRepository.GenerateStub actually creates a repository and calls the non static stub. Here is what the static methods actually do (copied from reflector)</p>
<pre><code>public static object GenerateStub(Type type, params object[] argumentsForConstructor)
{
MockRepository repository = new MockRepository();
object obj2 = repository.Stub(type, argumentsForConstructor);
repository.Replay(obj2);
return obj2;
}
</code></pre>
<p>It seems you're missing a call to Repository.Replay in your code.</p>
|
Hide Tab headers in WPF TabControl <p>What is the best way to hide Tab headers when there is only a single visible Tab?</p>
<p>I want to hide TabControl chrome completely, while leaving the content of the Tab visible.</p>
| <p>You can use a Style applied to TabItem with a DataTrigger that will collapse it if the parent TabControl has only one item:</p>
<pre><code><Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.Resources>
<x:Array x:Key="tabData" Type="{x:Type sys:String}">
<sys:String>do</sys:String>
<sys:String>re</sys:String>
<sys:String>mi</sys:String>
</x:Array>
</Grid.Resources>
<TabControl ItemsSource="{StaticResource tabData}">
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabControl}}, Path=Items.Count}" Value="1">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Grid>
</code></pre>
<p>If you want to get rid of the TabControl completely if there is only one item, that logic should probably be at a higher level.</p>
|
Show HH:mm 24H format in TemplateField using text property <p>I'm trying to show a 24 hours format using this line:</p>
<pre><code>Text='<%# Bind("Appointment", "{HH:mm}")
</code></pre>
<p>So how it'll be formated for showing for example 16:40 instead 4:40? </p>
| <p>if you don't need to <em>bind</em> it, try:</p>
<p>Text='<%# string.Format("{0:HH:mm}", Eval("Appointment"))%>'</p>
<p>otherwise i suppose you can update the field value in the OnDataBound event. </p>
|
OpenSocial server implementation <p>What is the preferred method of implementing the OpenSocial platform? I'm aware of Apache Shindig but can't really find any useful information on it. Also, is it possible to use an existing solution like the Rails-based <a href="http://lovdbyless.com/" rel="nofollow">lovdbyless</a> and add OpenSocial features to it?</p>
| <p>I've ported shindig over to .NET at <a href="http://code.google.com/p/pesta/" rel="nofollow">http://code.google.com/p/pesta/</a> and a sample site using it from partuza at <a href="http://www.codeplex.com/raya" rel="nofollow">http://www.codeplex.com/raya</a></p>
|
Synchronous work in a BackgroundWorker <p>My application performs time consuming work independently on several files. I created a BackgroundWorker to pass the work off to on each file, but it appears the backgroundworker is only capable of performing asynchronous work. Is it possible to do several asynchronous tasks in unison with it, or is there a similar object for performing synchronous operations?</p>
| <p>The background worker is usually used to update the UI and/or to pass off work so you don't freeze the UI when a long running process takes place. This means that you "pass" the background worker process the "file work" and then use a callback to update the UI(usually) all during which your APP remains responsive.</p>
<p>If the items are independent then you might want to spool up a few threads to split the work. Again, if I am understanding you correctly. If I am then you might want to look at <a href="http://www.yoda.arachsys.com/csharp/threads/" rel="nofollow">Jon Skeet's</a> threading article. </p>
|
Where would you put your new open-source .NET project? <p>I'm currently working on a .NET project that I will probably make open source.</p>
<p>There are lots of places to put it though, anyone have any experience for a friction-less effort? Codeplex? Google-code?</p>
<p>Note: I prefer Subversion for the projects source-control.</p>
| <p><strong><a href="http://code.google.com/" rel="nofollow">Google code</a> is my favorite.</strong> It has similar powerful simplicity and reliability just like other products from the Gmail.</p>
<p><strong>I would not recommend SourceForge</strong> to anyone. Reasons:</p>
<ul>
<li>Version control is slow</li>
<li>If you wire up integration server to their version control, they may ban your IP just for pinging version control frequently</li>
<li>UI is horrible and hard to navigate. You don't want to lose users just because of that.</li>
</ul>
<p>CodePlex is better than SourceForge, but it still has more development friction that I would like to have.</p>
|
Variable amount recurring billing <p>Hi i'm looking for a payment gateway that can do recurring billing that changes month to month. Fogbugz do this, they charge based on how many active users there were that month. All of the APIs that i've found only let you set a fixed amount and it's difficult/impossible to vary the subscription amount month to month.</p>
<p>Has anyone come across any services that do this?</p>
| <p><a href="http://www.braintreepaymentsolutions.com/">BrainTree</a> might be a good solution if you are manually triggering the re-bill each month. They will give you a 'token' that represents the credit card number originally supplied.</p>
<p>You can store this number, which is worthless to a potential thief.</p>
|
Windows UPS (Uninterruptible Power Supply) service - turn off UPS? <p>I'm using the UPS service to monitor the state of my UPS from an application -- the key at HKLM\SYSTEM\CCS\Services\UPS\Status has all the information you can get from the Power control panel. BUT -- I'd like to be able to tell the UPS to shut down from my app as well. I know that the service can tell the UPS to shut down -- for instance, after running a set number of minutes on battery -- and I'm wondering if there's some kind of command I can send to the service to initiate a shutdown manually.</p>
<p>I'm having trouble searching for this information -- people tend to misspell "Uninterruptible" (hrm, Firefox red-lined that but doesn't have an alternative) and "UPS" just gets hits for the shipping service. Maybe I can do something through System.ServiceController, or WMI?</p>
<p>CLARIFICATION: Yes, I am talking about powering down the physical UPS device. I know how to stop the service. I figured it would be a common problem -- I want my UPS to turn off with the PC. I had an idea I'm going to try, based on <a href="http://msdn.microsoft.com/en-us/library/ms789319.aspx" rel="nofollow">this page</a>. You see, APC (and everybody else) has to supply a DLL for the UPS service to call, and since the function calls are well documented, there's no reason I shouldn't be able to P/Invoke them. I'll re-edit this once I know whether or not it worked.</p>
<p>Update: I tried invoking UPSInit, then UPSTurnOff, and nothing happens. I'll tinker with it some more, but the direct call to apcups.dll might be a dead end.</p>
| <p>Check my comments to Herman, you want to shut the UPS down, not the UPS SERVICE, correct? I mean, you want that thing to shut off, kill the power, etc, right?</p>
<p>If so, you are looking it on a UPS by UPS model. I doubt two of them would work the same.</p>
<p>In your searches, instead of UPS, try "APC", or "battery". I think a lot of the code is what runs on laptops to deal with being on battery, etc...</p>
<p>Some place hidden in some dusty old files I have protocol information for APC UPS's, and the commands they respond to, and what they send to the PC etc. But this was WAY back in the day when we used to connect our UPS's to our computers with SERIAL cables... You could actually talk to a UPS with Qmodem or Hyperterm...</p>
<p>Learned it from talking to the guys at APC. They are very nice, and helpful. Now-a-days, I think you just post a URL coming from your Powerchute software, and it will talk directly to the UPS, and carry out your commands.</p>
|
How can I make this Ruby on Rails page more efficient? <p>I'm building a site where users can track their collection of figures for Dungeons & Dragons (www.ddmdb.com). The models/relationships involved in this funcitonality are the following:</p>
<p><strong>User:</strong></p>
<ul>
<li>id</li>
<li>login (username)</li>
<li><em>a bunch of other fields</em></li>
</ul>
<p><strong>Miniature:</strong></p>
<ul>
<li>id</li>
<li>name</li>
<li>number (# in the set, not count)</li>
<li>release_id (foreign key)</li>
<li><em>a bunch of other fields and foreign keys</em></li>
</ul>
<p><strong>Ownership:</strong></p>
<ul>
<li>id (is this really even needed?)</li>
<li>user_id</li>
<li>miniature_id</li>
<li>have_count</li>
<li>favorite (boolean)</li>
</ul>
<p>The pertinent relationships I have set up are as follows:</p>
<p><strong>User:</strong></p>
<ul>
<li>has_many :ownerships</li>
<li>has_many :miniatures, :through => :ownerships, :uniq => true, :conditions => "ownerships.have_count > 0"</li>
<li>has_many :favorites, :through => :ownerships, :source => :miniature, :uniq => true, :conditions => "ownerships.favorite = true"</li>
</ul>
<p><strong>Miniatures:</strong></p>
<ul>
<li>has_many :ownerships</li>
<li>has_many :owners, :through => :ownerships, :source => :user, :uniq => true, :conditions => "ownerships.have_count > 0"</li>
</ul>
<p><strong>Ownership:</strong></p>
<ul>
<li>belongs_to :user</li>
<li>belongs_to :miniature</li>
</ul>
<p>I have a page where user's can both view and update their collection, as well as view other user's collections. It contains a list of all the miniatures on the site and a text box next to each where the user can enter how many of each miniature they have. This functionality also exists in sub-lists of miniatures (filtered by type, release, size, rarity, etc.)</p>
<p>When a user creates an account they have no entries in the ownership. When they use the collection page or sub-list of miniatures to update their collection, I create entries in the ownership table for only the miniatures on the submitting page. So if it's the full Collection list I update all minis (even if the count is 0) or if it's a sub-list, I only update those miniatures. So at any time a particular user I may have:
- no entries in ownership
- entries for some of the miniatures
- entries for all the miniatures.</p>
<p>The problem I'm having is that I don't know how to query the database with a LEFT JOIN using a "Rails method" so that if a user doesn't have an entry for a miniature in Ownerships it defaults to a have_count of 0. Currently I query for each user_id/miniature_id combination individually as I loop through all miniatures and it's obviously really inefficient.</p>
<p><strong>View:</strong></p>
<pre><code><% for miniature in @miniatures %>
<td><%= link_to miniature.name, miniature %></td>
<td><%= text_field_tag "counts[#{miniature.id}]", get_user_miniature_count(current_user, miniature), :size => 2 %></td>
<% end %>
</code></pre>
<p><strong>Helper:</strong></p>
<pre><code>def get_user_miniature_count(user, miniature)
ownerships = user.ownerships
ownership = user.ownerships.find_by_miniature_id(miniature.id)
if ownership.nil?
return 0
else
return ownership.have_count
end
end
</code></pre>
<p>An alternate solution would be creating entries for all miniatures when a user signs up, but then I would also have to add a 0 have_count for all users when a new miniature is added to the database after they sign up. That seems like it could get a bit complex, but perhaps it's the right way to go?</p>
<p>Is there a way to do the join and supply a default value for miniatures where there's no entries in the Ownership table for that particular user?</p>
| <p>The first thing I would say is that the User model should own the code that works out how many of a given miniature the user owns, since it seems like "business logic" rather than view formatting.</p>
<p>My suggestion would be to add a method to your User model:</p>
<pre><code>def owns(miniature_id)
o = ownerships.detect { |o| o.miniature_id == miniature_id }
(o && o.have_count) || 0
end
</code></pre>
<p>Dry-coded, ymmv.</p>
<p>Edit: Note that ownerships is cached by Rails once loaded and detect is not overridden by ActiveRecord like find is, and so acts as you would expect it to on an Array (ie no database operations).</p>
|
Fast eclipse mode for PHP <p>Does anybody know of a fast PHP mode for eclipse? I have tried the Aptana PHP mode, and PDT, but neither can place a character in under a second, which is no way to write code.</p>
<p>Its probably due to my editing on a network drive, but it seems silly that an editor would depend so heavily on the hard drive.</p>
| <p>Try to disable Code Folding under Window > Preferences > PHP > Editor > Code Folding. If file is larger than 200 lines of code, this feature cause Eclipse to run really slow!</p>
<p>They said that this bug is fixed back in 2008. but I still have this problem :)</p>
|
How to make an image center (vertically & horizontally) inside a bigger div <p>I have a div 200 x 200 px. I want to place a 50 x 50 px image right in the middle of the div. </p>
<p>How can it be done?</p>
<p>I am able to get it centered horizontally by using <code>text-align: center</code> for the div. But vertical alignment is the issue..</p>
| <p>Personally, I'd place it as the background image within the div, the CSS for that being:</p>
<pre><code>#demo {
background: url(bg_apple_little.gif) no - repeat center center;
height: 200px;
width: 200px;
}
</code></pre>
<p>(Assumes a div with <code>id="demo"</code> as you are already specifying <code>height</code> and <code>width</code> adding a <code>background</code> shouldn't be an issue)</p>
<p>Let the browser take the strain.</p>
|
Architectural Suggestions in a Linux App <p>I've done quite a bit of programming on Windows but now I have to write my first Linux app. </p>
<p>I need to talk to a hardware device using UDP. I have to send 60 packets a second with a size of 40 bytes. If I send less than 60 packets within 1 second, bad things will happen.
The data for the packets may take a while to generate. But if the data isn't ready to send out on the wire, it's ok to send the same data that was sent out last time.
The computer is a command-line only setup and will only run this program.</p>
<p>I don't know much about Linux so I was hoping to get a general idea how you might set up an app to meet these requirements.
I was hoping for an answer like:</p>
<p>Make 2 threads, one for sending packets and the other for the calculations.</p>
<p>But I'm not sure it's that simple (maybe it is). Maybe it would be more reliable to make some sort of daemon that just sent out packets from shared memory or something and then have another app do the calculations? If it is some multiple process solution, what communication mechanism would you recommend?
Is there some way I can give my app more priority than normal or something similar?</p>
<p>PS: The more bulletproof the better!</p>
| <p>I've done a similar project: a simple software on an embedded Linux computer, sending out CAN messages at a regular speed.</p>
<p>I would go for the two threads approach. Give the sending thread a slightly higher priority, and make it send out the same data block once again if the other thread is slow in computing those blocks.</p>
<p>60 UDP packets per second is pretty relaxed on most systems (including embedded ones), so I would not spend much sweat on optimizing the sharing of the data between the threads and the sending of the packets.</p>
<p>In fact, I would say: <strong>keep it simple</strong>! I you really are the only app in the system, and you have reasonable control over that system, you have nothing to gain from a complex IPC scheme and other tricks. Keeping it simple will help you produce better code with less defects and in less time, which actually means more time for testing.</p>
|
Can you run EJB 2.1 beans in OSGi? <p>I have a J2EE 1.3 app that uses EJB 2.1 session and entity beans. Currently this app runs as an EAR file on JBoss. I'd like to switch to the SpringSource dm Application Server because of all the benefits that OSGi provides.</p>
<p>Does anyone know if there's an OSGi bundle that can act as an EJB container? Can <a href="http://openejb.apache.org/" rel="nofollow">OpenEJB</a> do this?</p>
| <p>hope that it could help you: </p>
<p><a href="http://darrylnelson.wordpress.com/2008/08/22/openejb-in-felix/#" rel="nofollow">http://darrylnelson.wordpress.com/2008/08/22/openejb-in-felix/#</a></p>
<p>It helps me a lot :-)</p>
|
Stacktrace information preserving paths of original source <p>I am using C#.net for application development.</p>
<p>To log and debug exceptions, I use the stacktrace.</p>
<p>I executed my application on another machine, but when errors occur it refers to the path of my development machine.</p>
<pre><code>Ex: D:\Projects\xyz.CS line no :12 _Error_message_here.
</code></pre>
<p>Why does it trace to the path on my <em>development</em> machine path even though I am running the application on another machine?</p>
| <p>The original compiled path is stored in the debug information within the PDB files.</p>
|
Unicode characters in Windows command line - how? <p>We have a project in TFS that has a non-English character (Å¡) in it. When trying to script a few build-related things we've stumbled upon a problem - we can't pass the <strong>Å¡</strong> letter to the command line tools. Command prompt or what not else messes it up, and the <strong>tf.exe</strong> utility can't find the specified project.</p>
<p>I've tried different formats for the .bat file (ANSI, UTF-8 with and without BOM) as well as scripting it in JavaScript (which is Unicode inherently) - but no luck. Anybody have an idea how to excecute a program and pass it a <strong>Unicode</strong> command line?</p>
| <p>Try:</p>
<pre><code>chcp 65001
</code></pre>
<p>which will change the code page to UTF-8. Also, you need to use Lucida console fonts.</p>
|
Read .config file in another assembly <p>Is there any possiblity to read a .config file in a dll assembly? At the moment I use OpenExeConfiguration on a Assembly.Location Property which seems to work. But I want to create separate .config files for different usages like ConfigModuleA.config, ConfigModuleB.config etc. </p>
<p>Any idea? </p>
| <p>Are you wanting to read another applications config file or just have some sections of the config file in a separate file (say, to make it more managable)?</p>
<p>If the latter just provide a <code>configSource</code> attribute on the config section you want to put somewhere else.</p>
<p>See - <a href="http://msdn.microsoft.com/en-us/library/ms228167.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms228167.aspx</a></p>
|
TestDriven.net with Gallio, MbUnit and NCover problems <p>Why doesnt TestDriven.Net work with my gallio/mbunit tests?</p>
<p>I've used TDD.Net with MbUnit v2 and not had any problems, but with the new gallio release on my new pc, it does nothing.</p>
<p>From the tdd right click menu in solution explorer, if i do "test with debugger" i get "0 passed, 0 failed, 0 skipped" in the VS status bar at the bottom of the screen.</p>
<p>If i right click my fixture and do the same, i get</p>
<pre><code>"The target type doesn't contain tests from a known test framework or a 'Main' method."
</code></pre>
<p>If i do it on an individual test, it looks like its not running the SetUp, so the test fails (but at least it runs)</p>
<p>I know this sounds like <a href="http://stackoverflow.com/questions/3984/testdrivennet-is-not-running-my-setup-methods-for-mbunit">this</a> problem, but my registry looks correct.</p>
<p>If i try and run NCover from the TDD.Net menu, nothing happens (other than an an output window flicker)</p>
<p>When i do "run unit tests" with resharper it picks them all up and runs correctly.</p>
<p>Im using Gallio/MbUnit 3.0.5.546, TDD.Net 2.18.2268, Resharper 4.1, VS 2k8 Pro 9.0.30729.1 SP, .Net 3.5 SP1, Windows Server 2k8 (x86)</p>
| <p>You just need to make sure you install TestDriven.Net before Gallio. Otherwise the Gallio installer will not install its extensions for TestDriven.Net.</p>
|
Regular expression for allow only numbers <p>I want to check the following with regular expression</p>
<pre><code>{Today,Format}
</code></pre>
<p>Today - will be remains as it is.
In the place of Format, we can allow the digits from 0 to 12.</p>
<p>for example: we have to allow</p>
<pre><code>{Today,0}
{Today,1}
{Today,2}
...
{Today,12}
</code></pre>
<p>and also have to allow </p>
<pre><code>{Today,}
{Today,Format}
</code></pre>
<p>Please help me and also refer me to some site to develop my regular expression skills.</p>
| <pre><code>\{Today,(\d|1[012]|Format)?\}
</code></pre>
<p>Meaning:</p>
<ul>
<li>Open curly brace;</li>
<li>'Today,';</li>
<li>Optionally one of the following: a digit (0-9), 1 followed by 0, 1 or 2 (10,11,12), 'Format'; and then</li>
<li>Close curly brace.</li>
</ul>
<p>As for resources I can recommend <a href="http://www.regular-expressions.info/" rel="nofollow">this site on regular expressions</a> and the book <a href="http://rads.stackoverflow.com/amzn/click/0596528124" rel="nofollow">Mastering Regular Expressions</a>.</p>
|
How do I use the built in password reset/change views with my own templates <p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p>
<p>I need to know exactly what context to add for each of the password reset and change views.</p>
| <p>If you take a look at the sources for <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py">django.contrib.auth.views.password_reset</a> you'll see that it uses <a href="http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py"><code>RequestContext</code></a>. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.</p>
<p>The b-list has a good <a href="http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/">introduction to context processors</a>.</p>
<p>Edit (I seem to have been confused about what the actual question was):</p>
<p>You'll notice that <code>password_reset</code> takes a named parameter called <code>template_name</code>:</p>
<pre><code>def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
</code></pre>
<p>Check <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.views.password_reset">password_reset</a> for more information.</p>
<p>... thus, with a urls.py like:</p>
<pre><code>from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
</code></pre>
<p><code>django.contrib.auth.views.password_reset</code> will be called for URLs matching <code>'/accounts/password/reset'</code> with the keyword argument <code>template_name = 'my_templates/password_reset.html'</code>.</p>
<p>Otherwise, you don't need to provide any context as the <code>password_reset</code> view takes care of itself. If you want to see what context you have available, you can trigger a <code>TemplateSyntax</code> error and look through the stack trace find the frame with a local variable named <code>context</code>. If you want to modify the context then what I said above about context processors is probably the way to go.</p>
<p>In summary: what do you need to do to use your own template? Provide a <code>template_name</code> keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.</p>
|
Checking flash file loading with javascript <p>Is there a way to check how much a flash file is (down)loaded to the page before it is shown?
Our team cant put loading indicator inside the flash file because the swf file is uploaded by our client. Is there some kind of property on xmlhttprequest that we can use to indicate how much has been downloaded?
Or any other suggestion to indicate on-screen the loaded percentage?</p>
<p>Thanks</p>
| <p>Do you have control over how the file is loaded in the browser? i have a theory that you could create a second flash movie, that would load the clients movie into it, and during that process you could show a progress indicator. </p>
<p>Flash has support for loading external .swf files, look <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14190" rel="nofollow">here</a> to see how.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.