input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to handle general exceptions in Asp.Net MVC? <p>I want to transfer all unhandled exceptions to an error page in Asp.Net MVC. What is the way to handle the unhandled exceptions in Asp.net MVC? Is there anything like application_error? </p>
| <p>check out the HandleError attribute. There's a good write up <a href="http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx" rel="nofollow">here</a>.</p>
|
What is my issue with tab-selecting in JQuery? <p>I want to create a webpage in which I can use the jQuery tabs both by a side-bar and by the upper button-bar of the jQuery tabs itself.</p>
<p>My code:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title>title here</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ui.core.js"></script>
<script type="text/javascript" src="ui.datepicker.js"></script>
<script type="text/javascript" src="ui.tabs.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="local.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#datepicker").datepicker();
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tabs").tabs();
});
$("select2").click(function() { // bind click event to link
$("$tabs").tabs("select", 1); // switch to third tab
return false;
});
</script>
</head>
<body>
<div id="container">
<div id="row">
<div id="leftsubcontainer"><div class="column-in">
<h4>rev0.1</h4>
<p>medewerkernaam</p>
<br/>
<div type="text" id="datepicker"></div>
<br/><br/>
<br/><br/>
<p>log out</p>
<button id="select2">kies derde</button>
<br/><br/>
</div></div>
<div id="rightsubcontainer"><div class="column-in">
<div id="tabs">
<ul>
<li><a href="#tabs-1">Nunc tincidunt</a></li>
<li><a href="#tabs-2">Proin dolor</a></li>
<li><a href="#tabs-3">Aenean lacinia</a></li>
</ul>
<div id="tabs-1">
<p>tekst1</p>
</div>
<div id="tabs-2">
<p>tekst 2</p>
</div>
<div id="tabs-3">
<p>tekst 3</p>
</div>
</div>
</div></div>
</div>
</div>
</body>
</html>
</code></pre>
<p>The problem is, that, whenever I click on the button, the tabs are not changing (i.e. it does not select the right tab). </p>
<p>Does anyone know what I have been doing wrong?</p>
| <p>You have a problem here :</p>
<pre><code>$("$tabs").tabs("select", 1);
</code></pre>
<p>You should use a # instead of $ :</p>
<pre><code>$("#tabs").tabs("select", 1);
</code></pre>
<p>And passing 1 as second parameter will select second tab, not third.</p>
|
UML class diagram relation type question <p>I have a data class with the following methods:</p>
<ul>
<li>ExecuteUDIQuery(string query)</li>
<li>ExecuteSelectQuery(string query)</li>
<li>ExecuteSP(string anme, string[,] params)</li>
</ul>
<p>I have a lot classes which use the data class. Now i want to create a class diagram, but i don't know what kind of relation the classes have with the data class. Is it a composite? Is it 1:1 or .. ?</p>
<p>An example of a class which use the data class is the Staff class. This class has a method Load(), which will load a staff object with the Id of the staff member. This method contains a query which is passed to the ExecuteSelectQuery(string query) method of the Data class. </p>
<p>EDIT:
The data class isn't static. However, i have my doubts. I actually don't know what to. The point is, the only thing it does is executing queries and returning the results.</p>
| <p>I would suggest its a <strong><em>usage</em></strong> dependency relationship.</p>
<p>See <a href="http://publib.boulder.ibm.com/infocenter/rsmhelp/v7r0m0/index.jsp?topic=/com.ibm.xtools.modeler.doc/topics/cdepend.html" rel="nofollow">here</a> for a brief description.</p>
|
ASP .Net WorldPay Integration <p>I'm wondering whether anyone has any useful information on integrating WorldPay into an ASP.Net web application? I'm looking to take payments for a fixed amount directly from the web site, no shopping cart required.</p>
<p>Essentially I'm just looking for some reference source code or a good article covering what's required. Does WorldPay support web services or REST etc?</p>
<p>Cheers,</p>
<p>Brian.</p>
| <p>Include on your "checkout" page the following form (with the relevant values):</p>
<pre><code><form action="https://select.worldpay.com/wcc/purchase" method="post">
<input type="hidden" name="instId" value="<your worldpay installation ID>" />
<input type="hidden" name="cartId" value="<a reference for this transaction>" />
<input type="hidden" name="amount" value="<the amount to pay>" />
<input type="hidden" name="currency" value="<your currency code i.e. GBP>" />
<input type="hidden" name="desc" value="<a description of this transaction>" />
<input type="hidden" name="testMode" value="<worldpay's test mode ID>" />
<input type="hidden" name="name" value="<customer's name>" />
<input type="hidden" name="address" value="<customer's full address>" />
<input type="hidden" name="postcode" value="<customer's postcode>" />
<input type="hidden" name="country" value="<country code i.e. GB>" />
<input type="hidden" name="email" value="<customer's email address>" />
</form>
</code></pre>
<p>Then in your Worldpay profile (on their website once you've registered) you'll have an option for postback URL (can't remember the exact label) which will POST the following keys to this URL (so it'll be a page on your website that receives this) containing the result of the transaction:</p>
<pre><code>string wp_rawauthcode = Request.Form["rawauthcode"];
string wp_amount = Request.Form["amount"];
string wp_installation = Request.Form["installation"];
string wp_tel = Request.Form["tel"];
string wp_address = Request.Form["address"];
string wp_mc_log = Request.Form["mc_log"];
string wp_rawauthmessage = Request.Form["rawauthmessage"];
string wp_authamount = Request.Form["authamount"];
string wp_amountstring = Request.Form["amountstring"];
string wp_cardtype = Request.Form["cardtype"];
string wp_avs = Request.Form["avs"];
string wp_cost = Request.Form["cost"];
string wp_currency = Request.Form["currency"];
string wp_testmode = Request.Form["testmode"];
string wp_authamountstring = Request.Form["authamountstring"];
string wp_fax = Request.Form["fax"];
string wp_transstatus = Request.Form["transstatus"];
string wp_compname = Request.Form["compname"];
string wp_postcode = Request.Form["postcode"];
string wp_authcost = Request.Form["authcost"];
string wp_desc = Request.Form["desc"];
string wp_cartid = Request.Form["cartid"];
string wp_transid = Request.Form["transid"];
string wp_callbackpw = Request.Form["callbackpw"];
string wp_sessionId = Request.Form["MC_sessionId"];
string wp_CusId = Request.Form["MC_cusId"];
string wp_authmode = Request.Form["authmode"];
string wp_name = Request.Form["name"];
string wp_shop = Request.Form["MC_shop"];
string wp_wafMerchMessage = Request.Form["wafMerchMessage"];
string wp_authentication = Request.Form["authentication"];
string wp_email = Request.Form["email"];
</code></pre>
<p>Perform some basic validation here like making sure the installation ID (wp_installation) matches what you expect, and the amount, currency etc before setting the order status to "Paid" or something.</p>
|
<select> width in IE not behaving as in other browsers <p>I have three select boxes.</p>
<pre><code><div style='float: left; padding-right: 10px;'>
<select size="10" name="company_id">
// a lot of options here
</select>
</div>
<div style='float: left; padding-right: 10px;'>
<select size="10" name="department_id" id="department_id">
// a lot of options here
</select>
</div>
<div style='float: left; padding-right: 10px;'>
<select size="10" name="user_id[]" id="user_id" multiple>
// a lot of options here
</select>
</div>
</code></pre>
<p>They are floated next to each other. When you select an item in the 1st one, an ajax query updates the values of the 2nd one. </p>
<p>What happens in Firefox and most other browsers is that it changes in size and pushes the 3rd one away. But in IE (6.0 and 7) the 2nd one changes size but it does not push the 3rd one away.</p>
<p>What i had done is to fix the size of the boxes but i want to fix this correctly, so anyone know how?</p>
<p>Here's the JQuery code i use to add the data to the departments select.</p>
<pre><code>$.get("ajax/fetchDepartment.php?sec=departments&company_id="+company_id,
function(data){
$("#department_id").html(data);
});
</code></pre>
<p><code>data</code> contains the <code><option>Stuff</option></code>'s needed</p>
<p>EDIT to add: The select boxes always have some value within them.</p>
<p>Here's a picture of what happens (i had to remove the items in the boxes via photoshop but you get my point)</p>
<p><img src="http://cznp.com/select%5Fbug.jpg" alt="selcet bug" /></p>
| <p>IE and select options have certain 'quirks' (some, regarding select boxes and innerHTML are detailed <a href="http://channel9.msdn.com/wiki/internetexplorerprogrammingbugs/" rel="nofollow">here</a>) about them that I've never really fully understood, but I can at least provide you with a workaround.
The trick is to add the options exlicitly to the select box, not just change the entire html of the select element wholesale. So the following works:</p>
<pre><code>function changeval() {
var option = document.createElement("option");
option.text = 'my long text value to change stuff';
option.value = 'test';
$('#department_id')[0].options.add(option);
}
</code></pre>
<p>While this does not:</p>
<pre><code>function changeval() {
var data = '<option value="test">my long test string with wide stuff</option>';
$("#department_id").html(data);
}
</code></pre>
<p>You might find this <a href="http://www.workingwith.me.uk/blog/software/web%5Fbrowser/internet%5Fexplorer/problems%5Fcreate%5Fa%5Fselect%5Fbox%5Fusing%5Fthe%5Fdom%5Fin" rel="nofollow">page</a> helpful -apparently he fixed it by just retouching the innerHTML, so that might be a simpler option. Up to you.</p>
<p>The solution from the second link would look like:</p>
<pre><code>function changeval() {
var data = '<option value="test">my long test string with wide stuff</option>';
$("#department_id").html(data);
$("#department_id").parent()[0].innerHTML += '';
}
</code></pre>
|
How to create jQuery Tabs out of Markdown <p>I'm currently running a PHP based Content-Management-System that generates its HTML content with the help of <a href="http://michelf.com/projects/php-markdown/extra/" rel="nofollow">Markdown Extra</a>. Most of the content is structured by headings and sub-headings which results in a very long page. At the beginning of each page I create a table of contents with the help of a list and <a href="http://michelf.com/projects/php-markdown/extra/" rel="nofollow">Markdown Extra's</a> <em>Header Id Attribute</em>.</p>
<p>In oder to shorten the length of a page view I'd like to use the jQuery's <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow">Tabs Plugin</a> on the first level of headings.</p>
<p>The Problem is that the output of <a href="http://michelf.com/projects/php-markdown/extra/" rel="nofollow">Markdown Extra</a> is not compatible with what the jQuery <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow">Tabs Plugin</a> is expecting because <a href="http://michelf.com/projects/php-markdown/extra/" rel="nofollow">Markdown Extra</a> is not wrapping the content of a section into a separate div-tag.</p>
<p>Is there a way how to make those two libraries work together?</p>
<h3>EDIT</h3>
<p>This is what the HTML output is looking like:</p>
<pre><code> <p>Some intro text...</p>
<h3>Table of content</h3>
<ul>
<li><a href="#sub1">Topic 1</a></li>
<li><a href="#sub2">Topic 2</a></li>
<li><a href="#sub3">Topic 3</a></li>
</ul>
<h3 id="sub1">Topic 1</h3>
<p>The content of this topic.</p>
<h3 id="sub2">Topic 2</h3>
<p>The content of this topic.</p>
<h3 id="sub3">Topic 3</h3>
<p>The content of this topic.</p>
</code></pre>
<p>.. and this is the corresponding Markdown code:</p>
<pre><code>Some intro text...
###Table of content###
* [Topic 1](#sub1)
* [Topic 2](#sub2)
* [Topic 3](#sub3)
###Topic 1### {#sub1}
The content of this topic.
###Topic 2### {#sub2}
The content of this topic.
###Topic 3### {#sub3}
The content of this topic.
</code></pre>
<h3>Solution</h3>
<p>With a little help of cobbal I made this jQuery statement that will transform the Markdown markup into something that the Tabs plugin will work with:</p>
<pre><code> $("#tabs :header").each(function()
{
var id = $(this).attr("id");
if(id=="") return;
var div = $("<div>");
var tagName = this.tagName;
$(this).nextAll().each(function()
{
if(this.tagName==tagName) return false;
div.append(this);
});
$(this).removeAttr("id");
div.attr("id", id);
$(this).before(div);
div.prepend(this);
});
</code></pre>
<p>But the fact that I need to transform the markup to fit the Tabs plugin rather than just tell the Tabs plugin that it should select its content in a different way may made this solution not the ideal one.</p>
| <p>on your document.ready</p>
<pre><code>$("#sub1,#sub2,#sub3").each(function() {
var containerDiv = $("<div>").attr("id", $(this).attr("id") + "div");
$(this).before(containerDiv);
containerDiv.append(this);
});
</code></pre>
<p>and change your markdown to</p>
<pre><code>...
* [Topic 1](#sub1div)
* [Topic 2](#sub2div)
* [Topic 3](#sub3div)
...
</code></pre>
|
Logging vs. Debugging <p><strong>Background:</strong> I've inherited a web application that is intended to create on-the-fly connections between local and remote equipment. There are a tremendous number of moving parts recently: the app itself has changed significantly; the development toolchain was just updated; and both the local and remote equipment have been "modified" to support those changes.</p>
<p>The bright side is that it has a reasonable logging system that will write debug messages to a file, and it will log to both the file and a real-time user screen. I have an opportunity to re-work the entire log/debug mechanism.</p>
<p><strong>Examples:</strong></p>
<ul>
<li>All messages are time-stamped and prefixed with a severity level.</li>
<li>Logs are for the customer. They record the system's responses to his/her requests.</li>
<li>Any log that identifies a problem also suggests a solution.</li>
<li>Debugs are for developers and Tech Support. They reveal the system internals.</li>
<li>Debugs indicate the function and/or line that generated them.</li>
<li>The customer can adjust the debug level on the fly to set the verbosity.</li>
</ul>
<p><strong>Question:</strong> What best practices have you used as a developer, or seen as a consumer, that generate useful logs and debugs?</p>
<p><hr /></p>
<p><strong>Edit:</strong> Many helpful suggestions so far, thanks! To clarify: I'm more interested in <em>what</em> to log: content, format, <em>etc</em>.--and the reasons for doing so--than specific tools.</p>
<p>What was it about the best logs you've seen that made them most helpful?</p>
<p><em>Thanks for your help!</em></p>
| <p>The absolutley most valueable thing done with any logging framework is a "1-click" tool that gathers all logs and mail them to me even when the application is deployed on a machine belonging to a customer.</p>
<p>And make good choices at what to log so you can roughly follow the main paths in your application.</p>
<p>As frameworks I've used the standards (log4net, log4java, log4c++)</p>
<p>do NOT implement your own logging framework, when there already is a good one out-of-the-box. Most people who do just reinvent the wheel.</p>
|
What is a sequence of actions in a default MSI installation (not custom)? <p>An MSI installer calls a lot of pre-defined actions during install - FindRelatedProducts, CheckVersion, etc. Different actions are called during different install types and sequences: admin, unattended, user, execute, deffered... and custom actions are queued 'before' or 'after' these predefined MSI actions.</p>
<p>Is there a complete list available that shows the exact sequence in which MSI actions are called in different install modes and sequences? Ideally with short comments about what each action does and what is a good practice to insert custom actions into.</p>
| <p>See the MSDN documentation, specifically the documentation on <a href="http://msdn.microsoft.com/en-us/library/aa372404%28VS.85%29.aspx">Using a Sequence Table</a>.</p>
<p>For offline reference, download the <a href="http://www.microsoft.com/downloadS/details.aspx?familyid=6A35AC14-2626-4846-BB51-DDCE49D6FFB6&displaylang=en">Windows Installer 4.5 SDK</a> and read <strong>MSI.CHM</strong> (it's much easier to navigate than the MSDN stuff anyway)</p>
|
Reading raw data from a video capture in JMF <p>I'm trying to read raw video frames from a video capture device using JMF - the Java Media Framework.</p>
<p>I've successfully written the "capture" part - using a <em>Player</em> object created by <em>Manager</em>, I can display realtime video from a webcam. I don't know how to go about creating a custom component to access the actual frames, however. This is probably because up until now <em>Manager</em> has created every class instance I needed for me.</p>
<p>I would like to start by writing a GUI component that displays the video. (I'm not familiar with AWT/Swing, but based on knowledge of other GUI frameworks, I'd say something derived from a, say, JPanel that draws the video when a repaint request is made or a new frame is available.) I would like to be able to process every new frame and loop on x/y over all the pixels. I have access to the raw/RGB format on my device, but automatic conversion from, say, YUV wouldn't hurt.</p>
<p>I have no idea where to start. The JMF documentation recommends I derive my class from <em>Processor</em> or <em>DataSink</em> in several different places. Using the <em>Processor</em> interface seems like an overkill - I would have no need for the playback and timing control functions, for example; and I wouldn't know how to implement them in the first place. Deriving from <em>DataSink</em> seems like a simpler option with less useless abstract functions. However, in either case, I'm at a complete loss as how to: </p>
<p>a) Connect the component to my video capture DataSource<br />
b) Access the actual frame buffers from within the class</p>
<p>I may even be going in a wrong direction here; I just wanted to document what I've tried so far. JMF documentation seems scarce and mostly oriented towards [designing] media players and converters.</p>
<p>Note: The Processing library seems to have a simple solution for this. I've seen an example along the lines of: <code>x = new Image(captureDevice.getFrame())</code> which seems to suggest pixel-level access is possible, through Image if not the intermediate type.</p>
<p>But I would really like to see how hard it is in JMF first.</p>
| <p>I'm sorry, but at this point, JMF is essentially dead. You would probably use FX for that, but FX isn't exactly doing well either. </p>
|
xHTML markup checker integrated in Selenium <p>Recently, I thought about how can I improve the quality of the projects, by using Continuous checking of xHTML source at Continuous Integration machine.</p>
<p>Look, we have a project</p>
<p><a href="http://sourceforge.net/projects/jtidy" rel="nofollow">http://sourceforge.net/projects/jtidy</a> - jTidy
JTidy is a Java port of HTML Tidy, a <code>HTML syntax checker</code> and pretty printer.</p>
<p>It can validate the xHTML through a command-line interface. Or this tool can be extended in the way we need, because all source code are open.</p>
<p>We can overwrite every Selenium validation method, such as assertTextPresent, or any other, so it will be calling the jTidy(by providing current state's HTML source), and if some errors or warnings will occur - it can be saved to Continuous Integration machine build's logs - so any project's related can see this info.</p>
<p>We can not to rewrite all the Selenium methods, to integrate this call on every step, but to make this calls where we want(after DOM manupulations).</p>
<p>Yes, we can use W3C markup validators for our sites, but there isn't any possibility to validate not initial state of page's source with this validators. After page creation, there might be lots of DOM manipulations which can produce markup errors/warnings - we can find it immediately with this scheme.</p>
<p>One of the benefits of using Continuous integration is that you have quick feedback from code - how it integrates with existing code base, test whether unit and functional tests pass. Why not to get an additional useful info, such as instant xHTML markup validation status. The earlier we identify the problem, the easier to fix it.</p>
<p>I haven't found anything on this theme in google yet.
And want to know, what do you think about this idea?</p>
| <p>Seems like a worthwhile idea.</p>
<p>I've done two similar things with CI before:</p>
<ol>
<li><p>I've used Ant's <a href="http://ant.apache.org/manual/Tasks/xmlvalidate.html" rel="nofollow">XMLValidate</a> task to validate static xhtml files as part of the build process</p></li>
<li><p>I've used httpunit to pull pages that I then parsed as xml</p></li>
</ol>
<p>But the idea of tying into Selenium to validate the content inherently during a functional test run is novel to me.</p>
|
Enable ASP.NET ASMX web service for HTTP POST / GET requests <p>I would like to enable a ASP.NET classic (ASMX) web service for HTTP POST and GET requests. I realise this can be done on a machine or application level by adding ...</p>
<pre><code><webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</code></pre>
<p>.. to the machine.config or web.config. My question is can HTTP POST and GET requests be enabled per web service or web method level rather than per application or machine?</p>
<p>My web service is written in c# using net 3.5sp1.</p>
| <p>Try to declare UseHttpGet over your method.</p>
<pre><code>[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
return "Hello World";
}
</code></pre>
|
dateutil.rrule.rrule.between() gives only dates after now <p>From the IPython console:</p>
<pre><code>In [16]: b
Out[16]: datetime.datetime(2008, 3, 1, 0, 0)
In [17]: e
Out[17]: datetime.datetime(2010, 5, 2, 0, 0)
In [18]: rrule(MONTHLY).between(b, e, inc=True)
Out[18]:
[datetime.datetime(2009, 3, 6, 14, 42, 1),
datetime.datetime(2009, 4, 6, 14, 42, 1),
datetime.datetime(2009, 5, 6, 14, 42, 1),
datetime.datetime(2009, 6, 6, 14, 42, 1),
datetime.datetime(2009, 7, 6, 14, 42, 1),
datetime.datetime(2009, 8, 6, 14, 42, 1),
datetime.datetime(2009, 9, 6, 14, 42, 1),
datetime.datetime(2009, 10, 6, 14, 42, 1),
datetime.datetime(2009, 11, 6, 14, 42, 1),
datetime.datetime(2009, 12, 6, 14, 42, 1),
datetime.datetime(2010, 1, 6, 14, 42, 1),
datetime.datetime(2010, 2, 6, 14, 42, 1),
datetime.datetime(2010, 3, 6, 14, 42, 1),
datetime.datetime(2010, 4, 6, 14, 42, 1)]
</code></pre>
<p>How do I make <code>between()</code> return dates starting from the begining (<code>b</code>) date?</p>
| <p>You need to pass <code>b</code> into rrule, like this:</p>
<pre><code>rrule(MONTHLY, dtstart = b).between(b, e, inc=True)
</code></pre>
<p>From these docs (<a href="http://labix.org/python-dateutil">http://labix.org/python-dateutil</a>), it looks like calling rrule without specifying dtstart will use datetime.datetime.now() as the start point for the sequence that you're later applying <code>between</code> to. That's why your values begin at 2009-03-06.</p>
|
Can I append to a BLOB in MSSQL database from C# without reading the original data? <p>I'd like to be able to append some data to a binary field in a MS SQL 2005 server from C# without reading the original data, concatenating it, and then setting it all back.</p>
<p>Is this possible?</p>
<p>Cheers!
Steve</p>
| <p>I don't know if this option exists in MSSQL 2005, but if someone is searching for appending info into varbinary(max) in MSSQL2008 it can be done like this:</p>
<pre><code>UPDATE [dbo].[Files] SET [FileContent].WRITE('0x',NULL,0)
WHERE Id = 1
</code></pre>
<p>Hope this will help someone. </p>
|
Python metaclasses <p>I've been hacking classes in Python like this:</p>
<pre><code>def hack(f,aClass) :
class MyClass(aClass) :
def f(self) :
f()
return MyClass
A = hack(afunc,A)
</code></pre>
<p>Which looks pretty clean to me. It takes a class, A, creates a new class derived from it that has an extra method, calling f, and then reassigns the new class to A.</p>
<p>How does this differ from metaclass hacking in Python? What are the advantages of using a <strong>metaclass</strong> over this?</p>
| <p>The definition of a class in Python is an instance of type (or an instance of a subclass of type). In other words, the class definition itself is an object. With metaclasses, you have the ability to control the type instance that becomes the class definition.</p>
<p>When a metaclass is invoked, you have the ability to completely re-write the class definition. You have access to all the proposed attributes of the class, its ancestors, etc. More than just injecting a method or removing a method, you can radically alter the inheritance tree, the type, and pretty much any other aspect. You can also chain metaclasses together for a very dynamic and totally convoluted experience.</p>
<p>I suppose the real benefit, though is that the class's type remains the class's type. In your example, typing:</p>
<pre><code>a_inst = A()
type(a_inst)
</code></pre>
<p>will show that it is an instance of <code>MyClass</code>. Yes, <code>isinstance(a_inst, aClass)</code> would return <code>True</code>, but you've introduced a subclass, rather than a dynamically re-defined class. The distinction there is probably the key.</p>
<p>As rjh points out, the anonymous inner class also has performance and extensibility implications. A metaclass is processed only once, and the moment that the class is defined, and never again. Users of your API can also extend your metaclass because it is not enclosed within a function, so you gain a certain degree of extensibility.</p>
<p>This slightly old article actually has a good explanation that compares exactly the "function decoration" approach you used in the example with metaclasses, and shows the history of the Python metaclass evolution in that context: <a href="http://www.ibm.com/developerworks/linux/library/l-pymeta.html" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-pymeta.html</a></p>
|
What is the impact of ITIL or CMMI on the development? <p>I read a lot of books about what practices work well or not in software development.
And I have NEVER heard about methodoly like ITIL or CMMI in any webcast or book or blogs in the development field.</p>
<p>I have heard about these methodologies in my school, and to me it seems to be bureaucratic practices.</p>
<p>However every books on development I've read talk about collaboration, or people over documentation. (Yes, lots of agile books)</p>
<p>So my question is : Does methodologies like ITIL or CMMI have some impact or relation with development or the everyday life of the developer ? And do you have great books or blogs which talk about some good ideas in these metodologies I can use on a development team ?</p>
| <p>ITIL is more focused on the infrastructure and support side and not development, so discussion of ITIL is probably more appropriate on the "IT" focused version of StackOverflow that is supposedly in development. As an aside, I take exception with calling that other site "IT" focused as IT encompasses infrastructure, support, and development in most enterprises...probably a good percentage of StackOverflow users are developers in IT departments.</p>
<p>I've worked with CMMI and the Team Software Process (TSP), both products of Watts Humphrey and the Carnegie Mellon Software Engineering Institute. If you are committed to continuous improvement and believe that measurement is at the heart of any continuous improvement, then you will find value in CMMI.</p>
<p>It is very easy to do CMMI (and TSP) wrong or in a way that alienates developers and ultimately ends up as window dressing or something that looks good on a pile of certifications. Look at the development vendors in India...they are miraculously all CMMI level 5. What they don't tell you is that was almost always one small project or team in their organization that worked hard to get the certification, but the repeatable practices are simply not there for 95% of their organization.</p>
<p>The focus on time tracking (clock punching), defect tracking (bug quotas), lines of code (lots of ways to "game" if you are so inclined), and making your process repeatable (making a developer feel like a cog with no freedom to innovate) turn off many developers. <-- note the jaded counter-arguments in parentheses.</p>
<p>The fact remains that 90% of the developers out there (few of which read StackOverflow or any technical blogs/web sites) shoot from the hip and are sorely lacking in self-awareness of where their opportunities to improve reside. For them, the process rigor and opportunity to make incremental improvements in quality through the self-awareness that repetition and measurement facilitate are valuable components of CMMI.</p>
<p>Done right, you get the same benefits from Agile methods like Scrum where again the focus is on repeatable iterations, learning from each iteration, and improving/narrowing in on your goal. It takes a lot of maturity and experience to lead a team in adopting either Agile methods or CMMI and get full value out of them.</p>
<p>Agile is sexy and CMMI is about as far from sexy as you can get, which is why you don't hear about it as much.</p>
|
Hibernate SQL Audit Logging <p>I want to do audit logging generated SQL statements in Hibernate. I wrote Custom Interceptor that extents EmptyInterceptor. I overrided <strong>onPrepareStatement</strong> method to get generated SQL. But When I debug this code I am only getting generated SQL without parameters like this.</p>
<pre><code>INSERT INTO TableA(Col1,Col2,Col3) VALUES(?,?,?)
</code></pre>
<p>How can I get full SQL statement that contains parameter values like this from Hibernate</p>
<pre><code>INSERT INTO TableA(Col1,Col2,Col3) VALUES("Value1","Value2","Value3")
</code></pre>
| <p>In hibernate cfg, you may set hibernate.show_sql property to true, this will cause Hibernate to output the perpared statements (without the parameter values bound to a query) to stdout.</p>
<p>To have the precompiled statements and list of parameters bound to them logged, set log4j.logger.org.hibernate.SQL=DEBUG in your commons-logging (or underlying log system) configuration.</p>
|
JSF commandButton with immediate="true" <p>I have a situation where there is a selectOneMenu that has a value bound to a backing bean.</p>
<p>I need to have a button that doesn't update model values (that is why it has immediate="true" property).</p>
<p>That button's action method changes the value the selectOneMenu is bound to, but when the page is redisplayed the original value is displayed (the one that was submitted) and not the one set in the action method.</p>
<p>Any ideas why that is happening?</p>
<p>If I didn't explain the problem good enough please let me know.</p>
<p><hr/>
EDIT:
As requested here is the source code in question:
<br/></p>
<h3>page code:</h3>
<pre><code><h:selectOneMenu id="selectedPerson"
binding="#{bindings.selectPersonComponent}"
value="#{bean.selectedPerson}">
<s:selectItems var="op" value="#{bean.allPersons}"
label="#{op.osoba.ime} #{op.osoba.prezime}"
noSelectionLabel="#{messages.selectAPerson}">
</s:selectItems>
<f:converter converterId="unmanagedEntityConverter" />
</h:selectOneMenu>
...
<a4j:commandButton action="#{bean.createNew}" value="#{messages.createNew}"
immediate="true" reRender="panelImovine">
</a4j:commandButton>
</code></pre>
<h3>java code:</h3>
<pre><code>private Person selectedPerson;
public String createNew() {
log.debug("New created...");
selectedPerson = null;
bindings.getSelectPersonComponent().setSubmittedValue(null); //SOLUTION
return "";
}
</code></pre>
<p>The solution is in the lined marked <b>SOLUTION</b> :)</p>
| <p>As it frequently happens a few moments after posting this question I have found an answer:</p>
<p>The cause of the problem is in detail explained here: <a href="https://cwiki.apache.org/confluence/display/MYFACES/Clear+Input+Components" rel="nofollow">ClearInputComponents</a></p>
<p>The problem is (as explained) that model values haven't been updated so the submitted inputs are still in component.submittedValue field and that field is displayed if not empty. It is emptied normally after model has been updated.</p>
<p>The first solution didn't work in my case because there is other important state in the view that mustn't get lost. But the second solution worked great:</p>
<pre><code>component.setSubmittedValue(null);
</code></pre>
<p>And that was all that was needed: it is a little extra work because components must be bound to some bean, but not that bad.</p>
|
Deserializing Chrome Bookmark JSON Data in C# <p>In response to a question I asked a few days ago, I'm attempting to stretch myself a little, and do something that I've not really focussed on much before. I've done some searching (both here, and in general), but can't find the answers (or even reasonable hints) to what I want to achieve (though, a few things come close-ish).</p>
<p>Basically, I'm trying to deserialize the data for the Google Chrome bookmarks file using the <a href="http://james.newtonking.com/pages/json-net.aspx">Json.NET library</a> (though, if there's a better alternative, I'm all for that - the documentation for this library is a little confusing in places). I'm a little confused as to the next step to take, due primarily to being used to PHP's fantastic handling of JSON data (using <a href="http://uk.php.net/json%5Fdecode">json_decode()</a>), allowing for a single function call, and then simple associative-array access.</p>
<p>The library (Json.NET) wants me to specify an Object type that it can deserialize the JSON data into, but I'm not really sure how to go about structuring such an Object, given the format of the Bookmarks file itself. The format is something along the lines of:</p>
<pre><code>{
"roots": {
"bookmark_bar": {
"children": [ {
"children": [ {
"date_added": "12880758517186875",
"name": "Example URL",
"type": "url",
"url": "http://example.com"
}, {
"date_added": "12880290253039500",
"name": "Another URL",
"type": "url",
"url": "http://example.org"
} ],
"date_added": "12880772259603750",
"date_modified": "12880772452901500",
"name": "Sample Folder",
"type": "folder"
}, {
"date_added": "12880823826333250",
"name": "Json.NET",
"type": "url",
"url": "http://james.newtonking.com/pages/json-net.aspx";
} ],
"date_added": "0",
"date_modified": "12880823831234250",
"name": "Bookmarks bar",
"type": "folder"
},
"other": {
"children": [ ],
"date_added": "0",
"date_modified": "0",
"name": "Other bookmarks",
"type": "folder"
}
},
"version": 1
}
</code></pre>
<p>Now, in PHP, I'd be far more used to doing something along the lines of the following, to get the data I wanted, and ending up with 'Json.NET':</p>
<pre><code>$data['roots']['bookmark_bar']['children'][0]['name'];
</code></pre>
<p>I can work out, simply enough, what objects to create to represent the data (something like a root object, then a bookmark list object, and finally an individual bookmark object) - but I'm really not sure as to how to implement them, and then get the library to deserialize into the relevant objects correctly.</p>
<p>Any advice that can be offered would be greatly appreciated.</p>
| <p>It is not necessary to declare a type that reflects the json structure:</p>
<pre><code> using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System;
class Program
{
static void Main(string[] args)
{
string json =
@"
{
""roots"": {
""bookmark_bar"": {
""children"": [ {
""children"": [ {
""date_added"": ""12880758517186875"",
""name"": ""Example URL"",
""type"": ""url"",
""url"": ""http://example.com""
}, {
""date_added"": ""12880290253039500"",
""name"": ""Another URL"",
""type"": ""url"",
""url"": ""http://example.org""
} ],
""date_added"": ""12880772259603750"",
""date_modified"": ""12880772452901500"",
""name"": ""Sample Folder"",
""type"": ""folder""
}, {
""date_added"": ""12880823826333250"",
""name"": ""Json.NET"",
""type"": ""url"",
""url"": ""http://james.newtonking.com/pages/json-net.aspx""
} ],
""date_added"": ""0"",
""date_modified"": ""12880823831234250"",
""name"": ""Bookmarks bar"",
""type"": ""folder""
},
""other"": {
""children"": [ ],
""date_added"": ""0"",
""date_modified"": ""0"",
""name"": ""Other bookmarks"",
""type"": ""folder""
}
},
""version"": 1
}
";
using (StringReader reader = new StringReader(json))
using (JsonReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer serializer = new JsonSerializer();
var o = (JToken)serializer.Deserialize(jsonReader);
var date_added = o["roots"]["bookmark_bar"]["children"][0]["date_added"];
Console.WriteLine(date_added);
}
}
</code></pre>
|
How can I make networking work in my WinCE app without launching IE first? <p>I have a simple WinCE network application (in C, Win32 APIs). I find that networking doesn't seem to work unless I launch IE (or another network app) first. I assume that IE is setting up my network interface in some way.</p>
<p>How can I do this for myself?</p>
<p>Might I need to display a list of available interfaces to the user (eg. WiFi/Ethernet/3G)?</p>
<p>Thanks.</p>
| <p>All I know is that Internet Explorer uses <a href="http://msdn.microsoft.com/en-us/library/aa383630%28VS.85%29.aspx" rel="nofollow">WinInet</a> (wininet.dll) for its networking, and you can too. WinInet is a MS API for working with http and ftp protocols. Many of the settings on the "Internet Options" control panel applet are actually WinInet settings (e.g. for dealing with cookies, setting up proxies on LANs, and autodial on dial-up networks). I'm 99% sure that anything that IE can do, you can do yourself using the API.</p>
|
Getting Firefox 3 to work with JSUnit <p>Thus far this is what I've tried, I'm using Firefox 3.07</p>
<ol>
<li><p>Make sure in <strong>about:config</strong> that the property <strong>browser.cache.check_doc_frequency</strong> is set to <strong>1</strong> which the browser interprets as "check for a new page every time".</p></li>
<li><p>Make sure in <strong>about:config</strong> that the property <strong>security.fileuri.strict_origin_policy</strong> is set to <strong>false</strong>.</p></li>
<li><p>When opening your browser be sure to specify to the <strong>testrunner.html</strong> page which test you want to run using the <strong>testpage</strong> parameter,<br/><br/>I.E.: <em>file:///.../testRunner.html?testpage=c:/temp/someTest.html</em></p></li>
<li><p>Tak an additional random parameter on the end to ensure that the cache is gone.</p></li>
</ol>
<p>Everything above seems to work, except it is still <em>caching</em> my <strong>*.js</strong> files for some stupid reason. I really thought it would have had to do with changing the random parameter at the end to kill the cache, but that doesn't seem to be doing the trick. What else can be done to make JSUnit work with Firefox 3.07? The files are located on my hdd.</p>
| <p>Have you tried CTRL + SHIFT + R to refresh without using cache?</p>
|
MVC + Templates <p>I am working on a system that gets templatse dynamicly, they contain tags like {{SomeUserControl}} {{SomeContent}}</p>
<p>I was wonder how I could use MVC to render those templates and replacing the tags in the best possible way as the templates will be edited via a web front end, and the content / macros will be create from the same web front end. </p>
| <p>You might wanna take a look at maybe using another view engine, here are some examples.</p>
<p><a href="http://andrewpeters.net/2007/12/19/introducing-nhaml-an-aspnet-mvc-view-engine/" rel="nofollow">NHaml</a><br />
<a href="http://dev.dejardin.org/" rel="nofollow">Spark</a><br />
<a href="http://nvelocity.sourceforge.net/" rel="nofollow">NVelocity</a><br />
<a href="http://www.castleproject.org/monorail/documentation/v1rc2/viewengines/brail/index.html" rel="nofollow">Brail</a></p>
<p>I'm sure there are many more but these are the ones I could think of.</p>
|
.Net inserting NULL values into SQL Server database from variable values <p>There have been similar questions but the answers weren't what I was looking for. I want to insert the a value of NULL into the SQL Server database if the reference is NULL or a value has not yet been assigned. At the moment I am testing for null and it looks like</p>
<pre><code>String testString = null;
if (testString == null)
{
command.Parameters.AddParameter(new SqlParameter("@column", DBNull.Value);
}
else
{
command.Parameters.AddParameter(new SqlParameter("@column", testString);
}
</code></pre>
<p>This looks and feels incredibly clumsy to me. I have quite a few values that I am inserting into a database and to test them all like the above is very verbose. Does .Net not handle this in some way. I thought maybe if I used string as opposed to String but that also does not appear to work. Looking around I found articles which talk about using Nullable types.</p>
<pre><code>System.Nullable<T> variable
</code></pre>
<p>This seems to work for primitives, int?, char? double? and bool?. So that might work for those but what about strings? Am I missing something here. What types should I be using for primitive values and for string values so that I do not have to repeatedly test values before inserting them.</p>
<p>EDIT:
Before I get too many answers about ternary operators. I like them but not in this context. It doesn't make sense for me to need to test that value and have all that extra logic, when that sort of thing could have been inplemented lower down in the .Net framework and if I knew what types to give then it would get it for free.</p>
<p><strong>Edit:</strong>
Okay, so guys help me formulate my plan of attack. I will use the Nullable for my primitives (int?, double? etc) and for my Strings I will use the String but the ?? test. This keeps things less verbose. Is there anything that I am missing here, like maybe losing some semantics?</p>
| <p>Even better than the ternary is the double-question-mark (??) operator. Takes the first non-null value. So:</p>
<pre><code>string x = null;
command.Parameters.AddParameter(
new SqlParameter("@column", (object)x ?? DBNull.Value);
</code></pre>
<p>would give you a parm with a value of DBNull.Value, but</p>
<pre><code>string x = "A String";
command.Parameters.AddParameter(
new SqlParameter("@column", (object)x ?? DBNull.Value);
</code></pre>
<p>Would give you a parm with "A String" as the value.</p>
|
Detect difference between & and %26 in location.hash <p>Analyzing the location.hash with this simple javascript code:</p>
<p><code><script type="text/javascript">alert(location.hash);</script></code></p>
<p>I have a difficult time separating out GET variables that contain a & (encoded as %26) and a & used to separate variables.</p>
<p>Example one:</p>
<ul>
<li>#code=php&age=15d</li>
</ul>
<p>Example two:</p>
<ul>
<li>#code=php%20%26%20code&age=15d</li>
</ul>
<p>As you can see, example 1 has no problems, but getting javascript to know that "code=php & code" in example two is beyond my abilities:</p>
<p>(Note: I'm not really using these variable names, and changing them to something else will only work so long as a search term does not match a search key, so I wouldn't consider that a valid solution.)</p>
| <p>There is no difference between %26 and & in a fragment identifier (âhashâ). â&â is only a reserved character with special meaning in a query (âsearchâ) segment of a URI. Escaping â&â to â%26â need be given no more application-level visibility than escaping âaâ to â%61â.</p>
<p>Since there is no standard encoding scheme for hiding structured data within a fragment identifier, you could make your own. For example, use â+XXâ hex-encoding to encode a character in a component:</p>
<pre><code>hxxp://www.example.com/page#code=php+20+2B+20php&age=15d
function encodeHashComponent(x) {
return encodeURIComponent(x).split('%').join('+');
}
function decodeHashComponent(x) {
return decodeURIComponent(x.split('+').join('%'));
}
function getHashParameters() {
var parts= location.hash.substring(1).split('&');
var pars= {};
for (var i= parts.length; i-->0;) {
var kv= parts[i].split('=');
var k= kv[0];
var v= kv.slice(1).join('=');
pars[decodeHashComponent(k)]= decodeHashComponent(v);
}
return pars;
}
</code></pre>
|
Get all lucene values that have a certain fieldName <p>To solve <a href="http://stackoverflow.com/questions/618227/faster-way-to-get-distinct-values-from-lucene-query">this</a> problem I created a new Lucene index where all possible distincted values of each field are indexed seperatly.</p>
<p>So it's an index with a few thousand docs that have a single Term.<br />
I want to extract all the values for a certain term. For example, I would like all values that have the fieldName "companyName".<br />
Defining a WildcardQuery is off course not a solution. Neither is enumerating ALL fields and only saving the ones with the correct fieldName.</p>
| <p>This should work (I take it it still is in C#)</p>
<pre><code>IndexReader.Open(/* path to index */).Terms(new Term("companyName", String.Empty));
</code></pre>
|
Using ASP.NET default Model Binders with DateTime <p>I've been trying to use the default ASP.NET MVC model binders but I'm having issues with binding DateTime. I've looked at Scott's post <a href="http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx" rel="nofollow">here</a> but it seems to be too sophisticated. Is there a simpler solution to binding DateTime?</p>
| <p>If you don't like Hanselman's solution you could try Castle's binders. They work like <a href="http://www.castleproject.org/monorail/documentation/trunk/usersguide/smartcontroller.html#date" rel="nofollow">this</a> and they can be <a href="http://blogger.forgottenskies.com/?p=258" rel="nofollow">used through MvcContrib</a>.</p>
|
Test to see if an xelement exists <p>I'm reading an XML file that looks like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<VehicleList>
<Vehicle>
<Item>
<Name>F-150</Name>
<Maker>Ford</Maker>
<Color>Black</Color>
<Price>30000</Price>
</Item>
<ItemSpecific>
<NameValueList>
<Name>Mileage</Name>
<Value>56000</Value>
</NameValueList>
<NameValueList>
<Name>Year</Name>
<Value>2003</Value>
</NameValueList>
</ItemSpecific>
</Vehicle>
<!-- more Vehicle nodes here -->
</Vehicles>
</code></pre>
<p>This is sample data returned from the eBay Web Service so don't grill me on the structure.</p>
<p>Anyway, I'm using code like this to read the xml and place all Vehicles in a List(of Vehicle) object, like so:</p>
<pre><code> Dim vehicles = From v in doc...<Vehicle> _
Let mile = (From x In v.<ItemSpecific>.<NameValueList> Where x.<Name>.Value = "Mileage" Select x.<Value>.Value).Single _
Let year = (From z In v.<ItemSpecific>.<NameValueList> Where z.<Name>.Value = "Year" Select z.<Value>.Value).Single _
Select New Vehicle With {.Name = v.<Item>.<Name>.Value, .Maker = v.<Item>.<Maker>.Value, .Color = v.<Item>.<Color>.Value, .Mileage = mile, .Year = year}
</code></pre>
<p>The resulting <code>List(Of Vehicle)</code> is then bound to an ASP.NET <code>ListView</code> control where the data is rendered. All goes well <em>if</em> all the desired nodes are present. For example, the Mileage node is conditional and is absent sometimes. Whenever the node isn't present I get a "<code>Sequence contains no elements</code>" error.</p>
<p>I've tried everything I know to get things working properly. Is there a way to test if an XElement exists?</p>
| <p>It depends on what you want to do when the node is not there. For instance if Nothing is acceptable then you can switch from .Single to .SingleOrDefault. The latter will return Nothing in the case of an empty sequence and will not throw an exception. </p>
<pre><code>Dim vehicles = From v in doc...<Vehicle> _
Let mile = (From x In v.<ItemSpecific>.<NameValueList> Where x.<Name>.Value = "Mileage" Select x.<Value>.Value).SingleOrDefault _
Let year = (From z In v.<ItemSpecific>.<NameValueList> Where z.<Name>.Value = "Year" Select z.<Value>.Value).SingleOrDefault _
Select New Vehicle With {.Name = v.<Item>.<Name>.Value, .Maker = v.<Item>.<Maker>.Value, .Color = v.<Item>.<Color>.Value, .Mileage = mile, .Year = year}
</code></pre>
|
Javascript image slider <p>Hi I'm looking for a simple Javascript Image slider that have the following features.
A little horizontal box that shows images thumbnail and slides them.
Once you select a thumbnail, the image shows on a div or some else where on the page.
I want something easy and pro looking.
Thanks</p>
| <p>If you can use jQuery there is a neat plugin called jQuery Cycle that can perform all sorts of image cycling.</p>
<p><a href="http://malsup.com/jquery/cycle/" rel="nofollow">link text</a></p>
|
Possible to call a function inside BoundColumn.DataField? <pre><code><asp:BoundColumn DataField="pos" HeaderText="Principal Office" />
</code></pre>
<p>would it be possible to somehow...</p>
<pre><code><asp:BoundColumn DataField="postProccess(pos)" HeaderText="Principal Office" />
</code></pre>
<p>...so I could modify the value as needed?</p>
<p>CRAP:</p>
<pre><code>A field or property with the name 'postProcess(pos)' was not found on the selected data source.
</code></pre>
<p>Anyone know how I can override that thing or something??</p>
| <p>Here is the full snippet you'd want to use for your template column...</p>
<pre><code><asp:TemplateColumn HeaderText="Principal Office">
<ItemTemplate>
<%# postProcess(Eval("pos")) %>
<ItemTemplate>
<asp:TemplateColumn>
</code></pre>
|
How to keep the document-tabs sorted by their last usage in Visual Studio 2008 <p>What is the registry change to tell Visual Studio to always position the current document in the window to the left.</p>
<p>The default implementation is such that if you have 10 documents open and you are editing the 5th one it's tab will be the 5th tab in the group. With the registry change when you click on the tab for the 5th document it becomes the 1st tab.</p>
| <p>(From <a href="http://blogs.msdn.com/saraford/archive/2008/10/09/did-you-know-you-can-keep-recently-used-files-from-falling-off-the-file-tab-channel-331.aspx" rel="nofollow">Sara Ford's blog</a>):</p>
<p>Under the <strong>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0</strong> key create a <strong>DWORD UseMRUDocOrdering = 1</strong>. </p>
<p>BTW: the above is for Visual Studio 2008. For Visual Studio 2005, replace <strong>9.0</strong> in the registry key name with <strong>8.0</strong>.</p>
|
Eclipse: Build and conform to different JRE versions <p>Is there a way to build my app using one version of the JRE but have my source conform to another version?</p>
<p>I would like to debug my app locally using 1.6 because OS X's 1.6 is much better than 1.4.2, but because of backwards compatibility reasons we actually ship using 1.4.2.</p>
| <p>You can manage this though the Run Configurations options. Create a new Run Configuration --> Java Application and then you can specify the JRE you want to use for that configuration. </p>
|
What's the most efficient test of whether a PHP string ends with another string? <p>The standard PHP way to test whether a string <code>$str</code> ends with a substring <code>$test</code> is:</p>
<pre><code>$endsWith = substr( $str, -strlen( $test ) ) == $test
</code></pre>
<p>Is this the fastest way?</p>
| <p>What Assaf said is correct. There is a built in function in PHP to do exactly that.</p>
<pre><code>substr_compare($str, $test, strlen($str)-strlen($test), strlen($test)) === 0;
</code></pre>
<p>If <code>$test</code> is longer than <code>$str</code> PHP will give a warning, so you need to check for that first.</p>
<pre><code>function endswith($string, $test) {
$strlen = strlen($string);
$testlen = strlen($test);
if ($testlen > $strlen) return false;
return substr_compare($string, $test, $strlen - $testlen, $testlen) === 0;
}
</code></pre>
|
Do Django custom authentication backends need to take a password? <p>Here's how my university handles authentication: we redirect the user to a website, they enter in their username and password, then they get redirected back to us with the username and a login key passed in the query string. When we get the user back, we call a stored procedure in the university's database that takes the username, login key, and ip address and tells us if this is valid.</p>
<p>I've got a Django custom authentication backend set up to handle our end of all of this. Does it make any difference one way or another whether I make it able to accept a password argument (since we're not actually taking their password)? Right now, I have it set up so that it takes the login key as the password argument. Would it be good, bad, or neither for me to change this to take this as say, login_key instead of as password?</p>
| <p>The <a href="http://docs.djangoproject.com/en/dev/topics/auth/">Django docs</a> say this:</p>
<blockquote>
<p>Either way, authenticate should check
the credentials it gets, and it should
return a User object that matches
those credentials, if the credentials
are valid. If they're not valid, it
should return None.</p>
</blockquote>
<p>The 'Either way' refers to whether the authenticate() method takes a username/password combination, or just a token. Your scenario falls between those two, so I'd think that the 'best' answer would be to write your authenticate() to take a username and a login key, and return the right User or None as appropriate.</p>
|
Rails: I can't call a function in a module in /lib - what am I doing wrong? <p>I know I'm doing something stupid or failing to do something intelligent - I'm frequently guilty of both.</p>
<p>Here's an example of what's causing me pain:</p>
<p>I have a module saved in /lib as test_functions.rb that looks like this</p>
<pre><code>module TestFunctions
def abc
puts 123
end
end
</code></pre>
<p>Going into ruby script/runner, I can see that the module is loading automatically (good ol' convention over configuration and all that...)</p>
<pre><code>>> TestFunctions.instance_methods
=> ["abc"]
</code></pre>
<p>so the method is known, let's try calling it</p>
<pre><code>>> TestFunctions.abc
NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):3
</code></pre>
<p>Nope. How about this?</p>
<pre><code>>> TestFunctions::abc
NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):4
</code></pre>
<p>Test
Nope again.</p>
<pre><code>defined?(TestFunctions::abc) #=> nil, but
TestFunctions.method_defined? :abc #=> true
</code></pre>
<p>Like I said at the top, I know I'm being dumb, can anyone de-dumb me?</p>
| <p>If you want <code>Module</code>-level functions, define them in any of these ways:</p>
<pre><code>module Foo
def self.method_one
end
def Foo.method_two
end
class << self
def method_three
end
end
end
</code></pre>
<p>All of these ways will make the methods available as <code>Foo.method_one</code> or <code>Foo::method_one</code> etc</p>
<p>As other people have mentioned, instance methods in <code>Module</code>s are the methods which are available in places where you've <code>include</code>d the <code>Module</code></p>
|
c# Label Visible and Invoke <p>I'm devolping a <strong>Windows Mobile</strong> aplication in <strong>Compact Framework 2.0 SP1</strong>.</p>
<p>How can I make invisible a label using invoke?</p>
<p>Thanks!</p>
| <p>You simply want to change the Label's Visible property? Generically speaking it's something like this:</p>
<pre><code>private void SetVisibility(Control target, bool visible)
{
if (target.InvokeRequired)
{
target.Invoke(new EventHandler(
delegate
{
target.Visible = visible;
}));
}
else
{
target.Visible = visible;
}
}
</code></pre>
|
I need help resetting the DEFAULT settings for ActiveX and Flash Player <p>When I start my web browser and I want to view a website or view something on a Flash Player I get this message:</p>
<blockquote>
<p>Your Security settings do not allow websites to use ActiveX controls installed on your computer. This page may not display correctly. click here for options.</p>
</blockquote>
<p>or I get this:</p>
<blockquote>
<p>If this site does not load, click here to install Flash.</p>
</blockquote>
<p>Can someone help me reset my settings so I don't have this problem anymore?</p>
| <p>i take it you are using Internet Explorer? Get a better browser like firefox if you are. </p>
|
Determining Class Responsibility and Collaborators <p>I'm using ActiveRecord to maintain information about users. The User class has the expected load(), insert(), update(), and delete() methods, setters, getters, and a few others. But I am having trouble deciding whether or not certain other methods should be included in the User class, or handled by collaborators.</p>
<p>Here's an example:</p>
<p>There are several transactions that a user might request that require confirmation. This is handled in a conventional way -- sending an email to the user with a link; clicking the link confirms that the user does indeed want the transaction to proceed. A hash of the verification key and it's expiration date/time persist as part of the user record.</p>
<p>Where should I draw the line in this process? Should there be a collaborator that handles verification (for example by taking the plain-text verification key from the query string and accepting a User object as a param)? Or should this be handled internally by the User class (passing the plain-text verification key in a method call)?</p>
<p>The very next thing that would happen upon verification, of course, is that the transaction would proceed requiring an update to the active record -- and there, it seems to me, the User class must have responsibility.</p>
<p>Any suggestions?</p>
| <p>You should delegate this task to a collaborator, which manages a <code>confirmations</code> table.</p>
<p>You would use the <code>Confirmation</code> model to track all confirmation requirements. The model will belong to <code>User</code>, as well as manage the confirmation hash and the action-to-be-confirmed (e.g. <code>activate_account</code>, <code>change_password</code> or <code>change_email</code> etc.).</p>
<p>The <code>Confirmation</code> controller would be responsible for validating the confirmation hash and chaining the appropriate action on the appropriate model (e.g. <code>activate_account</code> -> <code>user.activate()</code>, <code>change_password</code> -> <code>user.setPassword()</code> etc.) and remove the <code>Confirmation</code> from the <code>confirmations</code> table upon successful completion.</p>
<p>This will allow for better separation of logic, as well as allow you to scale better, e.g. to entertain more than one pending confirmation for a given user (say confirmation to change password <em>and</em> confirmation to change something else.)</p>
|
Is there a task supporting modern multithreaded archivers - 7zip, winrar etc.? <p>We are using the <a href="http://ant.apache.org/manual/Tasks/zip.html" rel="nofollow">Ant Zip task</a>, which is a bit obsolete (low processing speed for big files).</p>
<p>Can anyone point me to a mature Ant task, ready for production use, that supports multithreaded compression/decompression?</p>
<p>First of all I wish to increase speed of processing archive files.</p>
<p>I found <a href="http://www.pharmasoft.be/7z/" rel="nofollow">7ZIP Ant task</a>, but it looks abandoned, and it doesn't support multithreaded.</p>
| <p>Why not use the <a href="http://ant.apache.org/manual/Tasks/exec.html" rel="nofollow">exec task</a> with the command line version of 7zip?</p>
|
Java DomImplementationLS <p>I'm looking to create XML Document objects in Java and serialize them to a byte array (prior to sending them across a TCP connection). I currently have code that looks like this:</p>
<pre><code>public byte [] EncapsulateThingy( ThingyType thingy )
{
parser.reset(); // parser is a pre-existing DocumentBuilder object
Document doc = parser.newDocument();
doc.appendChild( doc.createElement("Thingy") );
// ... add nodes to doc to represent thingy
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( 8192 );
//
// Missing: Write doc to outputStream with xml version 1.0 and UTF-8
// encoding.
//
return outputStream.toByteArray();
}
</code></pre>
<p><a href="http://java.sun.com/javase/6/docs/api/org/w3c/dom/ls/DOMImplementationLS.html" rel="nofollow">The Sun Java documentation</a> has info on a set of interfaces which seems to start with DomImplementationLS for loading and saving XML, which I could use to fill in the missing piece above handily. But I can't figure out how to create an object which implements DomImplementationLS.</p>
<p>My ultimate goal is to serialize and deserialize very simple objects to XML encoded in byte arrays, so I can transmit them across a network. I am interested in keeping the solution lightweight, so that it can handle a high throughput of messages.</p>
<p>I am interested in alternate solutions, so long as they let me specify the exact XML structure which gets sent.</p>
<p>I of course have to provide the deserialization when these XML messages are consumed, but there is plenty of documentation and toturials available online for reading XML, but not much for writing it.</p>
<p>I would prefer solutions that are included in Java 6 without adding packages.</p>
| <p>Hope this helps:</p>
<pre><code>import java.io.ByteArrayOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
public class DomLsTest {
@Test
public void testDomLs() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
DOMImplementation di = db.getDOMImplementation();
Document d = di.createDocument("", "foo", null);
Element e = d.createElement("bar");
d.getDocumentElement().appendChild(e);
DOMImplementationLS ls = (DOMImplementationLS) di;
LSOutput lso = ls.createLSOutput();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
lso.setByteStream(baos);
LSSerializer lss = ls.createLSSerializer();
lss.write(d, lso);
System.out.println(baos.toString());
}
}
</code></pre>
<p>So, for your code, you would need to do something like:</p>
<pre><code>DOMImplementationLS ls = (DOMImplementationLS) parser.getDOMImplementation();
LSOutput lso = ls.createLSOutput();
lso.setByteStream(...);
LSSerializer lss = ls.createSerializer();
lss.write(..., lso);
</code></pre>
|
What influences the speed of code? <p>The way to see how fast your code is going, is performance profiling. There are tools for it and such, but I wonder what the factors are for code speed.</p>
<p>For instance, I've been told that image-editting software will use bitwise operations instead of integer variables to calculate their stuff, simply because it's faster.</p>
<p>So that must mean working with integers and other primitive types takes a few more steps to calculate compared to binairy.</p>
<p>There must be other stuff, but I don't have enough experience with how an OS connects to your hardware and the internal workings of many coding languages to know what.</p>
<p>So I'm asking here: do you know what influences the speed of code?</p>
<p><strong>Not</strong> necessarily the speed of programs.</p>
| <p>Integers <em>are</em> binary. Or rather, integers are simply integers, and can be represented in any number base. In base 10 you'd write 13, in base 16 you'd write d (or 0xd), in binary you'd write 1101 (or 0b1101). The Romans would've written XIII. They all represent the same <em>concept</em> of the number 'thirteen'. Among humans, we tend to use the base 10 representation, but when you ask a computer to process integers, it uses the binary representation. And it doesn't make a difference. Thirteen plus fortyfive yields the same result no matter how I write it. XIII + 0x2D = 13 + 45 = 0xd + 0b101101. It doesn't matter which representation you use, the result of an arithmetic operation is the same. Which is why we allow the CPU to use the binary representation for all integer processing.</p>
<p>Some programming languages also give you a "decimal" datatype, but that's generally related to floating-point arithmetics, where not all values can be represented in all bases (1/3 can be represented easily in base 3, but not in 2 or 10, for example. 1/10 can be represented in base 10, but not 2)</p>
<p>However, it is surprisingly difficult to single out any particular operations as "slow", because <em>it depends</em>. A modern CPU employs a lot of tricks and optimizations to speed up most operations most of the time. So really, what you need to do to get efficient code is avoid all the special cases. And there are a lot of them, and they're generally more to do with the combination (and order) of instructions, than which instructions are used.</p>
<p>Just to give you an idea of the kind of subtleties we're talking about, floating point arithmetic can be executed as fast (or sometimes faster than) integer arithmetics under ideal circumstances, but the latency is longer, meaning that ideal performance is harder to achieve. Branches which are otherwise almost free become painful because they inhibit instruction reordering and scheduling, in the compiler and on the fly on the CPU, which makes it harder to hide this latency.
Latency defines how long it takes from an instruction is initiated until the result is ready; most instructions only occupy the CPU one clock cycle Even if the result isn't yet ready the following cycle, the CPU is able to start another instruction then. Which means that if the result is not immediately needed, high-latency instructions are almost free. But if you need to feed the result to the next instruction, then that'll have to wait until the result is finished.</p>
<p>Certain instructions are just slow no matter what you do, and will typically stall the relevant parts of the CPU until the instruction has completed (square root is a common example, but integer division may be another. On some CPU's, doubles in general suffer from the same problem) - on the other hand, while a floating-point square root will block the FP pipeline, it won't prevent you from executing integer instructions simultaneously. </p>
<p>Sometimes, storing values in variables which could be recomputed again as needed, will be faster, because they can be put in a register saving a few cycles. Other times, it'll be slower because you run out of registers, and the value would have to be pushed to the cache, or even to RAM, making recomputation on every use preferable. The order in which you traverse memory makes a huge difference. Random (scattered) accesses can take hundreds of cycles to complete, but sequential ones are almost instant. Performing your reads/writes in the right pattern allows the CPU to keep the required data in cache almost all the time, and <em>usually</em> "the right pattern" means reading data sequentially, and working on chunks of ~64kb at a time. But sometimes not.
On an x86 CPU, some instructions take up 1 byte, others take 17. If your code contains a lot of the former, instruction fetch and decoding won't be a bottleneck, but if it's full of the longer instructions, that'll probably limit how many instructions can be loaded by the CPU each cycle, and then the amount it'd be able to execute doesn't matter.</p>
<p>There are very few <em>universal</em> rules for performance in a modern CPU. </p>
|
What are the differences between HTTP 1.0 and 1.1? <p>The latest StackOverflow <a href="http://blog.stackoverflow.com/2009/03/podcast-44/" rel="nofollow">podcast</a> has piqued my interest in the differences between HTTP 1.0 and HTTP 1.1.</p>
<p>Can anyone provide a simple list of the major differences between the HTTP 1.0 and HTTP 1.1 specifications?</p>
| <p>Have you checked <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.6.1">HTTP/1.1 â 19.6.1 Changes from HTTP/1.0</a>?</p>
|
Can I use Entity Framework with ASP.NET Membership? <p>I'm creating (really, re-creating) an app that has existing user and other data in MS-Access databases. The data will be moved to SQL Server, and part of that involves migrating users. I want to use EF to do ORM, and I am pretty sure I know what the data model will be in SQL Server. I am new to EF but not to ASP.NET, and I'd like to take advantage of the Membership features in ASP.NET. I am thinking about several ways to do this and would like some advice. I've done only a little research about this idea thus far, maybe it's been answered elsewhere. So, here goes a cluster of related questions.</p>
<ol>
<li><p>Can EF work with directly with ASP.NET Membership through some class or namespace that I'm not aware of?</p></li>
<li><p>If I transition users to the Membership system, to align their userids with data in other tables should I create another set of tables for user data atop the aspnet_* tables a la DotNetNuke?</p></li>
<li><p>I want to avoid a situation where I use the built-in Membership functions for only user authentication and switch over to EF context when I'm working with user-tagged data. Seems clumsy to withdraw user info to bind to a column in a GridView by going into a Membership user for every row, but maybe that's what's needed? Do I need to suck it up and replicate the Membership classes in EF for data retrieval purposes?</p></li>
<li><p>I was thinking of maybe implementing some kind of EF provider for Membership, on the idea that maybe then the provider could sit inside the overall EF data model. Is this crazy talk? (I've never written my own provider before)</p></li>
</ol>
<p>Feel free to tell me I am not making any sense.</p>
| <p>Why not do it the other way around? You can implement your own Membership provider for asp.net, that uses the model you want/need. </p>
<p>If the features you need aren't a complete match with the built-in asp.net membership implementation, you can just roll your own provider. If you will use just a couple features, you will have to implement just a couple methods (you don't have to fill implementation for all the methods). If you need more features than it supports, using the membership provider might get in your way.</p>
|
how to move a block or column of text <p>I have the following text as a simple case:</p>
<pre><code>...
abc xxx 123 456
wer xxx 345 678676
...
</code></pre>
<p>what I need to move a block of text xxx to another location:</p>
<pre><code>...
abc 123 xxx 456
wer 345 xxx 678676
...
</code></pre>
<p>I think I use visual mode to block a column of text, what are the other commands to move the block to another location?</p>
| <p>You should use blockwise visual mode (<kbd>Ctrl</kbd>+<kbd>v</kbd>).
Then <kbd>d</kbd> to delete block, <kbd>p</kbd> or <kbd>P</kbd> to paste block.</p>
|
How can I rewrite all urls to "/"? <p>Server: Apache</p>
<p>I'm looking to rewrite my urls in the following way, and I can't figure out a way to get it to work.</p>
<pre><code>http://website.com/index.html
</code></pre>
<p>I want it to redirect to:</p>
<pre><code>http://website.com/
</code></pre>
<p>So basically I want to load index.html, but not display it in the url. I also don't want to give it another name. I'm not looking for <strong>/index.html</strong> to become <strong>/index</strong></p>
<p>Additionally, I'm trying to have any GET data such as:</p>
<pre><code>http://website.com/index.html?id=0&name="fred"
</code></pre>
<p>To rewrite to:</p>
<pre><code>http://website.com/?id=0&name="fred".
</code></pre>
<p>If you have a solution that is not using .htaccess files that's fine as well.</p>
| <p>I believe this should work:</p>
<pre><code>RewriteEngine on
RewriteRule ^index\.html(.*)$ /$1 [R=permanent,L]
</code></pre>
<p>This will redirect any requests that start with <code>/index.html</code> to simply "<code>/</code>" and will preserve any arguments that come after <code>index.html</code></p>
|
How can I get the width and height of a text string with CAM::PDF? <p>I use the following to read a PDF file and get text strings of a page:</p>
<pre><code>my $pdf = CAM::PDF->new($pdf_file);
my $pagetree = $pdf->getPageContentTree($page_no);
# Get all text strings of the page
# MyRenderer is a separate package which implements getTextBlocks and
# renderText methods
my @text = $pagetree->traverse('MyRenderer')->getTextBlocks;
</code></pre>
<p>Now, <code>@text</code> has all the text strings and start x,y of each text string.</p>
<p>How can I get the width (and possibly the height) of each string?</p>
<p>MyRenderer package is as follows:</p>
<pre><code>package MyRenderer;
use base 'CAM::PDF::GS';
sub new {
my ($pkg, @args) = @_;
my $self = $pkg->SUPER::new(@args);
$self->{refs}->{text} = [];
return $self;
}
sub getTextBlocks {
my ($self) = @_;
return @{$self->{refs}->{text}};
}
sub renderText {
my ($self, $string, $width) = @_;
my ($x, $y) = $self->textToDevice(0,0);
push @{$self->{refs}->{text}}, {
str => $string,
left => $x,
bottom => $y,
right =>$x + $width,
};
return;
}
</code></pre>
<p><b>Update 1:</b>
There's a function <b>getStringWidth($fontmetrics, $string)</b>
in CAM::PDF. Altough there's a parameter $fontmetrics in that function, irespective of what I pass to that parameter, the function returns the same value for a given string.</p>
<p>Also, I am not sure of the unit of measure the returned value uses.</p>
<p><b>Update 2:</b>
I changed the renderText function to following:</p>
<pre><code>sub renderText {
my ($self, $string, $width) = @_;
my ($x, $y) = $self->textToDevice(0,0);
push @{$self->{refs}->{text}}, {
str => $string,
left => $x,
bottom => $y,
right =>$x + ($width * $self->{Tfs}),
font => $self->{Tf},
font_size => $self->{Tfs},
};
return;
}
</code></pre>
<p>Note that in addition to getting font and font_size, I multiplied $width with font size to get the real width of the string.</p>
<p>Now, only thing missing is the height.</p>
| <p>getStringWidth() depends heavily on the font metrics you provide. If it can't find the character widths in that data structure, then it falls back to the following code:</p>
<pre><code> if ($width == 0)
{
# HACK!!!
#warn "Using klugy width!\n";
$width = 0.2 * length $string;
}
</code></pre>
<p>which may be what you're seeing. When I wrote that, I thought it was better than returning 0. If your font metrics seem good and you think there's a bug in CAM::PDF, feel free to <a href="http://rt.cpan.org/Public/Dist/Display.html?Name=CAM-PDF" rel="nofollow">post more details</a> and I'll take a look.</p>
|
What's the best way to find the closest matching type to an existing type? <p>I've got a registry of classes and types in Python 2.5, like so:</p>
<pre><code>class ClassA(object):
pass
class ClassB(ClassA):
pass
MY_TYPES = {
basestring : 'A string',
int : 'An integer',
ClassA : 'This is ClassA or a subclass',
}
</code></pre>
<p>I'd like to be able to pass types to a function, and have it look up the closest matching type in the hierarchy. So, looking up <code>str</code> would return <code>"A string"</code> and looking up <code>ClassB</code> would return <code>"This is ClassA or a subclass"</code> The problem is, I don't know how to find the superclass (or, rather, trace the MRO chain) of a type object.</p>
<p>What's the best way of handling this?</p>
| <pre><code>from inspect import getmro
[st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]
['This is ClassA or a subclass']
</code></pre>
<p>or if you're only interested in first match(es) generator version:</p>
<pre><code>(st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))
</code></pre>
|
How to add value in a public property of List<string> type in c#? <pre><code>private List<string> _Baseline = new List<string>();
public List<string> Baseline
{
get { return _Baseline; }
set { _Baseline = value; }
}
</code></pre>
<p>How can I set this property?
It does not let me add using the add method; it throws an "object reference null" error. </p>
| <p>It should work if you did what you wrote here.
I guess you are using generics, and I can't see them in your post.</p>
<p>If you have a complex expression, split it. For example, change ObjectA.Prop.Other.Xyz.Add(..) to:</p>
<pre><code>SomeClass a = ObjectA.Prop;
SomeClass2 b = a.Other;
SomeClass3 c = b.Xyz;
c.Add(...)
</code></pre>
<p>this way you will find quickly where the null reference is.</p>
|
Referencing an external library in an Ant build <p>We have an ant build script for a project we're developing for a PDA. In eclipse we have a load of referenced libraries and I know how to get them to work when we run the jar on the PDA because we have a .lnk file where you can add the external libraries simply by adding the following:</p>
<pre><code>512#"\J9\PPRO11\bin\j9.exe" -jcl:ppro11 -cp "\dist\WiFiTest.jar;\placelab\lib\placelab.jar" j2medemo.wifi.WiFiTest
</code></pre>
<p>Adding whatever libraries we need after the -cp argument. However, I have no idea how to replicate this in the ant file (no idea is actually an exaggeration but after reading all the documentation I <em>still</em> don't understand it).</p>
<p>We have the following .</p>
<pre><code><target name="jar" depends="prepare">
<delete file="${dist}/${appname}.jar"/>
<delete file="${dist}/MANIFEST.MF"/>
<manifest file="${dist}/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="j2medemo.GUI.MapPanel"/>
</manifest>
<jar destfile="${dist}/${appname}.jar"
basedir="${classes}"
includes="**/*.class, **/*.jpg, **/*.gif,**/*.png,**/*.xml"
manifest="${dist}/MANIFEST.MF"
/>
</target>
</code></pre>
<p>I have tried adding everywhere I can think of but it doesn't help. Can I just add it to the the include part?</p>
<p>Secondly, we have a run target:</p>
<pre><code><target name="run" description="run" depends="jar">
<exec dir="${j9bin}" executable="${j9bin}\j9.exe">
<arg line="-jcl:ppro11 -cp '${dist}\${appname}.jar;placelab\lib\placelab.jar' ${mainclass}"/>
<env key="JAVA_HOME" path="${j9home}"/>
</exec>
</target>
</code></pre>
<p>And I wanted to change it to run a different class so I created the following two targets:</p>
<pre><code><target name="jarSAX" depends="prepare">
<delete file="${dist}/SAXParse.jar"/>
<delete file="${dist}/MANIFEST.MF"/>
<manifest file="${dist}/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="j2medemo.Routes.SAXParse"/>
</manifest>
<jar destfile="${dist}/SAXParse.jar"
basedir="${classes}"
includes="**/*.class, **/*.jpg, **/*.gif,**/*.png,**/*.xml"
manifest="${dist}/MANIFEST.MF"
/>
</target>
</code></pre>
<p>And</p>
<pre><code><target name="runSAXParser" description="run" depends="jarSAX">
<exec dir="${j9bin}" executable="${j9bin}\j9.exe">
<arg line="-jcl:ppro11 -cp '${dist}\SAXParse.jar' j2medemo.Routes.SAXParse"/>
<env key="JAVA_HOME" path="${j9home}"/>
</exec>
</target>
</code></pre>
<p>But if I try and run this I get the following error:</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: j2medemo.Routes.SAXParse
</code></pre>
<p>If anyone has any ideas/solutions for either questions that would be most helpful.</p>
| <p>From what I can tell, you need to add the classpath elements to the manifest. Should look something like this:</p>
<pre><code> <manifest file="${dist}/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Main-Class" value="j2medemo.Routes.SAXParse"/>
<attribute name="Class-Path" value="WiFiTest.jar;placelab.jar"/>
</manifest>
</code></pre>
<p>The classpath entries should be relative to the location of the Jar in the distributable. From there, you should be able to execute the jar directly (using the -jar command line option, I'm not sure what this is for J9). Should be similar to the analogous Java call:</p>
<pre><code>java -jar MainJar.jar
</code></pre>
|
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit <p>When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?</p>
<p>I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.</p>
| <p>You don't need to <code>commit</code>, you just need to <code>flush</code>. Here's some sample code. After the call to <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.flush">flush</a> you can access the primary key that was assigned. Note this is with SA 0.4.8.</p>
<pre><code>from sqlalchemy import *
from sqlalchemy.databases.mysql import *
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class User(Base):
__tablename__ = 'user'
user_id = Column('user_id', Integer, primary_key=True)
name = Column('name', String)
if __name__ == '__main__':
import unittest
from sqlalchemy.orm import *
import datetime
class Blah(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:', echo=True)
self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
Base.metadata.bind = self.engine
Base.metadata.create_all()
self.now = datetime.datetime.now()
def test_pkid(self):
user = User(name="Joe")
session = self.sessionmaker()
session.save(user)
session.flush()
print 'user_id', user.user_id
session.commit()
session.close()
unittest.main()
</code></pre>
|
Degrafa: Adding a RasterImage in ActionScript <p>I'm trying to add a RasterImage component to a Surface at runtime. My code runs as follows:</p>
<pre><code>var ri:RasterImage = new RasterImage();
ri.loadingLocation = new LoadingLocation('http://resources.mydomain.com/','crossdomain.xml');
ri.source = 'http://resources. mydomain.com/some.jpg'
this.myGeometryGroup.geometryCollection.addItem(ri);
</code></pre>
<p>Both the LoadingLocation and source paths work on an mxml declared RasterImage in the same document, but trying to create this in AS doesn't work.
I've tried every variation I could think of, including using null for LoadingLocation, embedded classes for source, etc.</p>
<p>With external resources, the application seizes up. With embedded resources nothing shows up. Any help would be appreciated-</p>
| <p>Nevermind- This was a bug in the framework. The Degrafa team heard about it and posted a fix in under an hour (!)</p>
|
Is there a way to get a difference report on two Jet (.mdb) databases? <p>I have code that depends a relatively small MS Jet (created in Access) database. Our source control process is far from all that it could/should be (which is a problem that needs to be solved immediately) and we have ended up with two versions of the same database. The person who edited the "other" version is no longer around to give me hints about what he changed. What is the best way to find the differences of the actual data contained in two versions of a database?</p>
| <p>Output all the forms and modules to text files and use a text compare utility.</p>
<p>For example:</p>
<pre><code>Sub ToText()
Dim frm, mdl
For Each frm In CurrentProject.AllForms
Application.SaveAsText acForm, frm.Name, "c:\docs\" _
& frm.Name & ".txt"
</code></pre>
<p>'SO formatting</p>
<pre><code>Next
For Each mdl In CurrentProject.AllModules
Application.SaveAsText acModule, mdl.Name, "c:\docs\" _
& mdl.Name & ".txt"
</code></pre>
<p>'SO formatting</p>
<pre><code>Next
End Sub
</code></pre>
|
What's the best way to get rid of nested ifs in code while checking for conditions? <p>I'm developing a BlackBerry app in Java and I have an Options class where all user settings are stored. The problem is I need to check some conditions in order to know how to react. As I keep adding more features, more GUI options are shown to the user, more settings are stored in the Options class and more conditions need to be checked for.</p>
<p>Take the following code for example:</p>
<pre><code>private void doCallMonitoring(int callId){
/*This is the part that I want to avoid. Having
multiple nested ifs. Here's just two conditions
but as I add more, it will get unmantainable
very quickly.*/
if(Options.isActive().booleanValue()){
callTime = new Timer();
TimerTask callTimeTask = new TimerTask(){
public void run(){
callTimeSeconds++;
if((callTimeSeconds == Options.getSoftLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
injectDTMFTone(Phone.getActiveCall());
}else if((callTimeSeconds >= Options.getHardLimit().intValue()) && (Phone.getActiveCall().getStatus() == PhoneCall.STATUS_CONNECTED)){
injectEndCall();
}
}
};
callTime.schedule(callTimeTask, 0,1000);
}else{
System.out.println("Service not active");
}
}
</code></pre>
<p>How I would want it to work is to verify all options with a single call and from there determine the curse of action. How can I achieve such a design?</p>
| <p>Another option is to make methods such as <code>injectDMTFTone()</code> check to see if they want to handle that condition, and return true or false depending on if it was handled or not.</p>
<p>For instance:</p>
<pre><code>public void run() {
callTimeSeconds++;
do {
if (handleInjectDMTFTone())
break;
if (handleInjectEndCall())
break;
} while(false);
callTime.schedule(callTimeTask, 0,1000);
}
boolean handleInjectDMTFTone() {
if ((callTimeSeconds != Options.getSoftLimit().intValue()) ||
(Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
return false;
injectDTMFTone(Phone.getActiveCall());
return true;
}
boolean handleInjectEndCall() {
if ((callTimeSeconds < Options.getHardLimit().intValue()) ||
(Phone.getActiveCall().getStatus() != PhoneCall.STATUS_CONNECTED))
return false;
injectEndCall();
return true;
}
</code></pre>
<p>Of course, instead of calling another <code>injectDMTFTone()</code> method or <code>injectEndCall()</code> method, you would just inline that logic right in those methods. In that way you've grouped all the logic of how and when to deal with those conditions in the same place.</p>
<p>This is one of my favorite patterns; use <code>if</code> statements as close to the top of methods as makes sense to eliminate conditions and return. The rest of the method is not indented many levels, and is easy and straightforward to read.</p>
<p>You can further extend this by creating objects that all implement the same interface and are in a repository of handlers that your <code>run</code> method can iterate over to see which will handle it. That may or may not be overkill to your case.</p>
|
Best way to decorate databound text in a wpf TextBlock <p>Let's say I have some multiline text that I'd like to format, and let's also say that it's databound. So, in XAML:</p>
<pre><code><TextBlock TextWrap="Wrap">
<TextBlock.Inlines>
<Run TextWeight="Bold" Text="{Binding Path=FirstName}" />
<Run TextStyle="Italic Text="{Binding Path=LastName}" />
</TextBlock.Inlines>
</TextBlock>
</code></pre>
<p>Now, this doesn't work because Run's Text isn't a dependency property. So, I'm wondering, what is the best way to style inline databound text like this?</p>
<p>Thanks in advance.</p>
| <p>There is a workaround posted <a href="http://code.logos.com/blog/2008/01/data%5Fbinding%5Fin%5Fa%5Fflowdocument.html" rel="nofollow">here</a>. It basically involves subclassing Run to be bindable. Works though.</p>
|
For a large project, what planning should be done before coding and how should it be approached? <p>What is your method of "mapping out" an idea before creating it? </p>
<p>Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace. What planning/design steps should I take before I start the actual work?</p>
<p>For example, should I map everything out page by page (their functionalities, data, etc.)?</p>
| <p>For a large project first think of a one-liner to description of your site (try to not use any buzzwords here). Next think of three design maxims (rules your design Should never conflict with). Then draw a few views and think up a few user cases (1 day) then work in code for 2 weeks (this will be a throw away prototype so just work as fast as you can forget about bugs and details, don't worry about code smells or design patterns, just make as much as you can), then revaluate all the steps above and throw away your two week prototype, and begin your project in a serious manner applying solid engineering and design. After a month has gone by evaluate your(team) moral and get feedback. If it all seems to be going ok, continue, you got a long ride ahead, otherwise just give up, do a postmortem, and start over with new goals.</p>
|
How to filter myself out of Google Analytics with a dynamic IP address? <p>Does anyone know how to setup Google Analytics to filter yourself out if you're visiting the site from a dynamic IP address? I don't want to include myself in my stats from home use where I have a dynamic IP address via Verizon FiOS.</p>
| <p>Google currently has a browser add-on that will block any visits of yours from showing up in any Analytics. <a href="http://tools.google.com/dlpage/gaoptout">http://tools.google.com/dlpage/gaoptout</a></p>
<p>Pluses and minuses of this opt-out versus filters are discussed in <a href="http://www.debi-z.com/2011/05/17/how-do-you-exclude-yourself-in-google-analytics/">this blog post</a>.</p>
|
NULL pointer with boost::shared_ptr? <p>What's the equivalent to the following:</p>
<pre><code>std::vector<Foo*> vec;
vec.push_back(NULL);
</code></pre>
<p>when dealing with <code>boost::shared_ptr</code>? Is it the following code?</p>
<pre><code>std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());
</code></pre>
<p>Note: I may push back a lot of such objects. Should I declare a global static <code>nullPtr</code> object somewhere? That way only one of them would have to be constructed:</p>
<pre><code>boost::shared_ptr<Foo> nullPtr;
</code></pre>
| <p>Your suggestion (calling the <code>shared_ptr<T></code> constructor with no argument) is correct. (Calling the constructor with the value 0 is equivalent.) I don't think that this would be any slower than calling <code>vec.push_back()</code> with a pre-existing <code>shared_ptr<T></code>, since construction is required in both cases (either direct construction or copy-construction).</p>
<p>But if you want "nicer" syntax, you could try the following code:</p>
<pre><code>class {
public:
template<typename T>
operator shared_ptr<T>() { return shared_ptr<T>(); }
} nullPtr;
</code></pre>
<p>This declares a single global object <code>nullPtr</code>, which enables the following natural syntax:</p>
<pre><code>shared_ptr<int> pi(new int(42));
shared_ptr<SomeArbitraryType> psat(new SomeArbitraryType("foonly"));
...
pi = nullPtr;
psat = nullPtr;
</code></pre>
<p>Note that if you use this in multiple translation units (source files), you'll need to give the class a name (e.g. <code>_shared_null_ptr_type</code>), move the definition of the <code>nullPtr</code> object to a separate .cpp file, and add <code>extern</code> declarations in the header file where the class is defined.</p>
|
What is the difference between signed and unsigned variables? <p>I have seen these mentioned in the context of C and C++, but what is the difference between signed and unsigned variables? </p>
| <p><strong>Signed variables</strong>, such as signed integers will <em>allow you to represent numbers both in the positive and negative ranges</em>.</p>
<p><strong>Unsigned variables</strong>, such as unsigned integers, will <em>only allow you to represent numbers in the positive</em>.</p>
<p>Unsigned and signed variables of the same type (such as <code>int</code> and <code>byte</code>) both have the same range (range of 65,536 and 256 numbers, respectively), but <strong>unsigned can represent a larger magnitude number than the corresponding signed variable</strong>.</p>
<p>For example, an <code>unsigned byte</code> can represent values from <code>0</code> to <code>255</code>, while <code>signed byte</code> can represent <code>-128</code> to <code>127</code>.</p>
<p>Wikipedia page on <a href="http://en.wikipedia.org/wiki/Signed%5Fnumber%5Frepresentations">Signed number representations</a> explains the difference in the representation at the bit level, and the <a href="http://en.wikipedia.org/wiki/Integer%5F%28computer%5Fscience%29">Integer (computer science)</a> page provides a table of ranges for each signed/unsigned integer type.</p>
|
Checkboxes on Rails <p>What's the correct way of making checkboxes that are related to a certain question in Ruby on Rails? At the moment I have:</p>
<pre><code><div class="form_row">
<label for="features[]">Features:</label>
<br><%= check_box_tag 'features[]', 'scenarios' %> Scenarios
<br><%= check_box_tag 'features[]', 'role_profiles' %> Role profiles
<br><%= check_box_tag 'features[]', 'private_messages' %> Private messages
<br><%= check_box_tag 'features[]', 'chatrooms' %> Chatrooms
<br><%= check_box_tag 'features[]', 'forums' %> Forums
<br><%= check_box_tag 'features[]', 'news' %> News
<br><%= check_box_tag 'features[]', 'polls' %> Polls
</div>
</code></pre>
<p>I also want to be able to automatically check the previously selected items (if this form was re-loaded). How would I load the params into the default value of these?</p>
| <p>You are looking at the following:</p>
<pre><code><div class="form_row">
<label for="features[]">Features:</label>
<% [ 'scenarios', 'role_profiles', ... , 'polls' ].each do |feature| %>
<br><%= check_box_tag 'features[]', feature,
(params[:features] || {}).include?(feature) %>
<%= feature.humanize %>
<% end %>
</div>
</code></pre>
<p>Although if you already have a <code>Feature</code> model, with a <code>features</code> table and a <code>has_many :features</code> relationship, you probably want this:</p>
<pre><code><div class="form_row">
<label for="feature_ids[]">Features:</label>
<% for feature in Feature.find(:all) do %>
<br><%= check_box_tag 'feature_ids[]', feature.id,
@model.feature_ids.include?(feature.id) %>
<%= feature.name.humanize %>
<% end %>
</div>
</code></pre>
|
free country, city database for sql server <p>have anyone used this before, i need free country, city, IP database for sqlserver</p>
| <p>I have used <a href="http://www.maxmind.com/app/geolitecity">http://www.maxmind.com/app/geolitecity</a> . It is a less exact version of their paid database. The free database claims to be "over 99.5% on a country level and 79% on a city level for the US within a 25 mile radius". You can see their accuracy detailed at <a href="http://www.maxmind.com/app/geolite_city_accuracy">http://www.maxmind.com/app/geolite_city_accuracy</a>.</p>
<p>The data is presented as a CSV file containing the starting IP block, ending IP block, and the location. It is easy enough to load into sqlserver. </p>
<p>APIs in C, C#, PHP, Java, Perl and the free version, GeoLite, has an IPv6 version in addition to the downloadable CSV Format.</p>
|
Schedule Controls for ASP.Net MVC <p>Are there any scheduling components, commercial or otherwise, for ASP.Net MVC? Our company currently uses the Infragistics WebSchedule controls, but they don't appear to support MVC.</p>
<p><strong>Edit:</strong>
I think I may have been a bit unclear, I am not looking for a task scheduler, rather I am looking for a web calendar/appointment/schedule management framework or component set. Something that would include a Month/Week/Day view of a calendar and allow me to create and display appointment items.</p>
<p>A framework that would let me build something like Google calendar, except the appointments would be stored in my database, not Googles.</p>
| <p>I just wanted to update with the scheduling tool we eventually choose.
<a href="http://www.dhtmlx.com/docs/products/dhtmlxScheduler/index.shtml">dhtmlxScheduler</a> - we are very happy with both the tool and the support.</p>
<p>Also - since it was never mentioned in any of the answers above, Telerik has a schedule tool that is compatible with ASP.Net MVC as well.</p>
|
Calling ASP.net Web Service from C# Application <p>I have a question. How can i invoke a web service and get the result from a C# desktop application. I am making a desktop app and I want it to be able to connect to my online ASP.net web services. How is this possible?</p>
| <ol>
<li>In Solution Explorer, right-click your project node and select Add <strong>Service</strong> Reference.</li>
<li>Enter the URL where your service WSDL is located. This is usually the URL of the service itself.</li>
<li>This generates a strongly-typed proxy class in a new Services References folder in your project.</li>
<li>Write code in your desktop app to instantiate the proxy class and invoke methods on it. The rest works like magic. :)</li>
</ol>
<p>AB Kolan was also correct, but Add <strong>Web</strong> Reference uses the old-style web services framework whereas Add <strong>Service</strong> References uses the new WCF stack. Important note: It is <strong>not</strong> required that the service itself use WCF for you to use WCF on the client side. WCF on the client is typically the best choice for any service, provided you can take a dependency on .NET 3.0 and above.</p>
|
Add a summary information to WiX generated MSI <p>How to add (or change a default values) a summary page information to a WiX-generated MSI file?</p>
<p>Summary page is the tab page which is visible if you right click on the MSI file in the Windows Explorer and includes following text fields:</p>
<p>Title,
Subject,
Author,
Category,
Keywords,
Comments</p>
<p></p>
| <p>That information is set in the field, for example:</p>
<pre><code><Wix xmlns='http://schemas.microsoft.com/wix/2003/01/wi'>
<Product
UpgradeCode="SOMEGUID-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
Name='MyApp'
Id='????????-????-????-????-????????????'
Language='1033'
Codepage='1252'
Version='1.0.0'
Manufacturer='MyCompany'>
<Package
Id="*"
Keywords="keyword1, keyword2, keyword3"
Description="summary of application"
Comments="some comments"
Manufacturer="mycompany"
InstallerVersion="300"
Languages="1033"
Compressed="yes"
SummaryCodepage="1252"/>
</code></pre>
|
how to convert byte* into jpeg file in VC++ <p>how to convert byte* into jpeg file in VC++</p>
<p>i am capturing Video samples and writing it as bmp files, but i want to write that video samples into jpeg file using MFC support in ATL COM.</p>
| <p>Use libjpg. Download from: <a href="http://www.ijg.org/" rel="nofollow">http://www.ijg.org/</a></p>
|
What does re.compile(r'[[]]') match? <p>With Python's re module, why do the following act differently:</p>
<pre><code>>>> r = re.compile(r'[][]')
>>> r.findall(r'[]')
['[', ']']
>>> r = re.compile(r'[[]]')
>>> r.findall(r'[]')
['[]']
>>> r.findall(r'][')
[]
</code></pre>
| <p>The regular expression "[[]]" matches the substring "[]". The first [ in the expression begins a character class, and the first ] ends it. There is only one character ([) in the class, and then it has to be followed by the second ]. So the expression is "any of the characters in "[", followed by a "]".</p>
|
Naming keys in resource files best practice <p>Does anyone have any recommendations on naming keys in resource files? For instance, do you base the name of your key on the text that needs to be localized or on the control that uses the text?</p>
<p>Say you have an edit button in several screens (one to edit a user, one to edit a group). You could use the following keys:</p>
<ul>
<li>editUserButton.label=Edit User...</li>
<li>editGroupButton.label=Edit Group...</li>
</ul>
<p>or</p>
<ul>
<li>editUser=Edit User...</li>
<li>editGroup=Edit Group...</li>
</ul>
<p>or</p>
<ul>
<li>user.edit=Edit User...</li>
<li>group.edit=Edit Group...</li>
</ul>
<p>What scheme do you prefer and why? </p>
| <p>I prefix my literals by usecase or action classname. eg:</p>
<pre>PlaceOrder.invalidId=Invalid id for order {0}
PlaceOrder.success=Your order {0} was successful
PlaceOrder.fail.visa=Your visa was ...
PlaceOrder.fail.communications=We could not...
PlaceOrder.submit=Buy now
Login=Login
Login.fail=Your credentials did not...
Login.alread=You are already logged in</pre>
<p>This way you avoid collisions:</p>
<pre>EditStudent=Edit
EditClass=Edit
EditCourse=Edit Course</pre>
<p>...and can also find what you need easier.</p>
<p>Another way I group is by entity:</p>
<pre>Person.id=#
Person.name=First name
Person.surname=Surname</pre>
<p>These can appear as headers on tables with the entities. It saves you in cases such as this:</p>
<pre>Person.id=#
Class.id=#
Course.id=Course Id</pre>
<p>Lastly by providing context in the property keys you can save yourself from false translations. For example I once had:</p>
<pre>no=no</pre>
<p>which was being used as an id (#) table header on the top left cell, but our french translator did this for French:</p>
<pre>no=non</pre>
<p>... he thought it was the word "no" (negative of yes). :)</p>
<p>Last (but not least) prefixing with classname will help you when you want to refactor/rename classes and quickly update these property keys without having to look at the templates.</p>
|
ofstream error <p>This is in reference to another question I asked, though it is its own question entirely.</p>
<p>when I compile I get two errors:</p>
<p>1>.\asst4.cpp(73) : error C2065: 'outfile' : undeclared identifier</p>
<p>1>.\asst4.cpp(73) : error C2228: left of '.close' must have class/struct/union</p>
<p>I'm slightly confused as to what I've done incorrectly here? Any reccomendations or ideas? (The actual outfile is near the top of the code.</p>
<p>Here is the full code:</p>
<pre><code>#include<iostream>
#include<fstream> //used for reading/writing to files.
#include<string> //needed for the filename.
#include<stdio.h> //for goto statement
using namespace std;
int main()
{
string start;
char choice;
char letter;
int x;
int y;
int z;
string filename;
int garbage = rand()%('!' - '~' + 1 );
cout << "Would you like to encrypt or decrypt a file? Please type enc, dec, or stop (case sensitive): " ;
cin >> start;
while(start == "enc")
{
x = 1;
y = 1;
cout << "How many garbage characters would you like between each correct character?: " ;
cin >> z;
cout << endl << "Please insert the name of the document you wish to encrypt, make sure you enter the name, and the file type (ie: filename.txt): " ;
cin >> filename;
ifstream infile(filename.c_str());
while(!infile.eof())
{
ofstream outfile("encrypted.txt", ios::out);
infile.get(letter);
if (x == y)
{
outfile << garbage;
x++;
}
else
{
if((x - y) == z)
{
outfile << letter;
y = x;
}
else
{
outfile << garbage;
x++;
}
}
}
cout << endl << "Encryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
infile.close();
outfile.close();
cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
cin >> choice;
if(choice == 'y')
{
start = "enc";
}
else
{
cout << endl << "Do you wish to decrypt a file? Please press y then enter if yes (case sensitive).";
if(choice = 'y')
{
start == "dec";
}
else
{
start == "no";
}
}
}
while(start == "dec")
{
//lets user choose whether to do another document or not.
//used to track each character in the document.
x = 1; //first counter for tracking correct letter.
y = 1; //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
//third counter (used as a check to see if the first two counters are equal).
//allows for user to input the filename they wish to use.
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename; //getline(cin, filename);
cout << endl;
cout << "'Every nth character is good', what number is n?: ";
cin >> z; //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
cout << endl;
z = z - 1; //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
if(infile.is_open()) //checks to see if the file is opened.
{
while(!infile.eof()) //continues looping until the end of the file.
{
infile.get(letter); //gets the letters in the order that that they are in the file.
if (x == y) //checks to see if the counters match...
{
x++; //...if they do, adds 1 to the x counter.
}
else
{
if((x - y) == z) //for every nth character that is good, x - y = nth - 1.
{
cout << letter; //...if they don't, that means that character is one you want, so it prints that character.
y = x; //sets both counters equal to restart the process of counting.
}
else //only used when more than every other letter is garbage, continues adding 1 to the first
{ //counter until the first and second counters are equal.
x++;
}
}
}
cout << endl << "Decryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
infile.close();
cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
cin >> choice;
if(choice == 'y')
{
start == "dec";
}
else
{
cout << endl << "Do you wish to encrypt a file? Please press y then enter if yes (case sensitive).";
if(choice == 'y')
{
start == "enc";
}
else
{
start == "no";
}
}
}
else //this prints out and program is skipped in case an incorrect file name is used.
{
cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
cout << "IE:" << " filename.txt" << endl;
cout << "You input: " << filename << endl;
cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
cin >> choice;
if(choice == 'y')
{
start == "dec";
}
else
{
start == "no";
}
}
getchar(); //because I use visual C++ express.
}
}
</code></pre>
<p>Thanks ahead of time!
Jeff</p>
| <p>Scoping issue. You are declaring outfile within your while loop, yet are trying to access it outside of said while loop.</p>
<p>Move <code>ofstream outfile("encrypted.txt", ios::out);</code> to the line right after your <code>ifstream infile(filename.c_str());</code> which is before your <code>while(!infile.eof())</code>.</p>
|
What is the purpose of "remove unused references" <p>I have read that removing unused references <a href="http://blogs.msdn.com/csharpfaq/archive/2004/10/20/245411.aspx">makes no difference</a> to the compiler as it ignores assemblies that are not being referenced in the code itself.</p>
<p>But I find it hard to believe because then, what is the real purpose of <a href="http://msdn.microsoft.com/en-us/library/7sfxafba.aspx">Removing unused references</a>? It doesn't have any noticeable effect on the size of the generated assembly or otherwise. Or is this <em>smart</em> behaviour limited to the C# compiler (csc.exe) and not inherent to vbc.exe?</p>
<p>If this functionality is so useless, why does <a href="http://www.jetbrains.com/resharper/">ReSharper</a> offer it as a feature? Why is it provided within the Visual Studio Project Configuration dialog?</p>
<p>The only activity I can think of where this would be useful is during Deployment. References (used or unused) would still be copied by the installer. But for assemblies that reside in the GAC (for instance, BCL assemblies), this would not be a problem either.</p>
| <p>It prevents the CLR from loading the referenced module at runtime. This will reduce startup time (since it takes time to load each module). Depending on the size of the module it might noticeably reduce startup time.</p>
<p>One way to test this is to create a test WinForms project, add a reference to an assembly that isn't used (e.g., System.Web) then run and attach to the executable (e.g., F5). View the loaded modules (Debug -> Windows -> Modules) and you'll see the referenced assembly was loaded.</p>
<p>If you think about it, it would be pretty hard for the CLR to determine whether or not a dependency (it's in the manifest as a dependency once you add a reference to it) is really used... Especially since the execution of some code paths can't be known in advance...</p>
|
Boolean column in Microsoft Access and filtering data using linq <p>[Apologies for long question but I thought it would be clearer for others to answer]</p>
<p>I have a Microsoft Access database and it contains a table "Customers" with following columns:</p>
<ul>
<li>ID (auto number)</li>
<li>Name (Text)</li>
<li>Active (yes/no)</li>
</ul>
<p>I created the database table class in C# as below:</p>
<pre><code>[Table (Name = "Products")]
public class Product
{
[Column (IsPrimaryKey = true, Name = "ProductID")]
public int ID;
[Column (Name = "ProductName")]
public string Name;
[Column (Name = "Active")]
public bool Active;
}
</code></pre>
<p>And I am using following code snippet to get the products which are active:</p>
<pre><code>using (var con = new OleDbConnection
(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\LearnLinq.accdb")) {
var db = new DataContext (con);
var productTable = db.GetTable<Product> ();
var allProducts = from p in productTable
where p.Active
select p;
foreach (var p in allProducts) {
AddLine ("ID: " + p.ID.ToString () +
", Name: " + p.Name +
", Active: " + p.Active.ToString ());
}
}
</code></pre>
<p>The problem is that above query results in "NO RECORDS". I tried to analysed the SQL generated and it says something like below:</p>
<pre><code>SELECT [t0].[ProductID] AS [ID], [t0].[ProductName] AS [Name], [t0].[Active]
FROM [Products] AS [t0]
WHERE [t0].[Active] = 1
</code></pre>
<p>Any clues why it should be happening?</p>
| <p>Try just using the OleDbCommand object with the generated SQL and iterating through what is returned using OleDbDataReader.</p>
<p>Then try with this SQL string</p>
<pre><code>SELECT [t0].[ProductID] AS [ID], [t0].[ProductName] AS [Name], [t0].[Active]
FROM
[Products] AS [t0]
WHERE [t0].[Active] = YES
</code></pre>
<p>I believe it may have something to do with the underlying values used for the Yes/No datatype in Jet database.</p>
<blockquote>
<p><strong>Yes/No</strong> </p>
<p>A Logical field can be
displayed as Yes/No, True/False, or
On/Off. In code, use the constants
True and False, equivalent to -1 and 0
respectively.</p>
</blockquote>
<p>Have a look at <a href="http://www.blsys.net/" rel="nofollow">BLS site</a> under Developer Community- There is source code for Linq to Access solution</p>
|
How to Persist the dependencies across postbacks in a Web application using Unity? <p>This link for unity framework on msdn states
<em>"<strong>You want to be able to cache or persist the dependencies across postbacks in a Web application</strong>"</em></p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd203319.aspx#" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd203319.aspx#</a></p>
<p>I am not sure what <em>all</em> the above statement means.
I am looking for an example how we can do this using Unity - not sure how Unity will resolve postbacks. Will it just persist dependency in session and retrieve it back ?</p>
| <p>I have written a short example of using Session and also using Cache. I have created a test class called incrementer which is very similar to if I made the class static or at least the variable. RegisterInstance is for a Singleton Resolve</p>
<pre><code> public class Incrementer
{
private int count;
private object synclock = new object();
public int GetCount()
{
return count;
}
public void Increment()
{
System.Threading.Monitor.Enter(synclock);
count++;
System.Threading.Monitor.Exit(synclock);
}
}
public IUnityContainer SessionUnityContainer
{
get
{
if (Session["SharedIncrementer"] == null)
{
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
Session["SharedIncrementer"] = container;
}
return Session["SharedIncrementer"] as IUnityContainer;
}
}
public IUnityContainer CacheUnityContainer
{
get
{
if (Cache["SharedIncrementer"] == null)
{
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
Cache["SharedIncrementer"] = container;
}
return Cache["SharedIncrementer"] as IUnityContainer;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Incrementer i1 = SessionUnityContainer.Resolve<Incrementer>();
Incrementer i2 = CacheUnityContainer.Resolve<Incrementer>();
for (int i = 0; i < 10; i++)
i1.Increment();
for (int i = 0; i < 5; i++)
i2.Increment();
Response.Write(i1.GetCount().ToString());
Response.Write(i2.GetCount().ToString());
}
</code></pre>
<p>Hope tihs helps:</p>
<p>Andrew</p>
<p><strong>EDIT: The following example cimply uses a singleton instance of the UnityContainer and if you keep refreshing the page will see it persisting the values previous.</strong></p>
<pre><code>public class Incrementer
{
private int count;
private object synclock = new object();
public int GetCount()
{
return count;
}
public void Increment()
{
System.Threading.Monitor.Enter(synclock);
count++;
System.Threading.Monitor.Exit(synclock);
}
}
public static class ExampleSettings
{
private static IUnityContainer container = null;
public static IUnityContainer Container
{
get
{
if (container == null)
{
container = new UnityContainer();
container.RegisterInstance<Incrementer>(new Incrementer());
}
return container;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
Incrementer i1 = ExampleSettings.Container.Resolve<Incrementer>();
for (int i = 0; i < 10; i++)
i1.Increment();
Response.Write(i1.GetCount().ToString());
}
</code></pre>
|
SWF object not playing my XML Playlist <p>I've tried to include <a href="http://www.youtubetune.com/" rel="nofollow">youtubetune</a> player to social network, but for somereason it wont play the xml files it should play.
I got around issue that the tracks dint even appear by uploading the neccessary swf files and swfobject.js file to my server. Now the tracks appears to the player, but the player wont play them.</p>
<p>You can see my player <a href="http://www.munsivu.net/index.php?sivu=profiili&id=1" rel="nofollow">here</a>. Scroll down to the player where is one track "Drowning - Rufio" the swf files are in /embed folder and the playlist.xml file is in /Tiedostot/Noctis-/ folder.</p>
| <p>Ok, solved it.. Seems like i forgot yt.swf file. (I saw that the media player used JW Player)</p>
|
business logic in constructors a good idea? <p>I'm currently rebuilding a specialised ticket system at work (mainly used to support people with faults in remote sensing hardware...). Anyway, I was wondering whether doing lots of workflow type activity in an object's constructor is a good idea.</p>
<p>For example, there is currently this:</p>
<pre><code>$ticket = new SupportTicket(
$customer,
$title,
$start_ticket_now,
$mail_customer
);
</code></pre>
<p>as soon as the object is created, it'll put a row into a database, go and mail the customer a confirmation e-mail, possibly send a text message to the nearest technician etc etc etc.</p>
<p>My question is, should a constructor be firing off all that work, or something more like:</p>
<pre><code>$ticket = new SupportTicket($customer, $title);
$customer->confirmTicketMailed($ticket);
$helpdesk->alertNewTicket($ticket);
</code></pre>
<p>If it helps, the objects are all based on the ActiveRecord style.</p>
<p>I guess it may be a matter of opinion, but what do you think is the best thing to do?</p>
| <p>If the constructor does all that work then the constructor knows about many other domain objects. This creates a dependency problem. Should the <code>ticket</code> really know about the <code>Customer</code> and the <code>HelpDesk</code>? When new features are added, isn't it likely that new domain objects will be added to the workflow, and doesn't that mean that our poor <code>ticket</code> will have to know about an ever increasing population of domain objects?</p>
<p>The problem with spiderwebs of dependency like this is that a source code change to any one of the domain object will have an impact upon our poor <code>ticket</code>. The <code>ticket</code> will have <em>so much</em> knowledge of the system that no matter what happens, the <code>ticket</code> will be involved. You will find nasty <code>if</code> statements gathering inside that constructor, checking the configuration database, and the session state, and so many other things. The <code>ticket</code> will grow to become a god class.</p>
<p>Another reason I dislike constructors that do things is that it makes the objects around them very hard to test. I like to write lots of mock objects. When I write a test against the <code>customer</code> I want to pass it a mocked out <code>ticket</code>. If the constructor of <code>ticket</code> controls the workflow, and the dance between <code>customer</code> and other domain objects, then it is unlikely that I will be able to mock it out to test the <code>customer</code>. </p>
<p>I suggest you read <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">The SOLID Principles</a>, a paper I wrote several years back about managing dependencies in object oriented designs. </p>
|
Simple DataBinding question <p>I can't figure out what is wrong for this simple binding.
when click on first or second radio button, no first or last name display.</p>
<p>1) Xaml</p>
<pre><code><Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<local:Person x:Key="personInfo"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<RadioButton Name="r1" Click="onClick1">1st person</RadioButton>
<RadioButton Name="r2" Click="onClick2">2nd person</RadioButton>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<TextBlock Name="t1">First Name</TextBlock>
<TextBox Name="fn" Text="{Binding Path=FirstName}"/>
<TextBlock Name="t2">Last Name</TextBlock>
<TextBox Name="ln" Text="{Binding Path=LastName}"/>
</StackPanel>
</Grid>
</Window>
</code></pre>
<p>2) Code-behind</p>
<pre><code>public partial class Window1 : Window
{
Person p = new Person();
Person[] list ;
public Window1()
{
InitializeComponent();
list = new Person[2] { new Person { FirstName = "John", LastName = "Smith"},
new Person { FirstName = "Steve", LastName = "King"} };
}
public void onClick1(Object h , RoutedEventArgs arg)
{
p.FirstName = list[0].FirstName;
p.LastName = list[0].LastName;
}
public void onClick2(Object h, RoutedEventArgs arg)
{
p = list[1];
}
}
</code></pre>
<p>3) Person.cs </p>
<pre><code>class Person : INotifyPropertyChanged
{
string firstName;
string lastName;
public string FirstName
{
get { return firstName; }
set { firstName = value;
OnPropertyChanged("FirstName");
}
}
public string LastName
{
get { return lastName; }
set { lastName = value;
OnPropertyChanged("LastName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
</code></pre>
<p>Thanks a lot!</p>
| <p>You need to actually set the binding source in code, to do that you need a name for the StackPanel. You must add the name to the last stack panel. The one in Row 1</p>
<pre><code><StackPanel
...
Name="m_panel" />
</code></pre>
<p>In the event code update the DataContext</p>
<pre><code>public void onClick1(Object h , RoutedEventArgs arg)
{
p.FirstName = list[0].FirstName;
p.LastName = list[0].LastName;
m_panel.DataContext = p;
}
</code></pre>
<p><strong>EDIT</strong> Clarified which StackPanel to name</p>
|
Natural language parsing, practical example <p>I am looking to use a natural language parsing library for a simple chat bot. I can get the Parts of Speech tags, but I always wonder. What do you do with the POS. If I know the parts of the speech, what then?</p>
<p>I guess it would help with the responses. But what data structures and architecture could I use.</p>
| <p>Natural language processing is wide and deep, with roots going back at least to the 60s. You could start reading up on <a href="http://en.wikipedia.org/wiki/Computational%5Flinguistics">computational linguistics</a> in general, <a href="http://en.wikipedia.org/wiki/Natural%5Flanguage%5Fgeneration">natural language generation</a>, <a href="http://en.wikipedia.org/wiki/Generative%5Fgrammar">generative grammars</a>, <a href="http://en.wikipedia.org/wiki/Markov%5Fchains">Markov chains</a>, <a href="http://en.wikipedia.org/wiki/Chatterbot">chatterbots</a> and so forth. </p>
<p>Wikipedia has a <a href="http://en.wikipedia.org/wiki/Natural%5Flanguage%5Fprocessing%5Ftoolkits">short list of libraries</a> which I assume you might have seen. Java doesn't have a long tradition in NLP, though I haven't looked at the Stanford libraries. </p>
<p>I doubt you'll get very impressive results without diving fairly deeply into linguistics and grammar. Not everybody's favourite school subject (or so I've heard reported -- loved'em meself!). </p>
|
Best way to search for a saturation value in a sorted list <p>A question from <a href="http://www.math.toronto.edu/oz/turgor/mathbattle/problems/mathbattleE1.pdf" rel="nofollow">Math Battle</a>.
This particular question was also asked to me in one of my job interviews.</p>
<p>" A monkey has two coconuts. It is fooling around by throwing coconut down from the balconies
of M-storey building. The monkey wants to know the lowest floor when coconut is broken.
What is the minimal number of attempts needed to establish that fact? "</p>
<p>Conditions: if a coconut is broken, you cannot reuse the same. You are left with only with the other coconut </p>
<p>Possible approaches/strategies I can think of are</p>
<ul>
<li>Binary break ups & once you find the floor on which the coconut breaks use upcounting from the last found Binary break up lower index.</li>
<li>Window/Slices of smaller sets of floors & use binary break up within the Window/Slice
(but on the down side this would require a Slicing algorithm of it's own.)</li>
</ul>
<p>Wondering if there are any other way to do this.</p>
| <p>Interview questions like this are designed to see how you think. So I would probably mention a O(N^0.5) solution as above, but also I would give the following discussion...</p>
<p>Since the coconuts may have internal cracking over time, the results may not be so consistent to a O(N^0.5) solution. Although the O(N^0.5) solution is efficient, it is not entirely reliable. </p>
<p>I would recommend a linear O(N) solution with the first coconut, and then verify the result with the second coconut. Where N is the number of floors in the building. So for the first coconut you try the 1st floor, then the 2nd, then the 3rd, ... </p>
<p>Assuming both coconuts are built structurally exactly the same and are dropped on the exact same angle, then you can throw the second coconut directly on the floor that the first one broke. Call this coconut breaking floor B. </p>
<p>For coconut #2, you don't need to test on 1..B-1 because you already know that the first cocounut didn't break on floor B-1, B-2, ... 1. So you only need to try it on B. </p>
<p>If the 2nd coconut breaks on B, then you know that B is the floor in question. If it doesn't break you can deduce that there were internal cracking and degradation of the coconut over time and that the test is flawed to begin with. You need more coconuts. </p>
<p>Given that building sizes are pretty limited, the extra confidence in your solution is worth the O(N) solution.</p>
<p>As @RafaÅ Dowgird mentioned, the solution also depends on whether the monkey in question is an African monkey or a European monkey. It is common knowledge that African monkeys throw with a much greater force. Hence making the breaking floor B only accurate with a variance of +/- 2 floors. </p>
<p>To guarantee that the monkey doesn't get tired from all those stairs, it would also be advisable to attach a string to the first coconut. That way you don't need to do 1+2+..+B = B*(B+1)/2 flights of stairs for the first coconut. You would only need to do exactly B flights of stairs. </p>
<p>It may seem that the number of flights of stairs is not relevant to this problem, but if the monkey gets tired out in the first place, we may never come to a solution. This gives new considerations for the <a href="http://en.wikipedia.org/wiki/Halting%5Fproblem" rel="nofollow">halting problem</a>.</p>
<p>We are also making the assumption that the building resides on earth and the gravity is set at 9.8m/s^2. We'll also assume that no gravitation waves exist. </p>
|
Free JPEG2000 Library or SDK for de-compression <p>I have written code to compress and decompress image files using a proprietary SDK for transmission from an aircraft via satellite. Unfortunately a license must be purchased for decompression as well as compression. Until now my applications have been mostly used in-house so I can keep track of the licenses and distribution. Now I need to provide the applications for outsiders and I can neither control distribution nor want to pay for the licenses.</p>
<p>Does anyone know of free de-compression programs, SDKs, or libraries? I program in C++ for Windows NT, 2000, XP. </p>
<p>My image files are raw data, monochrome, with 16bit unsigned pixels and the compression that is used is lossless or very mildly lossy.</p>
| <p>It's just a thought, but the de facto standard for JPEG2000 is <a href="http://www.kakadusoftware.com/">Kakadu</a> because Dr. Taubman pretty much wrote the JPEG2000 standard. Although it costs some money, it is the best library that I know of.</p>
|
Encode/Decode xxxclass to byte[] than send it to Remote PC with C# <p>Hi i have got a TCP/IP Socket project.</p>
<p>i can send string messages to Server with Client side and i can get responses from server.
But getting one string message and sending only one string (or any other object).I wanna Encode Personel class to Byte array after send to Clients from server side.And Decode it. than get values from my class. </p>
<p>//SERVER SIDE CODE Connect() starts at on form load</p>
<pre><code> private void Connect()
{
// start listen socket
dinleyiciSoket = new TcpListener(System.Net.IPAddress.Any, 10048);
dinleyiciSoket.Start();
Socket istemciSoketi = dinleyiciSoket.AcceptSocket();
NetworkStream agAkisi = new NetworkStream(istemciSoketi);
BinaryReader binaryOkuyucu = new BinaryReader(agAkisi);
BinaryWriter binaryYazici = new BinaryWriter(agAkisi);
string alinanMetin = binaryOkuyucu.ReadString();
MessageBox.Show(alinanMetin, "Yeni Genelge", MessageBoxButtons.OK);
binaryYazici.Write(true);
dinleyiciSoket.Stop();
Connect();
}
</code></pre>
<p>////////// CLIENT SIDE //////////////</p>
<pre><code> private string IpAdresi(string host)
{
string address = "";
IPAddress[] addresslist = Dns.GetHostAddresses(host);
foreach (IPAddress theaddress in addresslist)
{
if (theaddress.AddressFamily == AddressFamily.InterNetwork)
{
address = theaddress.ToString();
}
}
return address;
}
bool onay;
private void button1_Click(object sender, EventArgs e)
{
//create socket connection
Socket istemciBaglantisi = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//BaÄlantıyı gerçekleÅtir
if (istemciBaglantisi.Connected != true)
{
istemciBaglantisi.Connect(IPAddress.Parse(IpAdresi(txtHost.Text)), 10048);
}
agAkisi = new NetworkStream(istemciBaglantisi);
binaryYazici = new BinaryWriter(agAkisi);
binaryOkuyucu = new BinaryReader(agAkisi);
binaryYazici.Write(txtMesaj.Text);
onay = binaryOkuyucu.ReadBoolean();
MessageBox.Show(onay.ToString());
istemciBaglantisi.Close();
}
</code></pre>
| <p>Take a look at object serialization. <a href="http://www.codeproject.com/KB/cs/objserial.aspx" rel="nofollow">See here</a> for examples. That should get you going in the right direction.</p>
|
Calculate Bounding box coordinates from a rotated rectangle, Picture inside <p><img src="http://img7.imageshack.us/img7/2464/boundedbox.png" alt="Schema"></p>
<p>I have the coordinates of the top left Point of a rectangle as well as its width, height and rotation from 0 to 180 and -0 to -180.</p>
<p>I am trying to get the bounding coordinates of the actual box around the rectangle.
What is a simple way of calculating the coordinates of the bounding box
- min y, max y, min x, max x ?</p>
<p>The A point is not always on the min y bound, it can be anywhere.
I can use matrix the transform toolkit in as3 if needed.</p>
| <ul>
<li>Transform the coordinates of all four corners</li>
<li>Find the smallest of all four x's as <code>min_x</code> </li>
<li>Find the largest of all four x's and call it <code>max_x</code></li>
<li>Ditto with the y's</li>
<li>Your bounding box is <code>(min_x,min_y), (min_x,max_y), (max_x,max_y), (max_x,min_y)</code></li>
</ul>
<p>AFAIK, there isn't any royal road that will get you there much faster.</p>
<p>If you are wondering how to transform the coordinates, try:</p>
<pre><code>x2 = x0+(x-x0)*cos(theta)+(y-y0)*sin(theta)
y2 = y0-(x-x0)*sin(theta)+(y-y0)*cos(theta)
</code></pre>
<p>where (x0,y0) is the center around which you are rotating. You may need to tinker with this depending on your trig functions (do they expect degrees or radians) the sense / sign of your coordinate system vs. how you are specifying angles, etc.</p>
|
.Net Remoting vs. WCF <p>I am working on a .Net website which is going to have 1000s of concurrent users.</p>
<p>I am thinking of keeping the business components on the app server and UI components on the web server. Database (MS SQL Server 2005) will be hosted on another server. I am planning to use the load balancing as well.</p>
<p>Given this, what's the best way of communication from web server to app server if I want to have the optimum application performance and scalability?</p>
| <p>You can check <a href="http://msdn.microsoft.com/en-us/library/bb310550.aspx">here</a> a performance comparison between WCF and other communication technologies (including .Net remoting). The conclusion is : WCF is faster.</p>
|
Problem calling a function when it is in a .lib <p>I have a class with a static method that looks roughly like:</p>
<pre><code>class X {
static float getFloat(MyBase& obj) {
return obj.value(); // MyBase::value() is virtual
}
};
</code></pre>
<p>I'm calling it with an instance of MyDerived which subclasses MyBase:</p>
<pre><code>MyDerived d;
float f = X::getFloat(d);
</code></pre>
<p>If I link the obj file containing X into my executable, everything works as expected. If I'm expecting to get 3.14, I get it.</p>
<p>If I create a .lib that contains the X.obj file and link in the .lib, it breaks. When I call getFloat(), it's returning <b>-1.#IND00</b>. Is this some type of sentinel value that should tell me what's wrong here?</p>
<p>Is anything different when you link in a lib rather than an obj directly? </p>
<p>I don't get any compiler warnings or errors.</p>
<p><b>Edit:</b><br>
I'm using Visual Studio 2005 on Windows XP Pro SP3. To make sure I wasn't linking old files, I cloned the value() method into a new value2() method and called that instead. The behavior was the same.</p>
<p><b>Edit #2:</b><br>
So, if I trace into the call with my debugger, I'm finding that it isn't going into my value() method at all. Instead it's going into a different (unrelated) method. This makes me think my vtable is corrupted. I think the behavior I'm seeing must be a side effect of some other problem. </p>
<p><hr></p>
<p><b>Solved!</b> (thanks to Vlad)<br>
It turns out I was violating the one definition rule (ODR) although it wasn't evident from the code I posted. <a href="http://blogs.msdn.com/vcblog/archive/2007/05/17/diagnosing-hidden-odr-violations-in-visual-c-and-fixing-lnk2022.aspx" rel="nofollow">This</a> is a great article from the Visual C++ guys that explains the problem and one way to track it down. The <i>/d1reportSingleClassLayout</i> compiler flag is a fantastic learning tool.</p>
<p>When I dumped out the my class layout for MyBase and MyDerived in the two different projects, I found differences between the calling code and the library code. It turns out I had some <i>#ifdef</i> blocks in my header files and the corresponding <i>#define</i> statement was in the precompiled header for the main project but not in the subproject (the library). Have I mentioned how evil I think preprocessor macros are?</p>
<p>Anyway, I'm only posting this stuff because it might be helpful to somebody else. <a href="http://stackoverflow.com/questions/302446/how-can-one-inspect-a-vtable-in-visual-c">This question</a> was also very helpful to me.</p>
| <p>Since a lib is just a container, if you are linking the same .obj file in both cases then as Brian says they shouldn't (can't?) be a difference.</p>
<p>One thing to watch is if you changed the definition of MyBase you obviously need to recompile both the library and the code using it. For example, if you added a new virtual method to MyBase before the value method, then that would mess up the library since the v-table offset of value would be different.</p>
|
PHP: return life of current session <p>I am looking for a way to check on the life of a php session, and return the number of seconds a session has been "alive". </p>
<p>Is there a php function that I am missing out on?</p>
| <p>You could store the time when the session has been initialized and return that value:</p>
<pre><code>session_start();
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
}
</code></pre>
<p>And for retrieving that information from an arbitrary session:</p>
<pre><code>function getSessionLifetime($sid)
{
$oldSid = session_id();
if ($oldSid) {
session_write_close();
}
session_id($sid);
session_start();
if (!isset($_SESSION['CREATED'])) {
return false;
}
$created = $_SESSION['CREATED'];
session_write_close();
if ($oldSid) {
session_id($oldSid);
session_start();
}
return time() - $created;
}
</code></pre>
|
How to localize a Rails plugin? <p>I'd like to translate the OpenIdAuthentication plugin into another language but I'd like not to change the plugin directly.</p>
<p>Here's the basic structure of the messages I want to translate:</p>
<pre>module OpenIdAuthentication
class Result
ERROR_MESSAGES = {
:missing => "Sorry, the OpenID server couldn't be found",
:invalid => "Sorry, but this does not appear to be a valid OpenID",
:canceled => "OpenID verification was canceled",
:failed => "OpenID verification failed",
:setup_needed => "OpenID verification needs setup"
}
end
end</pre>
<p>It is something possible to translate them without changing the plugin directly?</p>
<p>Thanks!</p>
| <p>You can simply overwrite <code>OpenIdAuthentication::Result::ERROR_MESSAGES</code> by redefining it at any time after the plugin loads.</p>
<p>You may do so through a different plugin (that loads after <code>OpenIdAuthentication</code>), or from a file required after the plugin loads (e.g. <code>require lib/open_id_authentication_suppl.rb</code> in <code>environment.rb</code>):</p>
<p>The code will essentially be a copy-paste job, as follows:</p>
<pre><code>module OpenIdAuthentication
class Result
ERROR_MESSAGES = {
:missing => "<message in foreign language>",
:invalid => "<message in foreign language>",
:canceled => "<message in foreign language>",
:failed => "<message in foreign language>",
:setup_needed => "<message in foreign language>"
}
end
</code></pre>
<p>To integrate this with <a href="http://rails-i18n.org/wiki/pages/i18n-rails-guide" rel="nofollow">I18N-rails</a> (built into Rails 2.2.2, available as a gem/plugin in previous versions), do:</p>
<pre><code> class I18NResultMessages
def [](key)
I18n.t(key, :scope => 'openidauthentication.errors.messages')
end
end
class Result
ERROR_MESSAGES = I18NResultMessages.new
end
</code></pre>
<p>Then define and load your I18n yml file for <code>openidauthentication.errors.messages</code>'s various locales on Rails startup, and don't forget to set your <code>I18n.locale</code> every time you start processing a controller action based on the logged-in user's locale.</p>
|
Expose memory as read-only <p>In C can a function expose memory that it "manageds" at a lower level as readonly to those calling that function (exposing its address). <code>return * const</code> is not effective but I wondered if I was overlooking a programming tick?</p>
<p>Thanks.</p>
<pre><code>const uint8_t * get_value(int index)
{
static uint8_t data[2] = {0, 0};
return (const uint8_t *)&data[index];
}
int main(void)
{
uint8_t * value;
value = get_value(1);
*value += 1;
return 0;
}
</code></pre>
<blockquote>
<p><strong>@j_random_hacker</strong> Suggested a good compromise to my question that gives that extra barrier I'm looking for to prevent casual mis-use of that data.</p>
</blockquote>
<pre><code>typedef struct
{
const uint8_t * value;
const uint8_t size;
} readonly_t;
readonly_t get_value(int index, int size)
{
static uint8_t data[2] = {0, 0};
uint8_t rsize;
/* ... validate index, size params */
readonly_t r = { &data[index], rsize };
return r;
}
</code></pre>
| <p>It's C! You can't :) There is always a way to circumvent it. Just make it <code>const</code> and hope somebody will not change it.</p>
<p>If you are hosting an add-in or something, you should run it in a separate process to limit its access to memory.</p>
|
Emacs command to insert and indent line above cursor <p>I frequently find myself typing on a line, when I realize I need(ed) a variable definition (or something similar) on the line above. What I would like is to </p>
<ol>
<li>press C-return from anywhere on a line and have the cursor move to a newly inserted blank line above, with correct indentation (or at least the same as the original line).</li>
<li>be able to yank any text...</li>
<li>and C-u C-space to get back to the original position</li>
</ol>
<p>I've managed to do #1, but my emacs-fu isn't strong enough to do the rest.</p>
| <p>Here's my humble solution:</p>
<p><code><pre>
(defun insert-before-line ()
(interactive)
(let ((pos (point))
(cur-max (point-max)))
(beginning-of-line)
; I've changed the order of (yank) and (indent-according-to-mode)
; in order to handle the case when yanked line comes with its own indent
(yank)(indent-according-to-mode)
; could be as well changed to simple (newline) it's metter of taste
; and of usage
(newline-and-indent)
(goto-char (+ pos (- (point-max) cur-max)))))
</pre></code></p>
<p>Hope it helps.</p>
|
Thread does not receive messages <p>There is a thread in my Delphi application that has a message-waiting loop. Every time it receives a message, it starts doing some work. Here is the execute procedure of that thread:</p>
<pre><code>procedure TMyThread.Execute;
begin
while GetMessage(Msg, 0, 0, 0) and not Terminated do
begin
{thread message}
if Msg.hwnd = 0 then
begin
...
end
else
DispatchMessage(Msg);
end;
end;
</code></pre>
<p>Doing some tests using my application I discovered that the GetMessage function is main thread dependent. By this I mean that while the main thread is doing some work, the GetMessage function in my thread does not return even though a message is waiting to be received by it (the message is sent by yet another thread using the PostThreadMessage funciton: PostMessage(MyThreadId, WM_MyMessage, 0, 0)). </p>
<p>Only when the main thread finishes its work or the Application.ProcessMessages method is called, does GetMessage return and my thread starts doing its work. Implementing this kind of inter-thread communication I was sure that my threads would work independently and I would never expect that the reception of messages sent directly to a thread would be dependent on the main thread. </p>
<p>Doing the tests I used the WaitForSingleObject function in the main thread, waiting for an event for a few seconds. This is when I noticed that my thread was not doing any work even though messages were sent to it by another thread. When the WaitForSingleObject function finally finished waiting and the main thread became idle, the GetMessage function in my thread returned.</p>
<p>Could somebody explain me why it works this way? Is there a workaround to that? I would like to make my thread receive messages independently. All my threads are created by the main thread. May this be the reason?</p>
<p>Thanks for your help in advance.</p>
<p>Mariusz.</p>
<p><hr /></p>
<p>Mghie, you were absolutely right again (you have helped me with the messaging stuff lately, you might remember). As you suggested, GetMessage returns immediately, but the thread hangs, in fact, on a call to a main window method:</p>
<pre><code>procedure TMyThread.Execute;
begin
while GetMessage(Msg, 0, 0, 0) and not Terminated do
begin
{thread message}
if Msg.hwnd = 0 then
begin
...
if Assigned(FOnCommEventMethod) then
FOnCommEventMethod(FCommEventsQueueItem);
...
end
else
DispatchMessage(Msg);
end;
end;
</code></pre>
<p>FOnCommEventMethod is a method of object, declared as 'procedure (EventMask: Cardinal) of object;' (this thread handles serial port events). In this case the FOnCommEventMethod was assigned a procedure belonging to the main form class. When the method is called by my thread, the thread hangs waiting for the main thread to finish its work. </p>
<p>How come? As you can see, I don't use the Synchronize() method to call this procedure. Therefore I would not expect my thread to be synchronizing with the main thread. Does it happen implicitly? BTW, I understand that any GUI components should not be accessed by any other threads but the main one, so the Synchronize method should be used, but I am only doing some quick tests now.</p>
<p>Comming back to the WaitForSingleObject subject, I know I should not use it, but it was only a test thanks to which (coincidentally) I noticed the problem.</p>
<p>Thanks for your help. If you did not help me, I would probably get rid of messaging and use events instead, and finally I would notice that it was not the reason :-).</p>
| <blockquote>
<p>Only when the main thread finishes its work or the Application.ProcessMessages method is called, does GetMessage return and my thread starts doing its work.</p>
</blockquote>
<p>I doubt that this is really what's happening. AFAIK the two message loops should be independent of each other, as long as you don't use other means of synchronizing the threads, like <em>SendMessage()</em>. Are you sure that the thread does indeed block inside of <em>GetMessage()</em> and not inside of <em>Synchronize()</em> (which is using <em>SendMessage()</em> internally)?</p>
<blockquote>
<p>Doing the tests I used the WaitForSingleObject function in the main thread, waiting for an event for a few seconds.</p>
</blockquote>
<p>You should never use <em>WaitForSingleObject()</em> in the main thread with a timeout longer than say 100 milliseconds, as this will make your GUI appear sluggish. In fact I would advise you to not use it at all in the main thread, because this is simply polling. Post a message from your worker thread instead.</p>
|
BI with Django? <p>Is there a way to develop Bi (Business Intelligence) solutions with Django? Therefore it should be possible to define models with more than one Datasource.
Is anybody out there who has experienced BI with Django?
How could it work ?</p>
| <p>I'm not sure what your definition of BI is or why you assume that a BI solution requires more than one data source. </p>
<p>In my experience, BI means statistical analysis of data. A reporting schema, using dimensional techniques, can be the basis for it. The data is usually ETL'd from various transactional sources into the single, dimensional schema, which then becomes the source for all analysis.</p>
<p>If what I'm saying is correct, then you don't need multiple data sources.</p>
<p>Maybe another way to think about the question is: Do the ORM techniques built into Django lend themselves to modeling a dimensional star schema using objects?</p>
|
Android: Is there a PC port? <p>Is it possible to have Android running on <code>x86</code> computers?</p>
| <p>Looks like someone is working on it... <a href="http://www.androidx86.org/" rel="nofollow">http://www.androidx86.org/</a></p>
|
Named/Optional parameters in C# 3.0? <p>Is there a way to add optional parameters to C# 3.0 like there will be in C# 4.0? I gotta have this feature, I just can't wait!</p>
<p><b>Edit:</b></p>
<p>If you know a work-around/hack to accomplish this, post it also. Thanks!</p>
| <p>You can use an anonymous type and reflection as a workaround to named parameters:</p>
<pre><code>public void Foo<T>(T parameters)
{
var dict = typeof(T).GetProperties()
.ToDictionary(p => p.Name,
p => p.GetValue(parameters, null));
if (dict.ContainsKey("Message"))
{
Console.WriteLine(dict["Message"]);
}
}
</code></pre>
<p>So now I can call Foo like this:</p>
<pre><code>Foo(new { Message = "Hello World" });
</code></pre>
<p>... and it will write my message.</p>
<p>Basically I'm extracting all the properties from the anonymous type that was passed, and converting them into a dictionary of string and object (the name of the property and its value).</p>
|
Why would pthread_create() fail with only 2 threads active? <p>I'm having some trouble in my first foray into threads in C. I'm trying (for now) to write a very simple server program that accepts a socket connection and starts a new thread to process it. It seems to work fine except that it will only create about 300 threads (303, sometimes 304) before pthread_create() fails with the EAGAIN code, which means:</p>
<p>"The system lacked the necessary resources to create another thread, or the system-imposed limit on the total number of threads in a process {PTHREAD_THREADS_MAX} would be exceeded."</p>
<p>This is <em>not</em> 303 threads at the same time - each thread exits which is confirmed by gdb. Each time the process request function is called there are two threads running.</p>
<p>So it means "the system lacked the necessary resources". My question is (and it may be a bit stupid) - what are these resources? Presumably it's a memory leak in my program (certainly possible, likely even), but I'd have thought that even so it could manage more than 300 considering the rest of the program does very little.</p>
<p>How can I find out how much memory my program has available to confirm that it's running out of it? There's plenty of memory and swap free so presumably there's an artificial limit imposed by the OS (Linux).</p>
<p>Thanks</p>
| <p>If you are not creating the thread with the attribute <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread%5Fattr%5Fsetdetachstate.html" rel="nofollow"><code>PTHREAD_CREATE_DETACHED</code></a> (or detaching them with <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread%5Fdetach.html" rel="nofollow"><code>pthread_detach()</code></a>, you may need to call <a href="http://www.opengroup.org/onlinepubs/000095399/functions/pthread%5Fjoin.html" rel="nofollow"><code>pthread_join()</code></a> on each created thread after it exits to free up the resources associated with it.</p>
|
C# hashes <p>I'm new to C#</p>
<blockquote>
<ol>
<li>How do i hash files with C#</li>
<li>What is available ? (md5, crc, sha1, etc)</li>
<li>Is there an interface i should inherit?</li>
</ol>
</blockquote>
<p>Basically i want to checksum multiple files and store it in a db along with using two of my own checksums/hashes.</p>
| <blockquote>
<p>1.) How do i hash files with C#?</p>
</blockquote>
<p>You can utilize .NET classes under <em><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx">System.Security.Cryptography</a></em></p>
<blockquote>
<p>2.) What is available?</p>
</blockquote>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.keyedhashalgorithm.aspx">KeyedHashAlgorithm</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5.aspx">MD5</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.ripemd160.aspx">RIPEMD160</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha1.aspx">SHA1</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha256.aspx">SHA256</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha384.aspx">SHA384</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx">SHA512</a></li>
</ul>
<blockquote>
<p>3.) Is there an interface i should inherit?</p>
</blockquote>
<p>No you don't have to.
Take a look at <a href="http://msdn.microsoft.com/en-us/library/wet69s13.aspx">HashAlgorithm.Create(...)</a></p>
|
Purposely create two files to have the same hash? <p>If someone is purposely trying to modify two files to have the same hash, what are ways to stop them? Can md5 and sha1 prevent the majority case?</p>
<p>I was thinking of writing my own and I figure even if I don't do a good job if the user doesn't know my hash he may not be able to fool mine.</p>
<p>What's the best way to prevent this?</p>
| <p>MD5 is generally considered insecure if hash collisions are a major concern. SHA1 is likewise no longer considered acceptable by the US government. There <s>is</s> was a <a href="http://en.wikipedia.org/wiki/SHA-3">competition</a> under way to find a replacement hash algorithm, but the recommendation at the moment is to use the SHA2 family - SHA-256, SHA-384 or SHA-512. [<em>Update: 2012-10-02 <a href="http://www.nist.gov/itl/csd/sha-100212.cfm">NIST</a> has chosen <a href="http://en.wikipedia.org/wiki/Keccak">SHA-3</a> to be the algorithm <a href="http://keccak.noekeon.org/">Keccak</a>.</em>]</p>
<p>You can try to create your own hash â it would probably not be as good as MD5, and 'security through obscurity' is likewise not advisable.</p>
<p>If you want security, hash with multiple hash algorithms. Being able to simultaneously create files that have hash collisions using a number of algorithms is excessively improbable. [And, in the light of comments, let me make it clear: I mean publish both the SHA-256 and the Whirlpool values for the file â not combining hash algorithms to create a single value, but using separate algorithms to create separate values. Generally, a corrupted file will fail to match any of the algorithms; if, perchance, someone has managed to create a collision value using one algorithm, the chance of also producing a second collision in one of the other algorithms is negligible.]</p>
<p>The <a href="http://publictimestamp.org/">Public TimeStamp</a> uses an array of algorithms. See, for example, <a href="http://www.publictimestamp.org/index.pl?pass=search&pass2=ptiddetails&pt=search_ptid&ptid=877143">sqlcmd-86.00.tgz</a> for an illustration.</p>
|
How can I open 2+ instances of VLC and control them programmatically? <p>I was thinking about writing an app (in either C++ or C#) to help me sort videos faster and I was wondering: How can I open more then 2 (maybe more) instance of VLC and control them though my EXE? What are my options? I know I can <code>SendMessage</code> to the EXE directly. Could I do something like simulate user keys?</p>
<p>How do I open the VLC exes in my EXE? its been a while. Lately I have only done command line apps.</p>
| <p>Ryan is on the right path. You need to use the Process class to open a vlc.exe process, but then you need to append a command-line statement to that. VLC has a rich command-line argument syntax that will let you do a lot of things to a video file or capture device. </p>
<p>I recently wrote an application that allows users to customize multicast broadcasts from multiple satellite dishes, dvd devices and digital tv converter boxes via VLC. So it can be done, and fairly easily. </p>
|
C++ development on linux - where do I start? <p>I decided to leave my windows install behind and am now running Debian as my default OS. I have always coded in Windows and specifically with Visual Studio. I am currently trying to get used to compiling my code under linux.</p>
<p>Although I still have a lot of documentation to read, and don't expect you guys to make it too easy for me, it'd still be nice to get some pointers on where to start. I have some specific questions, but feel free to suggest/recommend anything else regarding the subject.</p>
<ul>
<li>What are recommended guides on creating a make file, how do I compile from this makefile (do I call g++ myself, do I use 'make'?)</li>
<li>Looking at other linux software, they almost always seem to have a 'configure' file. What exactly does it do? Does it only check if the required libraries are installed or does it more than just checking requirements?</li>
<li>How do I link libraries, and how does this relate to my makefile or g++ parameters? In windows I would compile the library, include some header files, tell my linker what additional lib file to link, and copy a dll file. How exactly does this process work in linux?</li>
<li>Recommendations for code editors? I am currently using nano and I've heard of vim and emacs, but don't know what the benefits of them are over eachother. Are there any others, and why would I consider them over any of the previous three? Note: I am not looking for an IDE.</li>
</ul>
<p>Any help, links to guides & documentation (preferably those that are aimed at beginners) are very much appreciated!</p>
| <blockquote>
<p>What are recommended guides on creating a make file, how do I compile from this makefile (do I call g++ myself, do I use 'make'?)</p>
</blockquote>
<p>You build from the makefile by invoking "make". And inside your makefile, you compile and link using g++ and ld.</p>
<blockquote>
<p>Looking at other linux software, they almost always seem to have a 'configure' file. What exactly does it do? Does it only check if the required libraries are installed or does it more than just checking requirements?</p>
</blockquote>
<p>It's a script usually used to set up various things based on the environment being used for building. Sometimes it's just a basic shell script, other times it invokes tools like Autoconf to discover what is available when building. The "configure" script is usually also a place for the user to specify various optional things to be built or excluded, like support for experimental features.</p>
<blockquote>
<p>How do I link libraries, and how does this relate to my makefile or g++ parameters? In windows I would compile the library, include some header files, tell my linker what additional lib file to link, and copy a dll file. How exactly does this process work in linux?</p>
</blockquote>
<p>ld is the GNU linker. You can invoke it separately (which is what most makefiles will end up doing), or you can have g++ delegate to it. The options you pass to g++ and ld determine where to look for included headers, libraries to link, and how to output the result.</p>
<blockquote>
<p>Recommendations for code editors? I am currently using nano and I've heard of vim and emacs, but don't know what the benefits of them are over eachother. Are there any others, and why would I consider them over any of the previous three? Note: I am not looking for an IDE.</p>
</blockquote>
<p>Vim and Emacs are very flexible editors that support a whole bunch of different usages. Use whatever feels best to you, though I'd suggest you might want a few minimal things like syntax highlighting.</p>
|
Is the Repository Pattern the same as the Asp.net Provider Model? <p>Since Asp.net 2.0, there is the Provider Model. On the implementation detail, a provider is class derived from ProviderBase which is an abstract class rather than an interface, but anyway the Provider Model is there so that we can have different implementation to swap in the out by just editing the web.config. For example if you create a blog app, you may have a BlogProvider : ProviderBase, then you can have implementations of BlogProvider like: SqlBlogProvider, OracleBlogProvider and even MockBlogProvider for testing.</p>
<p>Now, Repository Pattern is getting popular, and I feel it is to satisfy the same need, though in the implementation detail, you normally use interfaces, so IBlogProvider, and you'd inject different implementations through constructors rather than properties, but essentially I don't see the difference in what these 2 patterns gave us.</p>
<p>Personally, I feel Provider Model is more natural for me in the implementation. So, is there a difference between them or they are just the same thing with different names given by different communities?</p>
<p>I'd appreciate any comments on this,
Thanks,
Ray.</p>
| <p>The Repository and Provider patterns overlap, but they don't formally describe the same thing. I would almost say the Repository is a subset of Provider. In practice, I think the Repository pattern was <em>borne out of</em> a specific need - abstracting repositories - and evolved in the community into a more generic abstraction pattern. In that respect, they have come to be different terms that describe the same concept. However, from the original definitions, they are different in scope:</p>
<ul>
<li><p>The purpose of the Repository pattern is to abstract the specifics of a <em>repository</em> of data away from the application.</p></li>
<li><p>The purpose of the Provider model is to abstract the specifics of <em>anything</em> away from the application. This may be a data repository, but it is just as often some kind of logic. </p></li>
</ul>
<p>For example, in our application we have a ContextFactoryProvider, which contains different kinds of logic for determining which ContextFactory to use. There is no repository of data in this case; it's purely application logic that needs to change arbitrarily; the Provider model allows us to use the <a href="http://en.wikipedia.org/wiki/Single%5Fresponsibility%5Fprinciple">Single Responsibility Principle</a> to isolate each kind of logic into its own class and swap out that logic easily.</p>
|
Git and Trac (or similar) <p>In the past I have really enjoyed using <a href="http://trac.edgewall.org/">Trac</a> with subversion repositories hosted on some of my own servers. The integrated ticketing and online code browsing is very convenient.</p>
<p>I have used <a href="http://github.com">github</a> for some of my public projects but I don't have the money to shell out for an extra service, espcially when I am already paying for remote VPS hosting.</p>
<p>Does anyone know of or have any experience setting up something like Trac with git version control? Specifically, I can already push to a remote server but I would like some web interface that allows me (and people working with me) to see that commits and current state of the codebase online without making the project public. I am aware of <a href="http://trac-hacks.org/wiki/GitPlugin">GitPlugin</a> but have not been able to get it up and running successfully. Any other suggestions?</p>
<p>Integrated ticketing (and wiki) is desired but not an absolute necessity.</p>
<p><strong>Edit:</strong></p>
<p>After playing around with GitPlugin and Trac a bit more I have been able to get it up and running. The main problem was that I needed to explicitly enable the plugin for the trac environment by doing something like this in trac.ini:</p>
<pre><code>[components]
# for version 0.10
gitplugin.* = enabled
# for version 0.11
tracext.git.* = enabled
</code></pre>
<p>I may also try out <a href="http://www.redmine.org/">Redmine</a> and <a href="http://hjemli.net/git/cgit/">CGit</a> as this seem like other pieces of software that do what I am looking for. Any other suggestions are welcome.</p>
| <p>You should take a look at Redmine (<a href="http://www.redmine.org/">http://www.redmine.org/</a>). It has all of the features you mention and more. You can host it on your own vps (I do).</p>
|
How to convert *.txt file into Unicode <p>I have a requirement where a client will supply a file in encoding ANSI, but my system can only successfully read a file in UNICODE. So how do I tackle this issue? I know when I "save as" the file into as UNICODE encoded the file gets picked up. It's difficult to make the client comply with our request. So can I have any batch program for this folder to convert this file into UNICODE and then pick up? </p>
| <p><a href="http://en.wikipedia.org/wiki/Iconv"><code>iconv</code></a> can do that:</p>
<pre><code>Usage: iconv [OPTION...] [FILE...]
Convert encoding of given files from one encoding to another.
Input/Output format specification:
-f, --from-code=NAME encoding of original text
-t, --to-code=NAME encoding for output
Information:
-l, --list list all known coded character sets
Output control:
-c omit invalid characters from output
-o, --output=FILE output file
-s, --silent suppress warnings
--verbose print progress information
-?, --help Give this help list
--usage Give a short usage message
-V, --version Print program version
Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.
For bug reporting instructions, please see:
<http://www.gnu.org/software/libc/bugs.html>.
</code></pre>
|
How to add Application Settings from a custom component (WinForms) <p>I have a WinForms user control that, when added to a form, should automatically add some elements to application settings. (Of course, the user should be able to customize/disable this behavior.)</p>
<p>is that advisable? What is the "good" way to do this?</p>
<p><strong>[edit]</strong><br />
The control provides a default implementation for the file menu, the consumer only needs to wire up the menu/toolbar items in the designer, and implement some basic events. Part of this is a recent file list, which by default should be remembered.</p>
<p>I agree that the consumer needs full control whether or not he wants these settings added automatically. </p>
<p>So far, I expose the file list as a public string property, and the consumer can add the code to init and store this from/in the application config. If possible, I'd like to simplify this further so the consumer just provides the settings variable where he wants the setting to be stored (if he wants that at all).</p>
| <p>I don't think your control should be adding anything to the config file, unless it's been asked to do so.</p>
<p>Still, if the user "opts in" to this, then I think you're going to have to add some designer support to your control. Either through the ToolBoxItem, or through the designer being notified on a new control being added, the designer will then have to create and/or update the configuration information it needs.</p>
<p><hr /></p>
<p>Thanks for the clarification. You may want to look at <a href="http://msdn.microsoft.com/en-us/library/system.configuration.ipersistcomponentsettings.aspx" rel="nofollow">IPersistControlSettings interface</a>, especially what it has to say on the subject of ApplicationSettingsBase. That page should lead you to information on strongly-typed Settings in .NET 2.0. It allows default settings to be baked into a control or other library code, in such a way that if the settings change, the changes persist to the application's config file, either per-user or application-wide.</p>
|
Why can't I directly add attributes to any python object? <p>I have this code:</p>
<pre><code>>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
</code></pre>
<p>And this code:</p>
<pre><code>>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
</code></pre>
<p>From my Python knowledge, I would say that <code>datetime</code> overrides <code>setattr</code>/<code>getattr</code>, but I am not sure. Could you shed some light here?</p>
<p>EDIT: I'm not specifically interested in <code>datetime</code>. I was wondering about objects in general.</p>
| <p>My guess, is that the implementation of datetime uses <a href="http://docs.python.org/reference/datamodel.html#id3">__slots__</a> for better performance.</p>
<p>When using <code>__slots__</code>, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.</p>
<p>Read more here: <a href="http://docs.python.org/reference/datamodel.html">http://docs.python.org/reference/datamodel.html</a></p>
|
Changing Visual Studio 2008 New Tab Position <p>One of my pet peeves ever since Visual Studio 2005 (behavior is unchanged in VS 2008) came out was the placement of the new tabs when opened. These opened on the left of current tabs which was the opposite of where new tabs opened in Visual Studio 2003 and beyond.</p>
<p>In my opinion opening new tabs to the left of current tabs is counter-intuitive... Most tabbed applications including Firefox and IE7 open new tabs to the right. My question is, is there a configuration setting or hack to make tab opening behave like it did in Visual Studio 2003?</p>
| <p>** Not actually for VS 2008 - Only adding this here because it's the top hit on goog **</p>
<p>To set up tabs on the right for VS 2010 </p>
<p><a href="http://blogs.msdn.com/b/zainnab/archive/2010/04/16/the-best-of-visual-studio-2010-insert-documents-to-the-right-of-existing-tabs.aspx" rel="nofollow">Tools -> Options -> Environment -> Documents and select the "Insert documents to the right of existing tabs" option.</a></p>
|
A good uncertainty (interval) arithmetic library? <p><em>edited</em> </p>
<p>Given that the words "uncertain" and "uncertainty" are fairly ubiquitous, it's hard to Google "uncertainty arithmetic" and get anything immediately helpful. Thus, can anyone suggest a good library of routines, in almost any programming/scripting language, that implements handling of uncertain values, as per this description:</p>
<blockquote>
<p>Use uncertainty arithmetic to record values that are approximations, for which there is a measured tolerance. This is when we are unsure about a value, but know the upper and lower bounds it can have, expressed as a ±value. </p>
</blockquote>
| <p>I believe "<a href="http://en.wikipedia.org/wiki/Interval%5Farithmetic">Interval Arithmetic</a>" is the more common name for what you're looking for.
<a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/numeric/interval/doc/interval.htm">boost::interval</a> would be my first choice for a supporting library.</p>
|
Detecting Overridden Methods in Perl <p>Last week I was bitten <em>twice</em> by accidentally overriding methods in a subclass. While I am not a fan of inheritance, we (ab)use this in our application at work. What I would like to do is provide some declarative syntax for stating that a method is overriding a parent method. Something like this:</p>
<pre><code>use Attribute::Override;
use parent 'Some::Class';
sub foo : override { ... } # fails if it doesn't override
sub bar { ... } # fails if it does override
</code></pre>
<p>There are a couple of issues here. First, if method loading is delayed somehow (for example, methods loaded via AUTOLOAD or otherwise later installed in the symbol table), this won't detect those methods.</p>
<p>Walking the inheritance tree could also get similarly expensive. I do this with <a href="http://search.cpan.org/dist/Class-Sniff/" rel="nofollow">Class::Sniff</a>, but it's not really suitable for running code. I could walk the inheritance tree and simply match where there's a defined CODE slot in the appropriate symbol table and that would be faster, but if the method cache is invalidated, that would break if I were to cache those results.</p>
<p>So I have two questions: is this a reasonable approach and is there a hook which allows me to check if the method cache has changed? (search for 'cache' in 'perldoc perlobj').</p>
<p>Of course, this shouldn't break production code, I am thinking about only having it fail or warn if the TEST_HARNESS environment variable is active (and have an explicit environment variable to force it to be inactive, if production code were to set the TEST_HARNESS environment variable for some reason).</p></p>
| <p>One way to enforce this:</p>
<pre><code>package Base;
...
sub new {
my $class = shift;
...
check_overrides( $class );
...
}
sub check_overrides {
my $class = shift;
for my $method ( @unoverridable ) {
die "horribly" if __PACKAGE__->can( $method ) != $class->can( $method );
}
}
</code></pre>
<p>Memoization of check_overrides may be helpful.</p>
<p>If there are some cases where you want exemptions, have an alternate method name and
have the base class call that:</p>
<pre><code>package Base;
...
my @unoverridable = 'DESTROY';
sub destroy {}
sub DESTROY {
my $self = shift;
# do essential stuff
...
$self->destroy();
}
</code></pre>
|
What is the easiest way to display the contents of an ArrayList of Objects in a JTable? <p>I have an ArrayList of Track objects.
Each Track object has the following fields (all Strings): </p>
<p>url, title, creator, album, genre, composer</p>
<p>I want to display these tracks in a JTable, with each row being an instance of a Track object, and each column containing one of the properties of a Track object.</p>
<p>How can I display this data using a JTable? I've used an AbstractTableModel that implements the getValueAt() method correctly. Still, I dont see anything on the screen.</p>
<p>Or is it easier just to use arrays?</p>
| <p>In order to add contents to display on a <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html"><code>JTable</code></a>, one uses the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html"><code>TableModel</code></a> to add items to display.</p>
<p>One of a way to add a row of data to the <code>DefaultTableModel</code> is by using the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableModel.html#addRow%28java.lang.Object%5B%5D%29"><code>addRow</code></a> method which will take an array of <code>Object</code>s that represents the objects in the row. Since there are no methods to directly add contents from an <code>ArrayList</code>, one can create an array of <code>Object</code>s by accessing the contents of the <code>ArrayList</code>.</p>
<p>The following example uses a <code>KeyValuePair</code> class which is a holder for data (similar to your <code>Track</code> class), which will be used to populate a <a href="http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableModel.html"><code>DefaultTableModel</code></a> to display a table as a <code>JTable</code>:</p>
<pre><code>class KeyValuePair
{
public String key;
public String value;
public KeyValuePair(String k, String v)
{
key = k;
value = v;
}
}
// ArrayList containing the data to display in the table.
ArrayList<KeyValuePair> list = new ArrayList<KeyValuePair>();
list.add(new KeyValuePair("Foo1", "Bar1"));
list.add(new KeyValuePair("Foo2", "Bar2"));
list.add(new KeyValuePair("Foo3", "Bar3"));
// Instantiate JTable and DefaultTableModel, and set it as the
// TableModel for the JTable.
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Key", "Value"});
// Populate the JTable (TableModel) with data from ArrayList
for (KeyValuePair p : list)
{
model.addRow(new String[] {p.key, p.value});
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.