instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>What memory leak detection tools are available for use with open source C/C++ on Windows?</p>
|
<p>The <a href="http://teaching.idallen.com/c_programming/mem/" rel="nofollow noreferrer">mem (revised)</a> package is an effective and straightforward tool to detect memory buffer overflows, underflows, leaks, double-deletion, and dangling references.</p>
<p><a href="http://c.snippets.org/browser.php?sect=37#37" rel="nofollow noreferrer">Original link to c.snippets.org, now invalid.</a></p>
|
<p>WinDbg is always a good choice for any program open or closed.</p>
| 35,979
|
<p>I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.</p>
<p>Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.</p>
<p>So, what are your experiences, what works best?</p>
|
<p>Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.</p>
<p>That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.</p>
<p>So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.</p>
<p>[EDIT] Re-reading your question it seems as if you are using the term <em>site</em> to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.</p>
|
<p>It depends.</p>
<p>In my latest projects, I have implemented a single servlet that delegates to several servlet-like objects which are instantiated in a dependency injection fashion. For instance, I have something like this in my servlet (pseudo-code):</p>
<pre><code>for(Handler handler : handlers) {
if(handler.handle(request, response)) {
return;
}
}
</code></pre>
<p>where Handler is an interface with a boolean handle(request, response) method. I obtain my handlers from a container (be it Spring or something even more lightweight).</p>
<p>The reason for this is that I really like dependency injection, and it is difficult to achieve it in Servlets; and I really don't feel much at home with most frameworks that provide web-component dependency injection- I like the simplicity of servlets.</p>
<p>Were not for this, I would go with multiple servlets, although there's a trade-off; either you have an enormous web xml with lots (and lots) of servlet mappings or you have a very complex servlet (unless you use something like my d-i approach).</p>
| 34,245
|
<p>Wondering if I need to do something in my swf to be able to access the assets on a different server, meaning more than just specify the url to the asset. Will flash handle the 'go get crossdomain.xml and authenticate everything' behind the scenes or do I need to include some special code beyond simply requesting the swf file?</p>
|
<blockquote>
<p>Will flash handle the 'go get
crossdomain.xml and authenticate
everything' behind the scenes or do I
need to include some special code
beyond simply requesting the swf file?</p>
</blockquote>
<p>In the event of any cross-domain request, Flash will look for the crossdomain.xml file at the root of the domain. For example, if you are requesting an XML file from: <code>http://mysubdomain.mydomain.com/fu/bar/</code> </p>
<p>Flash will check if a crossdomain.xml file exist at: <code>http://mysubdomin.mydomain.com/crossdomain.xml</code></p>
<p>If you ever need to load a crossdomain.xml file from a different location, you can do it via <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/system/Security.html#loadPolicyFile()" rel="nofollow noreferrer">Security.loadPolicyFile</a> . Bear in mind that the location of this crossdomain have any impact on the security access you have.</p>
<p>You may also want to read up on the <a href="http://www.adobe.com/devnet/flashplayer/articles/fplayer9-10_security.html" rel="nofollow noreferrer">security changes in Flash Player 10</a>.</p>
|
<p>If you're just trying to access another swf, adding the crossdomain.xml will do all the work for you since Flash will do it for you</p>
| 26,237
|
<p>I have a Linq to Sql .dbml file which auto generates my method signatures for certain stored procedures. eg, I have in SQL <code>spGetEmployees(@Name)</code> so in my data context I have <code>spGetEmployees(string Name)</code>. </p>
<p>Now, my underlying sp changed to add an additional parameter: <code>spGetEmployees(@name, @count)</code> and so I want the function in my <code>DataContext</code> to change as well. Is there a way to do this without dropping the stored proc from the Linq to Sql class file and re-adding it? </p>
|
<p>Currently if you use the ui you must drop the function and add it back there is no refresh yet. You can automate this class with sqlmetal.exe this will allow you to regenerate these files every time you update your database.</p>
|
<p>Currently if you use the ui you must drop the function and add it back there is no refresh yet. You can automate this class with sqlmetal.exe this will allow you to regenerate these files every time you update your database.</p>
| 31,255
|
<p>In a project we have text files looking like this:</p>
<pre><code>mv A, R3
mv R2, B
mv R1, R3
mv B, R4
add A, R1
add B, R1
add R1, R2
add R3, R3
add R21, X
add R12, Y
mv X, R2
</code></pre>
<p>I need to replace the strings according to the following, but I am looking
for a more general solution.</p>
<pre><code>R1 => R2
R2 => R3
R3 => R1
R12 => R21
R21 => R12
</code></pre>
<p>I know I could do it in Perl, the replace() function in the following code,
but the real application is written in Java, so the solution needs to be
in Java as well. </p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use File::Slurp qw(read_file write_file);
my %map = (
R1 => 'R2',
R2 => 'R3',
R3 => 'R1',
R12 => 'R21',
R21 => 'R12',
);
replace(\%map, \@ARGV);
sub replace {
my ($map, $files) = @_;
# Create R12|R21|R1|R2|R3
# making sure R12 is before R1
my $regex = join "|",
sort { length($b) <=> length($a) }
keys %$map;
my $ts = time;
foreach my $file (@$files) {
my $data = read_file($file);
$data =~ s/\b($regex)\b/$map{$1}/g;
rename $file, "$file.$ts"; # backup with current timestamp
write_file( $file, $data);
}
}
</code></pre>
<p>Your help for the Java implementation would be appreciated.</p>
|
<p>I've actually had to use this sort of algorithm several times in the past two weeks. So here it is the world's second-most verbose language...</p>
<pre><code>import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/*
R1 => R2
R2 => R3
R3 => R1
R12 => R21
R21 => R12
*/
String inputString
= "mv A, R3\n"
+ "mv R2, B\n"
+ "mv R1, R3\n"
+ "mv B, R4\n"
+ "add A, R1\n"
+ "add B, R1\n"
+ "add R1, R2\n"
+ "add R3, R3\n"
+ "add R21, X\n"
+ "add R12, Y\n"
+ "mv X, R2"
;
System.out.println( "inputString = \"" + inputString + "\"" );
HashMap h = new HashMap();
h.put( "R1", "R2" );
h.put( "R2", "R3" );
h.put( "R3", "R1" );
h.put( "R12", "R21" );
h.put( "R21", "R12" );
Pattern p = Pattern.compile( "\\b(R(?:12?|21?|3))\\b");
Matcher m = p.matcher( inputString );
StringBuffer sbuff = new StringBuffer();
int lastEnd = 0;
while ( m.find()) {
int mstart = m.start();
if ( lastEnd < mstart ) {
sbuff.append( inputString.substring( lastEnd, mstart ));
}
String key = m.group( 1 );
String value = (String)h.get( key );
sbuff.append( value );
lastEnd = m.end();
}
if ( lastEnd < inputString.length() ) {
sbuff.append( inputString.substring( lastEnd ));
}
System.out.println( "sbuff = \"" + sbuff + "\"" );
</code></pre>
<p>This can be Java-ified by these classes: </p>
<pre><code>import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
interface StringReplacer {
public CharSequence getReplacement( Matcher matcher );
}
class Replacementifier {
static Comparator keyComparator = new Comparator() {
public int compare( Object o1, Object o2 ) {
String s1 = (String)o1;
String s2 = (String)o2;
int diff = s1.length() - s2.length();
return diff != 0 ? diff : s1.compareTo( s2 );
}
};
Map replaceMap = null;
public Replacementifier( Map aMap ) {
if ( aMap != null ) {
setReplacements( aMap );
}
}
public setReplacements( Map aMap ) {
replaceMap = aMap;
}
private static String createKeyExpression( Map m ) {
Set set = new TreeSet( keyComparator );
set.addAll( m.keySet());
Iterator sit = set.iterator();
StringBuffer sb = new StringBuffer( "(" + sit.next());
while ( sit.hasNext()) {
sb.append( "|" ).append( sit.next());
}
sb.append( ")" );
return sb.toString();
}
public String replace( Pattern pattern, CharSequence input, StringReplacer replaceFilter ) {
StringBuffer output = new StringBuffer();
Matcher matcher = pattern.matcher( inputString );
int lastEnd = 0;
while ( matcher.find()) {
int mstart = matcher.start();
if ( lastEnd < mstart ) {
output.append( inputString.substring( lastEnd, mstart ));
}
CharSequence cs = replaceFilter.getReplacement( matcher );
if ( cs != null ) {
output.append( cs );
}
lastEnd = matcher.end();
}
if ( lastEnd < inputString.length() ) {
sbuff.append( inputString.substring( lastEnd ));
}
}
public String replace( Map rMap, CharSequence input ) {
// pre-condition
if ( rMap == null && replaceMap == null ) return input;
Map repMap = rMap != null ? rMap : replaceMap;
Pattern pattern
= Pattern.compile( createKeyExpression( repMap ))
;
StringReplacer replacer = new StringReplacer() {
public CharSequence getReplacement( Matcher matcher ) {
String key = matcher.group( 1 );
return (String)repMap.get( key );
}
};
return replace( pattern, input, replacer );
}
}
</code></pre>
|
<p>You can use a HashMap:</p>
<pre><code>Map<String, String> map = new HashMap<String, String>();
map.put("R1", "R2");
map.put("R2", "R3");
for(String key: map.keySet()) {
str.replaceAll(key, map.get(key));
}
</code></pre>
<p>replaceAll also handles regular expressions.</p>
<p>EDIT: The above solution, as many have pointed out, doesn't work because it doesn't handle cyclic replacements. So this is my second approach:</p>
<pre><code>public class Replacement {
private String newS;
private String old;
public Replacement(String old, String newS) {
this.newS = newS;
this.old = old;
}
public String getOld() {
return old;
}
public String getNew() {
return newS;
}
}
SortedMap<Integer, Replacement> map = new TreeMap<Integer, Replacement>();
map.put(new Integer(1), new Replacement("R2", "R3"));
map.put(new Integer(2), new Replacement("R1", "R2"));
for(Integer key: map.keySet()) {
str.replaceAll(map.get(key).getOld(), map.get(key).getNew());
}
</code></pre>
<p>This works provided that you order the replacements properly and that you guard yourself against cyclic replacements. Some replacements are impossible:</p>
<pre><code>R1 -> R2
R2 -> R3
R3 -> R1
</code></pre>
<p>You must use some 'temp' variables for these:</p>
<pre><code>R1 -> R@1
R2 -> R@3
R3 -> R1
R@(\d{1}) -> R\1
</code></pre>
<p>You could write a library that it would do all these for you.</p>
| 49,941
|
<p>I'm operating a neighbourhood <a href="http://maps.google.de/maps/ms?ie=UTF8&hl=de&msa=0&msid=101021148567197540440.00043fcffa4cdf06fb4bc&ll=51.791948,8.173571&spn=0.033976,0.058365&t=h&z=14" rel="nofollow noreferrer">WIFI network in a rural environment</a>.</p>
<p>Now I'm looking fo a monitoring tool to run on a server (Windows or Linux) which would track bandwidth, uptime (clients as well as internet connection), etc...
Most of this information is exposed via SNMP by my routers and access points, so SNMP support is required.</p>
<p>Additional features should be: </p>
<ul>
<li>Graphical data representation</li>
<li>free license</li>
</ul>
<p>So what's the best choice for me?</p>
<p><em>Edit</em> These are the tools mentioned so far:</p>
<ul>
<li><a href="http://oss.oetiker.ch/mrtg/" rel="nofollow noreferrer">MRTG</a></li>
<li><a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">Munin</a></li>
<li><a href="http://www.nagios.org/" rel="nofollow noreferrer">Nagios</a></li>
<li><a href="http://www.zenoss.com/product/core" rel="nofollow noreferrer">Zenoss Core</a></li>
<li><a href="http://www.ntop.org/" rel="nofollow noreferrer">ntop</a></li>
<li><a href="http://cacti.net/features.php" rel="nofollow noreferrer">cacti</a></li>
<li><a href="http://www.zabbix.com/" rel="nofollow noreferrer">ZABBIX</a></li>
</ul>
|
<p><a href="http://oss.oetiker.ch/mrtg/" rel="nofollow noreferrer">MRTG</a> is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:</p>
<pre><code>cfgmaker --output=mrtg_myrouter.cfg public@1.2.3.4
</code></pre>
<p>MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)</p>
<p>For monitoring other stuff I like <a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">Munin</a>. I would describe it again, but I posted an answer a while ago <a href="https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733">here</a> (about graphing disc-usage).</p>
<p>Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)</p>
<p>There's an example installation of <a href="http://www.switch.ch/network/operation/statistics/geant2.html" rel="nofollow noreferrer">MRTG here</a>, and <a href="http://munin.ping.uio.no/" rel="nofollow noreferrer">Munin here</a></p>
|
<p>Also consider <a href="http://cactiez.cactiusers.org/" rel="nofollow">CactiEZ</a> on a VM or small server, it is a baremetal CentOS 6 based system.</p>
| 32,219
|
<p>Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system.</p>
<pre><code>private Boolean is64BitOperatingSystem()
{
RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment");
String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE");
if (processorArchitecture.Equals("x86")) {
return false;
}
else {
return true;
}
}
</code></pre>
<p>It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method?</p>
<p><strong>Edit</strong>: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.</p>
|
<p>Take a look at Raymond Chens solution:</p>
<p><a href="http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx" rel="nofollow noreferrer">How to detect programmatically whether you are running on 64-bit Windows</a></p>
<p>and here's the PINVOKE for .NET:</p>
<p><a href="http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y" rel="nofollow noreferrer">IsWow64Process (kernel32)</a></p>
<p><strong>Update:</strong> I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Ask yourself the questions, 1 - is the registry entry concerned properly documented by MS, 2 - If it is do they provide a definitive list of possible values that is guaranteed to permit you as a developer to make the informed decision between whether you are running 32 bit or 64 bit. If the answer is no, then call the API's, yeah it's a but more long winded but it is documented and definitive. </p>
|
<p>Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have access to what you need.</p>
| 2,595
|
<p>I'm developing a SOAP application that integrates with a 3rd party. I think the WSDL of this third party is very strange. I'm pretty new to SOAP, so I don't want to go asking them to fix it if it isn't broken. Here's some things I've noticed that I consider wrong about it, though I'm sure it's technically a valid document (hence the reason I wrote "best practices" in the title). Also, I'm using gSOAP as my SOAP library, which may be why I think some of these things are weird (I'm even newer to gSOAP than I am to SOAP in general).</p>
<ol>
<li><p>they have interfaces specified for both SOAP 1.1 and SOAP 1.2 in the same WSDL. This causes gSOAP to generate twice as many classes as it needs to, since I'm only going to use 1.2.</p></li>
<li><p>all of their namespaces are <code>http://tempuri.org</code>. That shouldn't be like that, right?</p></li>
<li><p>despite defining a bunch of RPC calls, their WSDL uses the document format. I'm thinking of asking them to switch to RPC format because it seems that gSOAP won't generate methods that take C++ typed parameters for document format. Instead, it creates a new class for every API function's input and response data. I'll have to write another layer of wrapping around the gSOAP stuff to provide a reasonable API to the rest of my app if I can't fix that. Also, AFAICT, the XML that will be going back and forth would be exactly the same as it is now if they switched to RPC, so I don't think it would be difficult.</p></li>
<li><p>elements have minOccurs = 0 yet when I submit requests without them, I get errors returned back indicating they're required (sometimes even stack traces of null pointer exceptions). They should specify them as minOccurs = 1 if they're required, right?</p></li>
<li><p>nearly all of the web service functions specify a response that includes an integer to indicate success (really a boolean) and an error message string. Should they be using SOAP faults for this? I think it would be easier for my application to handle if it was a fault since gSOAP will let me figure that out really easily (and print the error message trivially).</p></li>
</ol>
<p>Of course, I don't have high hopes that this 3rd party company will change their WSDL just because I've asked them to. At least I'll learn something... for all I know, none of these are wrong or even questionable. Thanks for your help.</p>
|
<p>1 - They probably consider this a feature. :-)</p>
<p>2 - That's horrible.</p>
<p>3 - Lots of people recommend this. It's called wrapped format.</p>
<p>4 - You're correct.</p>
<p>5 - It depends. Theoretically, you're probably correct, but in practice lots of SOAP toolkits don't have very good support for SOAP faults, so they might have deliberately chosen to not use exceptions.</p>
|
<p>What you have encountered is the typical third party laziness when creating their web services. I'd imagine you won't have much luck trying to reason with them, however you can hand edit the WSDL to remove the 1.1 definitions.</p>
| 35,767
|
<p>When doing case-insensitive comparisons, is it more efficient to convert the string to upper case or lower case? Does it even matter?</p>
<p>It is suggested <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c#12137">in this SO post</a> that C# is more efficient with ToUpper because "Microsoft optimized it that way." But I've also read <a href="http://www.petefreitag.com/item/175.cfm" rel="noreferrer">this argument</a> that converting ToLower vs. ToUpper depends on what your strings contain more of, and that typically strings contain more lower case characters which makes ToLower more efficient.</p>
<p>In particular, I would like to know:</p>
<ul>
<li>Is there a way to optimize ToUpper or ToLower such that one is faster than the other?</li>
<li>Is it faster to do a case-insensitive comparison between upper or lower case strings, and why?</li>
<li>Are there any programming environments (eg. C, C#, Python, whatever) where one case is clearly better than the other, and why?</li>
</ul>
|
<p>Converting to either upper case or lower case in order to do case-insensitive comparisons is incorrect due to "interesting" features of some cultures, particularly Turkey. Instead, use a <a href="http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx" rel="noreferrer">StringComparer</a> with the appropriate options.</p>
<p>MSDN has some <a href="http://msdn.microsoft.com/en-us/library/ms973919.aspx" rel="noreferrer">great guidelines</a> on string handling. You might also want to check that your code passes <a href="http://www.moserware.com/2008/02/does-your-code-pass-turkey-test.html" rel="noreferrer">the Turkey test</a>.</p>
<p>EDIT: Note Neil's comment around <em>ordinal</em> case-insensitive comparisons. This whole realm is pretty murky :(</p>
|
<p>It really shouldn't ever matter. With ASCII characters, it definitely doesn't matter - it's just a few comparisons and a bit flip for either direction. Unicode might be a little more complicated, since there are some characters that change case in weird ways, but there really shouldn't be any difference unless your text is full of those special characters.</p>
| 29,038
|
<p>I'm looking for a Java library that is geared towards network math and already tested. Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet. </p>
<p>Should I roll my own, or is there already a robust library for this?</p>
|
<p>We developed a Java IPv4 arithmetic library ourselves.
See it here: <a href="http://tufar.com/ipcalculator/" rel="noreferrer">http://tufar.com/ipcalculator/</a>
It is under BSD license. </p>
|
<p>The <a href="https://seancfoley.github.io/IPAddress/" rel="nofollow noreferrer">open-source IPAddress Java library</a> can do ip address manipulation such as conversion to/from ipv4/ipv6 and subnet checking. Disclaimer: I am the project manager.</p>
<p>It handles various network math operations, such as masking, bitwise or, setting prefix lengths, switch address to prefix block, iterating through a subnet, checking containment, replacing address segments, reversing addresses, calculating subnet intersection, subtracting one subnet from another, and others.</p>
<p>Here is some example code for testing if an ipv6 address is in a given subnet:</p>
<pre><code> String ipv6 = "2001:db8:57AB:0000:0000:0000:0000:0001";
String ipv6subnet = "2001:db8::/32";
String ipv4 = "1.2.3.4";
try {
IPAddressString ipv6addrstr = new IPAddressString(ipv6);
IPAddressString ipv6addrsubnetstr = new IPAddressString(ipv6subnet);
IPAddressString ipv4addrstr = new IPAddressString(ipv4);
IPAddress ipv6addr = ipv6addrstr.toAddress();
IPAddress ipv6addrsubnet = ipv6addrsubnetstr.toAddress();
IPAddress ipv4mappedaddr = ipv4addrstr.toAddress().toIPv6();
System.out.println(ipv6addrsubnet + " contains " + ipv6addr + ": " + ipv6addrsubnet.contains(ipv6addr)); //
System.out.println(ipv6addrsubnet + " contains " + ipv4mappedaddr + ": " + ipv6addrsubnet.contains(ipv4mappedaddr)); //
} catch(AddressStringException e) {
//e.getMessage has validation error
}
</code></pre>
<p>output:</p>
<pre><code>2001:db8::/32 contains 2001:db8:57ab::1 is true
2001:db8::/32 contains ::ffff:102:304 is false
</code></pre>
| 27,095
|
<p>I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc.</p>
<p>I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order.</p>
<p>So I'd have:</p>
<pre><code>28437 Ford Fiesta
328 Honda Civic
34949 Toyota Yaris
</code></pre>
<p>and so forth...</p>
<p>What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.</p>
|
<p>What version of .NET are you using? If you're using 3.5 - or can use C# 3.0 and <a href="http://www.albahari.com/nutshell/linqbridge.aspx" rel="nofollow noreferrer">LINQBridge</a> - then I'd definitely go with LINQ. First transform each line into some appropriate object, and then use OrderBy:</p>
<pre><code>var cars = lines.Select(line => Car.ParseLine(line))
.OrderBy(car => car.Manufacturer);
</code></pre>
|
<p>If you just have a bunch of strings in an Array, use</p>
<pre><code>Array.Sort(myArray)
</code></pre>
<p>That will put the strings in "myArray" in alphabetical order (case sensitive).</p>
<p>If you want to to different comparisons (like case-insensitive for example), you can define an own ICcomparer or use Linq-Extensions, preferrably with a lambda expression like</p>
<pre><code> string [] sArray = new string[] { "fsdhj", "FA", "FX", "fxx", "Äbc" };
sArray = sArray.OrderBy(s => s.ToLowerInvariant()).ToArray();
</code></pre>
<p>There's a whole bunch of other sorting methods, but these are the most basic. I could give you a more detailed answer to your problem, if I understood better what your input-object looks like. As long as it's just an array of strings, you should be fine with the above.</p>
<p>In response to the first two comments below I should also note that the invariant string-sorting method given above is not the best one for that particular job (see comments).</p>
<p>However it <strong>does</strong> illustrate the use of extension methods with lambda expressions, which come in very handy in situations where you don't have predefined IComparer-classes.</p>
| 35,988
|
<p>I've written a control in C# that overrides the built-in DropDownList control. For this I need a javascript resource included, which I'm including as an embedded resource then adding the <code>WebResource</code> attribute, which works fine.</p>
<p>However, I also need to reference a webservice, which I would normally include in the scriptmanager on the page like this</p>
<pre><code><asp:scriptmanager id="scriptmanager" runat="server">
<Services>
<asp:ServiceReference Path="~/Path/To/Service.asmx" />
</Services>
</asp:scriptmanager>
</code></pre>
<p>Is there any way to make the page include this reference in the code behind on the control I've created, similar to how it includes the embedded javascript file?</p>
|
<p>You can add a ScriptManagerProxy in the code or the markup of your control and add the service reference through it. The settings in the ScriptManagerProxy are merged with the "real" ScriptManager at compile time.</p>
|
<p>If you know the page the usercontrol is in you can do a ((PageName)this.Page).scriptmanager.Services.Add() from the user control</p>
| 13,860
|
<p>We've been fighting with <a href="http://haproxy.1wt.eu/" rel="noreferrer">HAProxy</a> for a few days now in Amazon EC2; the experience has so far been great, but we're stuck on squeezing more performance out of the software load balancer. We're not exactly Linux networking whizzes (we're a .NET shop, normally), but we've so far held our own, attempting to set proper ulimits, inspecting kernel messages and tcpdumps for any irregularities.
So far though, we've reached a plateau of about 1,700 requests/sec, at which point client timeouts abound (we've been using and tweaking <a href="http://www.hpl.hp.com/research/linux/httperf/" rel="noreferrer">httperf</a> for this purpose). A coworker and I were listening to the most recent Stack Overflow podcast, in which the Reddit founders note that their entire site runs off one HAProxy node, and that it so far hasn't become a bottleneck. Ack! Either there's somehow not seeing that many concurrent requests, we're doing something horribly wrong, or the shared nature of EC2 is limiting the network stack of the Ec2 instance (we're using a large instance type). Considering the fact that both Joel and the Reddit founders agree that network will likely be the limiting factor, is it possible that's the limitation we're seeing? </p>
<p>Any thoughts are greatly appreciated!</p>
<p><strong>Edit</strong> It looks like the actual issue was not, in fact, with the load balancer node! The culprit was actually the nodes running httperf, in this instance. As httperf builds and tears down a socket for each request, it spends a good amount of CPU time in the kernel. As we bumped the request rate higher, the TCP FIN TTL (being 60s by default) was keeping sockets around too long, and the ip_local_port_range's default was too low for this usage scenario. Basically, after a few minutes of the client (httperf) node constantly creating and destroying new sockets, the number of unused ports ran out, and subsequent 'requests' errored-out at this stage, yielding low request/sec numbers and a large amount of errors. </p>
<p>We also had looked at nginx, but We've been working with RighScale, and they've got drop-in scripts for HAProxy. Oh, and we've got too tight a deadline [of course] to switch out components unless it proves absolutely necessary. Mercifully, being on AWS allows us to test out another setup using nginx in parallel (if warranted), and make the switch overnight later on.</p>
<p><a href="https://www.frozentux.net/ipsysctl-tutorial/chunkyhtml/variablereference.html#AEN234" rel="noreferrer">This page</a> describes each of the sysctl variables fairly well (ip_local_port_range and tcp_fin_timeout were tuned, in this case).</p>
|
<p>Not really an answer to your question, but nginx and pound both have good reputations as load-balancers. Wordpress just <a href="http://barry.wordpress.com/2008/04/28/load-balancer-update/" rel="noreferrer">switched to nginx</a> with good results.</p>
<p>But more specifically, to debug your problem. If you aren't seeing 100% cpu usage (including I/O wait), then you are network bound, yes.
EC2 internally uses a gigabit network, try using an XL instance, so you have the underlying hardware to yourself, and don't have to share that gigabit network port.</p>
|
<p>Even though your issue solved. KEMP Technologies now have a fully blown load balancer for AWS. Might save you some hassle. </p>
| 32,552
|
<p>In the app I am working on, I want to allow the user to upload static HTML pages to replace the default "user profile" MVC View page. Is this possible? That is, the user uploaded html pages will totally run out of MVC, and it can include its own CSS links, etc.</p>
<p>Ideas? Suggestions?</p>
|
<p>Obviously the .net MVC framework handles static content already for images / css / js etc. It would just be a matter of extending that (routing?) to pass .html files through straight to IIS. That coupled with a dash of rewriting to make prettier urls should do the trick.</p>
<p>However, I would be very, very wary of allowing User Generated Content in the form of raw HTML uploads as you're leaving a very very wide door open. At best, you're going to wind up with people's pages full of spam/porn/adverts. At the worst, you'll be providing a gateway for people to upload cross-site scripting hacks and potentially uploading malicious content to damage your site. The could easily take an existing form on your site, hardcode a load of junk into it, and exectute it from their homepage and break a whole heap of things.</p>
<p>At the very least you should be parsing the uploaded content to reduce it down to just a block of content, and then wrapping that in your own etc. I would personally be much more inclined to just provide users with a nice WYSIWYG editor to edit a single block of content - any editor worth it's salt should provide you with sanitisation as to what elements it includes / excludes. Then store this content fragment in your database / on disc and have the request for a homepage go through a standard MVC controller route and load up that content.</p>
<hr>
<p>Edit - for you request for examples
You should be able to add an Ignore rule to your routing - there will probably already be examples of these already - crack open your Global.asax file - you will want to put in a call to the routes.IgnoreRoute method :</p>
<pre><code>routes.IgnoreRoute("UserPages/{*path}");
</code></pre>
<p>Should let IIS handle all requests for yourwebsite.com/UserPages/aUser/homepage.html - you can also play about a bit more with the wild card fragments / constraints for prettier solutions</p>
|
<p>I suggest you to make your custom ViewEngine that will allow to use static html markup with custom tags in it, that will be replaced by user info.</p>
<p>So, your view engine may accept something like that:</p>
<pre><code><html>
<body>
<b><user:FirstName /></b>
<b><user:LastName /></b>
</body>
</html>
</code></pre>
<p>and produce</p>
<pre><code><html>
<body>
<b>First Name</b>
<b>Last Name</b>
</body>
</html>
</code></pre>
<p>This custom markup you can store in database, for example.
You can take a look at custom ViewEngine implementations at <a href="http://www.codeplex.com/MVCContrib" rel="nofollow noreferrer">MVC Contrib project</a>.</p>
| 47,647
|
<p>Does anyone have a good set of Visio Stencils for MS SQL Server?</p>
|
<p>Some versions of Visio have database support built in. There are a couple of links on the MVP site for Visio:</p>
<p>New URL: <a href="http://visio.mvps.org/3rdParty/default.html" rel="nofollow noreferrer">http://visio.mvps.org/3rdParty/default.html</a>
Old URL: <a href="http://visio.mvps.org/3rdparty.htm" rel="nofollow noreferrer">http://visio.mvps.org/3rdparty.htm</a></p>
<p>Hope this helps!
Jeff</p>
|
<p>I haven't tried it myself but there is one at <a href="http://visiotoolbox.com/downloads.aspx?resourceid=1&aid=562" rel="nofollow noreferrer">http://visiotoolbox.com/downloads.aspx?resourceid=1&aid=562</a></p>
| 16,215
|
<p>in Javascript, the following:</p>
<pre><code>var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/".*?"/g);
alert(result);
</code></pre>
<p>yields "the quick","brown fox","jumps over","the lazy dog"</p>
<p>I want each matched element to be unquoted: the quick,brown fox,jumps over,the lazy dog</p>
<p>what regexp will do this?</p>
|
<p>This seems to work:</p>
<pre><code>var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.match(/[^"]+(?=(" ")|"$)/g);
alert(result);
</code></pre>
<p>Note: This doesn't match empty elements (i.e. ""). Also, it won't work in browsers that don't support JavaScript 1.5 (lookaheads are a 1.5 feature).</p>
<p>See <a href="http://www.javascriptkit.com/javatutors/redev2.shtml" rel="noreferrer">http://www.javascriptkit.com/javatutors/redev2.shtml</a> for more info.</p>
|
<p>Here's one way:</p>
<pre><code>var test = '"the quick" "brown fox" "jumps over" "the lazy dog"';
var result = test.replace(/"(.*?)"/g, "$1");
alert(result);
</code></pre>
| 17,771
|
<p>I'm looking for a book/site/tutorial on best practices for relational database design, tuning for performance etc. It turns out this kind of resource is a bit difficult to find; there's a lot of "here's normalization, here's ER diagrams, have at it," but not much in the way of real examples. Anyone have any ideas?</p>
|
<p>Book: <a href="https://rads.stackoverflow.com/amzn/click/com/0201752840" rel="noreferrer" rel="nofollow noreferrer">Database Design for Mere Mortals</a></p>
|
<p>Here are some resources I could find on the web. They include examples you are looking for:</p>
<ul>
<li><a href="http://databases.ncl.ac.uk/databases/Design/default.aspx" rel="nofollow noreferrer">Designing and creating a Relational Database - Dr Lorna Scammell: Newcastle University Database Adviser</a></li>
<li><a href="http://www.databasedev.co.uk/data_models.html" rel="nofollow noreferrer">Sample Data Models for Relational Database Design </a></li>
</ul>
| 3,270
|
<p>Do you have to pass delete the same pointer that was returned by new, or can you pass it a pointer to one of the classes base types? For example:</p>
<pre><code>class Base
{
public:
virtual ~Base();
...
};
class IFoo
{
public:
virtual ~IFoo() {}
virtual void DoSomething() = 0;
};
class Bar : public Base, public IFoo
{
public:
virtual ~Bar();
void DoSomething();
...
};
Bar * pBar = new Bar;
IFoo * pFoo = pBar;
delete pFoo;
</code></pre>
<p>Of course this is greatly simplified. What I really want to do is create a container full of boost::shared_ptr and pass it to some code that will remove it from the container when it is finished. This code will know nothing of the implementation of Bar or Base, and will rely on the implied delete operator in the shared_ptr destructor to do the right thing.</p>
<p>Can this possibly work? My intuition says no, since the pointers will not have the same address. On the other hand, a dynamic_cast<Bar*> should work, so somewhere the compiler is storing enough information to figure it out.
<hr>
Thanks for the help, everybody who answered and commented. I already knew the importance of virtual destructors, as shown in my example; after seeing the answer I gave it a little thought, and realized the <i>whole reason</i> for a virtual destructor is this exact scenario. Thus it had to work. I was thrown by the absence of a visible means of converting the pointer back to the original. A little more thinking led me to believe there was an invisible means, and I theorized that the destructor was returning the true pointer for delete to release. Investigating the compiled code from Microsoft VC++ confirmed my suspicion when I saw this line in ~Base:</p>
<pre><code>mov eax, DWORD PTR _this$[ebp]
</code></pre>
<p>Tracing the assembler revealed that this was the pointer being passed to the delete function. Mystery solved.</p>
<p>I've fixed the example to add the virtual destructor to IFoo, it was a simple oversight. Thanks again to everyone who pointed it out.</p>
|
<p>Yes, it will work, <strong>if and only if</strong> the base class destructor is virtual, which you have done for the <code>Base</code> base class but not for the <code>IFoo</code> base class. If the base class destructor is virtual, then when you call <code>operator delete</code> on the base class pointer, it uses dynamic dispatch to figure out how to delete the object by looking up the derived class destructor in the virtual function table.</p>
<p>In your case of multiple inheritance, it will only work if the base class you're deleting it through has a virtual destructor; it's ok for the other base classes to not have a virtual destructor, but only if you don't try to delete any derived objects via those other base class pointers.</p>
|
<p>This doesn't relate to your given example, but since you mentioned that you're really interested in <code>shared_ptr</code>'s behavior when deleting its owned object, you might be interested in using <code>shared_ptr</code>'s 'deleter'.</p>
<p>If the object owned by the <code>shared_ptr</code> needs special handling when being deleted, you can specify a 'deleter' for any particular <code>shared_ptr<></code>. The deleter is not part of the type, it's an attribute of a <code>shared_ptr<></code> instance, so your container of <code>shared_ptr<></code> objects could have some objects with different deleters. Here's what the Boost docs say about the <code>shared_ptr<></code> deleter:</p>
<blockquote>
<p>Custom deallocators allow a factory
function returning a <code>shared_ptr</code> to
insulate the user from its memory
allocation strategy. Since the
deallocator is not part of the type,
changing the allocation strategy does
not break source or binary
compatibility, and does not require a
client recompilation. For example, a
"no-op" deallocator is useful when
returning a <code>shared_ptr</code> to a statically
allocated object, and other variations
allow a <code>shared_ptr</code> to be used as a
wrapper for another smart pointer,
easing interoperability.</p>
</blockquote>
<p>It would be cleanest if you could modify <code>IFoo</code> to have a virtual destructor since you're planning to delete objects that are subclasses of it through an <code>IFoo</code> reference or pointer. But if you're stuck with an <code>IFoo</code> that cannot be corrected, then if you want to use <code>shared_ptr<IFoo></code> in your container, but have it pointing to a <code>Bar</code>, you could create the <code>shared_ptr</code> instance with a deleter that performs a downcast to a <code>Bar*</code> then does the delete operation. Downcasts are considered bad form, but this technique might be something that you could use in a bind.</p>
| 37,657
|
<p>Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)</p>
|
<p>this works for me in bash:</p>
<pre><code> svn status | egrep '^\?' | cut -c8- | xargs rm
</code></pre>
<p><a href="https://stackoverflow.com/users/50225/seth-reno">Seth Reno</a>'s is better:</p>
<pre><code>svn status | grep ^\? | cut -c9- | xargs -d \\n rm -r
</code></pre>
<p>It handles unversioned folders and spaces in filenames</p>
<p>As per comments below, this only works on files that subversion doesn't know about (status=?). Anything that subversion <em>does</em> know about (including Ignored files/folders) will not be deleted.</p>
<p>If you are using subversion 1.9 or greater you can simply use the <a href="https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options" rel="noreferrer">svn cleanup</a> command with --remove-unversioned and --remove-ignored options</p>
|
<p>For the people that like to do this with perl instead of python, Unix shell, java, etc. Hereby a small perl script that does the jib as well.</p>
<p>Note: This also removes all unversioned directories</p>
<pre><code>#!perl
use strict;
sub main()
{
my @unversioned_list = `svn status`;
foreach my $line (@unversioned_list)
{
chomp($line);
#print "STAT: $line\n";
if ($line =~/^\?\s*(.*)$/)
{
#print "Must remove $1\n";
unlink($1);
rmdir($1);
}
}
}
main();
</code></pre>
| 29,613
|
<p>What is the accepted/most commonly used way to manipulate dynamic (with all dimensions not known until runtime) multi-dimensional arrays in C and/or C++.</p>
<p>I'm trying to find the cleanest way to accomplish what this Java code does:</p>
<pre><code>public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int rows=sc.nextInt();
int cols=sc.nextInt();
int[][] data=new int[rows][cols];
manipulate(data);
}
public static void manipulate(int[][] data){
for(int i=0;i<data.length;i++)
for(int j=0;j<data[0].length.j++){
System.out.print(data[i][j]);
}
}
</code></pre>
<p>(reads from std_in just to clarify that dimensions aren't known until runtime).</p>
<p>Edit:I noticed that this question is pretty popular even though it's pretty old. I don't actually agree with the top voted answer. I think the best choice for C is to use a single-dimensional array as Guge said below "You can alloc rows<em>cols</em>sizeof(int) and access it by table[row*cols+col].".</p>
<p>There is a number of choices with C++, if you really like boost or stl then the answers below might be preferable, but the simplest and probably fastest choice is to use a single dimensional array as in C.</p>
<p>Another viable choice in C and C++ if you want the [][] syntax is lillq's answer down at the bottom is manually building the array with lots of malloc's.</p>
|
<p>Use <strong><a href="http://www.boost.org/doc/libs/1_37_0/libs/multi_array/doc/user.html" rel="noreferrer">boost::multi_array</a></strong>.</p>
<p>As in your example, the only thing you need to know at compile time is the number of dimensions. Here is the first example in the documentation :</p>
<pre><code>#include "boost/multi_array.hpp"
#include <cassert>
int
main () {
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
A[i][j][k] = values++;
// Verify values
int verify = 0;
for(index i = 0; i != 3; ++i)
for(index j = 0; j != 4; ++j)
for(index k = 0; k != 2; ++k)
assert(A[i][j][k] == verify++);
return 0;
}
</code></pre>
<p>Edit: As suggested in the comments, <a href="http://www.klaimsden.net/code/Test_MultiArray.cpp" rel="noreferrer">here is a "simple" example</a> application that let you define the multi-dimensional array size at runtime, asking from the console input.
Here is an example output of this example application (compiled with the constant saying it's 3 dimensions) :</p>
<pre><code>Multi-Array test!
Please enter the size of the dimension 0 : 4
Please enter the size of the dimension 1 : 6
Please enter the size of the dimension 2 : 2
Text matrix with 3 dimensions of size (4,6,2) have been created.
Ready!
Type 'help' for the command list.
>read 0.0.0
Text at (0,0,0) :
""
>write 0.0.0 "This is a nice test!"
Text "This is a nice test!" written at position (0,0,0)
>read 0.0.0
Text at (0,0,0) :
"This is a nice test!"
>write 0,0,1 "What a nice day!"
Text "What a nice day!" written at position (0,0,1)
>read 0.0.0
Text at (0,0,0) :
"This is a nice test!"
>read 0.0.1
Text at (0,0,1) :
"What a nice day!"
>write 3,5,1 "This is the last text!"
Text "This is the last text!" written at position (3,5,1)
>read 3,5,1
Text at (3,5,1) :
"This is the last text!"
>exit
</code></pre>
<p>The important parts in the code are the main function where we get the dimensions from the user and create the array with : </p>
<pre><code>const unsigned int DIMENSION_COUNT = 3; // dimension count for this test application, change it at will :)
// here is the type of the multi-dimensional (DIMENSION_COUNT dimensions here) array we want to use
// for this example, it own texts
typedef boost::multi_array< std::string , DIMENSION_COUNT > TextMatrix;
// this provide size/index based position for a TextMatrix entry.
typedef std::tr1::array<TextMatrix::index, DIMENSION_COUNT> Position; // note that it can be a boost::array or a simple array
/* This function will allow the user to manipulate the created array
by managing it's commands.
Returns true if the exit command have been called.
*/
bool process_command( const std::string& entry, TextMatrix& text_matrix );
/* Print the position values in the standard output. */
void display_position( const Position& position );
int main()
{
std::cout << "Multi-Array test!" << std::endl;
// get the dimension informations from the user
Position dimensions; // this array will hold the size of each dimension
for( int dimension_idx = 0; dimension_idx < DIMENSION_COUNT; ++dimension_idx )
{
std::cout << "Please enter the size of the dimension "<< dimension_idx <<" : ";
// note that here we should check the type of the entry, but it's a simple example so lets assume we take good numbers
std::cin >> dimensions[dimension_idx];
std::cout << std::endl;
}
// now create the multi-dimensional array with the previously collected informations
TextMatrix text_matrix( dimensions );
std::cout << "Text matrix with " << DIMENSION_COUNT << " dimensions of size ";
display_position( dimensions );
std::cout << " have been created."<< std::endl;
std::cout << std::endl;
std::cout << "Ready!" << std::endl;
std::cout << "Type 'help' for the command list." << std::endl;
std::cin.sync();
// we can now play with it as long as we want
bool wants_to_exit = false;
while( !wants_to_exit )
{
std::cout << std::endl << ">" ;
std::tr1::array< char, 256 > entry_buffer;
std::cin.getline(entry_buffer.data(), entry_buffer.size());
const std::string entry( entry_buffer.data() );
wants_to_exit = process_command( entry, text_matrix );
}
return 0;
}
</code></pre>
<p>And you can see that to accede an element in the array, it's really easy : you just use the operator() as in the following functions :</p>
<pre><code>void write_in_text_matrix( TextMatrix& text_matrix, const Position& position, const std::string& text )
{
text_matrix( position ) = text;
std::cout << "Text \"" << text << "\" written at position ";
display_position( position );
std::cout << std::endl;
}
void read_from_text_matrix( const TextMatrix& text_matrix, const Position& position )
{
const std::string& text = text_matrix( position );
std::cout << "Text at ";
display_position(position);
std::cout << " : "<< std::endl;
std::cout << " \"" << text << "\"" << std::endl;
}
</code></pre>
<p>Note : I compiled this application in VC9 + SP1 - got just some forgettable warnings.</p>
|
<p>There is no way to determine the length of a given array in C++. The best way would probably be to pass in the length of each dimension of the array, and use that instead of the .length property of the array itself.</p>
| 47,754
|
<p>I have this bit of script to widen a text box on mouseover and shorten it on mouseoff.</p>
<p>The problem I am having is that Internet Explorer doesn't seem to extend it's hover over the options of a select box.</p>
<p>This means in IE I can click the select, have the options drop down, but if I try to select one, they vanish and the select box re-sizes as soon as I move off the select box itself.</p>
<p>Example Code:</p>
<pre><code><script type='text/javascript'>
$(function() {
$('#TheSelect').hover(
function(e){
$('#TheText').val('OVER');
$(this).width( 600 );
},
function(e){
$('#TheText').val('OUT');
$(this).width( 50 );
}
);
});
</script>
</code></pre>
<p>And:</p>
<pre><code><input type='text' id='TheText' /><br /><br />
<select id='TheSelect' style='width:50px;'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
<option value='42,693,748,756'>Forty-two billion, six-hundred and ninety-three million, seven-hundred-forty-some-odd..... </option>
<option value='5'>Five</option>
<option value='6'>Six</option>
<option value='7'>Seven...</option>
</select>
</code></pre>
<p>Are there any workarounds for select boxes in IE? I would even consider a jquery replacement if anyone can recommend one that is really reliable.</p>
<p>Thanks!</p>
|
<p>Apparently IE doesn't consider the drop down bit part of the select element. It's doable, but it takes a bit of cheating with expando properties and blur/focus events to enable and disable the 'hide' effect to stop it kicking in when the mouse enters the drop-down part of the element.</p>
<p>Have a go with this:</p>
<pre><code>$(function() {
var expand = function(){ $(this).width(600) }
var contract = function(){ if (!this.noHide) $(this).width(50) }
var focus = function(){ this.noHide = true }
var blur = function(){ this.noHide = false; contract.call(this) }
$('#TheSelect')
.hover(expand, contract)
.focus(focus)
.click(focus)
.blur(blur)
.change(blur)
});
</code></pre>
<p>(Apologies if this isn't how one is supposed to use jQuery - I've never used it before :))</p>
|
<p>Had the same problem, and WorldWidewebb's answer worked very well on IE8. I just made a slight change, removing "select" from the selector, since I included the select box's class in the selector. Made it a really simple fix. </p>
<p>Also, i had it implemented on a menu that uses the hoverIntent jquery plugin, with no problems. (No interference).</p>
| 25,366
|
<p>I've allocated an "array" of <code>mystruct</code> of size <code>n</code> like this:</p>
<pre><code>if (NULL == (p = calloc(sizeof(struct mystruct) * n,1))) {
/* handle error */
}
</code></pre>
<p>Later on, I only have access to <code>p</code>, and no longer have <code>n</code>. Is there a way to determine the length of the array given just the pointer <code>p</code>?</p>
<p>I figure it <em>must</em> be possible, since <code>free(p)</code> does just that. I know <code>malloc()</code> keeps track of how much memory it has allocated, and that's why it knows the length; perhaps there is a way to query for this information? Something like...</p>
<pre><code>int length = askMallocLibraryHowMuchMemoryWasAlloced(p) / sizeof(mystruct)
</code></pre>
<p>I know I should just rework the code so that I know <code>n</code>, but I'd rather not if possible. Any ideas?</p>
|
<p>No, there is no way to get this information without depending strongly on the implementation details of <code>malloc</code>. In particular, <code>malloc</code> may allocate more bytes than you request (e.g. for efficiency in a particular memory architecture). It would be much better to redesign your code so that you keep track of <code>n</code> explicitly. The alternative is <em>at least</em> as much redesign and a much more dangerous approach (given that it's non-standard, abuses the semantics of pointers, and will be a maintenance nightmare for those that come after you): store the length<code>n</code> at the malloc'd address, followed by the array. Allocation would then be:</p>
<pre><code>void *p = calloc(sizeof(struct mystruct) * n + sizeof(unsigned long int),1));
*((unsigned long int*)p) = n;
</code></pre>
<p><code>n</code> is now stored at <code>*((unsigned long int*)p)</code> and the start of your array is now</p>
<pre><code>void *arr = p+sizeof(unsigned long int);
</code></pre>
<p><strong>Edit:</strong> Just to play devil's advocate... I know that these "solutions" all require redesigns, but let's play it out.
Of course, the solution presented above is just a hacky implementation of a (well-packed) struct. You might as well define:</p>
<pre><code>typedef struct {
unsigned int n;
void *arr;
} arrInfo;
</code></pre>
<p>and pass around <code>arrInfo</code>s rather than raw pointers.</p>
<p>Now we're cooking. But as long as you're redesigning, why stop here? What you really want is an abstract data type (ADT). Any introductory text for an algorithms and data structures class would do it. An ADT defines the public interface of a data type but hides the implementation of that data type. Thus, publicly an ADT for an array might look like</p>
<pre><code>typedef void* arrayInfo;
(arrayInfo)newArrayInfo(unsignd int n, unsigned int itemSize);
(void)deleteArrayInfo(arrayInfo);
(unsigned int)arrayLength(arrayInfo);
(void*)arrayPtr(arrayInfo);
...
</code></pre>
<p>In other words, an ADT is a form of data and behavior encapsulation... in other words, it's about as close as you can get to Object-Oriented Programming using straight C. Unless you're stuck on a platform that doesn't have a C++ compiler, you might as well go whole hog and just use an STL <code>std::vector</code>.</p>
<p>There, we've taken a simple question about C and ended up at C++. God help us all.</p>
|
<p>In <a href="http://www.uclibc.org/" rel="nofollow">uClibc</a>, there is a <code>MALLOC_SIZE</code> macro in <a href="http://git.uclibc.org/uClibc/tree/libc/stdlib/malloc/malloc.h#n103" rel="nofollow"><code>malloc.h</code></a>:</p>
<pre><code>/* The size of a malloc allocation is stored in a size_t word
MALLOC_HEADER_SIZE bytes prior to the start address of the allocation:
+--------+---------+-------------------+
| SIZE |(unused) | allocation ... |
+--------+---------+-------------------+
^ BASE ^ ADDR
^ ADDR - MALLOC_HEADER_SIZE
*/
/* The amount of extra space used by the malloc header. */
#define MALLOC_HEADER_SIZE \
(MALLOC_ALIGNMENT < sizeof (size_t) \
? sizeof (size_t) \
: MALLOC_ALIGNMENT)
/* Set up the malloc header, and return the user address of a malloc block. */
#define MALLOC_SETUP(base, size) \
(MALLOC_SET_SIZE (base, size), (void *)((char *)base + MALLOC_HEADER_SIZE))
/* Set the size of a malloc allocation, given the base address. */
#define MALLOC_SET_SIZE(base, size) (*(size_t *)(base) = (size))
/* Return base-address of a malloc allocation, given the user address. */
#define MALLOC_BASE(addr) ((void *)((char *)addr - MALLOC_HEADER_SIZE))
/* Return the size of a malloc allocation, given the user address. */
#define MALLOC_SIZE(addr) (*(size_t *)MALLOC_BASE(addr))
</code></pre>
| 28,799
|
<p>I just read Joel Spolsky's article, <a href="http://www.joelonsoftware.com/articles/fog0000000026.html" rel="nofollow noreferrer">Up the tata without a tutu</a>, where Joel says,</p>
<blockquote>
<p>In those days, there were no
application servers.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>There really weren't any other app
servers in those days.</p>
</blockquote>
<p>So basically, how did people write web apps in those days? Did they write their own implementations of web servers and app servers? And when did companies start coming out with 'standard' web/app servers like Tomcat, JBoss, etc? And can people also share any anecdotes related to this, if there any any? Links to websites also appreciated...</p>
|
<p>Ah, this takes me back. Yes, the very first web applications required writing your own web server. the first ones, like <a href="http://en.wikipedia.org/wiki/CERN_HTTPd" rel="noreferrer">CERN HTTPd</a>, where pretty straightforward programs: they listened on a port for basic connection requests, parsed out the file path, and returned a static file.</p>
<p>Pretty soon after that, people figured out how to fork/exec a program from the HTTP daemon that generated the HTML file, instead of serving it from a static file. Some of these were simple C programs; Perl became popular as well. But something like a banking system (I worked on one of these) would fork the program when a session started, then connect to an existing back end through something like <a href="http://en.wikipedia.org/wiki/CICS" rel="noreferrer">CICS</a> to get data, then generate the output using something like fprintf to send text to the socket connection.</p>
<p>App servers actually arrived when people realized they were writing repeated chunks of code that needed to talk to the back end "data layer" or "persistence layer" <em>and</em> to the front end web server.</p>
|
<p>Your web server would call CGI script, usually (in my experience) written in Perl or C.</p>
<p>I still have a few C-based web apps on my web site, including a fairly primitive forum system. It was pretty painful stuff, looking back - but it worked.</p>
| 47,260
|
<p>I am creating a left navigation system utilizing xml and xsl. Everything was been going great until I tried to use a special character in my xml document. I am using <code>&raquo;</code> and I get th error.</p>
<blockquote>
<p>reason: Reference to undefined entity 'raquo'.<br>
error code: -1072898046</p>
</blockquote>
<p>How do I make this work?</p>
|
<p>You are trying to use an <a href="http://en.wikipedia.org/wiki/SGML_entity" rel="noreferrer">HTML entity</a> in a non-HTML or non-XHTML document. These entities are declared in the document's <a href="http://en.wikipedia.org/wiki/Document_Type_Definition" rel="noreferrer">Document Type Definition (DTD)</a>.</p>
<p>You should use the numerical Unicode version of the <a href="http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references" rel="noreferrer">entity reference</a>. For example, in the case of <code>&raquo;</code> you should use <code>&#187;</code></p>
<p>Alternatively, you can <a href="http://www.w3schools.com/dtd/dtd_entities.asp" rel="noreferrer">define them in your XML document's DTD</a>:</p>
<pre><code><!ENTITY entity-name "entity-value">
<!ENTITY raquo "&#187;">
</code></pre>
<p>Otherwise, if your document is UTF-8, I believe you can just use the actual character directly in your XML document.</p>
<pre><code>»
</code></pre>
|
<p>Are you using the » symbol directly or are you defining it as &raquo; ? If you're using the escaped symbol, did you forget the semicolon?</p>
| 25,667
|
<blockquote>
<h4>Moderator note:</h4>
<p>This question is not a good fit for our question and answer format with the <a href="/help/on-topic">topicality rules</a> which currently apply for Stack Overflow. We normally use a "historical lock" for such questions where the content still has value. However, the answers on this question are actively maintained and a historical lock doesn't permit editing of the answers. As such, a "wiki answer" lock has been applied to allow the answers to be edited. You should assume the topicality issues which are normally handled by a historical lock are present (i.e. this question not a good example of an on-topic question for Stack Overflow).</p>
</blockquote>
<h2>Form-based authentication for websites</h2>
<p>We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. "Form based authentication for websites" should be a fine topic for such an experiment.</p>
<h3>It should include topics such as:</h3>
<ul>
<li>How to log in</li>
<li>How to log out</li>
<li>How to remain logged in</li>
<li>Managing cookies (including recommended settings)</li>
<li>SSL/HTTPS encryption</li>
<li>How to store passwords</li>
<li>Using secret questions</li>
<li>Forgotten username/password functionality</li>
<li>Use of <a href="https://en.wikipedia.org/wiki/Cryptographic_nonce" rel="nofollow noreferrer">nonces</a> to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">cross-site request forgeries (CSRF)</a></li>
<li><a href="http://openid.net/" rel="nofollow noreferrer">OpenID</a></li>
<li>"Remember me" checkbox</li>
<li>Browser autocompletion of usernames and passwords</li>
<li>Secret URLs (public <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> protected by digest)</li>
<li>Checking password strength</li>
<li>E-mail validation</li>
<li><em>and much more about</em> <a href="http://en.wikipedia.org/wiki/Form-based_authentication" rel="nofollow noreferrer">form based authentication</a>...</li>
</ul>
<h3>It should not include things like:</h3>
<ul>
<li>Roles and authorization</li>
<li>HTTP basic authentication</li>
</ul>
<h3>Please help us by:</h3>
<ol>
<li>Suggesting subtopics</li>
<li>Submitting good articles about this subject</li>
<li>Editing the official answer</li>
</ol>
|
<h2>PART I: How To Log In</h2>
<p>We'll assume you already know how to build a login+password HTML form which POSTs the values to a script on the server side for authentication. The sections below will deal with patterns for sound practical auth, and how to avoid the most common security pitfalls.</p>
<p><strong>To HTTPS or not to HTTPS?</strong></p>
<p>Unless the connection is already secure (that is, tunneled through HTTPS using SSL/TLS), your login form values will be sent in cleartext, which allows anyone eavesdropping on the line between browser and web server will be able to read logins as they pass through. This type of wiretapping is done routinely by governments, but in general, we won't address 'owned' wires other than to say this: Just use HTTPS.</p>
<p>In essence, the only <strong>practical</strong> way to protect against wiretapping/packet sniffing during login is by using HTTPS or another certificate-based encryption scheme (for example, <a href="https://en.wikipedia.org/wiki/Transport_Layer_Security" rel="noreferrer">TLS</a>) or a proven & tested challenge-response scheme (for example, the <a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange" rel="noreferrer">Diffie-Hellman</a>-based SRP). <em>Any other method can be easily circumvented</em> by an eavesdropping attacker.</p>
<p>Of course, if you are willing to get a little bit impractical, you could also employ some form of two-factor authentication scheme (e.g. the Google Authenticator app, a physical 'cold war style' codebook, or an RSA key generator dongle). If applied correctly, this could work even with an unsecured connection, but it's hard to imagine that a dev would be willing to implement two-factor auth but not SSL.</p>
<p><strong>(Do not) Roll-your-own JavaScript encryption/hashing</strong></p>
<p>Given the perceived (though now <a href="https://letsencrypt.org/" rel="noreferrer">avoidable</a>) cost and technical difficulty of setting up an SSL certificate on your website, some developers are tempted to roll their own in-browser hashing or encryption schemes in order to avoid passing cleartext logins over an unsecured wire.</p>
<p>While this is a noble thought, it is essentially useless (and can be a <a href="https://stackoverflow.com/questions/1380168/does-it-make-security-sense-to-hash-password-on-client-end">security flaw</a>) unless it is combined with one of the above - that is, either securing the line with strong encryption or using a tried-and-tested challenge-response mechanism (if you don't know what that is, just know that it is one of the most difficult to prove, most difficult to design, and most difficult to implement concepts in digital security).</p>
<p>While it is true that hashing the password <em>can be</em> effective against <strong>password disclosure</strong>, it is vulnerable to replay attacks, Man-In-The-Middle attacks / hijackings (if an attacker can inject a few bytes into your unsecured HTML page before it reaches your browser, they can simply comment out the hashing in the JavaScript), or brute-force attacks (since you are handing the attacker both username, salt and hashed password).</p>
<p><strong>CAPTCHAS against humanity</strong></p>
<p><a href="https://en.wikipedia.org/wiki/CAPTCHA" rel="noreferrer">CAPTCHA</a> is meant to thwart one specific category of attack: automated dictionary/brute force trial-and-error with no human operator. There is no doubt that this is a real threat, however, there are ways of dealing with it seamlessly that don't require a CAPTCHA, specifically properly designed server-side login throttling schemes - we'll discuss those later.</p>
<p>Know that CAPTCHA implementations are not created alike; they often aren't human-solvable, most of them are actually ineffective against bots, all of them are ineffective against cheap third-world labor (according to <a href="https://en.wikipedia.org/wiki/OWASP" rel="noreferrer">OWASP</a>, the current sweatshop rate is $12 per 500 tests), and some implementations may be technically illegal in some countries (see <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a>). If you must use a CAPTCHA, use Google's <a href="https://en.wikipedia.org/wiki/ReCAPTCHA" rel="noreferrer">reCAPTCHA</a>, since it is OCR-hard by definition (since it uses already OCR-misclassified book scans) and tries very hard to be user-friendly.</p>
<p>Personally, I tend to find CAPTCHAS annoying, and use them only as a last resort when a user has failed to log in a number of times and throttling delays are maxed out. This will happen rarely enough to be acceptable, and it strengthens the system as a whole.</p>
<p><strong>Storing Passwords / Verifying logins</strong></p>
<p>This may finally be common knowledge after all the highly-publicized hacks and user data leaks we've seen in recent years, but it has to be said: Do not store passwords in cleartext in your database. User databases are routinely hacked, leaked or gleaned through SQL injection, and if you are storing raw, plaintext passwords, that is instant game over for your login security.</p>
<p>So if you can't store the password, how do you check that the login+password combination POSTed from the login form is correct? The answer is hashing using a <a href="https://en.wikipedia.org/wiki/Key_derivation_function" rel="noreferrer">key derivation function</a>. Whenever a new user is created or a password is changed, you take the password and run it through a KDF, such as Argon2, bcrypt, scrypt or PBKDF2, turning the cleartext password ("correcthorsebatterystaple") into a long, random-looking string, which is a lot safer to store in your database. To verify a login, you run the same hash function on the entered password, this time passing in the salt and compare the resulting hash string to the value stored in your database. Argon2, bcrypt and scrypt store the salt with the hash already. Check out this <a href="https://security.stackexchange.com/a/31846/8340">article</a> on sec.stackexchange for more detailed information.</p>
<p>The reason a salt is used is that hashing in itself is not sufficient -- you'll want to add a so-called 'salt' to protect the hash against <a href="https://en.wikipedia.org/wiki/Rainbow_table" rel="noreferrer">rainbow tables</a>. A salt effectively prevents two passwords that exactly match from being stored as the same hash value, preventing the whole database being scanned in one run if an attacker is executing a password guessing attack.</p>
<p>A cryptographic hash should not be used for password storage because user-selected passwords are not strong enough (i.e. do not usually contain enough entropy) and a password guessing attack could be completed in a relatively short time by an attacker with access to the hashes. This is why KDFs are used - these effectively <a href="https://en.wikipedia.org/wiki/Key_stretching" rel="noreferrer">"stretch the key"</a>, which means that every password guess an attacker makes causes multiple repetitions of the hash algorithm, for example 10,000 times, which causes the attacker to guess the password 10,000 times slower.</p>
<p><strong>Session data - "You are logged in as Spiderman69"</strong></p>
<p>Once the server has verified the login and password against your user database and found a match, the system needs a way to remember that the browser has been authenticated. This fact should only ever be stored server side in the session data.</p>
<blockquote>
<p>If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already.</p>
</blockquote>
<p>If at all possible, make sure the session cookie has the secure and HTTP Only flags set when sent to the browser. The HttpOnly flag provides some protection against the cookie being read through XSS attack. The secure flag ensures that the cookie is only sent back via HTTPS, and therefore protects against network sniffing attacks. The value of the cookie should not be predictable. Where a cookie referencing a non-existent session is presented, its value should be replaced immediately to prevent <a href="https://owasp.org/www-community/attacks/Session_fixation" rel="noreferrer">session fixation</a>.</p>
<p>Session state can also be maintained on the client side. This is achieved by using techniques like JWT (JSON Web Token).</p>
<h2>PART II: How To Remain Logged In - The Infamous "Remember Me" Checkbox</h2>
<p>Persistent Login Cookies ("remember me" functionality) are a danger zone; on the one hand, they are entirely as safe as conventional logins when users understand how to handle them; and on the other hand, they are an enormous security risk in the hands of careless users, who may use them on public computers and forget to log out, and who may not know what browser cookies are or how to delete them.</p>
<p>Personally, I like persistent logins for the websites I visit on a regular basis, but I know how to handle them safely. If you are positive that your users know the same, you can use persistent logins with a clean conscience. If not - well, then you may subscribe to the philosophy that users who are careless with their login credentials brought it upon themselves if they get hacked. It's not like we go to our user's houses and tear off all those facepalm-inducing Post-It notes with passwords they have lined up on the edge of their monitors, either.</p>
<p>Of course, some systems can't afford to have <em>any</em> accounts hacked; for such systems, there is no way you can justify having persistent logins.</p>
<p><strong>If you DO decide to implement persistent login cookies, this is how you do it:</strong></p>
<ol>
<li><p>First, take some time to read <a href="https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence" rel="noreferrer">Paragon Initiative's article</a> on the subject. You'll need to get a bunch of elements right, and the article does a great job of explaining each.</p>
</li>
<li><p>And just to reiterate one of the most common pitfalls, <strong>DO NOT STORE THE PERSISTENT LOGIN COOKIE (TOKEN) IN YOUR DATABASE, ONLY A HASH OF IT!</strong> The login token is Password Equivalent, so if an attacker got their hands on your database, they could use the tokens to log in to any account, just as if they were cleartext login-password combinations. Therefore, use hashing (according to <a href="https://security.stackexchange.com/a/63438/5002">https://security.stackexchange.com/a/63438/5002</a> a weak hash will do just fine for this purpose) when storing persistent login tokens.</p>
</li>
</ol>
<h2>PART III: Using Secret Questions</h2>
<p><strong>Don't implement 'secret questions'</strong>. The 'secret questions' feature is a security anti-pattern. Read the paper from link number 4 from the MUST-READ list. You can ask Sarah Palin about that one, after her Yahoo! email account got hacked during a previous presidential campaign because the answer to her security question was... "Wasilla High School"!</p>
<p>Even with user-specified questions, it is highly likely that most users will choose either:</p>
<ul>
<li><p>A 'standard' secret question like mother's maiden name or favorite pet</p>
</li>
<li><p>A simple piece of trivia that anyone could lift from their blog, LinkedIn profile, or similar</p>
</li>
<li><p>Any question that is easier to answer than guessing their password. Which, for any decent password, is every question you can imagine</p>
</li>
</ul>
<p><strong>In conclusion, security questions are inherently insecure in virtually all their forms and variations, and should not be employed in an authentication scheme for any reason.</strong></p>
<p>The true reason why security questions even exist in the wild is that they conveniently save the cost of a few support calls from users who can't access their email to get to a reactivation code. This at the expense of security and Sarah Palin's reputation. Worth it? Probably not.</p>
<h2>PART IV: Forgotten Password Functionality</h2>
<p>I already mentioned why you should <strong>never use security questions</strong> for handling forgotten/lost user passwords; it also goes without saying that you should never e-mail users their actual passwords. There are at least two more all-too-common pitfalls to avoid in this field:</p>
<ol>
<li><p>Don't <em>reset</em> a forgotten password to an autogenerated strong password - such passwords are notoriously hard to remember, which means the user must either change it or write it down - say, on a bright yellow Post-It on the edge of their monitor. Instead of setting a new password, just let users pick a new one right away - which is what they want to do anyway. (An exception to this might be if the users are universally using a password manager to store/manage passwords that would normally be impossible to remember without writing it down).</p>
</li>
<li><p>Always hash the lost password code/token in the database. <em><strong>AGAIN</strong></em>, this code is another example of a Password Equivalent, so it MUST be hashed in case an attacker got their hands on your database. When a lost password code is requested, send the plaintext code to the user's email address, then hash it, save the hash in your database -- and <em>throw away the original</em>. Just like a password or a persistent login token.</p>
</li>
</ol>
<p>A final note: always make sure your interface for entering the 'lost password code' is at least as secure as your login form itself, or an attacker will simply use this to gain access instead. Making sure you generate very long 'lost password codes' (for example, 16 case-sensitive alphanumeric characters) is a good start, but consider adding the same throttling scheme that you do for the login form itself.</p>
<h2>PART V: Checking Password Strength</h2>
<p>First, you'll want to read this small article for a reality check: <a href="http://www.whatsmypass.com/?p=415" rel="noreferrer">The 500 most common passwords</a></p>
<p>Okay, so maybe the list isn't the <em>canonical</em> list of most common passwords on <em>any</em> system <em>anywhere ever</em>, but it's a good indication of how poorly people will choose their passwords when there is no enforced policy in place. Plus, the list looks frighteningly close to home when you compare it to publicly available analyses of recently stolen passwords.</p>
<p>So: With no minimum password strength requirements, 2% of users use one of the top 20 most common passwords. Meaning: if an attacker gets just 20 attempts, 1 in 50 accounts on your website will be crackable.</p>
<p>Thwarting this requires calculating the entropy of a password and then applying a threshold. The National Institute of Standards and Technology (NIST) <a href="https://en.wikipedia.org/wiki/Password_strength#NIST_Special_Publication_800-63" rel="noreferrer">Special Publication 800-63</a> has a set of very good suggestions. That, when combined with a dictionary and keyboard layout analysis (for example, 'qwertyuiop' is a bad password), can <a href="https://cubicspot.blogspot.com/2012/01/how-to-calculate-password-strength-part.html" rel="noreferrer">reject 99% of all poorly selected passwords</a> at a level of 18 bits of entropy. Simply calculating password strength and <a href="https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" rel="noreferrer">showing a visual strength meter</a> to a user is good, but insufficient. Unless it is enforced, a lot of users will most likely ignore it.</p>
<p>And for a refreshing take on user-friendliness of high-entropy passwords, Randall Munroe's <a href="https://xkcd.com/936/" rel="noreferrer">Password Strength xkcd</a> is highly recommended.</p>
<p>Utilize Troy Hunt's <a href="https://haveibeenpwned.com/API/" rel="noreferrer">Have I Been Pwned API</a> to check users passwords against passwords compromised in public data breaches.</p>
<h2>PART VI: Much More - Or: Preventing Rapid-Fire Login Attempts</h2>
<p>First, have a look at the numbers: <a href="https://www.lockdown.co.uk/?pg=combi&s=articles" rel="noreferrer">Password Recovery Speeds - How long will your password stand up</a></p>
<p>If you don't have the time to look through the tables in that link, here's the list of them:</p>
<ol>
<li><p>It takes <em>virtually no time</em> to crack a weak password, even if you're cracking it with an abacus</p>
</li>
<li><p>It takes <em>virtually no time</em> to crack an alphanumeric 9-character password if it is <strong>case insensitive</strong></p>
</li>
<li><p>It takes <em>virtually no time</em> to crack an intricate, symbols-and-letters-and-numbers, upper-and-lowercase password if it is <strong>less than 8 characters long</strong> (a desktop PC can search the entire keyspace up to 7 characters in a matter of days or even hours)</p>
</li>
<li><p><strong>It would, however, take an inordinate amount of time to crack even a 6-character password, <em>if you were limited to one attempt per second!</em></strong></p>
</li>
</ol>
<p>So what can we learn from these numbers? Well, lots, but we can focus on the most important part: the fact that preventing large numbers of rapid-fire successive login attempts (ie. the <em>brute force</em> attack) really isn't that difficult. But preventing it <em>right</em> isn't as easy as it seems.</p>
<p>Generally speaking, you have three choices that are all effective against brute-force attacks <em>(and dictionary attacks, but since you are already employing a strong passwords policy, they shouldn't be an issue)</em>:</p>
<ul>
<li><p>Present a <strong>CAPTCHA</strong> after N failed attempts (annoying as hell and often ineffective -- but I'm repeating myself here)</p>
</li>
<li><p><strong>Locking accounts</strong> and requiring email verification after N failed attempts (this is a <a href="https://en.wikipedia.org/wiki/Denial-of-service_attack" rel="noreferrer">DoS</a> attack waiting to happen)</p>
</li>
<li><p>And finally, <strong>login throttling</strong>: that is, setting a time delay between attempts after N failed attempts (yes, DoS attacks are still possible, but at least they are far less likely and a lot more complicated to pull off).</p>
</li>
</ul>
<p><strong>Best practice #1:</strong> A short time delay that increases with the number of failed attempts, like:</p>
<ul>
<li>1 failed attempt = no delay</li>
<li>2 failed attempts = 2 sec delay</li>
<li>3 failed attempts = 4 sec delay</li>
<li>4 failed attempts = 8 sec delay</li>
<li>5 failed attempts = 16 sec delay</li>
<li>etc.</li>
</ul>
<p>DoS attacking this scheme would be very impractical, since the resulting lockout time is slightly larger than the sum of the previous lockout times.</p>
<blockquote>
<p>To clarify: The delay is <em>not</em> a delay before returning the response to the browser. It is more like a timeout or refractory period during which login attempts to a specific account or from a specific IP address will not be accepted or evaluated at all. That is, correct credentials will not return in a successful login, and incorrect credentials will not trigger a delay increase.</p>
</blockquote>
<p><strong>Best practice #2:</strong> A medium length time delay that goes into effect after N failed attempts, like:</p>
<ul>
<li>1-4 failed attempts = no delay</li>
<li>5 failed attempts = 15-30 min delay</li>
</ul>
<p>DoS attacking this scheme would be quite impractical, but certainly doable. Also, it might be relevant to note that such a long delay can be very annoying for a legitimate user. Forgetful users will dislike you.</p>
<p><strong>Best practice #3:</strong> Combining the two approaches - either a fixed, short time delay that goes into effect after N failed attempts, like:</p>
<ul>
<li>1-4 failed attempts = no delay</li>
<li>5+ failed attempts = 20 sec delay</li>
</ul>
<p>Or, an increasing delay with a fixed upper bound, like:</p>
<ul>
<li>1 failed attempt = 5 sec delay</li>
<li>2 failed attempts = 15 sec delay</li>
<li>3+ failed attempts = 45 sec delay</li>
</ul>
<p>This final scheme was taken from the OWASP best-practices suggestions (link 1 from the MUST-READ list) and should be considered best practice, even if it is admittedly on the restrictive side.</p>
<blockquote>
<p><em>As a rule of thumb, however, I would say: the stronger your password policy is, the less you have to bug users with delays. If you require strong (case-sensitive alphanumerics + required numbers and symbols) 9+ character passwords, you could give the users 2-4 non-delayed password attempts before activating the throttling.</em></p>
</blockquote>
<p>DoS attacking this final login throttling scheme would be <em><strong>very</strong></em> impractical. And as a final touch, always allow persistent (cookie) logins (and/or a CAPTCHA-verified login form) to pass through, so legitimate users won't even be delayed <em>while the attack is in progress</em>. That way, the very impractical DoS attack becomes an <em>extremely</em> impractical attack.</p>
<p>Additionally, it makes sense to do more aggressive throttling on admin accounts, since those are the most attractive entry points</p>
<h2>PART VII: Distributed Brute Force Attacks</h2>
<p>Just as an aside, more advanced attackers will try to circumvent login throttling by 'spreading their activities':</p>
<ul>
<li><p>Distributing the attempts on a botnet to prevent IP address flagging</p>
</li>
<li><p>Rather than picking one user and trying the 50.000 most common passwords (which they can't, because of our throttling), they will pick THE most common password and try it against 50.000 users instead. That way, not only do they get around maximum-attempts measures like CAPTCHAs and login throttling, their chance of success increases as well, since the number 1 most common password is far more likely than number 49.995</p>
</li>
<li><p>Spacing the login requests for each user account, say, 30 seconds apart, to sneak under the radar</p>
</li>
</ul>
<p>Here, the best practice would be <strong>logging the number of failed logins, system-wide</strong>, and using a running average of your site's bad-login frequency as the basis for an upper limit that you then impose on all users.</p>
<p>Too abstract? Let me rephrase:</p>
<p>Say your site has had an average of 120 bad logins per day over the past 3 months. Using that (running average), your system might set the global limit to 3 times that -- ie. 360 failed attempts over a 24 hour period. Then, if the total number of failed attempts across all accounts exceeds that number within one day (or even better, monitor the rate of acceleration and trigger on a calculated threshold), it activates system-wide login throttling - meaning short delays for ALL users (still, with the exception of cookie logins and/or backup CAPTCHA logins).</p>
<p>I also posted a question with <a href="https://stackoverflow.com/questions/479233/what-is-the-best-distributed-brute-force-countermeasure">more details and a really good discussion of how to avoid tricky pitfals</a> in fending off distributed brute force attacks</p>
<h2>PART VIII: Two-Factor Authentication and Authentication Providers</h2>
<p>Credentials can be compromised, whether by exploits, passwords being written down and lost, laptops with keys being stolen, or users entering logins into phishing sites. Logins can be further protected with two-factor authentication, which uses out-of-band factors such as single-use codes received from a phone call, SMS message, app, or dongle. Several providers offer two-factor authentication services.</p>
<p>Authentication can be completely delegated to a single-sign-on service, where another provider handles collecting credentials. This pushes the problem to a trusted third party. Google and Twitter both provide standards-based SSO services, while Facebook provides a similar proprietary solution.</p>
<h2>MUST-READ LINKS About Web Authentication</h2>
<ol>
<li><a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Guide To Authentication</a> / <a href="https://www.owasp.org/index.php/Authentication_Cheat_Sheet" rel="noreferrer">OWASP Authentication Cheat Sheet</a></li>
<li><a href="https://pdos.csail.mit.edu/papers/webauth:sec10.pdf" rel="noreferrer">Dos and Don’ts of Client Authentication on the Web (very readable MIT research paper)</a></li>
<li><a href="https://en.wikipedia.org/wiki/HTTP_cookie#Drawbacks_of_cookies" rel="noreferrer">Wikipedia: HTTP cookie</a></li>
<li><a href="https://cups.cs.cmu.edu/soups/2008/proceedings/p13Rabkin.pdf" rel="noreferrer">Personal knowledge questions for fallback authentication: Security questions in the era of Facebook (very readable Berkeley research paper)</a></li>
</ol>
|
<p>Use <a href="http://openid.net/connect/" rel="noreferrer">OpenID Connect</a> or <a href="https://kantarainitiative.org/confluence/display/uma/Home" rel="noreferrer">User-Managed Access</a>.</p>
<p>As nothing is more efficient than not doing it at all.</p>
| 2,296
|
<p>I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page. </p>
<p>Since they are coming from a variety of ways, I am just curious as to the <strong>best</strong> way to <strong>redirect</strong> the user back to the calling page. I have some ideas, but would like to get other developers input.</p>
<p>Would you store the <strong>calling</strong> url in session? as a cookie? I like the concept of using an object <strong>handle</strong> the redirection.</p>
|
<p>I would store the referring URL using the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx" rel="noreferrer">ViewState</a>. Storing this outside the scope of the page (i.e. in the Session state or cookie) may cause problems if more than one browser window is open.</p>
<p>The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response.</p>
<pre><code>public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//Handle the case where the page is requested directly
throw new Exception("This page has been called without a referring page");
}
if (!IsPostBack)
{
ReturnUrl = Request.UrlReferrer.PathAndQuery;
}
}
public string ReturnUrl
{
get { return ViewState["returnUrl"].ToString(); }
set { ViewState["returnUrl"] = value; }
}
protected void btn_Click(object sender, EventArgs e)
{
//Do what you need to do to save the page
//...
//Go back to calling page
Response.Redirect(ReturnUrl, true);
}
}
</code></pre>
|
<p>I personally would store the required redirection info in an object and handle globally. I would avoid using a QueryString param or the like since they could try bouncing themselves back to a page they are not supposed to (possible security issue?). You could then create a static method to handle the redirection object, which could read the information and act accordingly. This encapsulates your redirection process within one page.</p>
<p>Using an object also means you can later extend it if required (such as adding return messages and other info).</p>
<p>For example (this is a 2 minute rough guideline BTW!):</p>
<pre><code>public partial class _Default : System.Web.UI.Page
{
void Redirect(string url, string messsage)
{
RedirectionParams paras = new RedirectionParams(url, messsage);
RedirectionHandler(paras); // pass to some global method (or this could BE the global method)
}
protected void Button1_Click(object sender, EventArgs e)
{
Redirect("mypage.aspx", "you have been redirected");
}
}
public class RedirectionParams
{
private string _url;
public string URL
{
get { return _url; }
set { _url = value; }
}
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
public RedirectionParams(string url, string message)
{
this.URL = url;
this.Message = message;
}
}
</code></pre>
| 5,734
|
<p>I'm new to RhinoMock's just been doing state unit testing up till now.</p>
<p>How do you test void functions?</p>
<p>Getting the following complie error when setting up expectation,</p>
<p><em>Expression does not produce a value</em></p>
<p>Basically I want to test that a certain mock's method is called a certain amount of times.</p>
<p>Cheers</p>
|
<p>You want to use LastCall.</p>
<p><a href="http://ayende.com/projects/rhino-mocks/api/files/LastCall-cs.html" rel="nofollow noreferrer">http://ayende.com/projects/rhino-mocks/api/files/LastCall-cs.html</a></p>
|
<p>Better yet, you can use the Expect.Call method with a lambda:</p>
<pre><code>Expect.Call(() => someVoidFunction());
</code></pre>
| 46,950
|
<p>I've started to add the time taken to render a page to the footer of our internal web applications. Currently it appears like this</p>
<blockquote>
<p>Rendered in 0.062 seconds</p>
</blockquote>
<p>Occasionally I get rendered times like this</p>
<blockquote>
<p>Rendered in 0.000 seconds</p>
</blockquote>
<p>Currently it's only meant to be a guide for users to judge whether a page is quick to load or not, allowing them to quickly inform us if a page is taking 17 seconds rather than the usual 0.5. My question is what format should the time be in? At which point should I switch to a statement such as</p>
<blockquote>
<p>Rendered in less than a second</p>
</blockquote>
<p>I like seeing the tenths of a second but the second example above is of no use to anyone, in fact it just highlights the limits of the calculation I use to find the render time. I'd rather not let the users see that at all! Any answers welcome, including whether anything should be included on the page.</p>
|
<p>"Rendered instantly" sounds way better than "Rendered in less than a second".</p>
|
<p>I think I over-emphasized it was for the users.</p>
<p>I know by using in trace in the web.config I can get accurate information on page render times along with times for accessing the database.</p>
<p>We have in the past had problems with applications running too slowly over the network although it's now fixed I'm adding the label to new applications so that users are aware it is something we are taking seriously and it's a very simple indicator for the developers.</p>
<p>Taking all that into account I like "Rendered Instantly" and write a lot of sense so I'll accept both your answer and kokos'. </p>
<p>Thanks</p>
| 3,006
|
<p>I've made this decorator, which results in an infinite redirect loop.</p>
<p>The problem is this: </p>
<pre><code>args[0].redirect(users.create_login_url(args[0].request.path))
</code></pre>
<p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p>
<pre><code>def admin_only(handler, *args):
def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted to enter an authorized page')
return redirect_to_login
else:
return redirect_to_login
</code></pre>
|
<p>It seems that you aren't defining your decorator properly.</p>
<p>A decorator is called only <strong>once</strong> every time you wrap a function with it; from then on the function that the decorator <strong>returned</strong> will be called. It seems that you (mistakenly) believe that the decorator function <strong>itself</strong> will be called every time.</p>
<p>Try something like this instead:</p>
<pre><code>def redirect_to_login(*args, **kwargs):
return args[0].redirect(users.create_login_url(args[0].request.path))
def admin_only(handler):
def wrapped_handler(*args, **kwargs):
user = users.get_current_user()
if user:
if authorized(user):
return handler(args[0])
else:
logging.warning('An unauthorized user has attempted '
'to enter an authorized page')
return redirect_to_login(*args, **kwargs)
else:
return redirect_to_login(*args, **kwargs)
return wrapped_handler
</code></pre>
<p>Note that in the above code, the decorator just defines a new function and returns it, and this new function itself does the relevant checks.</p>
|
<p>Are you sure proper status code is being sent, you can use live http headers add-on for firefox to check whether 301 or 303 is being sent or not.</p>
| 43,228
|
<p>I have an application that runs as a child application in a virtual directory.</p>
<p>I want to pass a value from the parent application, but I believe that Session is keyed per application, and won't work.</p>
<p>To further complicate things, the parent application is WebForms, while the child is NVelocity MVC.</p>
<p>Does anyone know a trick that allows me to use some sort of Session type functionality between virtual applications?</p>
<p>EDIT: A webservice isn't really what I had in mind, all I need to do is pass the logged in users username to the child app. Besides, if calling a webservice back on the parent, I won't get the same session, so I won't know what user.</p>
|
<p>Sounds like web service is the way to go. You could do something like the following:</p>
<ul>
<li>Have the WebForms app create some data in its database with a key of some kind associated to it.</li>
<li>Pass that key in the URL to the NVelocity MVC application.</li>
<li>Allow the NVMVC application to call a web service (REST,XML-RPC,SOAP,whatever) on the WebForms app using the key that was passed.</li>
</ul>
<p>This will get around any kind of session keying or cookie-domain problem you may have and allow you to pass some nicely structured data.</p>
|
<p>You can do a server-side HTTP Request, it looks something like this in C#:</p>
<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create("/ASPSession.ASP?SessionVar=" + SessionVarName);
req.Headers.Add("Cookie: " + SessionCookieName + "=" + SessionCookieValue);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream receiveStream = resp.GetResponseStream();
System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(receiveStream, encode);
string response = readStream.ReadToEnd();
resp.Close();
readStream.Close();
return response;
</code></pre>
<p>On the ASP side, I just verify that the request only comes from localhost, to prevent XSS-style attacks, and then the response is just the value of the Session variable.</p>
<p>Finding the cookie is easy enough, Session cookies all have similar names, so just examine the cookies collection until you find the appropriate cookie. Note, this does only work if the cookies are valid on the entire domain, and not just on the subfolder your are on.</p>
| 9,343
|
<p>...I have read a few threads on here that have discussed various methods and was just looking for some feedback on a proposed solution we came up with. In one of the threads a comment was posted recommending a public/private key which sounded great, this is what we were thinking...</p>
<p>Client Side -
1. Key is stored inside of Flash swf which is encrypted using 3rd party tool.
2. High score is hashed along with high-score value (EX: md5 ('ourSecretKey' + 200))
3. This value is sent via AMF to a PHP script on the server, along with the high-score (200)</p>
<p>Server Side -
1. Server receives data and hashes the passed high-score (200) + secret key ('ourSecretKey' stored on the server as well as in Flash) and checks against the passed hash if the value is a match it allows the high-score to be entered, else FAIL.</p>
<p>I know this isn't a foolproof solution but would this be acceptable? I mean would this be sufficient security on a high-score form for a simple online Flash game? Thoughts?</p>
<p>Thank you in advance!</p>
|
<p>For a ridiculously short value ( Ie: values < 64 characters ), MD5 as a hash becomes ineffective due to rainbow table attacks, and as the value you're sending will be shared over the wire, all they have to do is brute force the shared secret ( and they have a known product to work with ) </p>
<p>As such, thats not public key private key. its mererly shared secret. </p>
<p>Also, keep in mind this shared secret will be in your flash file you send to the user, which these days and be trivially disassembled and then your "secret" is not a secret any more. </p>
<p>You want a more challenge-response mechanism with proper crypto signing, where a new sign key is assigned for every game from the server, and multiple scores cannot be submitted with the same sign key. ( For extra protection ;) ) </p>
<ol>
<li>User starts game. Sign key is requested. ( the sign key is produced from another key which they cant access ).</li>
<li>Score is signed with sign key, and then sent </li>
<li>You verify the value of the sign with the key you sent them. </li>
<li>You discard the sign key you sent them. </li>
</ol>
<p>However, you <em>still</em> have the problem where you have no way to prevent the actual scoring system being tampered with. Somebody smart enough could just reverse engineer your SWF object and inject new code that just sets the score to their chosen value. </p>
|
<p>Wow</p>
<p>Pretty hard solutions 8). </p>
<p>I implemented system like this once. Although it won`t work for every game out there...</p>
<p>You should replay the game on server. When user play -- you store "state changes" and then simply feed it to you game in some kind of "replay" mode.</p>
| 38,962
|
<p>I am getting into strange situation regarding the RSS viewer on SharePoint</p>
<p>I have two environments of SharePoint (production & testing)</p>
<p>I was showing a specific RSS news (ABC) on both of them , and it was working after setting the proxies and other stuff.</p>
<p>Suddenly (may be due to some changes done on the production without testing), the RSS viewer on the production is not showing the RSS news it is showing protocol error, while it is still working fine on the testing environment.</p>
<p>Now the strange part is if I change the RSS of the one our management wants and put BBC or CNN news these works well on both the production and the test environment.</p>
<p>But the one we want it to work (which was working fine on both) do not work on the production and works fine on testing.</p>
<p>Any suggestions of how can I figure it out?</p>
|
<p>On top of the official Apple resources listed in the post arul linked to, here are some other good reads on the topic:<br><br>
<a href="http://web.archive.org/web/20060418151507/http://www.stepwise.com/Articles/Technical/HoldMe.html" rel="nofollow noreferrer">Hold me, use me, free me</a><br>
<a href="http://www.cocoadev.com/index.pl?MemoryManagement" rel="nofollow noreferrer">
CocoaDev.com 's Memory Management Section</a><br><br>
And for help debugging memory management problems:<br>
<a href="http://www.cocoadev.com/index.pl?NSZombieEnabled" rel="nofollow noreferrer">
NSZombieEnabled</a></p>
|
<p>I used the Memory Management video training course from the <a href="http://www.macdevnet.com" rel="nofollow noreferrer">Mac Developer Network</a>. Gave me exactly what I needed when I was starting out. It immediately paid benefits when I started having my own memory management problems. </p>
| 48,392
|
<p>A little while ago I managed to get Visual Studio 2008 (C++) into a state where, if I would select a keyword (or any symbol for that matter), by either double clicking on it or highlighting it, all other instances of that symbol within the current file would become highlighted too.</p>
<p>This was a really useful feature.</p>
<p>Since then it's gone away, and I don't know how to get it back.</p>
<p>Please help.</p>
<p>@Sander - that'll be it. Thanks!</p>
|
<p>I think you've installed <a href="http://www.hanselman.com/blog/IntroducingRockScroll.aspx" rel="noreferrer">RockScroll</a>. It also lights them up in the graphical scrollbar (its main feature)</p>
|
<p>There is something called "<strong>WordLight</strong>" by Mikhail Nasyrov.
An add-in for Visual Studio 2008 that highlights all occurrences of a selected text.
It searches and highlights substrings that are currently selected in a text editor.
Can be found at below link
<a href="https://marketplace.visualstudio.com/items?itemName=MikhailNasyrov.WordLight" rel="nofollow noreferrer">WordLight</a></p>
<p><a href="https://marketplace.visualstudio.com/items?itemName=MikhailNasyrov.WordLight" rel="nofollow noreferrer">https://marketplace.visualstudio.com/items?itemName=MikhailNasyrov.WordLight</a></p>
| 16,063
|
<p>I'm trying to get the unitpngfix to work but I can't seem to get the png to show up in IE6.</p>
<p>This this my code:</p>
<pre><code><html>
<head>
<style type="text/css">
#boxouter {
width: 12em;
height: 12em;
background: url(gradient.gif) #ffdf00 bottom repeat-x;
position: relative;
}
#boxinnerbr {
position: absolute;
bottom: 0;
right: 0;
width: 16px;
height: 16px;
background: url(corner.png);
}
</style>
<!--[if lt IE 7]>
<script type="text/javascript" src="unitpngfix.js"></script>
<![endif]-->
</head>
<body>
<div id="boxouter">
<div id="boxinnerbr"></div>
</div>
</body>
</html>
</code></pre>
<p>I've got the clear.gif in the right place and linked to properly etc, so I just can't understand why it isn't working.</p>
|
<p>I also had some problems with unitpngfix and I really dislike using the [if lt IE 7] and embedding styles in the html.
I found <a href="http://jquery.andreaseberhard.de/pngFix/" rel="nofollow noreferrer">this</a> jQuery plugin wich is unobtrusive and works well with PNG images and css backgrounds in IE6.</p>
|
<p>try</p>
<pre><code>background-image: url(corner.png);
</code></pre>
| 48,941
|
<p>Has anyone out there actually used inversion of control containers <em>within</em> compiler implementations yet? I know that by design, compilers need to be very fast, but I've always been curious about how IoC/DI could affect the construction of a programming language--hot-swappable syntaxes, anyone?</p>
|
<p>Lisp-style languages often do this. <a href="http://www.psg.com/~dlamkins/sl/chapter03-12.html" rel="nofollow noreferrer">Reader macros</a> are pieces of user-written code which extend the reader (and hence, the syntax) of a language. Plain-old macros are pieces of user-written code which also extend the language.</p>
<p>The entire syntaxes aren't hot-swappable, but certain pieces are extendable in various ways.</p>
<p>All this isn't a new idea. Before it was deemed worthy of a three-letter acronym, IoC was known as "late binding", and pretty agreed on as a Good Idea.</p>
|
<p>I wouldn't really call it <em>inversion</em> of control because it's natural for compilers. They are usually a series of passes that transform code in the input language to code in the output language. You can, of course, swap in a different pass (for example, gcc compiles multiple languages by using a different frontend).</p>
| 49,379
|
<p>Is there a tag in HTML that will only display its content if JavaScript is enabled? I know <code><noscript></code> works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they don't have it.</p>
<p>The only way I know how to do this is with the <code>document.write();</code> method in a script tag, and it seems a bit messy for large amounts of HTML.</p>
|
<p>Easiest way I can think of:</p>
<pre><code><html>
<head>
<noscript><style> .jsonly { display: none } </style></noscript>
</head>
<body>
<p class="jsonly">You are a JavaScript User!</p>
</body>
</html>
</code></pre>
<p>No document.write, no scripts, pure CSS.</p>
|
<p><a href="http://weblogs.asp.net/alex_papadimoulis/archive/2008/02/21/scriptonly-the-opposite-of-a-noscript.aspx" rel="nofollow noreferrer">Alex's article</a> springs to mind here, however it's only applicable if you're using ASP.NET - it could be emulated in JavaScript however but again you'd have to use document.write();</p>
| 5,023
|
<p>I've been working with <a href="http://www.microsoft.com/Sqlserver/" rel="nofollow noreferrer">Microsoft SQL Server</a> with many years now but have only just recently started to use <a href="http://www.mysql.com/" rel="nofollow noreferrer">MySQL</a> with my web applications, and I'm hungry for knowledge.</p>
<p>To continue with the long line of <a href="https://stackoverflow.com/questions/tagged/hidden-features">"hidden feature" questions</a>, I would like to know any hidden or handy features of MySQL which will hopefully improve my knowledge of this open source database.</p>
|
<p>Since you put up a bounty, I'll share my hard won secrets...</p>
<p>In general, all the SQLs I tuned today required using sub-queries. Having come from Oracle database world, things I took for granted weren’t working the same with MySQL. And my reading on MySQL tuning makes me conclude that MySQL is behind Oracle in terms of optimizing queries. </p>
<p>While the simple queries required for most B2C applications may work well for MySQL, most of the aggregate reporting type of queries needed for Intelligence Reporting seems to require a fair bit of planning and re-organizing the SQL queries to guide MySQL to execute them faster.</p>
<h1>Administration:</h1>
<p><code>max_connections</code> is the number of concurrent connections. The default value is 100 connections (151 since 5.0) - very small.</p>
<p>Note: </p>
<p>connections take memory and your OS might not be able to handle a lot of connections. </p>
<p>MySQL binaries for Linux/x86 allow you to have up to 4096 concurrent connections, but self compiled binaries often have less of a limit.</p>
<p>Set table_cache to match the number of your open tables and concurrent connections. Watch the open_tables value and if it is growing quickly you will need to increase its size.</p>
<p>Note: </p>
<p>The 2 previous parameters may require a lot of open files. 20+max_connections+table_cache*2 is a good estimate for what you need. MySQL on Linux has an open_file_limit option, set this limit.</p>
<p>If you have complex queries sort_buffer_size and tmp_table_size are likely to be very important. Values will depend on the query complexity and available resources, but 4Mb and 32Mb, respectively are recommended starting points.</p>
<p>Note: These are "per connection" values, among read_buffer_size, read_rnd_buffer_size and some others, meaning that this value might be needed for each connection. So, consider your load and available resource when setting these parameters. For example sort_buffer_size is allocated only if MySQL needs to do a sort. Note: be careful not to run out of memory.</p>
<p>If you have many connects established (i.e. a web site without persistent connections) you might improve performance by setting thread_cache_size to a non-zero value. 16 is good value to start with. Increase the value until your threads_created do not grow very quickly.</p>
<h1>PRIMARY KEY:</h1>
<p>There can be only one AUTO_INCREMENT column per table, it must be indexed, and it cannot have a DEFAULT value</p>
<p>KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.</p>
<p>A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL</p>
<p>If a PRIMARY KEY or UNIQUE index consists of only one column that has an integer type,
you can also refer to the column as "_rowid" in SELECT statements.</p>
<p>In MySQL, the name of a PRIMARY KEY is PRIMARY</p>
<p>Currently, only InnoDB (v5.1?) tables support foreign keys.</p>
<p>Usually, you create all the indexes you need when you are creating tables.
Any column declared as PRIMARY KEY, KEY, UNIQUE, or INDEX will be indexed.</p>
<p>NULL means "not having a value". To test for NULL, you <em>cannot</em> use the arithmetic comparison operators such as =, <, or <>. Use the IS NULL and IS NOT NULL operators instead:</p>
<p>NO_AUTO_VALUE_ON_ZERO suppresses auto increment for 0 so that only NULL generates the next sequence number. This mode can be useful if 0 has been stored in a table's AUTO_INCREMENT column. (Storing 0 is not a recommended practice, by the way.)</p>
<p>To change the value of the AUTO_INCREMENT counter to be used for new rows:</p>
<pre><code>ALTER TABLE mytable AUTO_INCREMENT = value;
</code></pre>
<p>or
SET INSERT_ID = value;</p>
<p>Unless otherwise specified, the value will begin with: 1000000 or specify it thus:</p>
<p>...) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1</p>
<h1>TIMESTAMPS:</h1>
<p>Values for TIMESTAMP columns are converted from the current time zone to UTC for storage,
and from UTC to the current time zone for retrieval.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/timestamp.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/timestamp.html</a>
For one TIMESTAMP column in a table, you can assign the current timestamp as the default value and the auto-update value.</p>
<p>one thing to watch out for when using one of these types in a WHERE clause, it is best to do
WHERE datecolumn = FROM_UNIXTIME(1057941242)
and not
WHERE UNIX_TIMESTAMP(datecolumn) = 1057941242.
doing the latter won't take advantage of an index on that column.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html</a></p>
<pre><code> UNIX_TIMESTAMP()
FROM_UNIXTIME()
UTC_DATE()
UTC_TIME()
UTC_TIMESTAMP()
</code></pre>
<p>if you convert a datetime to unix timestamp in MySQL:<br>
And then add 24 hours to it:<br>
And then convert it back to a datetime it magically loses an hour!</p>
<p>Here's what's happening. When converting the unix timestamp back to a datetime the timezone is taken into consideration and it just so happens that between the 28th and the 29th of October 2006 we went off daylight savings time and lost an hour. </p>
<p>Beginning with MySQL 4.1.3, the CURRENT_TIMESTAMP(), CURRENT_TIME(), CURRENT_DATE(), and FROM_UNIXTIME() functions return values in the connection's <em>current time zone</em>, which is available as the value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the current time zone.</p>
<p>The current time zone setting does not affect values displayed by functions such as UTC_TIMESTAMP() or values in DATE, TIME, or DATETIME columns.</p>
<p>NOTE: ON UPDATE <em>ONLY</em> updates the DateTime if a field is changed If an UPDATE results in no fields being changed then the DateTime is NOT updated!</p>
<p>Addtionally, the First TIMESTAMP is always AUTOUPDATE by default even if not specified</p>
<p>When working with Dates, I almost always convet to Julian Date becuase Data math is then a simple matter of adding or subtracing integers, and Seconds since Midnight for the same reason. It is rare I need time resoultion of finer granularity than seconds.</p>
<p>Both these can be stored as a 4 byte integer, and if space is really tight can be combined into UNIX time (seconds since the epoch 1/1/1970) as an unsigned integer which will be good till around 2106 as:</p>
<p>' secs in 24Hrs = 86400</p>
<p>' Signed Integer max val = 2,147,483,647 - can hold 68 years of Seconds </p>
<p>' Unsigned Integer max val = 4,294,967,295 - can hold 136 years of Seconds</p>
<h1>Binary Protocol:</h1>
<p>MySQL 4.1 introduced a binary protocol that allows non-string data values to be sent
and returned in native format without conversion to and from string format. (Very usefull) </p>
<p>Aside, mysql_real_query() is faster than mysql_query() because it does not call strlen()
to operate on the statement string. </p>
<p><a href="http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html" rel="nofollow noreferrer">http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html</a>
The binary protocol supports server-side prepared statements and allows transmission of data values in native format. The binary protocol underwent quite a bit of revision during the earlier releases of MySQL 4.1. </p>
<p>You can use the IS_NUM() macro to test whether a field has a numeric type.
Pass the type value to IS_NUM() and it evaluates to TRUE if the field is numeric:</p>
<p>One thing to note is that binary data <em>CAN</em> be sent inside a regular query if you escape it and remember MySQL requires <em>only</em> that backslash and the quote character be escaped.
So that is a really easy way to INSERT shorter binary strings like encrypted/Salted passwords for example.</p>
<h1>Master Server:</h1>
<p><a href="http://www.experts-exchange.com/Database/MySQL/Q_22967482.html" rel="nofollow noreferrer">http://www.experts-exchange.com/Database/MySQL/Q_22967482.html</a></p>
<p><a href="http://www.databasejournal.com/features/mysql/article.php/10897_3355201_2" rel="nofollow noreferrer">http://www.databasejournal.com/features/mysql/article.php/10897_3355201_2</a></p>
<p>GRANT REPLICATION SLAVE ON <em>.</em> to slave_user IDENTIFIED BY 'slave_password'</p>
<pre><code>#Master Binary Logging Config STATEMENT causes replication
to be statement-based - default
log-bin=Mike
binlog-format=STATEMENT
server-id=1
max_binlog_size = 10M
expire_logs_days = 120
#Slave Config
master-host=master-hostname
master-user=slave-user
master-password=slave-password
server-id=2
</code></pre>
<p>Binary Log File must read:</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/binary-log.html</a></p>
<p><a href="http://www.mydigitallife.info/2007/10/06/how-to-read-mysql-binary-log-files-binlog-with-mysqlbinlog/" rel="nofollow noreferrer">http://www.mydigitallife.info/2007/10/06/how-to-read-mysql-binary-log-files-binlog-with-mysqlbinlog/</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/mysqlbinlog.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/mysqlbinlog.html</a> </p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/binary-log.html</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/binary-log-setting.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/binary-log-setting.html</a></p>
<p>You can delete all binary log files with the RESET MASTER statement, or a subset of them with PURGE MASTER</p>
<p>--result-file=binlog.txt TrustedFriend-bin.000030</p>
<h1>Normalization:</h1>
<p><a href="http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html" rel="nofollow noreferrer">http://dev.mysql.com/tech-resources/articles/intro-to-normalization.html</a></p>
<h1>UDF functions</h1>
<p><a href="http://www.koders.com/cpp/fid10666379322B54AD41AEB0E4100D87C8CDDF1D8C.aspx" rel="nofollow noreferrer">http://www.koders.com/cpp/fid10666379322B54AD41AEB0E4100D87C8CDDF1D8C.aspx</a> </p>
<p><a href="http://souptonuts.sourceforge.net/readme_mysql.htm" rel="nofollow noreferrer">http://souptonuts.sourceforge.net/readme_mysql.htm</a></p>
<h1>DataTypes:</h1>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/storage-requirements.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/storage-requirements.html</a></p>
<p><a href="http://www.informit.com/articles/article.aspx?p=1238838&seqNum=2" rel="nofollow noreferrer">http://www.informit.com/articles/article.aspx?p=1238838&seqNum=2</a></p>
<p><a href="http://bitfilm.net/2008/03/24/saving-bytes-efficient-data-storage-mysql-part-1/" rel="nofollow noreferrer">http://bitfilm.net/2008/03/24/saving-bytes-efficient-data-storage-mysql-part-1/</a></p>
<p>One thing to note is that on a mixed table with both CHAR and VARCHAR, mySQL will change the CHAR's to VARCHAR's</p>
<p>RecNum integer_type UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (RecNum)</p>
<p>MySQL always represents dates with the year first, in accordance with the standard SQL and ISO 8601 specifications</p>
<h1>Misc:</h1>
<p>Turing off some MySQl functionality will result in smaller data files
and faster access. For example: </p>
<p>--datadir will specify the data directory and</p>
<p>--skip-innodb will turn off the inno option and save you 10-20M</p>
<p>More here
<a href="http://dev.mysql.com/tech-resources/articles/mysql-c-api.html" rel="nofollow noreferrer">http://dev.mysql.com/tech-resources/articles/mysql-c-api.html</a></p>
<p>Download Chapter 7 - Free</p>
<p>InnoDB is transactional but there is a performance overhead that comes with it. I have found MyISAM tables to be sufficient for 90% of my projects.
Non-transaction-safe tables (MyISAM) have several advantages of their own, all of which occur because: </p>
<p>there is no transaction overhead:</p>
<p>Much faster</p>
<p>Lower disk space requirements</p>
<p>Less memory required to perform updates</p>
<p>Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. </p>
<p>These Files <em>can</em> be copied to a storage location intact without using the MySQL Administrators Backup feature which is time consuming (so is the Restore)</p>
<p>The trick is make a copy of these files then DROP the table. When you put the files back
MySQl will recognize them and update the table tracking.</p>
<p>If you must Backup/Restore,</p>
<p>Restoring a backup, or importing from an existing dump file can takes a long time depending on the number of indexes and primary keys you have on each table. You can speed this process up dramatically by modifying your original dump file by surrounding it with the following:</p>
<pre><code>SET AUTOCOMMIT = 0;
SET FOREIGN_KEY_CHECKS=0;
.. your dump file ..
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;
SET AUTOCOMMIT = 1;
</code></pre>
<p>To vastly increase the speed of the reload, add the SQL command SET AUTOCOMMIT = 0; at the beginning of the dump file, and add the COMMIT; command to the end. </p>
<p>By default, autocommit is on, meaning that each and every insert command in
the dump file will be treated as a separate transaction and written to disk before the next one is started. If you don't add these commands, reloading a large database into InnoDB can take many hours...</p>
<p>The maximum size of a row in a MySQL table is 65,535 bytes</p>
<p>The effective maximum length of a VARCHAR in MySQL 5.0.3 and on = maximum row size (65,535 bytes)</p>
<p>VARCHAR values are not padded when they are stored. Trailing spaces are retained when
values are stored and retrieved, in conformance with standard SQL.</p>
<p>CHAR and VARCHAR values in MySQL are compared without regard to trailing spaces.</p>
<p>Using CHAR will only speed up your access if the whole record is fixed size. That is,
if you use any variable size object, you might as well make all of them variable size.
You gain no speed by using a CHAR in a table that also contains a VARCHAR.</p>
<p>The VARCHAR limit of 255 characters was raised to 65535 characters as of MySQL 5.0.3</p>
<p>Full-text searches are supported for MyISAM tables only. </p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html</a></p>
<p>BLOB columns have no character set, and sorting and comparison are based on the
numeric values of the bytes in column values </p>
<p>If strict SQL mode is not enabled and you assign a value to a BLOB or TEXT column that
exceeds the column's maximum length, the value is truncated to fit and a warning is generated.</p>
<h1>Useful Commands:</h1>
<p>check strict mode:
SELECT @@global.sql_mode;</p>
<p>turn off strict mode:</p>
<p>SET @@global.sql_mode= ''; </p>
<p>SET @@global.sql_mode='MYSQL40'</p>
<p>or remove:
sql-mode="STRICT_TRANS_TABLES,...</p>
<p>SHOW COLUMNS FROM <code>mytable</code></p>
<p>SELECT max(namecount) AS <code>virtualcolumn</code> FROM mytable ORDER BY virtualcolumn </p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-fields.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-fields.html</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_last-insert-id</a>
last_insert_id() </p>
<p>gets you the PK of the last row inserted in the current thread max(pkcolname) gets you last PK overall. </p>
<p>Note: if the table is empty max(pkcolname) returns 1 mysql_insert_id() converts the return type of the native MySQL C API function mysql_insert_id() to a type of
long (named int in PHP). </p>
<p>If your AUTO_INCREMENT column has a column type of BIGINT, the value returned by
mysql_insert_id() will be incorrect. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id</a></p>
<p>Just a note that when you’re trying to insert data into a table and you get the error:</p>
<pre><code>Unknown column ‘the first bit of data what you want to put into the table‘ in ‘field list’
</code></pre>
<p>using something like</p>
<pre><code>INSERT INTO table (this, that) VALUES ($this, $that)
</code></pre>
<p>it’s because you’ve not got any apostrophes around the values you’re trying to stick into the table. So you should change your code to:</p>
<pre><code>INSERT INTO table (this, that) VALUES ('$this', '$that')
</code></pre>
<p>reminder that `` are used to define MySQL fields, databases, or tables, not values ;)</p>
<p>Lost connection to server during query:</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/gone-away.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/gone-away.html</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html</a> </p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/server-parameters.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/server-parameters.html</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/show-variables.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/show-variables.html</a> </p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/option-files.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/option-files.html</a></p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/error-log.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.1/en/error-log.html</a></p>
<h1>Tuning Queries</h1>
<p><a href="http://www.artfulsoftware.com/infotree/queries.php?&bw=1313" rel="nofollow noreferrer">http://www.artfulsoftware.com/infotree/queries.php?&bw=1313</a></p>
<p>Well that should be enough to earn the bonus I would think... The fruits of many hours and many projects with a great <em>free</em> database. I develop application data servers on windows platforms mostly with MySQL. The worst mess I had to straighten out was</p>
<p><a href="https://stackoverflow.com/questions/101333/the-ultimate-mysql-legacy-database-nightmare">The ultimate MySQL legacy database nightmare</a></p>
<p>This required a series of appplications to process the tables into something usefull using many of the tricks mentioned here.</p>
<p>If you found this astoundingly helpfull, express your thanks by voting it up.</p>
<p>Also check out my other articles and white papers at: www.coastrd.com</p>
|
<p>InnoDB by default stores all tables in one global tablespace that will <em>never shrink</em>.</p>
<p>You can use <code>innodb_file_per_table</code> which will put each table in a separate tablespace that will be deleted when you drop the table or database.</p>
<p>Plan ahead for this since you have to dump and restore the database to reclaim space otherwise.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.1/en/multiple-tablespaces.html" rel="nofollow noreferrer">Using Per-Table Tablespaces</a></p>
| 48,161
|
<p>We have 2 flowdocuments that we'd like to compare similar to when using a diff viewer (winmerge, beyond compare, etc). Has anybody done this or know how to get the text out of a flowdocument to do a compare?</p>
|
<p>While Chrome will execute Javascript marked as "javascript1.7", it does not support JS1.7 features like the "let" scoped variable operator.</p>
<p>This code will run on Firefox 3.5 but not on Chrome using V8:</p>
<pre><code><script language="javascript" type="application/javascript;version=1.7">
function foo(){ let a = 4; alert(a); }; foo();
</script>
</code></pre>
<p>If you change language to "javascript1.7" and omit the type, it won't run with JS 1.7 features in Firefox 3.5. The type section is necessary.</p>
<p>This seems to be related to a general WebKit bug, <a href="https://bugs.webkit.org/show_bug.cgi?id=23097" rel="noreferrer">https://bugs.webkit.org/show_bug.cgi?id=23097</a>; it may be that Chrome emulates the Safari behavior even though it uses a different engine.</p>
<p><a href="http://www.mail-archive.com/v8-users@googlegroups.com/msg00731.html" rel="noreferrer">When asked about supporting JS 1.8 features</a>, the V8 team said they were trying to track the version used in Safari so pages would act the same in both browsers.</p>
|
<p>This is an old thread, however here goes. Google Chrome does not respond to the following</p>
<pre><code>function foo(){
let a = 4;
alert(a);
}
foo();
</code></pre>
<p>hence it does not support JavaScript 1.7</p>
| 38,472
|
<p>How is the guest account in SQL Server (2000, 2005, 2008) supposed to be used? What is it good for? I've tried enabling the account but I still can't get certain users to be able to refresh Excel 2007 PivotTables attached to views which I have given SELECT rights to GUEST.</p>
<p>What am I missing? </p>
|
<p>There is com.sun.xml.txw2.output.IndentingXMLStreamWriter</p>
<pre><code>XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(out));
</code></pre>
|
<p>With Spring Batch this requires a subclass since this <a href="https://jira.springsource.org/browse/BATCH-1867" rel="nofollow">JIRA BATCH-1867</a></p>
<pre><code>public class IndentingStaxEventItemWriter<T> extends StaxEventItemWriter<T> {
@Setter
@Getter
private boolean indenting = true;
@Override
protected XMLEventWriter createXmlEventWriter( XMLOutputFactory outputFactory, Writer writer) throws XMLStreamException {
if ( isIndenting() ) {
return new IndentingXMLEventWriter( super.createXmlEventWriter( outputFactory, writer ) );
}
else {
return super.createXmlEventWriter( outputFactory, writer );
}
}
}
</code></pre>
<p>But this requires an additionnal dependency because Spring Batch does not include the code to indent the StAX output:</p>
<pre><code><dependency>
<groupId>net.java.dev.stax-utils</groupId>
<artifactId>stax-utils</artifactId>
<version>20070216</version>
</dependency>
</code></pre>
| 37,007
|
<p>Given a string with a module name, how do you import everything in the module as if you had called:</p>
<pre><code>from module import *
</code></pre>
<p>i.e. given string S="module", how does one get the equivalent of the following:</p>
<pre><code>__import__(S, fromlist="*")
</code></pre>
<p>This doesn't seem to perform as expected (as it doesn't import anything).</p>
|
<p>Please reconsider. The only thing worse than <code>import *</code> is <em>magic</em> <code>import *</code>.</p>
<p>If you really want to:</p>
<pre><code>m = __import__ (S)
try:
attrlist = m.__all__
except AttributeError:
attrlist = dir (m)
for attr in attrlist:
globals()[attr] = getattr (m, attr)
</code></pre>
|
<p>I didn't find a good way to do it so I took a simpler but ugly way from <a href="http://www.djangosnippets.org/snippets/600/" rel="nofollow noreferrer">http://www.djangosnippets.org/snippets/600/</a></p>
<pre><code>try:
import socket
hostname = socket.gethostname().replace('.','_')
exec "from host_settings.%s import *" % hostname
except ImportError, e:
raise e
</code></pre>
| 17,760
|
<p>I am working with a set of data that looks something like the following.</p>
<blockquote>
<pre><code>StudentName | AssignmentName | Grade
---------------------------------------
StudentA | Assignment 1 | 100
StudentA | Assignment 2 | 80
StudentA | Total | 180
StudentB | Assignment 1 | 100
StudentB | Assignment 2 | 80
StudentB | Assignment 3 | 100
StudentB | Total | 280
</code></pre>
</blockquote>
<p>The name and number of assignments are dynamic, I need to get results simlilar to the following.</p>
<blockquote>
<pre><code>Student | Assignment 1 | Assignment 2 | Assignment 3 | Total
--------------------------------------------------------------------
Student A | 100 | 80 | null | 180
Student B | 100 | 80 | 100 | 280
</code></pre>
</blockquote>
<p>Now ideally I would like to sort the column based on a "due date" that could be included/associated with each assignment. The total should be at the end if possible (It can be calculated and removed from the query if possible.)</p>
<p>I know how to do it for the 3 assignments using pivot with simply naming the columns, it is trying to do it in a dynamic fashion that I haven't found a GOOD solution for yet. I am trying to do this on SQL Server 2005</p>
<p><strong>EDIT</strong></p>
<p>Ideally I would like to implement this WITHOUT using Dynamic SQL, as that is against the policy. If it isn't possible...then a working example with Dynamic SQL will work.</p>
|
<p>I know you said no dynamic <code>SQL</code>, but I don't see any way to do it in straight <code>SQL</code>.</p>
<p>If you check out my answers to similar problems at <a href="https://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803">Pivot Table and Concatenate Columns</a> and <a href="https://stackoverflow.com/questions/198716/pivot-in-sql-2005#199763">PIVOT in sql 2005</a></p>
<p>The dynamic <code>SQL</code> there is not vulnerable to injection, and there is no good reason to prohibit it. Another possibility (if the data is changing very infrequently) is to do code-generation - instead of dynamic <code>SQL</code>, the <code>SQL</code> is generated to a stored procedure on a regular basis.</p>
|
<pre><code>select studentname,[Assign1],[Assign2],[Assign3],[Total]
from
(
select studentname, assignname, grade from student
)s
pivot(sum(Grade) for assignname IN([Assign1],[Assign2],[Assign3],[Total])) as pvt
</code></pre>
| 26,271
|
<p>For some weeks now I simply can't run gem install in windows.
It sticks on this line:</p>
<pre><code>C:\Windows\System32>gem install rails --version 2.1.2
Bulk updating Gem source index for: http://gems.rubyforge.org/
</code></pre>
<p>Any ideas what it could be?</p>
|
<p>I had this same problem with gem version < 1.2. Upgrading to 1.2 fixed it.</p>
|
<p>It worked fine on my Windows Server 2003 machine. I am using gem version 1.3.0.</p>
| 28,641
|
<p>How do I prevent vim from replacing spaces with tabs when autoindent is on?</p>
<p>An example: if I have two tabs and 7 spaces in the beginning of the line, and <code>tabstop=3</code>, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that...</p>
|
<p>It is perhaps a good idea not to use tabs at all.</p>
<pre><code>:set expandtab
</code></pre>
<p>If you want to replace all the tabs in your file to 3 spaces (which will look pretty similar to <code>tabstop=3</code>):</p>
<pre><code>:%s/^I/ /
</code></pre>
<p>(where <code>^I</code> is the <kbd>TAB</kbd> character)</p>
<p>From the VIM online help:</p>
<pre><code>'tabstop' 'ts' number (default 8)
local to buffer
Number of spaces that a <Tab> in the file counts for. Also see
|:retab| command, and 'softtabstop' option.
Note: Setting 'tabstop' to any other value than 8 can make your file
appear wrong in many places (e.g., when printing it).
There are four main ways to use tabs in Vim:
1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
(or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim
will use a mix of tabs and spaces, but typing <Tab> and <BS> will
behave like a tab appears every 4 (or 3) characters.
2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
'expandtab'. This way you will always insert spaces. The
formatting will never be messed up when 'tabstop' is changed.
3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
|modeline| to set these values when editing the file again. Only
works when using Vim to edit the file.
4. Always set 'tabstop' and 'shiftwidth' to the same value, and
'noexpandtab'. This should then work (for initial indents only)
for any tabstop setting that people use. It might be nice to have
tabs after the first non-blank inserted as spaces if you do this
though. Otherwise aligned comments will be wrong when 'tabstop' is
changed.
</code></pre>
|
<p><a href="http://www.jwz.org/doc/tabs-vs-spaces.html" rel="nofollow noreferrer">Maybe the bottom of this can help you?</a></p>
<blockquote>
<p>Standard vi interprets the tab key literally, but there are popular vi-derived alternatives that are smarter, like vim. To get vim to interpret tab as an ``indent'' command instead of an insert-a-tab command, do this:</p>
<pre><code>set softtabstop=2
</code></pre>
</blockquote>
| 9,542
|
<p>I am looking for a way to determine what the Name/IP Address of the domain controller is for a given domain that a client computer is connected to.</p>
<p>At our company we have a lot of small little networks that we use for testing and most of them have their own little domains. As an example, one of the domains is named "TESTLAB". I have an Windows XP workstation that is a member of the TESTLAB domain and I am trying to figure out the name of the domain controller so that I can go and look to see what users have been defined for the domain. In our lab there is a mix of Windows Server 2000 and Windows Server 2003 (and in reality probably a couple of NT 4 Servers) so it would be nice to find a solution that would work for both.</p>
<p>Looking on the Internet, it looks like there are various utilities, such as Windows Power Shell or nltest, but these all require that you download and install other utilities. I was hoping to find a way to find the domain controller without having to install anything additional.</p>
<p><strong>EDIT</strong> If I wanted to write a program to find the domain controller or the users in the current domain, how would I go about doing that?</p>
|
<p>With the most simple programming language: DOS batch</p>
<pre><code>echo %LOGONSERVER%
</code></pre>
|
<p>To retrieve the information when the <code>DomainController</code> exists in a Domain in which your machine doesn't belong, you need something more.</p>
<pre><code> DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");
var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();
</code></pre>
| 46,114
|
<p>In a previous life, I might have done something like this:</p>
<pre><code><a href="#" onclick="f(311);return false;">Click</a><br/>
<a href="#" onclick="f(412);return false;">Click</a><br/>
<a href="#" onclick="f(583);return false;">Click</a><br/>
<a href="#" onclick="f(624);return false;">Click</a><br/>
</code></pre>
<p>Now with jQuery, I might do something like this:</p>
<pre><code><a class="clicker" alt="311">Click</a><br/>
<a class="clicker" alt="412">Click</a><br/>
<a class="clicker" alt="583">Click</a><br/>
<a class="clicker" alt="624">Click</a><br/>
<script language="javascript" type="text/javascript">
$(".clicker").bind("click", function(e) {
e.preventDefault();
f($(this).attr("alt"));
});
</script>
</code></pre>
<p>Except that using the alt attribute to pass the data from the DOM to jQuery feels like a hack, since that's not its intended purpose. What's the best practice here for storing/hiding data in the DOM for jQuery to access?</p>
|
<p><a href="http://docs.jquery.com/Core/data#name" rel="nofollow noreferrer">JQuery.data</a> lets you associate a dictionary to a DOM element. This data can be set via jQuery:</p>
<pre><code><a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<script language="javascript" type="text/javascript">
var values = new Array("311", "412", "583", "624");
$(".clicker").each(function(i, e) {
$(this).data('value', values[i]).click(function(e) {
f($(this).data('value'));
});
});
</script>
</code></pre>
<p>or (since jQuery 1.4.3) using the <a href="http://ejohn.org/blog/html-5-data-attributes/" rel="nofollow noreferrer">HTML5 data- attributes</a>, which work even in non-HTML5 documents:</p>
<pre><code><a class="clicker" data-value="311">Click</a><br/>
<a class="clicker" data-value="412">Click</a><br/>
<a class="clicker" data-value="583">Click</a><br/>
<a class="clicker" data-value="624">Click</a><br/>
<script language="javascript" type="text/javascript">
$(".clicker").click(function(e) {
f($(this).data('value'));
});
</script>
</code></pre>
|
<p>I'm sorry, but if you are already filling in the alt tag, I fail to see how delaying the assignment of the onclick handler to jQuery actually buys you anything. Isn't this just a case of "Now that I have a hammer, every problem looks like a nail." I think the jquery method is best used when the action does not depend on extra data than what can naturally be derived from the content, for example, class definition, tag type, etc.</p>
| 47,572
|
<p>Is it possible to replicate selected objects (accounts) in an Active Directory Domain. We have a need to replicate selected accounts through our firewall to a DC sitting in the DMZ. We don't want to replicate <em>all</em> accounts to this machine, in case it is compromised.</p>
<p>Any suggestions, help or products suggested most appreciated.</p>
|
<p>This isn't really a programming question, but anyway...</p>
<p>Unless the DC on your DMZ is in a different domain, you don't need to replicate anything, it has everything already. If it's in a different domain, what exactly do you actually want to replicate and why? Permissions? Settings?</p>
|
<p>Apologies - I have just clarified the needs with one of the programmers (slight mis-communication before). Turns out we just need a one-way trust from the DMZ domain, to the internal domain, for accessing some internal objects (files, SQL). I thought they needed to verify some internal users on the DMZ - not so.</p>
<p>Again, apologies, but it turned out to be rather simple.</p>
<p>Thanks for replying.</p>
| 33,576
|
<p>I'm trying to debug some IE-only issues for a site I'm developing. I'm running WDE because there's no Firebug for IE. I want to see whether some changes fix a bug, but no matter what I do, IE never picks up my changes. I've tried all of the following:</p>
<ul>
<li>stopping and restarting the debug evnironment</li>
<li>closing and re-opening WDE</li>
<li>closing and re-opening IE</li>
<li>clearing IE's "temporary internet files"</li>
<li>swearing at Microsoft for building such awful software</li>
</ul>
<p>Any help? Are there some cached files somewhere on the drive I could clear out?</p>
|
<p>IE Developer Toolbar has <em>"Clear Browser Cache ..."</em> and <em>"Clear Browser Cache for This Domain ..."</em> menu items.</p>
|
<p>Have you tried ctrl+f5? It reloads the current page and clears the cache. If even after that your changes don't propagate, the problems in your code.</p>
| 45,680
|
<p>What approach is the best way to make content-types restricted to a user in Django?</p>
<p>Let us say I want all users with the user-role "blogger" to have its own blog.</p>
<p>I have created a weblog app. How do I restrict it so that the user logged in can only post in his "own" blog, and how do I make views that shows only a user's blog?</p>
|
<p>First your blog entries has to be attached to user, so you know on whos blog display, it, right? models.py:</p>
<pre><code>class BlogEntry(models.Model):
user = models.ForeignKey(User, related_name='blog_entries')
other_field_1 = ...
other_field_2 = ...
</code></pre>
<p>Next, skip it in ModelForm, forms.py:</p>
<pre><code>class BlogEntryModelForm(forms.ModelForm):
class Meta:
exclude = ('user',)
</code></pre>
<p>Then, when user want to post entry you require he's logged, views.py:</p>
<pre><code>@login_required
def post_blog_entry(request):
....
if request.method == 'POST':
form = BlogEntryModelForm(request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.user = request.user
new_entry.save()
</code></pre>
<p>When you want display some user blog, views.py:</p>
<pre><code>def view_blog(request, blogger_name):
user = get_object_or_404(User, username=blogger_name)
entries = user.blog_entries.all()
</code></pre>
<p>User is django.contrib.auth.models.User
You can add custom role checking to views above to display 404 page or error page if user has no rights to create blog.</p>
<p>Optionally you can replace User from django.contrib.auth with your own User implementation but you'll have to write model, authentication and middleware for it as well...</p>
|
<p>I didnt try to implement this, but I found another soultion that worked very good. It was easy to implement and did everything i wanted.</p>
<p><a href="http://www.djangosnippets.org/snippets/1054/" rel="nofollow noreferrer">Check it out...</a></p>
| 49,250
|
<p>How do you draw the following dynamic <strong>3D</strong> array with OpenGL <strong>glDrawPixels()</strong>?
You can find the documentation here: <a href="http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html" rel="nofollow noreferrer">http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html</a></p>
<pre><code>float ***array3d;
void InitScreenArray()
{
int i, j;
int screenX = scene.camera.vres;
int screenY = scene.camera.hres;
array3d = (float ***)malloc(sizeof(float **) * screenX);
for (i = 0 ; i < screenX; i++) {
array3d[i] = (float **)malloc(sizeof(float *) * screenY);
for (j = 0; j < screenY; j++)
array3d[i][j] = (float *)malloc(sizeof(float) * /*Z_SIZE*/ 3);
}
}
</code></pre>
<p>I can use only the following header files:</p>
<pre><code>#include <math.h>
#include <stdlib.h>
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
</code></pre>
|
<p>Uh ... Since you're allocating <i>each single pixel</i> with a separate <code>malloc()</code>, you will have to draw each pixel with a separate call to <code>glDrawPixels()</code>, too. This is (obviously) insane; the idea of bitmapped graphics is that the pixels are stored in an adjacent, compact, format, so that it is quick and fast (<i>O(1)</i>) to move from one pixel to another. This looks very confused to me.</p>
<p>A more sensible approach would be to allocate the "3D array" (which is often referred to as a 2D array of pixels, where each pixel happens to consist of a red, green and blue component) with a single call to <code>malloc()</code>, like so (in C):</p>
<pre><code>float *array3d;
array3d = malloc(scene.camera.hres * scene.camera.vres * 3 * sizeof *array3d);
</code></pre>
|
<p>wouldn't you want to use glTexImage2D() instead: see <a href="https://stackoverflow.com/questions/1080545/how-to-display-a-raw-yuv-frame-in-a-cocoa-opengl-program">here</a></p>
| 32,478
|
<p>For a university mid-term project I have to design a configurable processor, to write the code in VHDL and then synthesize it on a Spartan 3E FPGA board from Digilent. I'm a beginner so could you point me to some information about configurable processors, to some ideas related to the concept?</p>
|
<p>You can check out my <a href="https://stackoverflow.com/questions/148229/best-way-to-learn-how-to-use-fpgas#367127">answer for a related question</a>. We did nearly the same, building a CPU in VHDL for a FPGA board.</p>
|
<p>This is just a mockup so please be aware i will clean it up<br>
<br>
fetch instruct1,<br>
fetch instruct2, fetch datas1<br>
fetch instruct3, fetch datas2, process datas1<br>
fetch instruct4, fetch datas3, process datas2, store1 datas1<br>
fetch instruct5, fetch datas4, process datas3, store2 datas1<br>
fetch instruct6, fetch datas5, process datas4, store3 datas1<br>
fetch instruct7, fetch datas6, process datas5, store4 datas1<br>
fetch instruct8, fetch datas7, process datas6, store5 datas1<br></p>
<p>basically these are the main components of a processor
Part 1
ALU: Arithmetic Logic Unit (this is where draeing would come in handy)
AN ALU has 2 input ports and an output port. THe 2 input ports get operated on and the result outputed. To know which instruction the ALU has to accomplish there is a control Port.
Basically this is the name of the command. So if the control port has 4bits there are 16 possible instructions. </p>
<p>Part 2
REGISTER UNIT: This is a set of memory cells (cache memory). The contents of this memory is often transferred to the ALU's input ports.</p>
<p>Part3
Control Unit: This is sort of like the orchestra master of the cpu. Its job is to
1send the data to the ALU input
2Readwhich instruction needs to happen in the Instruction Registers,send those codes to the ALU control ports</p>
<p>Interface. This is how the RAM and other peripherals communicate with the cpu</p>
<p>Everytime the intruction outputs a result it has to be stored. It can be stored in RAM so a ram write must be ready once the result is ready. At the same time, a RAM read of the next instruction's inputs can occurs.And also at the same time, the next next instruction can be fetched from RAM. </p>
<p>Generating 1 instruction usually requires more than 1 clock cycle. Processing an in struction is analogeous to industrial production. So chain work is done. </p>
<p>VLIW The programming we write is linear, meaning instructions happening one after the other. But CPUs today (not ARMs though) have multiple ALU's so multiple instructions are processed at the same time. </p>
<p>So you have processing units chain working multiple instructions at the same time (pipeline)
and you have alot of those units (superscalar)</p>
<p>It then becomes a question of what can/need to do to taylor your cpu architecture.</p>
| 28,340
|
<p>I have a page that spits out db data in long horizontal tables. </p>
<p>I need to print it nicely so it does not cut off. Any tips ?</p>
|
<p>If it doesn't fit on the paper in a readable font, it just doesn't.. In my opinion, huge horizontal tables (be it a HTML table or an Excel sheet with many columns) don't lend well to printing. For that matter, they don't lend well to viewing on a screen either. Remember vertical scrolling is much easier for your users than horizontal scrolling - all thanks to that little wheel on your mouse.</p>
<p>Worst case, you might need to write a seperate print version which uses a vertical layout.</p>
|
<p>To ensure your table won't disappear into the Printer Abyss, ensure that its container has a width set to 100%.</p>
<p>I assume you know how to use print specific CSS (<code><style type="text/css" media="print"></code>).<br>
Since printers and computer monitors can have very different resolutions,
do most of your size-setting in <code>em</code>'s in the print CSS, and hide non-essential
elements when printing (<code>display:none</code>).</p>
<p>Also, to increase readability on paper, use a white background, black text,
and serif fonts (Times New Roman, etc.), which have a reputation for being more legible on paper.</p>
<p>Different browsers do printing their own way (even more than on screen),
so play around a bit and see if you can get better results from another browser.
That is, of course, if printing is not required to work perfectly across
the entire browser spectrum.</p>
| 37,339
|
<p>Are there any alternatives to MS Access?</p>
<p>Requirements:</p>
<ul>
<li>Portable Database file</li>
<li><strong>Integrated form development for data entry</strong></li>
<li>No compiling necessary. Can be modified on the fly.</li>
</ul>
<hr />
<p>Two more requirements:</p>
<ul>
<li><p>Available for Linux or Windows</p>
</li>
<li><p>Does not have to be free</p>
<p>EDIT: Emphasised <em>Integrated form development for data entry</em> as the top voted answers for this question, at the time of edit, both recommend a simple database system. The reason why Access is still so hard to replace for simple department level CRUD (and more) applications is the integration of database, data entry forms and reporting tool. Simply recommending a database does <em>not</em> answer the question as posed.</p>
</li>
</ul>
|
<p><a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLite</a> is always my choice for lightweight databases, though it doesn't have a form creator as it's just a database. </p>
<p>SQLite is great because:</p>
<ul>
<li>It's just a library to be called by your application, not a server.</li>
<li>There's no configuration.</li>
<li>Your database is just a file.</li>
</ul>
<p>(... and you can use in memory databases for testing, for those addicted to unit tests :)</p>
|
<p><a href="http://www.sqlite.org" rel="nofollow noreferrer">SQLite</a> is awesome.</p>
| 27,351
|
<p>I'm working with the SerialPort class in the Compact Framework, but I can't recive more than 2047 bytes. Exists any limit for the amount of bytes that I can recive? or How can I setup the object? I was trying with the WriteBufferSize and ReadBufferSize properties but they didn't work.</p>
|
<p>My guess is that it is either a processor or platform limitation. <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=22421&SiteID=1" rel="nofollow noreferrer">This post</a> from the MSDN forums seems to confirm my suspicions. </p>
|
<p>Can you set up a thread to pull the data into another (larger) buffer that you allocate yourself? I'd say that's the best workaround.</p>
| 6,464
|
<p>What do I need to look at to see whether I'm on Windows or Unix, etc?</p>
|
<pre><code>>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Linux'
>>> platform.release()
'2.6.22-15-generic'
</code></pre>
<p>The output of <a href="https://docs.python.org/library/platform.html#platform.system" rel="noreferrer"><code>platform.system()</code></a> is as follows:</p>
<ul>
<li>Linux: <code>Linux</code></li>
<li>Mac: <code>Darwin</code></li>
<li>Windows: <code>Windows</code></li>
</ul>
<p>See: <a href="https://docs.python.org/library/platform.html" rel="noreferrer"><code>platform</code> — Access to underlying platform’s identifying data</a></p>
|
<p>How about a simple Enum implementation like the following? No need for external libs!</p>
<pre><code>import platform
from enum import Enum
class OS(Enum):
def checkPlatform(osName):
return osName.lower()== platform.system().lower()
MAC = checkPlatform("darwin")
LINUX = checkPlatform("linux")
WINDOWS = checkPlatform("windows") #I haven't test this one
</code></pre>
<p>Simply you can access with Enum value</p>
<pre><code>if OS.LINUX.value:
print("Cool it is Linux")
</code></pre>
<p>P.S It is python3</p>
| 2,412
|
<p>I have a problem that I feel is best implimented in a stand alone windows application, but needs to pass data to a web page that is already open. </p>
<p>Is it possible to pass the data directly to the web page?</p>
<p>If so, what is the best way to go about it?</p>
<p>(Its my first question, so go easy on me!)</p>
|
<p>They are usually used to add some form of standard functionality to a class, without having to redefine it all. You can probably think of them a bit like interfaces in Java, but instead of just defining a list of methods that need to be implemented, many of them will actually <em>be</em> implemented by including the module.</p>
<p>There are a few examples in the standard library:</p>
<p>Singleton - A module that can be mixed into any class to make it a singleton. The initialize method is made private, and an instance method added, which ensures that there is only ever one instance of that class in your application.</p>
<p>Comparable - If you include this module in a class, defining the <=> method, which compares the current instance with another object and says which is greater, is enough to provide <, <=, ==, >=, >, and between? methods.</p>
<p>Enumerable - By mixing in this module, and defining an <strong>each</strong> method, you get support for all the other related methods such as collect, inject, select, and reject. If it's also got the <=> method, then it will also support sort, min, and max.</p>
<p>DataMapper is also an interesting example of what can be done with a simple include statement, taking a standard class, and adding the ability to persist it to a data store.</p>
|
<p>It is largely used as one might use multiple inheritance in C++ or implementing interfaces in Java/C#. I'm not sure where your experience lies, but if you have done those things before, mixins are how you would do them in Ruby. It's a systemized way of injecting functionality into classes.</p>
| 46,356
|
<p>I can never remember the number. I need a memory rule.</p>
|
<p>It's 2,147,483,647. Easiest way to memorize it is via a tattoo.</p>
|
<pre><code>max_signed_32_bit_num = 1 << 31 - 1; // alternatively ~(1 << 31)
</code></pre>
<p>A compiler should optimize it anyway.</p>
<p>I prefer <code>1 << 31 - 1</code> over </p>
<p><code>0x7fffffff</code> because you don't need count <code>f</code>s</p>
<p><code>unsigned( pow( 2, 31 ) ) - 1</code> because you don't need <code><math.h></code></p>
| 12,017
|
<p>Here's the scenario</p>
<p>I have a Grid with some TextBlock controls, each in a separate cell in the grid. Logically I want to be able to set the Visibility on them bound to a property in my ViewModel. But since they're each in a separate cell in the grid, I have to set each TextBlock's Visibility property.</p>
<p>Is there a way of having a non-visual group on which I can set common properties of its children? Or am I dreaming?</p>
|
<p>There is no non-visual group that would make this possible.</p>
<p>Setting the Visibility properties, directly or in a common Style shared by all of the TextBlocks, is probably the simplest solution.</p>
|
<p>It may be possible to make a custom control that redirects all its add/remove children methods to its own parent, while still keeping a record of its contents so it can apply its own property styles. Would be tricky though.</p>
| 43,590
|
<p>I want to automate tests on my web application, and it uses postgresql. Does anyone know how define a restore point on a postgresql database and restore to an earlier state?
I heard something about point in time recovery, but i dont if this is what i need.</p>
<p>Thanks in advance</p>
|
<p>I use <a href="http://www.sqlalchemy.org/" rel="noreferrer">SQL Alchemy</a> with cPython (I don't know if it'll work with IronPython though). It'll be pretty familiar to you if you've used Hibernate/nHibernate. If that's a bit too verbose for you, you can use <a href="http://elixir.ematia.de/trac/wiki" rel="noreferrer">Elixir</a>, which is a thin layer on top of SQL Alchemy. To use either one of those, you'll need <a href="http://pyodbc.sourceforge.net/" rel="noreferrer">pyodbc</a>, but that's a pretty simple install.</p>
<p>Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.</p>
|
<p>If you are want the quick and dirty way with CPython (also works for 3.X python):</p>
<p>Install PYWIN32 after you install python <a href="http://sourceforge.net/projects/pywin32/files/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/files/pywin32/</a></p>
<p>Import the following library:
import odbc</p>
<p>I created the following method for getting the SQL Server odbc driver (it is slightly different in naming depending on your version of Windows, so this will get it regardless):</p>
<pre><code>def getSQLServerDriver():
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ODBC\ODBCINST.INI")
sqlServerRegExp = re.compile('sql.*server', re.I | re.S)
try:
for i in range(0, 2048):
folder = winreg.EnumKey(key, i)
if sqlServerRegExp.match(folder):
return folder.strip()
except WindowsError:
pass
</code></pre>
<p>Note: if you use the above function, you'll need to also import these two libraries: winreg and re</p>
<p>Then you use the odbc API 1 information as defined here: <a href="http://www.python.org/dev/peps/pep-0248/" rel="nofollow">http://www.python.org/dev/peps/pep-0248/</a></p>
<p>Your connection interface string should look something like this (assuming you are using my above method for getting the ODBC driver name, and it is a trusted connection):</p>
<pre><code>dbString = "Driver={SQLDriver};Server=[SQL Server];Database=[Database Name];Trusted_Connection=yes;".replace('{SQLDriver}', '{' + getSQLServerDriver() + '}')
</code></pre>
<p>This method has many down sides. It is clumsy because of only supporting ODBC API 1, and there are a couple minor bugs in either the API or the ODBC driver that I've run across, but it does get the job done in all versions of CPython in Windows.</p>
| 36,949
|
<p>Like, let's say I had a tree structure, then I would use, naturally a tree control, since that GUI element maps perfectly to the structure.</p>
<p>But what I have is a graph, potentially too wide to fit in one web page. I can't think of examples of GUIs that really match the structure. Some ideas I have that don't quite fit are, the web itself, with hyperlinks, the browser back button, and the forward button. But that just shows you one node at a time. I would like to display as many nodes as I can, and allow navigation to a new area of the graph. Something like Google maps might be a good model, in that you have full freedom to scroll in any direction.</p>
|
<p>Facebook used to do this, <em>way</em> back in the day, to visualize your friends. They drew nodes as little boxes, with lines connecting them, as expected. They drew the graphs into an SVG image, so you could easily zoom in and out.</p>
<p>Another option might be to draw into a <code><canvas></code> tag and scale that somehow. I imagine that's possible, but I don't know much about <code><canvas></code></p>
<p>Another option would be to draw it into an inline frame or other box that allows the user to scroll horizontally and vertically.</p>
|
<p>You could try <a href="http://prefuse.org/" rel="nofollow noreferrer">prefuse</a>. It is an open source interactive data visualization toolkit. It has a very nice collection of layouts that can be used for displaying node graphs along with other visualization effects. The toolkit comes in two different flavours, one in Java and another in Actionscript, which can be used in Flash/Flex.</p>
| 30,491
|
<p>I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?</p>
<p>Ideally I'd want to capture all output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent).</p>
<p>I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.</p>
|
<p>For logging standard output, you can use a stdout wrapper, such as this one:</p>
<pre><code>from __future__ import with_statement
class OutWrapper(object):
def __init__(self, realOutput, logFileName):
self._realOutput = realOutput
self._logFileName = logFileName
def _log(self, text):
with open(self._logFileName, 'a') as logFile:
logFile.write(text)
def write(self, text):
self._log(text)
self._realOutput.write(text)
</code></pre>
<p>You then have to initialize it in your main Python file (the one that runs everything):</p>
<pre><code>import sys
sys.stdout = OutWrapper(sys.stdout, r'c:\temp\log.txt')
</code></pre>
<p>As to logging exceptions, the easiest thing to do is to wrap <code>MainLoop</code> method of wx.App in a try..except, then extract the exception information, save it in some way, and then re-raise the exception through <code>raise</code>, e.g.:</p>
<pre><code>try:
app.MainLoop()
except:
exc_info = sys.exc_info()
saveExcInfo(exc_info) # this method you have to write yourself
raise
</code></pre>
|
<p>There are various ways. You can put a try..catch block in the wxApplication::OnInit, however, that would not always work with Gtk. </p>
<p>A nice alternative would be to override the Application::HandleEvent in your wxApplication derived class, and write a code like this:</p>
<pre><code>void Application::HandleEvent(wxEvtHandler* handler, wxEventFunction func, wxEvent& event) const
{
try
{
wxAppConsole::HandleEvent(handler, func, event);
}
catch (const std::exception& e)
{
wxMessageBox(std2wx(e.what()), _("Unhandled Error"),
wxOK | wxICON_ERROR, wxGetTopLevelParent(wxGetActiveWindow()));
}
}
</code></pre>
<p>It's a C++ example, but you can surely translate to Python easily.</p>
| 20,070
|
<p>So you've just been put on the spot by The Boss.
You've got 15 minutes to come up with a back of the envelope estimate for the addition of some new feature. Your boss (fortunately) recognizes that you can't provide an accurate estimate in that time so expecting something that is in the right order of magnitude.</p>
<p>The question is how do you go about giving a estimate in the time frame that is accurate to an order of magnitude?</p>
<hr>
<p>Note that this is meant to be a quick and dirty estimate, not something that might be expected from questions like <a href="https://stackoverflow.com/questions/14279/how-to-estimate-the-length-of-a-programming-task#14289">this</a></p>
|
<p>Place finger in mouth, lick, wave in air and make up a number based on past experience. Then double it.</p>
<p>Really, its just experience that counts. You imagine what the task entails you doing, and you know how long it'll take you to do that. Double it for unanticipated items. This is also why you never ask junior programmers for such estimates.</p>
|
<p>I personally refuse this type of thing. But then i work for myself, so i dont answer to a boss. Just a client, but its easier to make them understand its hard to do on the spot.</p>
| 13,489
|
<p>Due to company constraints out of my control, I have the following scenario:</p>
<p>A COM library that defines the following interface (no CoClass, just the interface):</p>
<pre><code>[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IService Interface"),
pointer_default(unique)
]
IService : IDispatch
{
HRESULT DoSomething();
}
[
object,
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
dual,
nonextensible,
helpstring("IProvider Interface"),
pointer_default(unique)
]
IServiceProvider : IDispatch
{
HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );
HRESULT GetService( LONG serviceIndicator, IService ** result );
};
[
uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx),
version(1.0),
]
library ServiceLibrary
{
importlib("stdole2.tlb");
interface IService;
interface IServiceProvider;
};
</code></pre>
<p>I have a COM (written w/ C++) that implements both interfaces and provides our application(s) with said service. All is fine, I think.</p>
<p>I'm trying to build a new <code>IProvider</code> and <code>IService</code> in .NET (C#). </p>
<p>I've built a Primary Interop Assembly for the COM library, and implemented the following C#:</p>
<pre><code>[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewService : IService
{
// adds a couple new properties
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewService : INewService
{
// implement interface
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public interface INewProvider : IServiceProvider
{
// adds nothing, just implements
}
[ComVisible( true )]
[Guid( "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" )]
public class NewProvider : INewProvider
{
// implement interface
}
</code></pre>
<p>When I attempt to slip this into the existing runtime, I am able to create the <code>NewProvider</code> object from COM (C++), and <code>QueryInterface</code> for IServiceProvider. When I attempt to call a method on the IServiceProvider, a <code>System.ExecutionEngineException</code> is thrown. </p>
<p>The only other thing I can find, is by looking at the .tlh files created by the #import, shows the legacy COM IExistingProvider class correctly shows that it is derived from IServiceProvider. However the .NET class shows a base of IDispatch. I'm not sure if this a sign, indication, helpful, something else.</p>
|
<p>It could be a problem with the name <em>IServiceProvider</em>. Check that you haven't already imported an interface with the same name.</p>
<p>When I create an COM Interface library using your IDL, and then try to import it from another client, I get the warning:</p>
<pre><code>Warning 65 warning C4192: automatically excluding 'IServiceProvider' while importing type library 'ServiceLibrary.dll'
</code></pre>
<p>Otherwise, you can try renaming it to IServiceProvider2. That's what I did, and everything works fine. I'm using Visual Studio 2008.</p>
<p>If this code runs properly on your machine (it works perfectly on mine) then the problem could be in your implementation.</p>
<p>IDL:</p>
<pre><code>import "oaidl.idl";
[
object,
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C43),
dual,
nonextensible,
helpstring("IService Interface"),
pointer_default(unique)
]
interface IService : IDispatch
{
HRESULT DoSomething(void);
}
[
object,
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C44),
dual,
nonextensible,
helpstring("IProvider Interface"),
pointer_default(unique)
]
interface IServiceProvider2 : IDispatch
{
HRESULT Init( IDispatch *sink, VARIANT_BOOL * result );
HRESULT GetService( LONG serviceIndicator, IService ** result );
};
[
uuid(9219CC5B-31CC-4868-A1DE-E18300F73C45),
version(1.0),
]
library ServiceLibrary
{
importlib("stdole2.tlb");
interface IService;
interface IServiceProvider2;
};
</code></pre>
<p>C#:</p>
<pre><code>using System.Runtime.InteropServices;
using System.Windows.Forms;
using ServiceLibrary;
using IServiceProvider=ServiceLibrary.IServiceProvider2;
namespace COMInterfaceTester
{
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B2")]
public interface INewService : IService
{
string ServiceName { get; }
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B3")]
public class NewService : INewService
{
public string _name;
public NewService(string name)
{
_name = name;
}
// implement interface
#region IService Members
public void DoSomething()
{
MessageBox.Show("NewService.DoSomething");
}
#endregion
public string ServiceName
{
get { return _name; }
}
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B4")]
public interface INewProvider : IServiceProvider
{
// adds nothing, just implements
}
[ComVisible(true)]
[Guid("2B9D06B9-EB59-435e-B3FF-B891C63108B5")]
public class NewProvider : INewProvider
{
// implement interface
public void Init(object sink, ref bool result)
{
MessageBox.Show("NewProvider.Init");
}
public void GetService(int serviceIndicator, ref IService result)
{
result = new NewService("FooBar");
MessageBox.Show("NewProvider.GetService");
}
}
}
</code></pre>
<p>C++ Client:</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <atlbase.h>
#import "COMInterfaceTester.tlb" raw_interfaces_only
#import "ServiceLibrary.dll" raw_interfaces_only
using std::cout;
int _tmain(int argc, _TCHAR* argv[])
{
CoInitialize(NULL); //Initialize all COM Components
COMInterfaceTester::INewProviderPtr pNewProvider(__uuidof(COMInterfaceTester::NewProvider));
ServiceLibrary::IServiceProvider2 *pNewProviderPtr;
HRESULT hr = pNewProvider.QueryInterface(__uuidof(ServiceLibrary::IServiceProvider2), (void**)&pNewProviderPtr);
if(SUCCEEDED(hr))
{
VARIANT_BOOL result = VARIANT_FALSE;
int *p = NULL;
hr = pNewProviderPtr->Init((IDispatch*)p, &result);
if (FAILED(hr))
{
cout << "Failed to call Init";
}
ServiceLibrary::IService *pService = NULL;
hr = pNewProviderPtr->GetService(0, &pService);
if (FAILED(hr))
{
cout << "Failed to call GetService";
}
else
{
COMInterfaceTester::INewService* pNewService = NULL;
hr = pService->QueryInterface(__uuidof(COMInterfaceTester::INewService), (void**)&pNewService);
if (SUCCEEDED(hr))
{
CComBSTR serviceName;
pNewService->get_ServiceName(&serviceName);
if (serviceName == "FooBar")
{
pService->DoSomething();
}
else
cout << "Unexpected service";
pNewService->Release();
}
pService->Release();
}
pNewProviderPtr->Release();
}
else
cout << "Failed to query for IServiceProvider2";
pNewProvider.Release();
CoUninitialize (); //DeInitialize all COM Components
}
</code></pre>
|
<p>You may have to specify additional attributes on your class to have it marshal correctly. I would look through available attributes <a href="http://msdn.microsoft.com/en-us/library/d4w8x20h(VS.71).aspx" rel="nofollow noreferrer">here</a> and maybe look at <a href="http://www.codeproject.com/KB/COM/cominterop.aspx" rel="nofollow noreferrer">this tutorial</a> if you haven't done so already.</p>
| 23,757
|
<p>In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.</p>
<pre><code>DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
</code></pre>
<p>So if tblCustomer looks like this: </p>
<pre><code>ParentID CustID
5 5
1 8
5 4
4 1
</code></pre>
<p>The result I get from the code above is: </p>
<pre><code>ParentID CustID
4 1
5 4
5 5
</code></pre>
<p>What I want is just the last row of that result: </p>
<pre><code>ParentID CustID
5 5
</code></pre>
<p>How do I just return the last record generated in the CTE (which would be highest level CustID)?</p>
<p>Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT * FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.</p>
|
<p>If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:</p>
<pre><code>DECLARE @LookupID int
--Our test value
SET @LookupID = 1;
WITH cteLevelOne (ParentID, CustID, Depth) AS
(
SELECT a.ParentID, a.CustID, 1
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID, c.Depth + 1
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustID
)
select * from CTELevelone where Depth = (select max(Depth) from CTELevelone)
</code></pre>
<p>or, adapting what trevor suggests, this could be used with the same CTE: </p>
<pre><code>select top 1 * from CTELevelone order by Depth desc
</code></pre>
<p>I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either.</p>
|
<p>First the cte will not be finished if any of the parent child are same. As it is a recursive CTE it has to be terminated. Having Parent and cust id same , the loop will not end.</p>
<p>Msg 530, Level 16, State 1, Line 15
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.</p>
| 5,577
|
<p>Access Datasheet view appears to be blank(charaters appear in white hence not visible) in WSS3.0</p>
|
<p>It sounds like a styling problem on your SharePoint page.</p>
|
<p>I got the issue fixed, only the page property needed to be changed and it worked. Now the data sheet is visible with data inside it in balck color</p>
| 46,798
|
<p>Is there any way to re-generate views from newly updated model?</p>
|
<p>Unless you've made a lot of changes to the scaffold, it's probably easier just to overwrite the current scaffold:</p>
<pre><code>./script/generate -f scaffold Model
</code></pre>
|
<p>The scaffold is not intended to <em>create</em> the interface, only to make a starting point for further development. I'm not sure it's even possible (without a lot of unnecessary work) to redo a scaffold, it's much quicker to manually edit the view and controller anyway.</p>
| 42,792
|
<p>Can someone provide a simple explanation of <strong>methods</strong> vs. <strong>functions</strong> in OOP context?</p>
|
<p>A <strong>function</strong> is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.</p>
<p>A <strong>method</strong> is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences:</p>
<ol>
<li>A method is implicitly passed the object on which it was called.</li>
<li>A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).</li>
</ol>
<p>(this is a simplified explanation, ignoring issues of <a href="http://en.wikipedia.org/wiki/Scope_(computer_science)" rel="noreferrer">scope</a> etc.)</p>
|
<p>A function is a set of instructions or procedures to perform a specific task. it can be used to split code into easily understandable parts, which can be invoked or reused as well.</p>
<p>Methods are actions that can be performed on objects. it is also known as functions stored as object properties.</p>
<p><strong>Major Difference:</strong>
A function doesn’t need any object and is independent, while the method is a function, which is linked with any object.</p>
<pre><code>//firstName() is the function
function firstName(){
cosole.log('John');
}
firstName() //Invoked without any object
</code></pre>
<pre><code>const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
};
//person.name is the method
person.name = function() {
return this.firstName + " " + this.lastName;
};
document.getElementById("demo").innerHTML =
"My father is " + person.name() //performs action on object;
</code></pre>
| 18,825
|
<p>Does anyone know how to write to an excel file (.xls) via OLEDB in C#? I'm doing the following:</p>
<pre><code> OleDbCommand dbCmd = new OleDbCommand("CREATE TABLE [test$] (...)", connection);
dbCmd.CommandTimeout = mTimeout;
results = dbCmd.ExecuteNonQuery();
</code></pre>
<p>But I get an OleDbException thrown with message:</p>
<blockquote>
<p>"Cannot modify the design of table
'test$'. It is in a read-only
database."</p>
</blockquote>
<p>My connection seems fine and I can select data fine but I can't seem to insert data into the excel file, does anyone know how I get read/write access to the excel file via OLEDB?</p>
|
<p>You need to add <code>ReadOnly=False;</code> to your connection string</p>
<pre><code>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=fifa_ng_db.xls;Mode=ReadWrite;ReadOnly=false;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";
</code></pre>
|
<ul>
<li>How do I check the permissions for writing to an excel file for my application (I'm using excel 2007)?</li>
<li>The file is not read only, or protected (to my knowledge).</li>
<li>My connection String is: </li>
</ul>
<blockquote>
<p>"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=fifa_ng_db.xls;Mode=ReadWrite;Extended
Properties=\"Excel
8.0;HDR=Yes;IMEX=1\""</p>
</blockquote>
| 8,242
|
<p>I can't seems to change the default color of the required field validator. In the source it is:</p>
<pre><code><span class="required">*</span>
<asp:RequiredFieldValidator ID="valReq_txtTracks" runat="server"
ControlToValidate="txtTracks"
Display="Dynamic" />
</code></pre>
<p>Here's what I have in my .skin file:</p>
<pre><code><asp:RequiredFieldValidator runat="server"
CssClass="error-text"
ErrorMessage="required" />
</code></pre>
<p>In the rendered source I see:</p>
<pre><code><span class="required">*</span>
<span id="ctl00_ctl00_cphContent_cphContent_valReq_txtTracks" class="error-text" style="color:Red;display:none;">required</span>
</code></pre>
<p>Notice the "style=color:Red;". That needs to go. I can't override it with a css-class because it's inline CSS. What should I do?</p>
|
<p>There is a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.forecolor.aspx" rel="noreferrer">RequiredFieldValidator.ForeColor</a> property you can set to control the color. Note that if you want to set the color in CSS, then you need to set ForeColor="" to clear it on the control.</p>
|
<p>Using <code>!important</code> seems to work fine in Firefox and IE, but for some reason not in Google Chrome... no biggie though, Chrome's share is still very low.</p>
<pre><code>.form_error
{
font: bold 15px arial black,arial,verdana,helvetica !important;
color: #ff0000 !important;
}
</code></pre>
| 27,052
|
<p>I have a few batch files I need to run frequently in developing a certain project. I'd like to create a Visual Studio toolbar called "MyProject" and have commands underneath to execute these batch files. What is the easiest way to accomplish this?</p>
|
<p>In the <em>Tools...</em> menu, select <em>External Tools...</em> and add references to the batch files. Then right-click on a toolbar, select <em>Customize...</em>, go to the <em>Toolbars</em> tab, click on <em>New...</em>, name your new toolbar, click on <em>OK</em>, go to the <em>Commands</em> tab, select the <em>Tools</em> category and drag-drop the appropriate <em>External Command</em> Command onto your custom tool bar.</p>
<p>If you need to run batch files that always run right before or after a build, you're probably better off making use of <a href="http://msdn.microsoft.com/en-us/library/e2s2128d.aspx" rel="noreferrer">build events</a>.</p>
|
<ol>
<li>How to install an icon in Visual Studio to run a batch file.</li>
<li>On the menu go to Tools > External Tools</li>
<li>Click Add and fill in the following:
<ol>
<li>Title: The name that shows up for the icon name.</li>
<li>Command: Browse to the file name and click ok or put the file path and file name here.</li>
<li>Check Use Output window if you want to see the batch files output in visual Studio.</li>
<li>Click OK.</li>
</ol></li>
<li>Make note of the position # of the Menu contents you just added starting from position 1 at top. You will use this as External Command # later on.</li>
<li>Go to Tools > Customize or right click in the toolbar area and click Customize.</li>
<li>Go to the Toolbars tab click New, Name the Toolbar name and click Ok.</li>
<li>Go to the Commands tab, select the Toolbar radio button, in the dropdown to the right select your toolbar name.</li>
<li>Click the Add Command Button. In the Categories select Tools and in the Commands to the right pick External Command # from above and click ok. It will appear in the tool bar now ready to go.</li>
</ol>
| 26,205
|
<p>Can anyone recommend a book or a website that explains Internet Explorer Automation using VB.NET? I understand that mshtml and ShDocVw.dll can do this, but I need a resource that will explain it to me. I want to read/write values as well as click buttons.</p>
<p>The only book I have come across so far is .Net Test Automation Recipes. Is this the one for me?</p>
<p>Thanks!</p>
|
<p>You can take a look at <a href="http://watin.sourceforge.net/index.html" rel="nofollow noreferrer">WatiN</a> if you want some source code that goes in depth in terms of automating IE. In fact it may do exactly what you are trying to do.</p>
|
<p>Check this article :
Internet Explorer Late Binding Automation
Internet Explorer automation sample code using late binding, without Microsoft.mshtml and shdocvw dependency.</p>
<p><a href="http://www.codeproject.com/KB/cs/IELateBindingAutowod.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/IELateBindingAutowod.aspx</a></p>
| 12,246
|
<p>I have found the "Getting Started" documents for developing apps on iPhone.</p>
<ol>
<li><p>I wanted the community's opinion on <strong>what I should know/learn</strong> (in terms of languages or concepts)?</p></li>
<li><p>How long would it take for a moderate programmer to learn and build an app that manages a list, connects to certain websites, etc?</p></li>
<li><p>How to get an app I made onto the iPhone? Just ZIP then install with .ipa file?</p></li>
</ol>
|
<blockquote>
<p>I wanted the community's opinion on what I should know/learn (in terms of
languages or concepts)?</p>
</blockquote>
<p>You will be using Objective-C and Cocoa. These are fairly strange concepts to crasp if you have not done MAC programming before, but after a short while you will probably fall in love with them. The most important concept to remember with iPhone development is <strong>memory management</strong> as the device has no concept of garbage collection.</p>
<blockquote>
<p>How long would it take for a moderate programmer to learn and build
an app that manages a list, connects
to certain websites, etc?</p>
</blockquote>
<p>Not too long. There are a multitude of example applications on the internet, and many helpful folk on stackoverflow.com</p>
<blockquote>
<p>How to get an app I made onto the iPhone? Just ZIP then install with
.ipa file?</p>
</blockquote>
<p>You will need to download the SDK, create an app using xcode on the mac (or similar environment for windows if there is one) - you can test with simulator without giving apple anything, but in order to <em>legitimately</em> test on device you need to become an apple developer.</p>
<p>However If you jailbreak your device, you will be able to follow one of several methods to get your application on the iphone bypassing apples restrictions.</p>
|
<p>First of all: buy a mac if you don't have one already, the windows tooling pipeline is basically non-existant. And trying to run OSX on non-apple harware is illegal in most situations.</p>
<p>Download the iPhone SDK. <a href="http://developer.apple.com/iphone/" rel="nofollow noreferrer">http://developer.apple.com/iphone/</a> should have everything you need.</p>
<p>Objective-C is a little bit on the strange side but a moderate programmer should be able to pick it up quite quickly.</p>
<p>Installation: i have no idea sorry...use the app store ;)</p>
| 46,421
|
<p>I've been trying to figure out how to print in Adobe AIR. I know the standard javascript functions don't work. The AIRforJSDev guide says:
"The window.print() method is not supported within Adobe
AIR 1.0. There are other methods available via the exposed AIRAPIs that give you access to printing within the runtime"</p>
<p>But I can't find those functions. I've looked in the language reference but can't find them there anywhere. Where are they and what are they ? </p>
|
<p>What you need to do is access the AS3 <a href="http://livedocs.adobe.com/flex/201/langref/flash/printing/PrintJob.html" rel="nofollow noreferrer">flash.printing.PrintJob</a> API. Here's a page on <a href="http://livedocs.adobe.com/air/1/devappshtml/help.html?content=ProgrammingHTMLAndJavaScript_05.html" rel="nofollow noreferrer">accessing flash API from javascript</a> (basically you just do window.runtime.XYZ where XYZ is the flash API). </p>
<p>You should look up tutorials on printing in flash, just need minor tweaks to do it from JS. Here's two random tutorials on printing in flash I found: <a href="http://blog.tikikitchen.com/2008/04/18/printing-in-flash-in-1000000000-simple-steps" rel="nofollow noreferrer">one</a>, <a href="http://snipplr.com/view/4942/as3-flash-printing-basics/" rel="nofollow noreferrer">two</a></p>
|
<p>If you're talking about just printing out to the console then you'll want the trace() method.</p>
<p>This can be accessed using air.trace() from within javascript assuming you have the AIRAliases.js file included.</p>
| 14,475
|
<p>Does anyone have any best practices, tips & tricks, or recommendations for how to create modal Alert Views with Cocoa Touch?</p>
<p>I like to think there is a way to make this difficult task trivial or at least easier.</p>
|
<p>You can use something like this:</p>
<pre><code>void AlertWithMessage(NSString *message)
{
/* open an alert with an OK button */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Name of the Application"
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
}
</code></pre>
|
<p>I just use UIAlertView to display modal alerts. What additional functionality are you looking for?</p>
| 45,128
|
<p>I have a custom control that inherits from WebControl and implements IValidator, but I also want to have a property for ValidationGroup. From research, it appears I need to inherit from BaseValidator to do so. Can anybody provide a successfull example from a ASP.Net custom control that implements both BaseValidator and IValidator?</p>
|
<p>I use <a href="http://www.esperanto.mv.ru/UniRed/ENG/" rel="nofollow noreferrer">UniRed</a> for Unicode-intensive stuff. (I don't use it as a general purpose editor though: jEdit). UniRed displays the hex value for the current glyph in the lower screen, which is really handy (even for ASCII).</p>
|
<p><a href="http://www.ultraedit.com/products/ultraedit.html" rel="nofollow noreferrer">Ultraedit</a> is my favorite text editor and it is advertised as having good Unicode support</p>
<p><a href="http://www.ultraedit.com/support/tutorials_power_tips/ultraedit/unicode.html" rel="nofollow noreferrer">http://www.ultraedit.com/support/tutorials_power_tips/ultraedit/unicode.html</a>.</p>
<p>It has the find / replace / regex features you're looking for as well as almost every other feature I have ever needed.</p>
| 29,046
|
<p>I have a bit of a problem. I wrote an API a long time ago for our production system, and it used Apache XML Beans. The schema was homogeneous (ie no imports, everything was from within the same schema), and everything worked just fine, even if the code for API handling was incredibly verbose. I've since written a far simpler and more elegant restful API using JAXB, with parts of the old one in mind, ie different schema, but some of the elements are identical. In the hopes of cleaning up and simplifying my binding code in the old API, I've replaced some of the parts by deleting them and importing the new schema and using those elements instead. However, whenever I try to parse documents that use the new mixture of schema, I get a validation error from XML Beans :</p>
<pre><code>error: cvc-complex-type.2.4a: Expected element 'redundant-element@http://www.my.com/old/xmlns' instead of 'redundant-element@http://www.my.com/new/xmlns' here in element redundant-element-list@http://www.my.com/old/xmlns
</code></pre>
<p>Has anybody encountered this before ? Have any solutions or ideas ? I'd really appreciate it. Thank you kindly.</p>
|
<p>Handle the Leave event of your textBox1. Inside the event handler, if your conditions are not met, for e.g. if the user has not entered some input, reset the focus back to the control.</p>
<pre><code>private void textBox1_Leave(object sender, EventArgs e)
{
if string.isNullOrEmpty(textBox1.Text)
{
textBox1.focus();
}
}
</code></pre>
<p>Do this for each of your controls or do it more generic like:</p>
<pre><code>private void textBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (string.isNullOrEmpty(textBox.Text)
{
textBox.focus();
}
}
</code></pre>
|
<p>Handle the Leave event of your textBox1. Inside the event handler, if your conditions are not met, for e.g. if the user has not entered some input, reset the focus back to the control.</p>
<pre><code>private void textBox1_Leave(object sender, EventArgs e)
{
if string.isNullOrEmpty(textBox1.Text)
{
textBox1.focus();
}
}
</code></pre>
<p>Do this for each of your controls or do it more generic like:</p>
<pre><code>private void textBox_Leave(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (string.isNullOrEmpty(textBox.Text)
{
textBox.focus();
}
}
</code></pre>
| 35,708
|
<p>In a .net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing?</p>
<hr>
<p>The queue is a great idea. I've been throwing around that type of process for awhile with my old company.</p>
|
<p>From a high level, yes. :D The main thing is some place to store the templates. A database is a great option unless you're not already using one, then file systems work fine.</p>
<p>WSIWIG editors (such as fckeditor) work well and give you some good options regarding the features that you allow.</p>
<p>Some sort of token replacement system is also a good idea if you need it. For example, if someone puts %FIRSTNAME% in the email template, the code that generates the email can do some simple pattern matching to replace known tokens with other known values that may be dynamic based on user or other circumstances.</p>
|
<p>Are you just talking about the interface and storage, or the implementation of sending the emails as well?</p>
<p>Yes, a SQL table with FROM, TO, Subject, Body should work for storage and, heck, a textbox or even maybe a RichText box should work for editing.</p>
<p>Or is this a web interface?</p>
<p>For actually sending it, check out the System.Web.Mail namespace, it's pretty self explanatory and easy to use :)</p>
| 2,803
|
<p>As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?</p>
|
<p>Use the <<a href="http://nant.sourceforge.net/release/0.85-rc1/help/tasks/attrib.html" rel="noreferrer">attrib</a>> task. For example, to make the file "test.txt" read/write, you would use</p>
<pre><code><attrib file="test.txt" readonly="false"/>
</code></pre>
|
<p>Also, for a list of files, the command is:</p>
<pre><code><attrib readonly="false">
<fileset basedir="mydirectory">
<include name="**"/>
</fileset>
</attrib>
</code></pre>
| 10,106
|
<p>I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.</p>
<p>I tried something like this:</p>
<pre><code>void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
</code></pre>
<p>But i get a template error calling random_shuffle with rand. However this works:</p>
<pre><code>unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
</code></pre>
<p>Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?</p>
|
<p>In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).</p>
<p>This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler.</p>
|
<p>I thought it was worth pointing out that this is now pretty straightforward in C++11 using only the standard library:</p>
<pre><code>#include <random>
#include <algorithm>
std::random_device rd;
std::mt19937 randEng(rd());
std::shuffle(vec.begin(), vec.end(), randEng);
</code></pre>
| 17,744
|
<p>I would like to build a web application on Castle MonoRail, I was wondering how can we use an action with extension and another action without extension? How can HTML helper generator url for us?</p>
<p>Ex: </p>
<ul>
<li><a href="http://mysite.com/Products/list" rel="nofollow noreferrer">http://mysite.com/Products/list</a></li>
<li><a href="http://mysite.com/Products/abc.castle" rel="nofollow noreferrer">http://mysite.com/Products/abc.castle</a></li>
</ul>
|
<p>The answer is <strong>Yes</strong>, you can, by using routing.
The exact method you need to use to get the routing working depends upon which version of Monorail you are using. However, adding routing can have some negative impact on performance unless you are careful.</p>
<p>It is also worth noting that you don't have to use the extension ".castle" or ".rails" in case this is what is distasteful to you.</p>
|
<p>You can try creating a routing role like</p>
<pre><code>/<controller>/<action>.castle
</code></pre>
<p>and it would do the trick.</p>
| 41,413
|
<p>I've been looking for a tool to extract exception information from a C++ program. The most wanted feature I'm looking for: I want to know all the exceptions that can be thrown from a function (which would include all the function that is called from that function recursively).</p>
<p>I've always thought that documenting errors and exceptions in particular is very hard (and takes a lot of effort to keep up to date). But if there is some way to automate that, it would be very helpful.</p>
<p>A tool for windows and Visual Studio would be preferred but not necessary, I could always work around that.</p>
|
<p><a href="http://www.gimpel.com/" rel="nofollow noreferrer">PC-Lint</a> claims to do static exception analysis of C++ code.<br>
<a href="http://www.coverity.com/" rel="nofollow noreferrer">Coverity</a> is another static C++ code analysis tool that apparently informs you of unhandled exceptions.<br>
<a href="http://www.automatedqa.com/products/aqtime/index.asp" rel="nofollow noreferrer">AQtime</a> claims to have exception tracing as part of its code analysis. Plus, they advertise Visual Studio integration.<br>
<a href="https://web.archive.org/web/20111007220353/http://testingfaqs.org/t-static.html" rel="nofollow noreferrer">Here</a> is a list of several static code analysis tools.</p>
|
<p>EDoC++ (<a href="http://edoc.sourceforge.net" rel="nofollow noreferrer">http://edoc.sourceforge.net</a>) is another alternative.</p>
| 4,793
|
<p>I need to be able to retrieve a CREATE TABLE script to recreate a specific table in a SQL Server (2000) database, programmatically (I'm using C#). Obviously you can do this with Enterprise Manager but I would like to automate it. </p>
<p>I've been playing around with SQLDMO which offers a Backup command, but I'm not sure if this will give a SQL CREATE TABLE script and seems to require the creation of a SQL Service device, and I would prefer to avoid modifying the database.</p>
|
<p>Take a look at <a href="http://www.stackoverflow.com/questions/21547/in-mssql-how-do-i-generate-a-create-table-statement-for-a-given-table">my solution</a>. It's a sql script which uses the INFORMATION_SCHEMA tables to get the necessary information. It's basic, but might work for you.</p>
|
<p>You can use SMO to generate the scripts. For more info see: <a href="http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated" rel="nofollow noreferrer">http://www.sqlteam.com/article/scripting-database-objects-using-smo-updated</a></p>
| 7,144
|
<p>Can pipes be used across LAN computers?</p>
<p>In particular I'm looking for Windows, but if you have more info on other platforms, that will also help others who find this thread later. </p>
|
<p>Yes they can.</p>
<blockquote>
<p>Named pipes can be used to provide
communication between processes on the
same computer or between processes on
different computers across a network.
If the server service is running, all
named pipes are accessible remotely</p>
</blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/aa365590.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365590.aspx</a></p>
|
<p>It should also be noted that a TCP/IP connection is effectively a pipe in the sense that you shove bytes in one end and they come out the other. TCP/IP connections are available on pretty much any platform you are likely to care about.</p>
| 23,298
|
<p>I am using DoCmd.SendObject to send emails from MS access 2003. It opens the outlook with all relevant fields filled. But the user may not choose to send the email at that time. In that case, a prompt 'Send Action was cancelled' appears. Is there a way to catch this non-sending of email by user</p>
|
<p>It is possible to use Outlook events from Microsoft Access with a class module. You will find details in the <a href="http://wiki.lessthandot.com/index.php/Access_and_Email" rel="nofollow noreferrer">LessThanDot wiki</a>, under the heading "Example: Use Outlook Events with Access"</p>
|
<p>Perhaps Tony Toews's <a href="http://www.granite.ab.ca/Access/email.htm" rel="nofollow noreferrer">Access EMail FAQ</a> would be of use to you.</p>
| 22,670
|
<p>What is the best method for executing FTP commands from a SQL Server stored procedure? we currently use something like this:</p>
<pre><code>EXEC master..xp_cmdshell 'ftp -n -s:d:\ftp\ftpscript.xmt 172.1.1.1'
</code></pre>
<p>The problem is that the command seems to succeed even if the FTP ended in error. Also, the use of <code>xp_cmdshell</code> requires special permissions and may leave room for security issues.</p>
|
<p>If you're running SQL 2005 you could do this in a CLR integration assembly and use the FTP classes in the System.Net namespace to build a simple FTP client.</p>
<p>You'd benefit from being able to trap and handle exceptions and reduce the security risk of having to use xp_cmdshell.</p>
<p>Just some thoughts.</p>
|
<p>If you need to do FTP from within the database, then I would go with a .NET assembly as Kevin suggested. That would provide the most control over the process, plus you would be able to log meaningful error messages to a table for reporting.</p>
<p>Another option would be to write a command line app that read the database for commands to run. You could then define a scheduled task to call that command line app every minutes or whatever the polling period needed to be. That would be more secure than enabling CLR support in the database server.</p>
| 2,627
|
<p>When I press F5 in Visual Studio 2008, I want Google Chrome launched as the browser that my ASP.NET app runs in. May I know how this can be done?</p>
|
<p>Right click on an .aspx file and click "Browse with..." then select Chrome and click "Set as Default." You can select more than one browser in the list if you want.</p>
<p>There's also this really great <a href="http://visualstudiogallery.msdn.microsoft.com/bb424812-f742-41ef-974a-cdac607df921/" rel="noreferrer">WoVS Default Browser Switcher Visual Studio extension</a>.</p>
|
<p>In case you are using Visual Studio 2019: To change default browser
type defaults in home, then click browser.</p>
<p>See this picture:</p>
<p><a href="https://i.stack.imgur.com/qVaJp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qVaJp.jpg" alt="defaults apps" /></a></p>
<p><a href="https://learn.microsoft.com/en-us/answers/questions/31013/browser-selection-in-visual-studio-2019.html" rel="nofollow noreferrer">Reference/Source</a></p>
| 8,365
|
<p>Is there an easy way to create a table in SQL Server (2005) from an Excel spreadsheet. I'm thinking maybe some tool?</p>
<p>Thanks in advance.</p>
|
<p>If the data is not that big and if it is a simple table, easiest way is to create and open the table in SQL Server Management Studio and copy paste the excel data into it.</p>
<p>Other solutions are using DTS or using <a href="https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=205" rel="nofollow noreferrer">SSIS</a>..</p>
|
<p>You can write VBA code in Excel:</p>
<ul>
<li>Open a connection to the database</li>
<li>Build the table</li>
<li>Start filling records by looping through the rows of the spreadsheet Excel</li>
</ul>
| 21,607
|
<p>As good developers we keep our code as standard compliant as possible to help in porting between platforms. But what tools are available that help us build the code in a uniform way across multiple platforms.</p>
<p>*nix family has <code>make</code> but Windows needs <code>nmake</code>.</p>
<p>I have read about <a href="http://www.scons.org" rel="nofollow noreferrer">SCons</a> but never used it in anger. What is your favorite build tool, why do you find it effective and are there any limitations (<strong>i.e.</strong> platforms with bad support etc).</p>
<p>Cross platform IDEs as well.</p>
|
<p>cmake for c/c++ environments is good. <a href="http://www.cmake.org/" rel="nofollow noreferrer">http://www.cmake.org/</a></p>
|
<p>If you're in the Java world, there are quite a few tools which are cross-platform. Apache Ant and Maven are both build tools which will run on any platform which has Java available for it.</p>
<p>Cruise Control (continuous integration tool) also works on Windows and Linux (it's written in Java as well).</p>
<p>I haven't had any real issues with the core tools, the only problems I've sometimes had have come from things external to the build process, i.e. publishing artifacts - this will vary between systems so I've found there's no single way of setting it up.</p>
| 21,397
|
<p>I'm trying to make it so when a user scrolls down a page, click a link, do whatever it is they need to do, and then come back to the pages w/ links, they are at the same (x-y) location in the browser they were before. How do I do that?</p>
<p>I'm a DOM Newbie so I don't know too much about how to do this. </p>
<p>Target Browsers: IE6/7/8, Firefox 2/3, Opera, Safari</p>
<p>Added: I'm using a program called JQuery to help me learn</p>
|
<p>To get the x-y location of where a user clicked on a page, use the following jQuery code:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#special").click(function(e){
$('#status2').html(e.pageX +', '+ e.pageY);
});
});
</script>
</head>
<body>
<h2 id="status2">
0, 0
</h2>
<div style="width: 100px; height: 100px; background:#ccc;" id="special">
Click me anywhere!
</div>
</body>
</html>
</code></pre>
|
<p>you can use offsetLeft and offsetTop</p>
| 9,323
|
<p>
We recently switched our Windows software packages from RPM (cygwin) to MSI (wix). Having a native packaging is a much welcome change and we intend to stick with it. However, MSI feels overly complicated for what it does and doesn't seem to provide some basic abilities. But I'm probably mistaken.
</p>
<p>
Is there a way to list all installed MSI from the command line ?
</p>
|
<p>Mabybe <a href="http://msdn.microsoft.com/en-us/library/aa394378(VS.85).aspx" rel="noreferrer">this</a> is a good starting point for you example VB Script from MSDN:</p>
<pre><code>strComputer = "."
Set objWMIService = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
strComputer & _
"\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("SELECT * FROM Win32_Product")
If colSoftware.Count > 0 Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile( _
"c:\SoftwareList.txt", True)
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Version
Next
objTextFile.Close
Else
WScript.Echo "Cannot retrieve software from this computer."
End If
</code></pre>
|
<p>I'm not sure if this is what you need but you can query the uninstall list from the command line with:</p>
<pre><code>REG QUERY HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall
</code></pre>
| 24,122
|
<p>I regularly achieve 100% coverage of libraries using TDD, but not always, and there always seem to be parts of applications left over that are untested and uncovered.<br>
Then there are the cases when you start with legacy code that has very few tests and very little coverage. </p>
<p>Please say what your situation is and what has worked that at least <em>improved</em> coverage.<br>
I'm assuming that you are measuring coverage during unit testing, but say if you are using other techniques.</p>
|
<p>Delete code.</p>
<p>This isn't snarky, but actually serious. Any time I would see the smallest amount of code duplication or even code that I couldn't get to execute, I deleted it. This increased coverage and increased maintainability.</p>
<p>I should note that this is more applicable to increasing the coverage of old code bases vs. new code bases. </p>
|
<p><a href="http://en.wikipedia.org/wiki/Framework_for_Integrated_Tests" rel="nofollow noreferrer">FIT testing</a> has improved our code coverage. It has been great because it is an entirely different tack.</p>
<p>Background: we have a mix of legacy and new code. We try to unit/integration test the new stuff as much as possible, but because we are migrating to Hibernate/Postgres and away from an OODB, there isn't much point to testing the legacy code.</p>
<p>For those who don't know, FIT is a way to test software from the user perspective. Essentially, you can specify desired behaviour in HTML tables: the tables specify the actions against the software and the desired results. Our team writes 'glue code' (aka FIT test) that map the actions to calls against the code. Note that these tests operate in a view 'from space' compared to unit tests.</p>
<p>Using this approach, we have increased our code-coverage by several percentage points. An added bonus is that these tests will bridge across versions: they will test legacy code but then, later, new code. i.e. they serve as regression tests, in a sense.</p>
| 20,597
|
<p>Consider two tables transaction and category each having their own ID and information.</p>
<p>A transaction can have more than one category, I have read creating a 3rd table to link transaction and category using their IDs is best. But what would you call this table, assuming you would have many like it?</p>
<p>transactionCategories is the best I'm coming up with, is there anything better?</p>
|
<p>My naming scheme for these is to use the terminology of the domain for the interaction if there is one (eg. not <code>student_class</code>, but <code>enrollment</code>). When there is no such terminology, then you fall back onto <code>transaction_category</code> or <code>category_transaction</code> whichever sounds better. </p>
<p>Also, I always name my tables in the singular (e.g. student and not students).</p>
|
<p>TransactionCategories is just fine. There probably isn't anything "better", just different.</p>
<p>At times in the past, when I have created a table that just has the two foreign keys it needs to resolve the many-to-many, I append "Xref" to its name, which gives a clue that it doesn't have any attributes. It's just there to resolve the many-to-many.</p>
| 35,853
|
<p>Is there a <a href="http://en.wikipedia.org/wiki/ZeroConf" rel="nofollow noreferrer">ZeroConf</a> client extension for Firefox/XULRunner to be used in a zeroConf environment based on either <a href="http://files.multicastdns.org/draft-cheshire-dnsext-multicastdns.txt" rel="nofollow noreferrer">mDNS</a> or <a href="http://en.wikipedia.org/wiki/Service_Location_Protocol" rel="nofollow noreferrer">SLP</a>?</p>
<p>I know of an extension already that's being developed by the <a href="http://svn.openkomodo.com/openkomodo/browse/addons/sdconnector/" rel="nofollow noreferrer">ActiveState Open Komodo</a> folks but it requires PyXPCOM support to be baked into the XULRunner runtime in order to access the Apple <a href="http://developer.apple.com/networking/bonjour/download/" rel="nofollow noreferrer">Bonjour</a> libs for Windows. Is there anything else available?</p>
|
<p><a href="http://www.opensrs.com" rel="nofollow noreferrer">www.opensrs.com</a> charge a one-off $95 setup fee (which converts into $95 credit on the account). That's not quite what you asked for, but it is pretty low. You get access to a well documented, functional API. However you need to pay for domains by making a credit to your account, then buying the domain from there. I don't think there are any limits on how small this initial deposit can be.</p>
|
<p><a href="http://www.dotster.com/resources/partnerships/" rel="nofollow noreferrer">Dotster</a> Actually has a free reseller program, and they used to have an API that you could use to register domain names. Something to look into anyway, if you want to automatically register domain names.</p>
| 23,427
|
<p>I'm looking for a (preferably free) component for Delphi for users to easily select about 100 different colours.</p>
<p>I've currently got one as part of DevExpress's editors, but it only has about 20 proper colours to choose, with a bunch of other 'Windows' colours like clHighlight, clBtnFace, etc.</p>
<p>It's for regular users, so would like to avoid requiring them to manually select RGB values. </p>
<p>Something similar to the colour picker in MS Paint might work, or something that lists X11/web colours:</p>
<p><a href="http://en.wikipedia.org/wiki/Web_Colors" rel="noreferrer">http://en.wikipedia.org/wiki/Web_Colors</a></p>
<p>So, please let me know if you got any recommendations.</p>
<p><strong>Thanks for the suggestions from everyone</strong></p>
<p>All of the suggestions were good, I didn't realise the MS Paint colour dialog can be called, that's all I needed and is the simplest solution. Thanks</p>
|
<p>What's wrong with the TColorDialog?<br>
It gives you the standard Windows color dialog, exactly the same as in MSPaint...<br>
Add these options to show it directly expanded and with all colors available. </p>
<pre><code>object ColorDialog1: TColorDialog
Options = [cdFullOpen, cdAnyColor]
end
</code></pre>
|
<p>There was an article about creating a custom colour selection component in issue 3 of the blaise pascal magazine.</p>
<p><a href="http://www.blaisepascal.eu/blaisepascal_3/color_selection_component_david_dirkse.php" rel="nofollow noreferrer">http://www.blaisepascal.eu/blaisepascal_3/color_selection_component_david_dirkse.php</a></p>
| 35,371
|
<p>Does anyone know how to debug <code>JSP</code> in <strong>IntelliJ</strong> IDEA?</p>
<p>When I set breakpoint in my <code>JSP</code> files, those breakpoints never seem to take effect. The debugger never hits them. IDEA seems to think that the breakpoints are valid. I do see a red dot placed to the left of the line where I place my breakpoint.</p>
<p>I read in IntelliJ forum <a href="http://intellij.net/forums/thread.jspa;jsessionid=2B86A25AECC06A4BE3447388882AA79F?messageID=5218405&#5218405" rel="noreferrer">in this post</a> that <code>JSP</code> files need to be under web-inf for debugging to work. </p>
<p>But then I also read that <code>JSP</code> files placed under web-inf won't be directly accessible by the user.</p>
<p>I am not sure who's really right. </p>
|
<p>For JSP debugging in Intellij there are some configurations that must be in order. The fact that Intellij always allows you to add a breakpoint on a JSP line does not necessarily imply that you’ve configured JSP debugging. In the following I refer to Intellij 8 configuration, w.r.t. previous versions you will need to do similar operations as the concepts are the same.</p>
<p>In order to enable JSP debugging you must do two steps: set a web application configuration in your project and add a web application server configuration.</p>
<p><em>Web application Configuration</em>: in order to have JSP debugging, you must have a “web” facet in your project structure, pointing to the correct web.xml file. Depending on the kind of web application structure you are using, the facet may be detected automatically by Intellij (go anyway to check what it has done) or you may have to add it manually. Remember in the “Java EE build settings” tab to set as anable “Create web facet exploded directory”; if you don’t want duplications, a trick is just to enable it and point to your already existing directory.</p>
<p><em>(Web) Application server</em>: Go to “edit configurations”, there you have to add to configurations an application server, not launch the web server as an application like any other. In this way Intellij will be able to intercept JSP calls. In the list of application servers, you should have the default one, Tomcat. Be sure to have a local Tomcat installation before you do this, and point to that when adding the web application server. The last trick is going to the “Deployment” tab and selecting as “Deployment source” the same facet that you configured in the previous step.</p>
<p>The same configuration works if you want to use another web application server, I tested it with the latest Caucho Resin releases and debugging works fine (it didn’t with the previous Intellij and Resin combinations).</p>
<p>If you don’t see Tomcat in the list of available application servers to add, check the plugins in the general Intellij settings pane: in the latest releases, more and more functionality has become “pluggable”, and even very basic functions may be disabled; this plugin is called “Tomcat integration”.</p>
<p>Finally, it is surely not true that JSP files need to be under WEB-INF to be under debugging.</p>
|
<p>For the second part of your question ("jsp files placed under web-inf won't be directly accessible by user") that is correct. To allow users to access JSP files in the WEB-INF folder servlet and servlet-mapping entries need to be made in the web.xml file for each JSP page. </p>
| 5,381
|
<p>I'm using browser automation for testing web sites but I need to verify HTTP requests from the browser (i.e., images, external scripts, XmlHttpRequest objects). Is there a way to programmatically instantiate a proxy or packet sniffer for the browser to use in order to see what its sending?</p>
<p>I'm already using Fiddler to watch the traffic but I want something that's UI-less that I can use in continuous build integration.</p>
<p>Can I easily get the HTTP-specific information from WinpCap?</p>
|
<p>Try winpcap . It's a driver/library combination which can be used to monitor packets. Based on what you are trying to do (watch traffic w/o a UI), this is probably a simpler solution than writing your own proxy.</p>
|
<p>Have you looked at implementing an Http Module or an Http Handler (.ashx)? They will allow you to intercept each and every web request and process them as you need before getting to your page.</p>
| 16,622
|
<p>When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during <code>wm_close</code> - is <code>DestroyHandle</code> the .net equivalent?</p>
<hr>
<p>I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg:</p>
<pre><code>void Dispose(bool disposing) {
otherObject.Event -= myEventHandler;
}
</code></pre>
|
<p>Normally <code>DestroyHandle</code> is being called in <code>Dispose</code> method. So you need to make sure that all controls are disposed to avoid resource leaks.</p>
|
<p>Normally <code>DestroyHandle</code> is being called in <code>Dispose</code> method. So you need to make sure that all controls are disposed to avoid resource leaks.</p>
| 6,506
|
<p>I would like to know what kind of toolkits, languages, libraries exist for agent-based modeling and what are the pros/cons of them?</p>
<p>Some examples of what I am thinking of are
<a href="http://www.swarm.org" rel="noreferrer">Swarm</a>, <a href="http://repast.sourceforge.net/" rel="noreferrer">Repast</a>, and <a href="http://www.aitia.hu/services_and_products/simulation_systems/mass" rel="noreferrer">MASS</a>.</p>
|
<p>I found a survey from June 2009 that answer your question: </p>
<p>Survey of Agent Based Modelling and Simulation Tools</p>
<p>Au. R.J. Allan </p>
<blockquote>
<p><strong>Abstract</strong><br>
Agent Based Modelling and Simulation is a computationally
demanding technique based on discrete event simulation and having its
origins in genetic algorithms. It is a powerful technique for
simulating dynamic complex systems and observing “emergent” behaviour.
The most common uses of ABMS are in social simulation and optimisation
problems, such as traffic flow and supply chains. We will investigate
other uses in computational science and engineering. ABMS has been
adapted to run on novel architectures such as GPGPU (e.g. nVidia using
CUDA). Argonne National Laboratory have a Web site on Exascale ABMS
and have run models on the IBM BlueGene with funding from the SciDAC
Programme. We plan to organise a workshop on ABMS methodolgies and
applications in summer of 2009. Keywords agent based modelling,
Archaeology</p>
</blockquote>
<p><a href="http://epubs.cclrc.ac.uk/bitstream/3637/ABMS.pdf" rel="nofollow noreferrer">http://epubs.cclrc.ac.uk/bitstream/3637/ABMS.pdf</a></p>
|
<p>PHP and Java developers should take a look at <a href="http://kato.sourceforge.net/kato.html" rel="nofollow noreferrer">KATO</a>.</p>
| 20,131
|
<p>In bash, environmental variables will tab-expand correctly when placed after an echo command, for example:</p>
<pre><code>echo $HOME
</code></pre>
<p>But after cd or cat, bash places a \ before the $ sign, like so:</p>
<pre><code>cd \$HOME
</code></pre>
<p>If I use a variable as the second argument to a command, it won't expand at all:</p>
<pre><code>cp somefile $HOM
</code></pre>
<p>What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress?</p>
|
<p>Try <strong><em>complete -r cd</em></strong> to remove the special programmatic completion function that many Linux distributions install for the <code>cd</code> command. The function adds searching a list of of directories specified in the CDPATH variable to tab completions for <code>cd</code>, but at the expense of breaking the default completion behavior.</p>
<p>See <a href="http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion" rel="nofollow noreferrer">http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion</a> for more gory details.</p>
|
<p>I'm answering 4-year-old question! Fantastic!</p>
<p>This is a bash bug/feature which was unintentionally introduced in v4.2, and was unnoticed for a long period of time. This was pointed out by geirha in <a href="https://askubuntu.com/questions/41891/bash-auto-complete-for-environment-variables">this tread</a>. Confirmed as unintended feature <a href="http://lists.gnu.org/archive/html/bug-bash/2011-02/msg00296.html" rel="nofollow noreferrer">here</a> </p>
<p>I came across this problem when running Ubuntu at home. At work I have bash-3.00, so I've spent some time browsing around to see what's going on. I wonder if I can 'downgrade'....</p>
| 12,887
|
<p>I am developing a C++ domain model class library which should provide some facilities or a framework (i.e. interface classes etc) for writing/reading class instance data to/from both a binary file and a RDBMS. The basis for this library is an application that uses a RDBMS, and there are several methods which instantiate a class by performing a sequence of database retrieve and update calls to fetch collections of member data. The serialized data access has a different way of organizing its data, so I want the domain model to be completely ignorant of primary/foreign keys, IDs etc. </p>
<p>To solve this problem, I consider using the <a href="http://en.wikipedia.org/wiki/Data_Access_Object" rel="nofollow noreferrer">Data Access Object</a> (DAO) pattern, and would like to have some advice on the 'granularity', lifetime and use of DAO objects (in your replies, please note that I'll be using C++, not Java, and that the domain class cannot hold any ID/key info from the RDBMS or binary file store):</p>
<ol>
<li>Does each Foo instance of a domain object have its own FooDAO instance, or is there a single FooDAO instance for all instances of class Foo?</li>
<li>Is the FooDAO created once for each Foo instance, or would the FooDAO instance be created only when access to data is needed, and destroyed immediately afterwards?</li>
<li>The <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html" rel="nofollow noreferrer">J2EE</a> page on DAO introduces a DTO in addition to the DAO. Why can't the DAO transfer the data?</li>
<li>For a complex domain class Foo that has instances of other domain classes Bar, it seems inevitable that the FooDAO class uses the BarDAO class to retrieve data. This would lead to parallel hierarchies/dependencies in the domain class structure and the DAO class structure. How can this be managed best?</li>
</ol>
<p>Thanks for your help! </p>
|
<p>I don't have a good solution for you, but I can tell you what I have, and some thoughts and experiences. I have built something very similar, based on a model I had seen used before, as a C++ library.</p>
<p>Some thoughts, in no particular order:</p>
<ul>
<li>Have a separate instance of the DAO object for each instance in the DB. If you have a shared instance, thread synchronization may be a problem, and you'll be forced into doing a lot of copies.</li>
<li>My library DAO classes use types closely associated with the RDBMS types, for a couple of reasons. First, the library supports automatic creation and update of storage in the underlying data store, so the classes need to have enough information to create the tables. Second, it makes data transition much easier, and optimizable (you can do direct ODBC/OLEDB data copies using the native interfaces, for example). The downside is that you can't have "nice" class types in the DAO objects (eg: string abstractions with more data than the actual string buffer).</li>
<li>I create on demand, certainly, because there's potentially much more data in the store than would be practical to put in memory.</li>
<li>I try to keep the DAO classes simple, with minimal accessor functionality, and "close" to the underlying data structures. That means no inheritance from other DAO classes, instances have key variable members, etc.</li>
</ul>
<p>On top of the DAO classes I build more accessible classes which represent the data in my application, and may or may not map 1-1 to a DAO class. These are allowed to have any type of members and structure, are supposed to be what the app uses, and have methods to copy data to/from the DAO classes which underlie them.</p>
<p>Hope that helps.</p>
|
<p>I don't know the best implementation, but here's what I've seen done:</p>
<ol>
<li>Separate for each instance.</li>
<li>Created right before it is needed and destroyed right after.</li>
<li>Don't know.</li>
<li>Combine the data outside of the DAO instances, thereby avoiding the coupling.</li>
</ol>
<p>Disclaimer: This is just what I've seen done.</p>
| 24,037
|
<p>I'm writing an editor for large <em>archive files</em> (see below) of 4GB+, in native&managed C++.</p>
<p>For accessing the files, I'm using <em>file mapping</em> (see below) like any sane person. This is absolutely great for reading data, but a problem arises in actually editing the archive.
File mapping does not allow resizing a file while it's being accessed, so I don't know how I should proceed when the user wants to insert new data in the file (which would exceed the file's original size, when it was mapped.)</p>
<p>Should I remap the whole thing every time? That's bound to be slow. However, I'd want to keep the editor real-time with exclusive file access, since that simplifies the programming a lot, and won't let the file get screwed by other applications while being modified. I wouldn't want to spend an eternity working on the editor; It's just a simple dev-tool for the actual project I'm working on.</p>
<p>So I'd like to hear how you've handled similar cases, and what other archiving software and especially other games do to solve this?</p>
<p>To clarify:</p>
<ul>
<li><p>This is not a text file, I'm writing a specific binary <em>archive file format</em>. By which I mean a big file that contains many others, in directories. Custom archive files are very common in game usage for a number of reasons. With my format, I'm aiming to a similar (but somewhat simpler) structure as with <a href="http://www.wunderboy.org/docs/gcfformat.php" rel="nofollow noreferrer">Valve Software's GCF format</a> - I would have used the GCF format as it is, but unfortunately no editor exists for the format, although there are many great implementations for reading them, like <a href="http://nemesis.thewavelength.net/index.php?p=35" rel="nofollow noreferrer">HLLib</a>.</p></li>
<li><p>Accessing the file must be fast, as it is intended for storing game resources. So it's not a database. Database files would be contained inside it, along with GFX, SFX etc. files.</p></li>
<li><p>"File mapping" as talked here is a specific technique on the Windows platform, which allows direct access to a large file through creating "views" to parts of it, see here: <a href="http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx</a> - This technique allows minimal latency and memory usage and is a no-brainer for accessing any large files.
So this does <em>not</em> mean reading the whole 4GB file into memory, it's exactly the contrary.</p></li>
</ul>
|
<p>What do you mean by 'editor software'? If this is a text file, have you tried existing production-quality editors, before writing your own? If it's a file storing binary data, have you considered using an RDBMS and manipulating its contents using SQL statements?</p>
<p>If you absolutely have to write this from scratch, I'm not sure that mmapping is the way to go. Mmapping a huge file will put a lot of pressure on your machine's VM system, and unless there are many editing operations all over the file its efficiency may lag behind a simple read/write scheme. Worse, as you say, you have problems when you want to extend the file.</p>
<p>Instead, maintain buffer windows to the file's data, which the user can modify. When the user decides to save the file, traverse sequentially the file and the edited buffers to create the new file image. If you have disk space it's easier to write a new file (especially if a buffer's size has changed), otherwise you need to be clever on how you read-ahead existing data, before you overwrite it with the new contents. </p>
<p>Alternatively, you can keep a journal of editing operations. When the user decides to save the file, perform a topological sort on the journal and play it on the existing file to create the new one.</p>
<p>For exclusive file access use the file locking of your operating system or implement application-level locking (if only your editor will touch these files). Depending on mmap for exclusive access constrains your implementation choices.</p>
|
<p>I'd build the large file from pieces at build-time. You have your editor deal with normal, flat files, in the usual file system (with subdirectories, etc., as appropriate). You then have a compile step that gathers all of these pieces together into your <em>archive</em> file format.</p>
| 23,783
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.