instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I need to insert some data into a table in Oracle. </p>
<p>The only problem is one of the fields is a timestamp(6) type and it is required data. I don't care about what actually goes in here I just need to get the right syntax for an entry so that the database will accept it.</p>
<p>I'm using the gui web client to enter data however I don't mind using raw SQL if I have to.</p>
<p>Thanks.</p>
|
<p>I dunno if this helps at all, but in SQL*Plus I did this:</p>
<pre><code>create table x ( a timestamp(6));
insert into x values ( current_timestamp );
select * from x;
</code></pre>
<p>getting me this:</p>
<pre><code>T
---------------------------------------------------------------------------
15-OCT-08 02.01.25.604309 PM
</code></pre>
<p>So it looks like that works.</p>
<p>If you need to put a previously-known value into the column, how about the TO_TIMESTAMP() function? Something like this:</p>
<pre><code>select to_timestamp('27/02/2002 15:51.12.539880', 'dd/mm/yyyy hh24:mi.ss.ff')
from dual ;
</code></pre>
|
<p>Here are a couple of different TO_TIMESTAMP functions that worked for me...</p>
<p>This TO_TIMESTAMP function worked on an INSERT against a column of type TIMESTAMP(6):</p>
<pre><code>TO_TIMESTAMP('04/14/2015 2:25:55','mm/dd/yyyy hh24:mi.ss.ff')
</code></pre>
<p>This TO_TIMESTAMP function worked on an INSERT against a column of type DATE:</p>
<pre><code>TO_TIMESTAMP('04/15/2015','mm/dd/yyyy')
</code></pre>
| 25,040
|
<p>My AS3-heavy project tests fine in the IDE, but some parts don't work in the browser when published. Any ideas what could be causing this?</p>
|
<p>It might help if you provide some more specific information on what's not working. Can you post a link? Furthermore, are any parts of your project referencing any remote objects? If so, you might want to make sure your remote objects are located where your app expects them to be. You may also need to add a crossdomain.xml to your server root if you're doing any cross site scripting.</p>
|
<p>Cross domain issues?</p>
<p>Case sensitivity on a non-windows server? </p>
<p>You can always initiate a remote debug with the flash debugger to establish the cause. The docs explain how to do this.</p>
| 26,677
|
<p>I'm using <code>ColdFusion</code> to populate a template that includes HTML unordered lists (<code><ul></code>s).</p>
<p>Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns.</p>
<p>Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling.</p>
|
<p>So I dug up this article from A List Apart <a href="http://www.alistapart.com/articles/multicolumnlists" rel="noreferrer">CSS Swag: Multi-Column Lists</a>. I ended up using the first solution, it's not the best but the others require either using complex HTML that can't be generated dynamically, or creating a lot of custom classes, which could be done but would require loads of in-line styling and possibly a huge page.</p>
<p>Other solutions are still welcome though.</p>
|
<p>To output the list into multiple grouped tag you can loop in this fashion.</p>
<pre><code><cfset list="1,2,3,4,5,6,7,8,9,10,11,12,13,14">
<cfset numberOfColumns = "3">
<cfoutput>
<cfloop from="1" to="#numberOfColumns#" index="col">
<ul>
<cfloop from="#col#" to="#listLen(list)#" index="i" step="#numberOfColumns#">
<li>#listGetAt(list,i)#</li>
</cfloop>
</ul>
</cfloop>
</cfoutput>
</code></pre>
| 2,692
|
<p>We're using Spring/Hibernate on a Websphere Application Server for AIX. On my Windows machine, the problem doesn't occur--only when running off AIX. When a user logs in with an account number, if they prefix the '0' to their login ID, the application rejects the login. In the DB2 table, the column is of numeric type, and there shouldn't be a problem converting '090....' to '90...'</p>
<p>Anyone else experience a problem like this? Both machines have Java v1.5.</p>
<p>To be more specific, the flow is FormView -> LoginValidator -> LoginController</p>
<p>In LoginValidator, the value of login is null with the prefixed 0. Without the 0, the value is what it should be (But again, this is only on the AIX environment--on 2 Windows environments it's fine). Here's the snippet of code where the object equals null..</p>
<pre><code>public class LoginValidator implements Validator {
public boolean supports(Class clazz) {
return Login.class.equals(clazz);
}
@SuppressWarnings("all")
public void validate(Object obj, Errors errors) {
System.out.println("Inside LoginValidator");
Login login = (Login) obj;
//null value
System.out.println("Before conversion in Validator, store id = "
+ login.getStoreId());
}
}
</code></pre>
<p>I've also written this short Java program for constructing a Long from a String, and using the java binary that is packaged with WebSphere</p>
<pre><code>public class String2Long {
public static void main(String[] args){
String a = "09012179";
String b = "9012179";
Long _a = new Long(a);
Long _b = new Long(b);
System.out.println(a + " => " + _a); //09012179 => 9012179
System.out.println(b + " => " + _b); //9012179 => 9012179
System.out.println("_a.equals(_b) " + _a.equals(_b)); //_a.equals(_b) true
}
}
</code></pre>
<p><a href="https://stackoverflow.com/questions/291286/java-not-converting-string-to-long-object-properly#292709"><h1>SOLUTION</h1></a></p>
|
<p><h1>SOLUTION</H1></p>
<p>A co-worker did some research on Spring updates, and apparently this error was correct in v. 2.5.3:</p>
<blockquote>
<p>CustomNumberEditor treats number with leading zeros as decimal (removed unwanted octal support while preserving hex)</p>
</blockquote>
<p>We were using Spring 2.0.5. We simply replaced the jars with Spring 2.5.4, and it worked as it should have!</p>
<p>Thanks to everyone for your help/assistance. We will make use of Unit tests in the future, but this just turned out to be a Spring bug.</p>
|
<p>I don't know much about Java, but this might happen the string is interpreted as octal string because of the leading "0".</p>
<p>You can probably work around this using Long.parseLong(a, 10).</p>
| 37,147
|
<p>I am doing something like this:</p>
<pre><code>#include <signal.h>
class myClass {
public:
void myFunction ()
{
signal(SIGIO,myHandler);
}
void myHandler (int signum)
{
/**
* Handling code
*/
}
}
</code></pre>
<p>I am working on Ubuntu, using gcc. </p>
<p>But it won't compile. It is complaining with:</p>
<blockquote>
<p>error: the argument with type <code>void (MyClass::)(int)</code> doesn't agree with <code>void (*) (int)</code></p>
</blockquote>
<p>Any clues? Or maybe it is just that I cannot use a signal inside classes? Are signals only allowed in C? </p>
<p>The error message is an approximate translation because my compiler is not in English.</p>
|
<p>The second parameter of signal should be a pointer to a function accepting an int and returning void. What you're passing to signal is a pointer to a <em>member</em> function accepting an int and returning void (its type being <code>void (myClass::*)(int)</code>). I can see three possibilities to overcome this issue:</p>
<p>1 - Your method <code>myHandler</code> can be static: this is great, make it static</p>
<pre><code>class myClass
{
public:
void myFunction ()
{
signal(SIGIO, myClass::myHandler);
}
static void myHandler (int signum)
{
// handling code
}
};
</code></pre>
<p>2 - Your method shouldn't be static: if you're planning to use signal with only one instance, you can create a private static object, and write a static method that simply call the method on this object. Something along the lines of</p>
<pre><code>class myClass
{
public:
void myFunction ()
{
signal(SIGIO, myClass::static_myHandler);
}
void myHandler (int signum)
{
// handling code
}
static void static_myHandler(int signum)
{
instance.myHandler(signum);
}
private:
static myClass instance;
};
</code></pre>
<p>3 - However, if you're planning on using the signal with multiple instances, things will get more complicated. Perhaps a solution would be to store each instance you want to manipulate in a static vector, and invoking the method on each of these :</p>
<pre><code>class myClass
{
public:
void myFunction () // registers a handler
{
instances.push_back(this);
}
void myHandler (int signum)
{
// handling code
}
static void callHandlers (int signum) // calls the handlers
{
std::for_each(instances.begin(),
instances.end(),
std::bind2nd(std::mem_fun(&myClass::myHandler), signum));
}
private:
static std::vector<myClass *> instances;
};
</code></pre>
<p>and somewhere, do a single call to</p>
<pre><code>signal(SIGIO, myClass::callHandlers);
</code></pre>
<p>But I think that if you end up using the last solution, you should probably think about changing your handling design :-)!</p>
|
<p>You can use singleton pattern</p>
<pre><code> static MyClass &getInstance() {
static MyClass instance;
return instance;
</code></pre>
| 44,633
|
<p>Here is the full error: <code>SqlException: A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 1 - I/O Error detected in read/write operation)</code></p>
<p>I've started seeing this message intermittently for a few of the unit tests in my application (there are over 1100 unit & system tests). I'm using the test runner in ReSharper 4.1.</p>
<p>One other thing: my development machine is a VMWare virtual machine.</p>
|
<p>I ran into this many moons ago. Bottom line is you are running out of available ports.</p>
<p>First make sure your calling application has connection pooling on.</p>
<p>If that does then check the number of available ports for the SQL Server.</p>
<p>What is happening is that if pooling is off then every call takes a port and it takes by default 4 minutes to have the port expire, and you are running out of ports.</p>
<p>If pooling is on then you need to profile all the ports of SQL Server and make sure you have enough and expand them if necessary.</p>
<p>When I came across this error, connection pooling was off and it caused this issue whenever a decent load was put on the website. We did not see it in development because the load was 2 or 3 people at max, but once the number grew over 10 we kept seeing this error. We turned pooling on, and it fixed it.</p>
|
<p>We saw this in our environment, and traced part of it down to the "NOLOCK" hint in our queries. We removed the NOLOCK hint and set our servers to use Snapshot Isolation mode, and the frequency of these errors was reduced quite a bit.</p>
| 7,599
|
<p>A colleague of mine states that <strong>booleans as method arguments are not acceptable</strong>. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.</p>
<p>What's easier to understand?</p>
<pre><code>file.writeData( data, true );
</code></pre>
<p>Or</p>
<pre><code>enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
</code></pre>
<p>Now I got it! ;-)<br>
This is definitely an example where an enumeration as second parameter makes the code much more readable.</p>
<p>So, what's your opinion on this topic?</p>
|
<p>Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory.</p>
<p>But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable.</p>
|
<p>It really depends on the exact nature of the argument. If it is not a yes/no or true/false then a enum makes it more readable. But with an enum you need to check the argument or have acceptable default behaviour since undefined values of the underlying type can be passed.</p>
| 16,450
|
<p>I'm having some trouble navigating Java's rule for inferring generic type parameters. Consider the following class, which has an optional list parameter:</p>
<pre><code>import java.util.Collections;
import java.util.List;
public class Person {
private String name;
private List<String> nicknames;
public Person(String name) {
this(name, Collections.emptyList());
}
public Person(String name, List<String> nicknames) {
this.name = name;
this.nicknames = nicknames;
}
}
</code></pre>
<p>My Java compiler gives the following error:</p>
<pre><code>Person.java:9: The constructor Person(String, List<Object>) is undefined
</code></pre>
<p>But <code>Collections.emptyList()</code> returns type <code><T> List<T></code>, not <code>List<Object></code>. Adding a cast doesn't help</p>
<pre><code>public Person(String name) {
this(name,(List<String>)Collections.emptyList());
}
</code></pre>
<p>yields</p>
<pre><code>Person.java:9: inconvertible types
</code></pre>
<p>Using <code>EMPTY_LIST</code> instead of <code>emptyList()</code></p>
<pre><code>public Person(String name) {
this(name, Collections.EMPTY_LIST);
}
</code></pre>
<p>yields</p>
<pre><code>Person.java:9: warning: [unchecked] unchecked conversion
</code></pre>
<p>Whereas the following change makes the error go away:</p>
<pre><code>public Person(String name) {
this.name = name;
this.nicknames = Collections.emptyList();
}
</code></pre>
<p>Can anyone explain what type-checking rule I'm running up against here, and the best way to work around it? In this example, the final code example is satisfactory, but with larger classes, I'd like to be able to write methods following this "optional parameter" pattern without duplicating code.</p>
<p>For extra credit: when is it appropriate to use <code>EMPTY_LIST</code> as opposed to <code>emptyList()</code>?</p>
|
<p>The issue you're encountering is that even though the method <code>emptyList()</code> returns <code>List<T></code>, you haven't provided it with the type, so it defaults to returning <code>List<Object></code>. You can supply the type parameter, and have your code behave as expected, like this:</p>
<pre><code>public Person(String name) {
this(name,Collections.<String>emptyList());
}
</code></pre>
<p>Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:</p>
<pre><code>public Person(String name) {
List<String> emptyList = Collections.emptyList();
this(name, emptyList);
}
</code></pre>
<p>then the <code>emptyList()</code> call would correctly return a <code>List<String></code>.</p>
|
<p>Since Java 8 this kind of code compiles as expected and the type parameter gets inferred by the compiler.</p>
<pre><code>public Person(String name) {
this(name, Collections.emptyList()); // Inferred to List<String> in Java 8
}
public Person(String name, List<String> nicknames) {
this.name = name;
this.nicknames = nicknames;
}
</code></pre>
<p>The new thing in Java 8 is that the <a href="https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types" rel="nofollow noreferrer"><em>target type</em></a> of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.</p>
<p>In this case the parameter type of the constructor will be the target type for <code>Collections.emptyList()</code>, and the return value type will get chosen to match the parameter type.</p>
<p>This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.</p>
<p>Java is getting closer to proper <a href="https://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system" rel="nofollow noreferrer">Hindley–Milner</a> type inference with every release!</p>
| 39,458
|
<p>I know that attributes are extremely useful. There are some predefined ones such as <code>[Browsable(false)]</code> which allows you to hide properties in the properties tab. Here is a good question explaining attributes: <a href="https://stackoverflow.com/questions/20346/c-what-are-attributes">What are attributes in .NET?</a></p>
<p><strong>What are the predefined attributes (and their namespace) you actually use in your projects?</strong> </p>
|
<p><code>[DebuggerDisplay]</code> can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example:</p>
<pre><code>[DebuggerDisplay("FirstName={FirstName}, LastName={LastName}")]
class Customer
{
public string FirstName;
public string LastName;
}
</code></pre>
<p>This is how it should look in the debugger:</p>
<p><img src="https://i.stack.imgur.com/qEZNZ.jpg" alt="alt text"></p>
<p>Also, it is worth mentioning that <code>[WebMethod]</code> attribute with <code>CacheDuration</code> property set can avoid unnecessary execution of the web service method. </p>
|
<pre><code>// on configuration sections
[ConfigurationProperty]
// in asp.net
[NotifyParentProperty(true)]
</code></pre>
| 17,468
|
<p>So, I have a penchant for Easter Eggs... this dates back to me being part of the found community of the Easter Egg Archive.</p>
<p>However, I also do a lot of open source programming.</p>
<p>What I want to know is, what do you think is the best way to SYSTEMATICALLY and METHODICALLY obfuscate code.</p>
<p>Examples in PHP/Python/C/C++ preferred, but in other languages is fine, if the methodology is explained properly. </p>
|
<p>In that case, you should use/write an "obfuscator". A program that does the job for you.<br></p>
<p>The Salamander Obfuscator can be used to obfuscate .Net programs, but it is more to prevent decompilation, thus not exactly what you need.<br></p>
<p>A good place to learn about obfuscation in C is <a href="http://www.ioccc.org/" rel="nofollow noreferrer">International Obfuscated C Code Contest</a> </p>
|
<p>The question is how to create seemingly non-obfuscated code in plain sight (open source) without it appearing to perform another function. </p>
| 15,281
|
<p>I'm trying to add a custom font as a resource in my application.
I have a "CustomFont" directory in the application and all the fonts inside of it are set to "Resource"</p>
<pre><code><Window.Resources>
<Style x:Key="Gotham-XLight">
<Setter Property="TextElement.FontFamily"
Value="/CustomFonts;Component/#Gotham-XLight" />
</Style>
</Window.Resources>
</code></pre>
<p>And then on my TextBlock I have this: (inside a grid)</p>
<pre><code><TextBlock x:Name="TimeTextBlock" Style="{DynamicResource Gotham-XLight}"
TextAlignment="Center" FontSize="25" FontWeight="Bold"
Foreground="White" Text="TextBlockTimer"
Margin="105,242.974,0,226.975" HorizontalAlignment="Left"
Width="221.919" />
</code></pre>
<p>But I'm not seeing my font as people say. Am I doing something wrong?</p>
|
<p>You may want to check the name of the font, you need to specify the name of the font not the name of the file.</p>
<p>Double click on the font file and it should show a "Font name:" that's what you want to make sure is specified in your style.</p>
|
<p>Late reply but worth mentioning. To add a custom font that will apply globally in your window you could add this in your csproj file to include the fonts from the Fonts folder of your project as resources.</p>
<pre><code> <ItemGroup>
<Resource Include="Fonts\*.ttf" />
</ItemGroup>
</code></pre>
<p>Then in your window XAML you can specify the FontFamily in the Window part:</p>
<pre><code><Window x:Class="Namespace.MainWindow"
...
FontFamily="/Fonts/#[FONT NAME]"
Title="">
<Grid>
...
</Grid>
</Window>
</code></pre>
<p>I hope this could help somebody, as I spent some time to figure it out.</p>
| 46,750
|
<p>What is the minimum I need to add to a .NET 2.0 WebSite's web.config to make it .NET 3.5? </p>
<p>Visual Studio adds all the config sections and script handlers, but if you aren't using those are they are really necessary?</p>
<p>Is there a command line tool to "upgrade" a .NET 2.0 web.config to 3.5?</p>
|
<p>There is a good description of the 3.5 web.config available here:
<a href="https://web.archive.org/web/20211020153237/https://www.4guysfromrolla.com/articles/121207-1.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20211020153237/https://www.4guysfromrolla.com/articles/121207-1.aspx</a></p>
<p>The assemblies and config sections are important because they tell the runtime to use the new 3.5 dlls instead of the 2.0 dlls</p>
<p>The <em>codedom</em> section tells the compiler to use 3.5.</p>
<p>If you're not using ASP.Net Ajax you can probably skip the rest. I've never tested that though.</p>
|
<p>It depends on which features you want to include. Most of the 3.5 ASP.NET extensions are optional. You will want to include the assembly for System.Core and System.Xml.Linq. You will also to add compiler support for C# 3.0 if you plan to use that in your code behind. If you're deploying to IIS 7 there are HTTP handlers for the ASP.NET extensions and script modules.</p>
| 5,408
|
<p>What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the <code>ATTACH</code> command on the SQLite 3 command line tool?</p>
|
<p>There are a few steps to see the tables in an SQLite database:</p>
<ol>
<li><p>List the tables in your database:</p>
<pre><code>.tables
</code></pre></li>
<li><p>List how the table looks:</p>
<pre><code>.schema tablename
</code></pre></li>
<li><p>Print the entire table:</p>
<pre><code>SELECT * FROM tablename;
</code></pre></li>
<li><p>List all of the available SQLite prompt commands:</p>
<pre><code>.help
</code></pre></li>
</ol>
|
<p>The ".schema" commando will list available tables and their rows, by showing you the statement used to create said tables:</p>
<pre>
sqlite> create table_a (id int, a int, b int);
sqlite> .schema table_a
CREATE TABLE table_a (id int, a int, b int);
</pre>
| 10,853
|
<p>After researching on the topic of claims-Based security (or a federated security model). I've been coming across many examples that use <a href="http://en.wikipedia.org/wiki/Windows_CardSpace" rel="nofollow noreferrer">CardSpace</a> as an example. The main article that I read that gave a really great explanation of the subject was a <a href="https://connect.microsoft.com/Downloads/DownloadDetails.aspx?SiteID=642&DownloadID=12901" rel="nofollow noreferrer">PDF</a> by Microsoft on a framework called <a href="https://connect.microsoft.com/Downloads/Downloads.aspx?SiteID=642" rel="nofollow noreferrer">Zermatt</a>. </p>
<p>The claims-based security architecture I'm looking into is the equivalent of implementing an <a href="http://msdn.microsoft.com/en-us/library/ff650503.aspx" rel="nofollow noreferrer">STS</a> Authentication Broker in combination with an STS Authorization Broker. This way, when I create a new service all I need to do is ensure that the service will only accept claims issued by the Authorization Broker. And as noted in the article, the Authorization Broker would only accept claims issued by the Authentication Broker. </p>
<p>When that's setup, any time a client attempts to use the new service, it must authenticate with the <strong><em>Authentication Broker</em></strong> <strong>(issuing an authenticated claim)</strong> and then get authorized with the
<strong><em>Authorization Broker</em></strong> <strong>(issuing an authorized claim)</strong>.</p>
<p>This is all fine and dandy and the architecture is clear, but I don't see exactly how to implement an STS. As I mentioned, most (if not all) examples around the web are showing how to use CardSpace, but that doesn't exactly work when you have a database backing up your authentication scheme.</p>
<p><strong>Sample Scenario</strong></p>
<p><a href="http://img512.imageshack.us/img512/8329/claimsbasedsecurityza6.jpg" rel="nofollow noreferrer">alt text http://img512.imageshack.us/img512/8329/claimsbasedsecurityza6.jpg</a></p>
|
<p>I think I found my answer :D</p>
<p><a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel" rel="nofollow noreferrer">http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel</a>
<a href="http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel2" rel="nofollow noreferrer">http://www.theserverside.net/tt/articles/showarticle.tss?id=ClaimsBasedSecurityModel2</a></p>
<p>And then there's the latest Microsoft Geneva Framework announced at PDC. Perfect for what I need. (now if only my own answer were marked as the answer :P)</p>
<p><a href="http://www.microsoft.com/geneva" rel="nofollow noreferrer">http://www.microsoft.com/geneva</a></p>
|
<p>The best thing to implement an STS on on the Windows platform is to use <a href="http://en.wikipedia.org/wiki/Active_Directory_Federation_Services" rel="nofollow noreferrer">AD FS</a>.</p>
<p>See this blog for details, <a href="http://blogs.msdn.com/vbertocci/archive/2007/11/19/developing-a-minimal-sts-with-adfs-2-identity-framework-part-i-the-sts-itself.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/vbertocci/archive/2007/11/19/developing-a-minimal-sts-with-adfs-2-identity-framework-part-i-the-sts-itself.aspx</a>.</p>
| 28,812
|
<p>In a C++ Windows (XP and NT, if it makes a difference) application I'm working on, I need to get the network name associated with the computer the code is executing on, so that I can convert local filenames from C:\filename.ext to \\network_name\C$\filename.ext. How would I do this?</p>
<p>Alternatively, if there's a function that will just do the conversion I described, that would be even better. I looked into WNetGetUniversalName, but that doesn't seem to work with local (C drive) files.</p>
|
<p>You'll want Win32's GetComputerName:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms724295(VS.85).aspx</a></p>
|
<p>I agree with Pascal on using winsock's gethostname() function.
Here you go:</p>
<pre><code>#include <winsock2.h> //of course this is the way to go on windows only
#pragma comment(lib, "Ws2_32.lib")
void GetHostName(std::string& host_name)
{
WSAData wsa_data;
int ret_code;
char buf[MAX_PATH];
WSAStartup(MAKEWORD(1, 1), &wsa_data);
ret_code = gethostname(buf, MAX_PATH);
if (ret_code == SOCKET_ERROR)
host_name = "unknown";
else
host_name = buf;
WSACleanup();
}
</code></pre>
| 3,230
|
<p>I have some Java code that uses curly braces in two ways</p>
<pre><code>// Curly braces attached to an 'if' statement:
if(node.getId() != null)
{
node.getId().apply(this);
}
// Curly braces by themselves:
{
List<PExp> copy = new ArrayList<PExp>(node.getArgs());
for(PExp e : copy)
{
e.apply(this);
}
}
outAMethodExp(node);
</code></pre>
<p>What do those stand-alone curly braces after the first <code>if</code> statement mean?</p>
|
<p>The only purpose of the extra braces is to provide scope-limit. The <code>List<PExp> copy</code> will only exist within those braces, and will have no scope outside of them.</p>
<p>If this is generated code, I assume the code-generator does this so it can insert some code (such as this) without having to worry about how many times it has inserted a <code>List<PExp> copy</code> and without having to worry about possibly renaming the variables if this snippet is inserted into the same method more than once.</p>
|
<p>I think they just define an unnamed level of scope.</p>
| 29,834
|
<p>I am trying to understand some assembly.</p>
<p>The assembly as follows, I am interested in the <code>testl</code> line:</p>
<pre><code>000319df 8b4508 movl 0x08(%ebp), %eax
000319e2 8b4004 movl 0x04(%eax), %eax
000319e5 85c0 testl %eax, %eax
000319e7 7407 je 0x000319f0
</code></pre>
<p>I am trying to understand that point of <code>testl</code> between <code>%eax</code> and <code>%eax</code>? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true?</p>
|
<p>It tests whether <code>eax</code> is 0, or above, or below. In this case, the jump is taken if <code>eax</code> is 0.</p>
|
<p>we could see the <strong>jg</strong>,<strong>jle</strong>
If <code>testl %edx,%edx. jle .L3</code>we could easy find <strong>jle</strong>is suit <code>(SF^OF)|ZF</code>,if %edx is zero ,ZF=1,but if %edx is not zero and is -1,after the testl ,the OF=0,and the SF =1,so the flag =true,that implement jump
.sorry ,my English is poor</p>
| 17,718
|
<p>I am considering adding validation on some insert and update statements for MS SQL Server 2005.
I want to be able to check the values inserted before it is written into the table - in this particular case, it is an integer field where the data must conform to a rule.
So a simple schema could be:</p>
<pre><code>([id] [int] identity(1,1), [name] [nvarchar], [magicvalue] [int])
</code></pre>
<p>And magicvalue is the one I'm going to validate. However, it is a general question for the "best practice" when indexes and foreign key constraints are not suitable. I guess I am unsure whether triggers or constraints are the way to go, or if there are other ways. </p>
<p>An example is optional :)</p>
|
<p>Use constraints for this</p>
<p>e.g</p>
<pre><code>CREATE TABLE [dbo].[SalesHistory](
[SaleID] [int] NOT NULL,
[Product] [char](150) NULL,
[SaleDate] [datetime] NULL,
[SalePrice] [money] NULL CHECK (SalePrice > 4)
)
</code></pre>
|
<p>Use constraints for this</p>
<p>e.g</p>
<pre><code>CREATE TABLE [dbo].[SalesHistory](
[SaleID] [int] NOT NULL,
[Product] [char](150) NULL,
[SaleDate] [datetime] NULL,
[SalePrice] [money] NULL CHECK (SalePrice > 4)
)
</code></pre>
| 49,465
|
<p>How do you update your SQL sever database when installing your product's update? Are there any tools that will integrate with windows installer?
My typical schema changes are:</p>
<ul>
<li>Adding/removing columns</li>
<li>Adding/removing tables.</li>
<li>Adding views.</li>
<li>Adding/alter indexs.</li>
</ul>
|
<p>Not sure about integration with the windows installer, but you might look into Red Gate's <a href="http://www.red-gate.com/products/SQL_Packager/index.htm" rel="nofollow noreferrer">SQL Packager</a></p>
|
<p><a href="http://www.acresso.com/products/installation/installshield.htm" rel="nofollow noreferrer">InstallShield</a> lets you execute SQL scripts as part of an installation. Not tried it though, just remember it was on the GUI last time I looked!</p>
| 14,067
|
<p>a colleague pointed me the other day to <a href="http://jakarta.apache.org/bcel/" rel="nofollow noreferrer">BCEL</a> which , as best I can tell from his explanation and a quick read, a way to modify at run time the byte code. My first thought was that it sounded dangerous, and my second thought was that it sounded cool. Then I gave it some more thought and I recalled the <a href="https://blog.codinghorror.com/monkeypatching-for-humans/" rel="nofollow noreferrer">codinghorror post on monkey-patching</a> and realized that this was basically the same thing. Has anyone ever used BCEL for anything practical? Am I right that this is basically run time monkey patching, or am I missing something?</p>
|
<p>It's a bit more low-level than classic monkey patching, and from what I read, the classes already loaded into the VM are not updated. It only supports saving it to class files again, not modifying run time classes.</p>
|
<p>You might look at it as monkey patching. I prefer not to use it (maybe I never faced a good use case for it?), but be familiar with it (to have an idea how Spring and Hibenrate use it and why).</p>
| 6,393
|
<p>What I'd like to do is produce an HTML/CSS/JS version of the following. The gridlines and other aspects are not important. It's more of a question how to do the background databars.</p>
<p><a href="https://i.stack.imgur.com/tPLAD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tPLAD.png" alt="alt text"></a><br>
<sub>(source: <a href="http://blogs.tech-recipes.com/shamanstears/files/2008/04/excel_databars2.png" rel="nofollow noreferrer">tech-recipes.com</a>)</sub> </p>
|
<p>Make the bars as background images and position them to show values. eg. with a fixed column width of 100px:</p>
<pre><code><div style="background: url(bg.gif) -50px 0 no-repeat;">5</div>
<div style="background: url(bg.gif) -20px 0 no-repeat;">8</div>
</code></pre>
<p>If your columns have to be flexible size (not fixed, and not known at the time the page is produced), it's a bit trickier:</p>
<pre><code><style type="text/css">
.cell { position: relative; }
.cell .back { position: absolute; z-index: 1; background: url(bg.gif); }
.cell .value { position: relative; z-index: 2; }
</style>
<div class="cell">
<div class="back" style="width: 50%;">&nbsp;</div>
<div class="value">5</div>
</div>
<div class="cell">
<div class="back" style="width: 80%;">&nbsp;</div>
<div class="value">8</div>
</div>
</code></pre>
|
<p>A javascript-based solution like this <a href="http://slayeroffice.com/code/gradient/" rel="nofollow noreferrer">cross-browser gradient</a> might be a good start.</p>
<p>With some DHTML, you can make a <a href="http://slayeroffice.com/code/gradientProgressBar/" rel="nofollow noreferrer">bar with a given length</a>.</p>
| 36,581
|
<p>I have a client that thought a highly dynamic ASP.NET application was a very simple sytem, yet to implement it in the manner in which they needed for future grown it has grown to well over 100 different code files.</p>
<p>I am looking for a way, most likely with some sort of static code analysis tool to put some numbers that might "make sense" to a non-technical person. I fully understand that Lines of Code and other metrics are not really "valid" items to evaluate, but in this case this is the type of thing I need, Lines of Code, Number of XML comments, Total Files, Total Folders. </p>
<p>I know I can look some of these up, but I'm looking for an easy way to get these values in bulk! I found a few old posts here, but nothing that specifically talked about .NET (Current versions) and/or C#.</p>
<p>Ideally I want something that can investigate a C# WAP project. SQL Server would be an AWESOME value add, but not a 100% needed item!</p>
|
<p>No - SQLite does not support concurrent write access to the same database file. SQLite will simply block one of the transactions until the other one has finished.</p>
|
<p>Not necessarily. If sqlite3 is compiled with the thread safe macro (check via the <pre>int sqlite3_threadsafe(void)</pre> function), then you can try to access the same DB from multiple threads without the risk of corruption. Depending on the lock(s) required, however, you may or may not be able to actually modify data (I don't believe sqlite3 supports row locking, which means that to write, you'll need to get a table lock). However, you can try; if one threads blocks, then it will automatically write as soon as the other thread finishes with the DB.</p>
| 46,312
|
<p>I have a KTerminalInterface (from kparts) in my qt/kdelib app, and I run a command within it.</p>
<p>The problem is: how can I know if the program is terminated? I need to know it because at its end I must reset some variable.</p>
<p>Does anyone got a similar problem?!?</p>
|
<p>It isn't possible to communicate with the process once launched via TerminalInterface in KDE 4, since KonsolePart (which implements TerminalInterface) no longer has processExited() or receivedData() signals. In KDE 4, KonsolePart is for interactive terminal sessions, not for your app to use.</p>
<p>In KDE 4, use <a href="http://api.kde.org/4.x-api/kdelibs-apidocs/kdecore/html/classKProcess.html" rel="nofollow noreferrer">KProcess</a> to spawn an external command from your app, communicate with it, and detect when it terminates. See the <a href="http://doc.trolltech.com/4.4/qprocess.html" rel="nofollow noreferrer">QProcess</a> parts of its API.</p>
|
<p>you might be able to use <a href="http://docs.python.org/library/os.html#os.waitpid" rel="nofollow noreferrer">os.waitpid</a>(-1) to wait for child processes (with another thread if you can't have the main one block).</p>
| 49,036
|
<p>Which Computer-aided Software Engineering tools do you use and why? In what ways do they increase your productivity or help you design your programs? Or, in case you do not use CASE tools, what are your reasons for this?</p>
|
<p>The best CASE tool I had to work with is the <a href="http://www.sparxsystems.com.au/products/ea/index.html" rel="nofollow noreferrer">Enterprise Architect</a> from <a href="http://www.sparxsystems.com.au/" rel="nofollow noreferrer">Sparx</a>.</p>
<p>It's lightweight comparing to Rose (easier to buy and cheaper too) but extremely powerful. You could do great UML diagrams or database model or anything else you want but in a nice and organised way. </p>
<p>It greatly helps on the initial stages of the elaboration process as you could create domain model, do some preliminary use cases, map them to the requirements and present all of it in a nice way to the customer. It helps me thinking and I re-factor my design with it until I am satisfied enough to start proper documentation.
It is also very good for database models as it could reverse-engineer most databases very neatly.</p>
<p>The only (but quite serious) drawback it has in my eyes is that its documentation generator is, to put it mildly, crap. Getting a proper document from it is almost impossible unless you invest a significant amount of work in the templates and then it would be only OK.</p>
|
<p>I have used Rational Rose and a few other similar packages in the past. Mostly I have used them for the UML diagram elements and have not gone into the more detailed functionality such as code generation etc.</p>
<p>I mostly use them for aiding the design process and clarifying my own ideas. Often I find that, in trying to come up with a design for a componant, I end up needing to write down / draw what I want to happen so I can get a clear overview in my mind of what needs to happen and why. I have found that in a lot of cases, what I end up trying to draw is essentially the same as a predefined kind of diagram in UML, such as a Use Case Diagram etc. and by then adopting that style, it becomes easier to get my ideas on paper as I have some framework to work within.</p>
<p>So, I use CASE tools principally for thier UML / designing tools at a highish, semi-abstract level.</p>
| 19,026
|
<p>Does any one know any good resources for creating Visual Slick macros?</p>
|
<p>I'd start with the <a href="http://community.slickedit.com/index.php?board=4.0" rel="nofollow noreferrer">official community forum</a> for SlickEdit macros.</p>
|
<p>This is a great resource to start with. I wrote my first one <a href="http://blog.slickedit.com/2010/04/lets-make-a-macro-part-1-outputting-debug-values/" rel="nofollow">here</a></p>
| 10,926
|
<p>I need to replace character (say) <strong>x</strong> with character (say) <strong>P</strong> in a string, but only if it is contained in a quoted substring.
An example makes it clearer:</p>
<pre><code>axbx'cxdxe'fxgh'ixj'k -> axbx'cPdPe'fxgh'iPj'k
</code></pre>
<p>Let's assume, for the sake of simplicity, that quotes always come in pairs. </p>
<p>The obvious way is to just process the string one character at a time (a simple state machine approach);<br>
however, I'm wondering if regular expressions can be used to do all the processing in one go.</p>
<p>My target language is C#, but I guess my question pertains to any language having builtin or library support for regular expressions.</p>
|
<p>I was able to do this with Python:</p>
<pre><code>>>> import re
>>> re.sub(r"x(?=[^']*'([^']|'[^']*')*$)", "P", "axbx'cxdxe'fxgh'ixj'k")
"axbx'cPdPe'fxgh'iPj'k"
</code></pre>
<p>What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string.</p>
<p>This relies on your assumption that the quotes are always balanced. This is also not very efficient.</p>
|
<p>Sorry to break your hopes, but you need a push-down automata to do that. There is more info here:
<a href="http://en.wikipedia.org/wiki/Pushdown_automaton" rel="nofollow noreferrer">Pushdown Automaton</a></p>
<p>In short, Regular expressions, which are finite state machines can only read and has no memory while pushdown automaton has a stack and manipulating capabilities.</p>
<p>Edit: spelling...</p>
| 16,779
|
<p>I am having problems manually looping through xml data that is received via an HTTPService call, the xml looks something like this: </p>
<pre><code><DataTable>
<Row>
<text>foo</text>
</Row>
<Row>
<text>bar</text>
</Row>
</DataTable>
</code></pre>
<p>When the webservice result event is fired I do something like this:</p>
<pre><code>for(var i:int=0;i&lt;event.result.DataTable.Row.length;i++)
{
if(event.result.DataTable.Row[i].text == "foo")
mx.controls.Alert.show('foo found!');
}
</code></pre>
<p>This code works then there is more than 1 "Row" nodes returned. However, it seems that if there is only one "Row" node then the <em>event.DataTable.Row</em> object is not an error and the code subsequently breaks. </p>
<p>What is the proper way to loop through the <em>HTTPService</em> result object? Do I need to convert it to some type of <em>XMLList</em> collection or an <em>ArrayCollection</em>? I have tried setting the resultFormat to <em>e4x</em> and that has yet to fix the problem...</p>
<p>Thanks.</p>
|
<p>The problem lies in this statement</p>
<pre><code>event.result.DataTable.Row.length
</code></pre>
<p><code>length</code> is not a property of <code>XMLList</code>, but a method:</p>
<pre><code>event.result.DataTable.Row.length()
</code></pre>
<p>it's confusing, but that's the way it is.</p>
<p><em>Addition:</em> actually, the safest thing to do is to always use a <code>for each</code> loop when iterating over <code>XMLList</code>s, that way you never make the mistake, it's less code, and easier to read:</p>
<pre><code>for each ( var node : XML in event.result.DataTable.Row )
</code></pre>
|
<p>I would store it in an Xml object and then use its methods to search for the node value you need.</p>
<pre><code>var returnedXml:Xml = new Xml(event.result.toString());
</code></pre>
| 6,219
|
<p>What do I have to do to convert a DIB to a BMP?</p>
|
<p>Check the API GdipCreateBitmapFromGdiDib</p>
<p>Example:
<a href="http://www.codeproject.com/KB/GDI-plus/DIBtoBitmap.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/GDI-plus/DIBtoBitmap.aspx</a></p>
|
<p><a href="http://www.imagemagick.org/www/formats.html" rel="nofollow noreferrer">Imagemagick's </a>convert function will do this (and many other conversions) for you on the command line. Free, open source, available on all major platforms. This is a great piece of software that should be in anyone's toolbox.</p>
| 34,249
|
<p>When developing custom ecommerce solutions, which "off the shelf" .NET based shipping components have you had luck with? </p>
<p>It absolutely must give real-time shipping quotes and be easily integrated into a ASP.NET website. Ideally I'd like it to support most of the common US domestic shipping companies (UPS, FedEx, USPS, etc.). </p>
<p>Thanks!</p>
|
<p>There's <a href="http://www.dotnetship.com/" rel="nofollow noreferrer">.net SHIP</a>, which I haven't used, but I have used their .net CHARGE product with success.</p>
|
<p>UPS has web services available which are easy to expose via .NET proxies, etc. That's what we have used. For other shippers like DHL, FedEx, and USPS, we have our own estimates based on our own shipping and handling costs.</p>
<p>Typically you're going to want to pad their costs with your own costs. </p>
| 24,711
|
<p>I would like to update a dll for a server process without stopping the service. How do I do that?
A bit like how asp.net automatically picks up new dlls placed in the bin folder.</p>
|
<p>Asp.Net uses a technique called <a href="http://www.odetocode.com/articles/305.aspx" rel="noreferrer">shadow copy</a></p>
<p>If you copy an updated dll into an application’s bin subdirectory, the ASP.NET runtime recognizes there is new code to execute. Since ASP.NET cannot swap the dll into the existing AppDomain , it starts a new AppDomain. The old application domain is “drain stopped”, that is, existing requests are allowed to finish executing, and once they are all finished the AppDomain can unload. The new AppDomain starts with the new code and begins taking all new requests. </p>
<p>Typically, when a dll loads into a process, the process locks the dll and you cannot overwrite the file on disk. However, AppDomains have a feature known as Shadow Copy that allows assemblies to remain unlocked and replaceable on disk. </p>
<p>The runtime initializes ASP.NET with Shadow Copy enabled for the bin directory. The AppDomain will copy any dll it needs from the bin directory to a temporary location before locking and loading the dll into memory. Shadow Copy allows us to overwrite any dll in the bin directory during an update without taking the web application offline. </p>
|
<p>When a process has loaded a dll it is not possible to change it.</p>
<p>IIS does not keep a DLL loaded in memory when it is not being used (<a href="http://blogs.msdn.com/david.wang/archive/2006/01/29/HOWTO-Replace-an-ISAPI-DLL-on-a-Live-Server.aspx" rel="nofollow noreferrer">affected by the Cache property</a>) and i assume the same is the case with ASP.NET. If you follow the same strategy you could update your dlls too. </p>
<p>However if your dlls are being used, you should have a way to tell your server process to unload all your dlls. </p>
<p>For this to happen the server process must load all the DLLS using the LoadLibrary calls such that it can unload them when it receives a communication asking it to do so. </p>
<p>Communicating with the server process can be done by creating a globally available named event that can be accessed by the new program and used to signal the running process that an update is about to happen. (You could also think of other variations of doing this).</p>
| 28,023
|
<p>When attempting to compile my C# project, I get the following error:</p>
<pre><code>'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
</code></pre>
<p>Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this?</p>
<hr>
<p>@Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the <a href="http://pastebin.com/mcd2607b" rel="noreferrer">contents of the csproj file on pastebin</a>.</p>
<p>@Derek: No problem. Here's the compiler output.</p>
<pre><code>------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------
Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll
------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs
error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file
Compile complete -- 1 errors, 0 warnings
------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------
Project not selected to build for this solution configuration
========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ==========
</code></pre>
<p>I have also uploaded the icon I am using. You can <a href="http://rowdypixel.com/tmp/CleanerMenu.ico" rel="noreferrer">view it here.</a></p>
<hr>
<p>@Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief. :)</p>
<p>@Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem.</p>
<p>Now if only I can figure out why it previously worked with all the other sizes...</p>
|
<p>I don't know if this will help, but from <a href="http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/4217bec6-ea65-465f-8510-757558b36094/" rel="noreferrer">this forum</a>:</p>
<blockquote>
<p>Add an .ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error.</p>
</blockquote>
<p>Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it).</p>
|
<p>Is this a file you created and added to the project or did it mysteriously show up?</p>
<p>You can maybe check your .csproj file and see how it is being referenced (it should be a simple xml file and you can search for CSC97.tmp).</p>
<p>Perhaps post the information you find so we can have more details to help solve your problem</p>
| 2,865
|
<p>Can anyone recommend any programmer-friendly (i.e. extensible) frameworks or systems for performing network level packet <a href="http://en.wikipedia.org/wiki/Fuzzing" rel="noreferrer">fuzzing</a>?</p>
<p>I'm looking for such a system where I can program in additional packet formats and various ways of breaking those packets in a protocol-dependent manner.</p>
<p>I know how to Google. I'm looking for specific recommendations :)</p>
<p>thanks!</p>
|
<p>You might be interested in <a href="http://lcamtuf.coredump.cx/afl/" rel="nofollow">American Fuzzy Lop</a> combined with <a href="https://github.com/zardus/preeny" rel="nofollow">Preeny</a>. It's a fuzzer that is quite simple to use and employs genetic algorithms, which in this case means that it's going to detect which changes in input bits lead to new code paths and pay more attention to those.</p>
|
<p>I know fuzzled is really good as a framework, if you fancy with Perl : <a href="http://www.securiteam.com/tools/5FP0Q1PKUS.html" rel="nofollow noreferrer">http://www.securiteam.com/tools/5FP0Q1PKUS.html</a></p>
<p>JborFuzz and most of other fuzzers won't do it since they are not designed as a framework, certainly not for network level. </p>
| 45,510
|
<p>I'm using an SqlCommand object to insert a record into a table with an autogenerated primary key. How can I write the command text so that I get the newly created ID when I use the ExecuteScalar() method?</p>
|
<pre><code>INSERT INTO YourTable(val1, val2, val3 ...)
VALUES(@val1, @val2, @val3...);
SELECT SCOPE_IDENTITY();
</code></pre>
<p>Don't forget the semicolons at the end of each statement.</p>
|
<p>Straight out of the <a href="http://forums.whirlpool.net.au/forum-replies-archive.cfm/699785.html" rel="nofollow noreferrer">Whirlpool</a>:</p>
<blockquote>
<p>If you're using MS SQL you can use "SELECT @@IDENTITY as Value" after your insert to get the last ID generated</p>
</blockquote>
<p>and:</p>
<blockquote>
<p><code>@@IDENTITY</code> and <code>SCOPE_IDENTITY</code> return the last identity value generated in any table in the current session. However, <code>SCOPE_IDENTITY</code> returns the value only within the current scope; <code>@@IDENTITY</code> is not limited to a specific scope.</p>
</blockquote>
<p><strong>Edit:</strong> As pointed out in the comments, you should always use <code>SCOPE_IDENTITY</code>, not <code>@@IDENTITY</code>.</p>
| 42,842
|
<p>I am new to C#. I wanted to do a simple program with some type of loops.
I wanted my program to loop through the numbers that the user enters and if it is less than a number then write keep guessing,but once they enter the number 25 i wanted it to say Merry Christmas.. Please Help</p>
<pre><code>int number;
do
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
} while (number < 25);
</code></pre>
<p>C# Beginner</p>
|
<p>Try the following: </p>
<pre><code>int number = 0;
while (number != 25)
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
if (number != 25)
Console.WriteLine("Keep guessing");
else
Console.WriteLine("Merry Christmas");
}
</code></pre>
|
<pre><code>int number;
do
{
Console.WriteLine("Guess a number between 20 through 25");
number = int.Parse(Console.ReadLine());
} while (number != 25);
Console.WriteLine("Merry Christmas");
</code></pre>
<p>Would be correct if you want them to be able to enter numbers higher than 25.</p>
| 37,119
|
<p>What do you think of <a href="http://quagga.net" rel="nofollow noreferrer">Quagga</a> compared to XORP as a dynamic software routing engine? What are the technical merits of each engine comparatively? Additionally, what do most people think of them from a programming view. Who has manipulated networks using these enginers? I was wondering from an OSPF, routing, BGP protocol user's perpspective. </p>
|
<p>The following does not answer your question completely, but the Vyatta open source routers and the OpenSolaris customer gateway software for Amazon VPC both use quagga to implement BGP support.</p>
<p>From <a href="http://en.wikipedia.org/wiki/XORP" rel="nofollow noreferrer">the wikipedia entry for XORP</a>,</p>
<blockquote>
<p>"The software suite was selected
commercially as the routing platform
for the Vyatta line of products in its
early releases, but later has been
replaced with quagga.</p>
</blockquote>
|
<blockquote>
<p>What do you think of Quagga compared to XORP as a dynamic software routing engine? </p>
</blockquote>
<p>It is one of many options, but not particularly of very much use to you based upon your questions/information that you posted here. Have you tried looking into some of the alternatives such as (nothing comes to mind)?</p>
<blockquote>
<p>What are the technical merits of each engine comparatively? </p>
</blockquote>
<p>Small, fast, oddly placed, optimized, super-heroic and more filler for a resume.</p>
<blockquote>
<p>Additionally, what do most people think of them from a programming view. </p>
</blockquote>
<p>I can't speak for most people, but I for myself do not give it much credit or merit, or well... you know what I mean.</p>
<blockquote>
<p>Who has manipulated networks using these enginers? </p>
</blockquote>
<p>I could not find specific references, but I do remember reading that both Disney and the 'famous' YUV corporation of South Africa both played with this notion before. I believe Disney abandoned it with the fall of Michael Eisner. </p>
<blockquote>
<p>I was wondering from an OSPF, routing, BGP protocol user's perpspective.</p>
</blockquote>
<p>I am a BGP protocol user's prospective. Hopefully we hear from OSPF and routing user's perspectives shortly.</p>
<p>Good question.</p>
| 10,697
|
<p>What tools are available to encrypt or password-protect a file stored on the IFS?</p>
<p>*integrated file-system, accessible from Windows</p>
|
<ol>
<li>You could setup object security so only certain users can view the file.</li>
<li>There are encryption tools available for purchase. There is also some built-in APIs for encrypting. </li>
</ol>
<p>Here are some resources to look into:</p>
<ol>
<li><a href="http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/apis/qc3Scenario.htm" rel="nofollow noreferrer">Scenario: Key Management and File Encryption Using the Cryptographic Services APIs</a></li>
<li><a href="http://www.ibmsystemsmag.com/i5/june04/administrator/8475p4.aspx" rel="nofollow noreferrer">The Next Step in Security</a></li>
<li><a href="http://www.itjungle.com/fhg/fhg042705-story01.html" rel="nofollow noreferrer">A Simple Encryption/Decryption Algorithm for Numbers</a></li>
<li><a href="http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=/apis/catcrypt.htm" rel="nofollow noreferrer">Cryptographic Services APIs</a></li>
</ol>
<p>Most of these articles deal with encrypting data in a table, but the concepts should help you encrypt a file on the IFS.</p>
|
<p>You can set the authority to the file so only users in one group have access to it. I think its option 9 I don't have access to a iseries at this moment.</p>
| 25,020
|
<p>I want to be able to list only the directories inside some folder.
This means I don't want filenames listed, nor do I want additional sub-folders.</p>
<p>Let's see if an example helps. In the current directory we have:</p>
<pre><code>>>> os.listdir(os.getcwd())
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p
ython-wininst.log', 'NEWS.txt', 'pymssql-wininst.log', 'python.exe', 'pythonw.ex
e', 'README.txt', 'Removemod_python.exe', 'Removepymssql.exe', 'Scripts', 'tcl',
'Tools', 'w9xpopen.exe']
</code></pre>
<p>However, I don't want filenames listed. Nor do I want sub-folders such as \Lib\curses. Essentially what I want works with the following:</p>
<pre><code>>>> for root, dirnames, filenames in os.walk('.'):
... print dirnames
... break
...
['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'Scripts', 'tcl', 'Tools']
</code></pre>
<p>However, I'm wondering if there's a simpler way of achieving the same results. I get the impression that using os.walk only to return the top level is inefficient/too much.</p>
|
<p>Filter the result using os.path.isdir() (and use os.path.join() to get the real path):</p>
<pre><code>>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
</code></pre>
|
<pre><code>-- This will exclude files and traverse through 1 level of sub folders in the root
def list_files(dir):
List = []
filterstr = ' '
for root, dirs, files in os.walk(dir, topdown = True):
#r.append(root)
if (root == dir):
pass
elif filterstr in root:
#filterstr = ' '
pass
else:
filterstr = root
#print(root)
for name in files:
print(root)
print(dirs)
List.append(os.path.join(root,name))
#print(os.path.join(root,name),"\n")
print(List,"\n")
return List
</code></pre>
| 17,068
|
<p>A while ago I noticed I don't have a magnifying-glass next to my datatables. I used to have it, and somehow, sometime, it disappeared...<br>
Has anyone seen this happen? Do you know how to help me view my datatables again? </p>
<p><strong>Update:</strong> I'm still clueless about this. Could anyone point me in some direction, where should I even start looking for an answer? Thanks a lot. </p>
<p><strong>Update:</strong> I changed to a new computer, and still the same problem. But I pinpointed it to being only in Visual Studio 2005. On Visual Studio 2008 I have perfectly normal DataSet and Datatable visualizers.
So I tried re-installing VS2005, to make sure all the components were installed, nothing left out - but Nada. Still no visualizer.</p>
<p><strong>Update:</strong> Found the solution to my problem: <a href="https://stackoverflow.com/questions/239206/datatable-visualizer-disappeared-from-my-visual-studio/1978806#1978806">My answer</a></p>
|
<p>I was really bothered by the problem, so I turned to Microsoft support, and they solved my problem! The short solution is that apparently one of the DLL's in the My Documents\Visual Studio 2005\Visualizers folder was corrupted. I deleted all the contents of the folder, and the visualizer came back.<br>
The long answer can be found <a href="http://blogs.msdn.com/farukcelik/archive/2009/11/24/where-s-my-good-old-friend-dataset-visualizer.aspx" rel="noreferrer">in this post written by Faruk Celik</a> - the person from Microsoft who solved my problem.</p>
|
<p>I tried everything in this post but nothing worked for me. I am running Windows 7 64-bit. Eventually I was able to find a solution in <a href="https://stackoverflow.com/questions/8408234/visual-studio-dataset-and-datatable-visualizer-not-working-in-watch-window/8448629#8448629">this post</a></p>
| 29,593
|
<p>I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the <a href="http://search.cpan.org/dist/AuthCAS" rel="nofollow noreferrer">AuthCAS</a> Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the <a href="http://search.cpan.org/dist/IO-Socket-SSL" rel="nofollow noreferrer">IO::Socket::SSL</a> module:</p>
<pre><code> 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]')
([CAS Server] substituted for real server name)
</code></pre>
<p>Symptoms/Tests:</p>
<ol>
<li>If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.</li>
<li>If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.</li>
<li>If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.</li>
</ol>
<p>Here is the bare-bones script that produces the error:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use AuthCAS;
use CGI::Carp qw( fatalsToBrowser );
my $id = $ENV{QUERY_STRING};
my $q = new CGI;
my $target = "http://localhost/cgi-bin/testCAS.cgi";
my $cas = new AuthCAS(casUrl => 'https://cas_server/cas');
if ($id eq ""){
my $login_url = $cas->getServerLoginURL($target);
printf "Location: $login_url\n\n";
exit 0;
} else {
print $q->header();
print "CAS TEST<br>\n";
## When coming back from the CAS server a ticket is provided in the QUERY_STRING
print "QUERY_STRING = " . $id . "</br>\n";
## $ST should contain the received Service Ticket
my $ST = $q->param('ticket');
my $user = $cas->validateST($target, $ST); #### This is what fails
printf "Error: %s\n", &AuthCAS::get_errors() unless (defined $user);
}
</code></pre>
<p>Any ideas on where the conflict might be?</p>
<hr>
<p>The error is coming from the line directly above the snippet Cebjyre quoted namely</p>
<pre><code>$ssl_socket = new IO::Socket::SSL(%ssl_options);
</code></pre>
<p>namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.</p>
|
<p>As usually happens when I post questions like this, I found the problem. It turns out the <a href="http://search.cpan.org/dist/Crypt-SSLeay" rel="nofollow noreferrer">Crypt::SSLeay</a> module was not installed or at least not up to date. Of course the error messages didn't give me any clues. Updating it and all the problems go away and things are working fine now.</p>
|
<p>Well, from the <a href="http://search.cpan.org/src/OSALAUN/AuthCAS-1.3.1/lib/AuthCAS.pm" rel="nofollow noreferrer">module source</a> it looks like that IO::Socket error is coming from get_https2</p>
<pre><code>[...]
unless ($ssl_socket) {
$errors = sprintf "error %s unable to connect https://%s:%s/\n",&IO::Socket::SSL::errstr,$host,$port;
return undef;
}
[...]
</code></pre>
<p>which is called by callCAS, which is called by validateST.</p>
<p>One option is to temporarily edit the module file to put some debug statements in if you can, but if I had to guess, I'd say the casUrl you are supplying isn't matching up to the _parse_url regex properly - maybe you have three slashes after the https?</p>
| 4,645
|
<p>The title is self explanatory. Is there a way of directly doing such kind of importing?</p>
|
<p>The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: <a href="http://www.fpns.net/willy/msbackup.htm" rel="noreferrer">http://www.fpns.net/willy/msbackup.htm</a></p>
<p>The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.</p>
<p>You will need to use SQL server to extract these. SQL Server Express is free and will do the job.</p>
<p>So, install SQL Server Express edition, and open the SQL Server Powershell. There execute <code>sqlcmd -S <COMPUTERNAME>\SQLExpress</code> (whilst logged in as administrator)</p>
<p>then issue the following command.</p>
<pre><code>restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO
</code></pre>
<p>This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.</p>
<pre><code>RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH
MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf',
MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO
</code></pre>
<p>At this point you have extracted the database - then install <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=c039a798-c57a-419e-acbc-2a332cb7f959&displaylang=en" rel="noreferrer">Microsoft's "Sql Web Data Administrator".</a> together with <a href="http://www.eggheadcafe.com/articles/20040913.asp" rel="noreferrer">this export tool</a> and you will have an SQL script that contains the database.</p>
|
<p>I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best.</p>
<p>You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the "real" database, because the two databases don't always work well together, especially when dealing with dates.</p>
| 18,902
|
<p>I need to create a function that will produce a balloon popup in the
taskbar using javascript. </p>
<p>Is it possible? Whats the shortest and easiest way to do this?</p>
<p>or else what will be the available method.. </p>
<p>Thanks.</p>
|
<p>The closest you could get is to make one fixed to the bottom of the viewport of the browser. You could tailor it to appear as though it were part of the windows chrome, but this does tend to annoy users, who don't appreciate attempts to 'fool' them into believing a dialogue/popup/whatever is coming from their OS when it actually isn't.</p>
<p>See: <a href="http://www.codinghorror.com/blog/archives/001164.html" rel="nofollow noreferrer">Jeff Atwood on the horrors of fake interfaces</a></p>
|
<p>Impossible from a browser. And a good thing.</p>
| 31,073
|
<p>I was reading the example chapter from <a href="http://www.manning.com/rahien/" rel="nofollow noreferrer">the book by Ayende</a> and on the website of <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">the Boo language</a> I saw a reference to the <a href="http://specter.sourceforge.net/" rel="nofollow noreferrer">Specter BDD Framework</a>.</p>
<p>I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.</p>
<p>Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.</p>
<hr>
<p>A few year later visiting this question. I think we can safely assume <a href="http://www.specflow.org/" rel="nofollow noreferrer">Specflow</a> and some others like <a href="http://nspec.org/" rel="nofollow noreferrer">NSpec</a> became the tools we are using.</p>
|
<p>Create one Message table, containing a unique MessageId and the various properties you need to store for a message.</p>
<pre><code>Table: Message
Fields: Id, TimeReceived, MessageDetails, WhateverElse...
</code></pre>
<p>Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message.</p>
<pre><code>Table: QuoteMessage
Fields: QuoteId, MessageId
Table: JobMessage
Fields: JobId, MessageId
</code></pre>
<p>In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the <em>same</em> message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).</p>
|
<p>Why not just have both QuoteId and JobId fields in the message table? Or does a message have to be regarding either a quote or a job and not both?</p>
| 3,999
|
<p>Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.</p>
<p>Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument 'storage' and appends a permutation to it whenever it finds one:</p>
<pre><code>def getPermutations(string, storage, prefix=""):
if len(string) == 1:
storage.append(prefix + string) # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], storage, prefix+string[i])
storage = []
getPermutations("abcd", storage)
for permutation in storage: print permutation
</code></pre>
<p>(Please don't care about inefficiency, this is only an example.)</p>
<p>Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:</p>
<pre><code>def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], prefix+string[i])
for permutation in getPermutations("abcd"):
print permutation
</code></pre>
<p>This code does <em>not</em> work (the function behaves like an empty generator).</p>
<p>Am I missing something?
Is there a way to turn the above recursive algorithm into a generator <em>without replacing it with an iterative one</em>?</p>
|
<pre><code>def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string
else:
for i in xrange(len(string)):
for perm in getPermutations(string[:i] + string[i+1:], prefix+string[i]):
yield perm
</code></pre>
<p>Or without an accumulator:</p>
<pre><code>def getPermutations(string):
if len(string) == 1:
yield string
else:
for i in xrange(len(string)):
for perm in getPermutations(string[:i] + string[i+1:]):
yield string[i] + perm
</code></pre>
|
<p>The interior call to getPermutations -- it's a generator, too.</p>
<pre><code>def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], prefix+string[i]) # <-----
</code></pre>
<p>You need to iterate through that with a for-loop (see @MizardX posting, which edged me out by seconds!)</p>
| 30,926
|
<p>I'm not sure whether I'm asking the question correctly, but I've been told SQL Server cannot run on a Novell server. Is this true? If yes, why not?</p>
|
<p>NOW I see your problem! Sorry dude!</p>
<p>Yes, VERY easy. Kinda.</p>
<p>SQL Server used to be able to talk IPX (the netware protocol) but I think Netware will now talk TCPIP, and you can run IPX and TCP/IP on the same network without an issue - windows clients can run both at the same time, 99% of routers handle all protocols etc.</p>
<p>Windows (XP/2003/etc) can run the netware client, so it can talk to shares etc. </p>
<p>Use the SQL Server logins (rather than windows integrated logins), and it'll work from anything - we have Java on Linux talking to SQL Server on windows just fine :) It's all in the connection string: userid=username;pwd=whatever;server=yourserverhere; etc. But you MUST use the SQL Server Configuration Manager to set these up - the default is shared memory, so you have to enable TCPIP etc.</p>
|
<p>The core issue is how are you authenticating to the SQL database. If you have an Active Directory tree, and an eDirectory you can easily link the two via Novell Identity Manager, which will synchronize users, groups, etc (any object you care to map between the two systems) as well as passwords.</p>
<p>Thus the same object exists in both locations so each system can use it as much it needs too. The license for Identity Manager is included with the Open Enterprise Server license (OES can run on Netware or on SUSE Linux Enterprise Server (SLES)).</p>
<p>Then you could use the Active Directory integrated authentication.</p>
<p>Beyond that, your Netware server likely does not need to connect to the database directly. If it does, you will be writing or using an application that includes the database connectivity. At which point it becomes a question of is there a client for this OS or not.</p>
| 5,206
|
<p>Observing one year of estimations during a project I found out some strange things that make me wonder if evidence based scheduling would work right here?</p>
<ul>
<li>individual programmers seem to have favorite numbers (e.g. 2,4,8,16,30 hours) </li>
<li>the big tasks seem to be underestimated by a fix value (about 2) but the standard deviation is low here</li>
<li>the small tasks (1 or 2 hours) are absolutely wide distributed. In average they have the same average underestimation factor of 2, but the standard deviation is high:
<ul>
<li>some 5 minute spelling issues are estimated with 1 hour</li>
<li>other bugfixes are estimated with 1 hour too, but take a day</li>
</ul></li>
</ul>
<p>So, is it really a good idea to let the programmers break down the 30 hours task down to 4 or 2 hours steps during estimations? Won't this raise the standard deviation? (Ok, let them break it down - but perhaps after the estimations?!)</p>
|
<ul>
<li>Yes, your observations are exatly the sort of problems EBS is designed to solve.</li>
<li>Yes, it's important to break bigger tasks down. Shoot for 1-2 day tasks, more or less.
<ul>
<li>If you have things estimated at under 2 hrs, see if it makes sense to group them. (It might not -- that's ok!)</li>
<li>If you have tasks that are estimated at 3+ days, see if there might be a way to break them up into pieces. There should be. If the estimator says there is not, make them defend that assertion. If it turns out that the task really just takes 3 days, fine, but the more of these you have, the more you should be looking hard in the mirror and seeing if folks aren't gaming the system.</li>
<li>Count 4 & 5 day estimates as 2x and 4x as bad as 3 day ones. Anyone who says something is going to take longer than 5 days and it can't be broken down, tell them you want them to spend 4 hrs thinking about the problem, and how it can be broken down. Remember, that's a task, btw.</li>
</ul></li>
<li>As you and your team practice this, you will get better at estimating.</li>
<li>...You will also start to recognize patterns of failure, and solutions will present themselves.</li>
<li>The point of <strong>Evidence</strong> based scheduling is to use <strong>Evidence</strong> as the basis for your schedule, not a collection of wild-assed guesses. It's <em>A Good Thing</em>...!</li>
</ul>
|
<p>"So, is it really a good idea to let the programmers break down the 30 hours task down to 4 or 2 hours steps during estimations? Won't this raise the standard deviation? (Ok, let them break it down - but perhaps after the estimations?!)"</p>
<p>I certainly don't get this question at all.</p>
<p>What it sounds like you're saying (you may not <em>be</em> saying this, but it sure sounds like it)</p>
<ol>
<li><p>The programmers can't estimate at all -- the numbers are always rounded to "magic" values and off by 2x.</p></li>
<li><p>I can't trust them to both define the work and estimate the time it takes to do the work.</p></li>
<li><p>Only I know the correct estimate for the time required to do the task. It's not a round 1/2 day multiple. It's an exact number of minutes.</p></li>
</ol>
<p>Here's my follow-up questions:</p>
<p>What are you saying? What can't you do? What problem are you having? Why do you think the programmers estimate badly? Why can't they be trusted to estimate?</p>
<p>From your statements, nothing is broken. You're able to plan and execute to that plan. I'd say you were totally successful and doing a great job at it.</p>
| 38,517
|
<p>I am working on a build system. The build system posts the results as a zip file in a directory. Unfortunately I have no easy way to know the name of the zip file, because it is timestamped. For the next operation, I must decompress this zip file to some specific location and then do some more file operations.</p>
<p>I guess I could change the build system so I specify the name of the result zip file from the command line, however, I though it might be easiest just to find out which one is the newest file and unzip it (if the previous process is successful). </p>
<p>How can I issue an unzip command that will only take effect on the newest zip file in the directory, ignoring all others?</p>
<p>EDIT: I decided to use the capabilities in ANT for this task instead. However, it is still a neat trick to have up the sleve... Thanks for the answer!</p>
|
<p>This should do it:</p>
<pre><code>FOR /F usebackq %%i IN (`DIR /B /O-D *.ZIP`) DO UNZIP %%i && GOTO DONE || GOTO DONE
:DONE
</code></pre>
<p>This works as follows:</p>
<ul>
<li><code>DIR /B /O-D *.ZIP</code> lists all ZIP files in reverse date order in a "bare" - i.e. name only - format.</li>
<li><code>FOR /F usebackq</code> is used to loop over the output of the command.</li>
<li><code>&& GOTO DONE || GOTO DONE</code> makes sure the <code>UNZIP</code> is only run for the first file. You need both <code>&&</code> (and) and <code>||</code> (or) in case the unzip fails for some reason.</li>
</ul>
<p>You'll need to change <code>UNZIP %%i</code> for whatever unzip command you want to use.</p>
<p><strong>EDIT</strong>
The above will work as long as the Zip filename doesn't contain any spaces. If you want to handle filenames with spaces, use the following variant:</p>
<pre><code>FOR /F "tokens=*" %%i IN ('DIR /B /O-D *.ZIP') DO UNZIP "%%i" && GOTO DONE || GOTO DONE
:DONE
</code></pre>
<p>The differences are:</p>
<ul>
<li><p>The "tokens=*" option returns the whole of the filename even if it contains spaces.</p></li>
<li><p>The filename passed to UNZIP is quoted</p></li>
<li><p>This variant uses single quotes for the DIR command so doesn't need the "usebackq" option.</p></li>
</ul>
|
<p>Why use bat files when you have powershell or console applications?</p>
| 21,576
|
<p>what's the easiest way to bulk load my iTunes library xml into an existing SQL Server database?</p>
|
<p>bcp with xml flag.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms162802.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms162802.aspx</a></p>
<p>It really depends how you want it in there and what you're purposes are, which you haven't explained.</p>
|
<p>I would recommend looking at the iTunes COM interface. There is an C# SDK that is straightforward to use and the documentation is good. You can download it here: <a href="http://developer.apple.com/sdk/itunescomsdk.html" rel="nofollow noreferrer">SDK</a></p>
| 36,689
|
<p>I have an ASP.NET application.
Basically the delivery process is this one :</p>
<ul>
<li>Nant builds the application and creates a zip file on the developer's computer with the application files without SVN folders and useless files. This file is delivered with a Nant script.</li>
<li>The zip and nant files are copied to the client's computer</li>
<li>the Nant script replaces the current website files with the file contained in the zip file.</li>
</ul>
<p>My problem is that with this process I have an Unauthorized access error when I try to open the website.
It seems that the files need to have a permission set for the user "<strong>IIS_WPG</strong>".</p>
<p>I don't have the power to change IIS configuration so I have to manually change the permissions of each file. And each time I replace the files the permissions are removed and I need to set them again.</p>
<p>So I have two questions :</p>
<ul>
<li>Can I change files permissions with Nant ? How to do it ?</li>
<li>Is it possible to avoid this problem ? (developers don't have this user on their computers)</li>
</ul>
|
<p>You need to run the CACLS program in windows to grant permissions to files and folders. From Nant, you can do this with the EXEC task.</p>
<p>Try a tag block like:</p>
<pre><code><exec program="cacls">
<arg value="*" />
<arg value="/G IIS_WPG:F" />
</exec>
</code></pre>
|
<p>We ended up writing our own task for this with some fairly straight forward code:</p>
<pre><code>[TaskName("addusertodir")]
public class AddUserToDirectorySecurity : Task
{
[TaskAttribute("dir", Required=true)]
public string DirPath { get; set; }
[TaskAttribute("user", Required=true)]
public string UserName { get; set; }
protected override void ExecuteTask()
{
FileSystemAccessRule theRule1 = new FileSystemAccessRule(UserName, FileSystemRights.ListDirectory, AccessControlType.Allow);
FileSystemAccessRule theRule2 = new FileSystemAccessRule(UserName, FileSystemRights.ReadAndExecute, AccessControlType.Allow);
FileSystemAccessRule theRule3 = new FileSystemAccessRule(UserName, FileSystemRights.Read, AccessControlType.Allow);
DirectorySecurity theDirSecurity = new DirectorySecurity();
theDirSecurity.AddAccessRule(theRule1);
theDirSecurity.AddAccessRule(theRule2);
theDirSecurity.AddAccessRule(theRule3);
Directory.SetAccessControl(DirPath, theDirSecurity);
}
}
</code></pre>
<p>Then you can write a nant script that loads the custom task and executes:</p>
<pre><code><loadtasks>
<fileset>
<include name="MyTask.dll"/>
</fileset>
</loadtasks>
<addusertodir dir="MyDir" user="IIS_WPG"/>
</code></pre>
<p>Obviously, this could be modified for your certain rules or you could even parameterize this in the task if you so wish. We preferred this over the using the exec task as it have us a bit more control over permissions that were being applied.</p>
| 28,879
|
<p>Why would IE 7 display HTTP Error "Bad request" 400 on the same page that Firefox loads without complaining?</p>
|
<p>When you get a message like this turn off friendly HTTP error messages in IE. To do this go to Tools -> Internet Options -> Advanced. Uncheck show friendly HTTP error messages. Once you have done this you should get a more detailed message which will point you to the real problem. </p>
<p>Do you have a URL that you could share to further diagnose the problem?</p>
|
<p>Perhaps you're experiencing an <a href="http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx" rel="nofollow noreferrer" title="IE7 bug">IE7 bug</a> <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/11/02/Dealing-with-IE-_2600_quot_3B00_Operation-Aborted_2600_quot_3B002E00_-Or_2C00_-how-to-Crash-IE.aspx" rel="nofollow noreferrer" title="involving javascript">involving javascript</a>?</p>
<p>It doesn't exactly fit your description, but it was IE specific, and quite a pain to track down.</p>
| 48,230
|
<p>I am writing a very specialized app in C# that floats as a mostly transparent window over the entire desktop. I want to be able to create and pass mouse events to applications behind mine, and have them appear to operate "normally", responding to those events. It would also be preferable if the window manager could respond.</p>
<p>I am not a Windows guru, and am unsure of how to best accomplish this.</p>
<p>From this page:
<a href="http://bytes.com/forum/thread270002.html" rel="noreferrer">http://bytes.com/forum/thread270002.html</a></p>
<p>it would appear that mouse_event would be good, except that since my app is floating over everything else, I'm guessing my generated events would never make it to the other apps underneath.</p>
<p>It seems the alternative is SendMessage, but that requires a fair amount of manual manipulation of windows, and the mouse events generated aren't "authentic."</p>
<p>Any thoughts on the best way to approach this?</p>
|
<p>After looking at System hooks and other low level solutions I found a much simpler method.</p>
<p>First, set the TransparencyKey and BackColor of the form to be the same. This didn't make any visual difference to me as my form was visually transparent already, but this will help in letting mouse events through.</p>
<p>Second, the following code will let mouse events "fall" through your form.</p>
<pre><code>protected override CreateParams CreateParams
{
get
{
CreateParams createParams = base.CreateParams;
createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
return createParams;
}
}
</code></pre>
<p>Lastly, set TopMost to be true.</p>
<p>Your form will now float on top of everything visually, but will give up focus to all other apps.</p>
|
<p>If you disable the control and return you're able to pass the MouseDown event to the parent.</p>
| 20,912
|
<p>I purchased a (very) low tier printer a while back, and now I am looking to start upgrading. First on my list is to upgrade the controller<sup>1)</sup>.</p>
<p>My initial plan was to upgrade to an Arduino Mega with a RAMPS 1.4 running Marlin, but as I started to try to find a RAMPS 1.4 board I started questioning my plan. Almost every source I could find for the board was either out of stock or very sketchy. Then I discovered that RAMPS 1.6 exists, but I can find even fewer places with it in stock.</p>
<p>Is the Mega + RAMPS combo still what people are using? I made a printer 4 years ago and that was what I used, but due to the scarcity of RAMPS boards for sale I am now unsure if it is still being used by the community.</p>
<p>If RAMPS still is the recommendation, what brands are reputable? (I'm trying to figure out if using RAMPS 1.4 with a Mega is an outdated solution and if there are better solutions these days.)</p>
<hr>
<p><em><sup>1)</sup> Upgrading is necessary for:<br>
Temperature/humidity sensors for monitoring/feedback; enclosure heaters (plan on having enclosed build space, work in a relative cold space); larger display with plenty of tactile switches; light sensor so the LEDs illuminating the enclosure can be modulated to provide more constant light levels for a webcam; possibly some joy sticks to manually maneuver the extruder and bed; etc. Basically I want something that can feasibly handle any unnecessary sensor/input I may eventually want to add. I'm familiar with Arduino and know it has those capabilities, but have no clue about other controllers.</em></p>
|
<p>If you own a Raspberry Pi , you may first want to try Klipper firmware. This firmware does the heavy lifting on the RPi itself and sends commands to the printer board via USB. </p>
<p>My Ender 3 pro works much better with this firmware. </p>
|
<p>As per <a href="https://reprap.org/wiki/RAMPS_1.6" rel="nofollow noreferrer">https://reprap.org/wiki/RAMPS_1.6</a>,</p>
<blockquote>
<p>The RAMPS 1.6 is the second RAMPS iteration released by BIQU/BIGTREETECH. It replaces the original green power connector with a pair of screw terminals, adds a larger heatsink over the MOSFETS, and has a larger bed MOSFET. It maintains the surface-mounted fuses and flush MOSFETS of the RAMPS 1.5.</p>
<p>Also, the positions of the D1 and D2 diodes have been swapped from the positions in RAMPS 1.4, the D1 diode is now the diode closest to fuse F2. The same is true for RAMPS 1.5, also manufactured by BIQU/BIGTREETECH.</p>
</blockquote>
<p>In other words, RAMPS 1.6 is pretty much the same as the 1.4 board. It just has some minor changes.</p>
<p>As for availability, I have found numerous listings for RAMPS 1.4 and RAMPS 1.6 on Amazon (US) and Ebay (US) for under $10.</p>
| 1,587
|
<p>I am working on a web application that is designed to display a bunch of data that is updated periodically with AJAX. The general usage scenario would be that a user would leave it open all day and take a glance at it now and then.</p>
<p>I am encountering a problem where the browsers memory footprint is growing slowly over time. This is happening in both Firefox and IE 7 (Although not in Chrome). After a few hours, it can cause IE7 to have a footprint of ~200MB and FF3 to have a footprint of ~400MB.</p>
<p>After a lot of testing, I have found that the memory leak only occurs if the AJAX calls are being responded to. If the server doesn't respond to anything, I can leave the page open for hours and the footprint won't grow.</p>
<p>I am using prototype for my AJAX calls. So, I'm guessing there is an issue with the onSuccess callback creating these memory leaks. </p>
<p>Does anyone have any tips on preventing memory leaks with prototype / AJAX? Or any methods on how to troubleshoot this problem?</p>
<p>EDIT: found out the issue lies in a js graphing library I am using. Can be seen <a href="http://code.google.com/p/flotr/issues/detail?id=5" rel="noreferrer">here</a>. </p>
|
<p>The biggest thing you can watch out for is events, and how you assign them.</p>
<p>For instance, take this scenario (since you haven't provided one):</p>
<pre><code><div id="ajaxResponseTarget">
...
</div>
<script type="text/javascript">
$(someButton).observe('click', function() {
new Ajax.Updater($('ajaxResponseTarget'), someUrl, {
onSuccess: function() {
$$('#ajaxResponseTarget .someButtonClass').invoke('observe', 'click', function() {
...
});
}
});
});
</script>
</code></pre>
<p>This will create a memory leak, because when <code>#ajaxResponseTarget</code> is updated (internally, Prototype will use <code>innerHTML</code>) elements with <code>click</code> events will be removed from the document without their events being removed. The second time you click <code>someButton</code>, you will then have twice as many event handlers, and garbage collection can't remove the first set.</p>
<p>A way to avoid this is to use event delegation:</p>
<pre><code><div id="ajaxResponseTarget">
...
</div>
<script type="text/javascript">
$('ajaxResponseTarget').observe('click', function(e) {
if(e.element().match('.someButtonClass')) {
...
}
});
$(someButton).observe('click', function() {
new Ajax.Updater($('ajaxResponseTarget'), someUrl);
});
</script>
</code></pre>
<p>Because of the way DOM events work, the "click" on <code>.someButtonClass</code> will fire also on <code>#ajaxResponseTarget</code>, and Prototype makes it dead simple to determine what element was the target of the event. No events are assigned to elements <em>within</em> <code>#ajaxResponseTarget</code>, so there is no way for replacing its contents to orphan events from targets within.</p>
|
<p>I may be wrong but it sounds like you are creating closures around the response object. Each response object will be different which results in an increased memory footprint.</p>
| 34,807
|
<p>The error happens trying to do an insert from a stored proc. I tried running DBCC CHECKDB as suggested by the kb article that Jonathan Holland suggested and it returned with the all clear.</p>
|
<p>Bummer dude.</p>
<p><a href="http://support.microsoft.com/kb/828337" rel="nofollow noreferrer">http://support.microsoft.com/kb/828337</a></p>
|
<p>Bummer dude.</p>
<p><a href="http://support.microsoft.com/kb/828337" rel="nofollow noreferrer">http://support.microsoft.com/kb/828337</a></p>
| 18,687
|
<p>I'm responsible for some test database servers. Historically, too many other poeple have access to them. They run on <code>SQL Server 2005</code>. </p>
<p>I've been writing queries and wrapping them in scripts so I can run a regular audit of rights. Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the <code>sysadmin</code> role on their login - it was a single line query for the latter.</p>
<p>But how to find out which logins have a User Mapping to a particular (or any) database? </p>
<p>I can find the <code>sys.database_principals</code> and <code>sys.server_principals</code> tables. I have located the <code>sys.databases table</code>. I haven't worked out how to find out which users have rights on a database, and if so, what. </p>
<p>Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?</p>
|
<p>Check out this msdn reference article on <a href="http://msdn.microsoft.com/en-us/library/ms189802.aspx" rel="nofollow noreferrer">Has_Perms_By_Name</a>. I think you're really interested in examples D, F and G</p>
<hr>
<p>Another idea... I fired up SQL profiler and clicked on the ObjectExplorer->Security->Users. This resulted in (approx) the following query being issued.</p>
<pre><code>SELECT *
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp
ON dp.grantee_principal_id = u.principal_id and dp.type = N'CO'
WHERE (u.type in ('U', 'S', 'G', 'C', 'K'))
ORDER BY [Name] ASC
</code></pre>
|
<pre><code>
select * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid
</code></pre>
<p>This will get you what users are mapped to which logins within a single database.</p>
| 9,180
|
<p>Working with an Oracle 9i database from an ASP.NET 2.0 (VB) application using OLEDB. Is there a way to have an insert statement return a value? I have a sequence set up to number entries as they go into the database, but I need that value to come back after the insert so I can do some manipulation to the set I just entered in the code-behind VB.</p>
|
<p>Some possibilities:</p>
<p>1) Use the RETURNING clause:</p>
<pre><code>INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS')
RETURNING empno INTO :variable;
</code></pre>
<p>2) Use the sequence CURRVAL:</p>
<pre><code>INSERT INTO emp (empno, ename) VALUES (emp_seq.NEXTVAL, 'ANDREWS');
SELECT emp_seq.CURRVAL INTO :variable FROM DUAL;
</code></pre>
<p>CURRVAL returns the last sequence value generated by your session.</p>
|
<p>If this value is the key the database creates, you've ran into a good example why you should use UUIDs as your table key, and generate them in code.</p>
<p>This method will give you faster performance in your setup.</p>
| 34,032
|
<p>For the umpteenth time my laptop just shut down in the middle of my game because my power cable had disconnected without me noticing it.</p>
<p>Now I want to write a little C# program that detects when my power cable disconnects and then emits a nice long System beep. What API could I use for that?</p>
|
<p>This should be trivial to implement using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus.aspx" rel="noreferrer">SystemInformation.PowerStatus</a> property. And even though that lives in Windows.Forms, it should be perfectly usable from a system service.</p>
<p>For a solution that also works on the Compact Framework, see <a href="http://msdn.microsoft.com/en-us/library/aa457088.aspx" rel="noreferrer">HOWTO: Get the Device Power Status</a></p>
|
<p>This may very much depend on your exact operating system.
Here are some calls for windows XP, I am sure you can find the Vista equivalents:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms704147(VS.85).aspx" rel="nofollow noreferrer" title="MSDN link">http://msdn.microsoft.com/en-us/library/ms704147(VS.85).aspx</a></p>
| 45,267
|
<p>I have an Ender 3 pro. In my country electricity outage is an issue, though it comes back pretty instantaneously, when I hit the resume button on the Ender 3 pro after heating the hot end and the bed when the hot end lifts the Y-axis or X-axis shifts a little bit, I do not understand why as when there is no power outage the prints are just flawless.</p>
<p>I have also tried tightening everything but feels like the motors are having their own fun tilting an extra step for no reason. I have thrown away many prints because of this problem as I work in robotics and prototyping is a necessary thing for me and so is the accuracy.</p>
|
<p>Not sure on your exact firmware, but it could be that it is using a <a href="https://marlinfw.org/docs/gcode/M413.html" rel="nofollow noreferrer">M413 power loss recovery</a> rather than a power loss interrupt pin. Possible you might be able to change this with your current firmware, but worst case you could install a new controller that does support this power loss interrupt pin.</p>
<p>Depending on the frequency and duration of your power outages it may be worth getting an uninterruptible power supply (UPS). With the heat bed off <a href="https://rads.stackoverflow.com/amzn/click/com/B000FBK3QK" rel="nofollow noreferrer" rel="nofollow noreferrer">this UPS</a> would run a full print easily. It would even handle a heat bed for shorter outages.</p>
<p>Where you work in robotics, you are probably electrically savvy enough to set your printer up on <a href="https://youtu.be/5uUb-VnTzlU?t=625" rel="nofollow noreferrer">direct DC battery power</a>, which would be cheaper than a UPS of equivalent energy storage. If you need help going that route just post over on electrical engineering stack exchange with the power supply info.</p>
|
<p>you'll need a UPS with EMI filter. I had this same issue and I opt to a regular desktop UPS and the problem was still there. So, I connected a EMI filter and it worked.</p>
| 2,095
|
<p>I want to put a <code>Canvas</code> with an image in my window, and then I want to <em>pack</em> widgets on top of it, so the Canvas acts as a background. </p>
<p>Is it possible to have two states for the <code>pack</code> manager: one for one set of widgets and another for another set?</p>
|
<p>The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent. </p>
<p>However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame. </p>
<p>You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.</p>
<p>One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)</p>
|
<p>Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly.</p>
<ul>
<li>COM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way.</li>
<li>QT will also let you do this in a similar manner.</li>
<li>GTK is slightly harder.</li>
</ul>
| 13,742
|
<p>Is there a way to 'pre-build' a snippet of HTML before adding it to the DOM?</p>
<p>For example:</p>
<pre><code>$mysnippet.append("<h1>hello</h1>");
$mysnippet.append("<h1>world</h1>");
$("destination").append($mysnippet);
</code></pre>
<p>where <strong>$mysnippet</strong> doesnt exist in the DOM. I'd like to dynamically build up some lumps of html and then insert them into the page at appropriate points later.</p>
|
<p>Yes pretty much exactly how you have done it</p>
<p>Some extension of this...</p>
<pre><code>$('<div>').attr('id', 'yourid').addClass('yourclass').append().append()...
</code></pre>
<p>and then finally</p>
<pre><code>.appendTo($("#parentid"));
</code></pre>
|
<p>Sure, just build them as a string:</p>
<pre><code>$mysnippet = "<h1>hello</h1>";
$mysnippet = $mysnippet + "<h1>world</h1>";
$("destination").append($mysnippet);
</code></pre>
| 43,774
|
<p>Here is the sample code for my accordion:</p>
<pre><code><mx:Accordion x="15" y="15" width="230" height="599" styleName="myAccordion">
<mx:Canvas id="pnlSpotlight" label="SPOTLIGHT" height="100%" width="100%" horizontalScrollPolicy="off">
<mx:VBox width="100%" height="80%" paddingTop="2" paddingBottom="1" verticalGap="1">
<mx:Repeater id="rptrSpotlight" dataProvider="{aSpotlight}">
<sm:SmallCourseListItem
viewClick="PlayFile(event.currentTarget.getRepeaterItem().fileID);"
Description="{rptrSpotlight.currentItem.fileDescription}"
FileID = "{rptrSpotlight.currentItem.fileID}"
detailsClick="{detailsView.SetFile(event.currentTarget.getRepeaterItem().fileID,this)}"
Title="{rptrSpotlight.currentItem.fileTitle}"
FileIcon="{iconLibrary.getIcon(rptrSpotlight.currentItem.fileExtension)}" />
</mx:Repeater>
</mx:VBox>
</mx:Canvas>
</mx:Accordion>
</code></pre>
<p>I would like to include a button in each header like so:</p>
<p><img src="https://i.stack.imgur.com/EN3kP.jpg" alt="wishful" onclick="alert('xss')"></p>
|
<p>Thanks, I got it working using <a href="http://code.google.com/p/flexlib/" rel="nofollow noreferrer">FlexLib</a>'s CanvasButtonAccordionHeader.</p>
|
<p>You will have to create a custom header renderer, add a button to it and position it manually. Try something like this:</p>
<pre><code><mx:Accordion>
<mx:headerRenderer>
<mx:Component>
<AccordionHeader xmlns="mx.containers.accordionClasses.*">
<mx:Script>
<![CDATA[
import mx.controls.Button;
private var extraButton : Button;
override protected function createChildren( ) : void {
super.createChildren();
if ( extraButton == null ) {
extraButton = new Button();
addChild(extraButton);
}
}
override protected function updateDisplayList( unscaledWidth : Number, unscaledHeight : Number ) : void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
extraButton.setActualSize(unscaledHeight - 6, unscaledHeight - 6);
extraButton.move(unscaledWidth - extraButton.width - 3, (unscaledHeight - extraButton.height)/2);
}
]]>
</mx:Script>
</AccordionHeader>
</mx:Component>
</mx:headerRenderer>
<mx:HBox label="1"><Label text="Text 1"/></HBox>
<mx:HBox label="1"><Label text="Text 2"/></HBox>
<mx:HBox label="1"><Label text="Text 3"/></HBox>
</mx:Accordion>
</code></pre>
| 3,274
|
<p>I use <em>Eclipse 3.3</em> in my daily work, and have also used <em>Eclipse 3.2</em> extensively as well. In both versions, sometimes the Search options (Java Search, File Search, etc) in the menu get disabled, seemingly at random times. However, with <kbd>Ctrl</kbd>+<kbd>H</kbd>, I am able to access the search functionality. Does anyone know why this happens? Has it been fixed in <em>Eclipse 3.4</em>?</p>
|
<p>window > close all perspective works for me.</p>
|
<p>I had this problem too. It appeared when I installed the m2eclipse plugin.</p>
<p>I had not found a solution, but you can use <kbd>Ctrl</kbd>+<kbd>H</kbd> shortcut instead.
And you can navigate between tabs with <kbd>Ctrl</kbd>+<kbd>PgDown</kbd> or <kbd>Ctrl</kbd>+<kbd>PgUp</kbd> keys.</p>
<p>I've uninstalled the following pluings and it worked. </p>
<ul>
<li>Maven integration </li>
<li>PMD </li>
<li>eclipse checkstyle plugin</li>
<li>EclEmma (coverage)</li>
</ul>
<p>I don't know which of those cause the problem. To uninstall a plugin: Help -> Software Updates...-> "Installed Software" tab.</p>
| 16,118
|
<p>Something's slowing down my Javascript code in IE6 to where there's a noticeable lag on hover. It's fine in FF, so using firebug isn't that helpful. What tools are out there to help debug this in IE?</p>
<p><strong>A little more info:</strong> I don't think there's actually any JS running on the objects that I'm mousing over. (At least none that I've put in.) Just css :hover stuff. Also, I've got both jquery and dojo running on the project, so who knows what they're doing in the background.</p>
|
<p>Just a tip of what that "something" could be...</p>
<p><strong>String concatenation</strong> in IE is (or at least was when I <a href="http://forums.thedailywtf.com/forums/p/8931/169331.aspx" rel="noreferrer">tested</a>) very slow. Opera finished after 0.2s, Firefox after 4.1s and Internet Explorer 7 still hadn’t finished after 20 <strong>minutes</strong>!!!</p>
<p>Don't do:</p>
<pre><code>for (var i=0, i < 200; i++) { s = s + "something";}
</code></pre>
<p>Instead, temporarily use an array, and then join it:</p>
<pre><code>var s=[];
for (var i=0; i < 200; i++) s.push("something");
s=s.join("");
</code></pre>
|
<p>The lag could also be from a DOM update. When IE needs to re-render a page due to a DOM change, it can be noticeably slower than Firefox. Typically the cursor will freeze when this happens.</p>
| 38,501
|
<p>Should we really close this question: <a href="https://3dprinting.stackexchange.com/questions/10200/3d-printer-part-clones-from-china-legality">3d printer part clones from china - legality</a>..? </p>
<p>Are legal questions on topic? We have a legal section in the <a href="https://3dprinting.meta.stackexchange.com/questions/276/game-plan-what-is-on-topic">Game plan - What is on-topic?</a> and a <a href="https://3dprinting.stackexchange.com/questions/tagged/legal" class="post-tag" title="show questions tagged 'legal'" rel="tag">legal</a> tag.</p>
|
<p><strong>I say allow them.</strong> </p>
<p>To let you know what's out there, I work at <a href="http://hyrel3d.com" rel="nofollow noreferrer">Hyrel</a>. </p>
<p>Our printers can take <a href="https://www.youtube.com/watch?v=B0lvN-aPYHI" rel="nofollow noreferrer">spindle (milling) heads and additional axes</a>, and even <a href="https://www.youtube.com/watch?v=OceUiuTixPA" rel="nofollow noreferrer">diode</a> and <a href="https://youtu.be/FnYDoNkgOrI" rel="nofollow noreferrer">CO2 lasers</a>, and they all operate on the same gcode - we tell people E is for Emit as well as Extrude. We even have a <a href="https://www.youtube.com/watch?v=azFY-IqDB_0" rel="nofollow noreferrer">TIG welding</a> attachment. </p>
<p>We also run our <a href="https://www.youtube.com/watch?v=KIGeQmXNbNE" rel="nofollow noreferrer">Fadal CNC machines</a> on our printer software and firmware. </p>
<p>To many people this is a natural progression for a well-built 3D positioning system, and I encourage a broader definition.</p>
|
<p>This is a tricky one, as 3d printers are starting to be bundled with lasers. Note those kits will totally blind you. 3d printers are being bundled with everything, really if you look at the things <a href="http://diabasepe.com/" rel="nofollow noreferrer">http://diabasepe.com/</a> is making. (Cool guys btw)</p>
<p>However. To me this is the same as asking about a woodburning kit question in an electronics forum, because they both use soldering irons. If we allow a removal base machines, such as lasers, we will also have to allow discussions about CNC machines.</p>
<p>In the case of that question, they would get bonus points if it was a pure gcode question. Maybe even if it was on a multi use machine.. Instead its asking us to debug their laser setup. Thats not really formatted for stackoverflow anyways. They need to go to a forum. Also as someone that once made a Cheap Chinese laser cutter use a RAMPS 1.4 board, I know exactly how similar they are. But in the end, additive manufacturing isn't this kind of laser (as we have SLA and powder printing)</p>
<p>At first I was this is dead simple not on topic. Thinking about laser and 3d printing is a good counter arguments, but that is not what this topic is. It is not additive manufacturing, and its not being done to a part which was additively made. </p>
<p>I think its a firm off topic. </p>
| 67
|
<p>Suppose someone is building you a CMS (Content Management System) from scratch. What are the most important features to include and why?</p>
|
<ul>
<li>security - <a href="http://www.owasp.org/index.php/Top_10_2007" rel="noreferrer">OWASP Top 10</a></li>
<li>user management & user roles</li>
<li>action and view permissions</li>
<li>content versioning and audit</li>
<li>some form of workflow and notifications</li>
<li>i18n support on literals and object versions</li>
<li>normalized database schema design</li>
<li>some form of content import-export</li>
<li>assets management and thumbnail generation for uploads</li>
<li>Valid XHTML (compressed with GZIP)</li>
<li>Rich text editing (e.g FCKeditor) which generates accessible markup</li>
<li>Valid and minified CSS and javascript (e.g using YUI)</li>
<li>automatically generated sitemaps.org document</li>
<li>integration with Google Analytics</li>
<li>automatic RSS feeds</li>
<li>open search support</li>
<li>print css and/or print versions of content</li>
<li>SEO consideration for duplicate content (e.g use of canonical tag)</li>
</ul>
|
<p>When working with clients, I often heard a number of requirements that, in my opinion, had little to do with what a modern CMS really needs. Far too often emphasis was on features that should have been in the domain of template designers, such as support for responsive design (whatever that really means), the ability to add brand elements etc. </p>
<p>I compiled a list of the top 5 features a modern CMS needs at <a href="http://www.simoahava.com/content-management/modern-cms-top-5-features/" rel="nofollow">http://www.simoahava.com/content-management/modern-cms-top-5-features/</a></p>
<p>Modular architecture and strong security are the most important features from a technical standpoint. Complete control over content, source code and the software solution itself are all huge perks for any CMS. </p>
<p>Simo Ahava</p>
| 49,834
|
<p>As I build *nix piped commands I find that I want to see the output of one stage to verify correctness before building the next stage but I don't want to re-run each stage. Does anyone know of a program that will help with that? It would keep the output of the last stage automatically to use for any new stages. I usually do this by sending the result of each command to a temporary file (i.e. tee or run each command one at a time) but it would be nice for a program to handle this.</p>
<p>I envision something like a tabbed interface where each tab is labeled with each pipe command and selecting a tab shows the output (at least a hundred lines) of applying that command to to the previous result.</p>
|
<p>Use 'tee' to copy the intermediate results out to some file as well as pass them on to the next stage of the pipe, like so:</p>
<pre><code>cat /var/log/syslog | tee /tmp/syslog.out | grep something | tee /tmp/grep.out | sed 's/foo/bar/g' | tee /tmp/sed.out | cat >>/var/log/syslog.cleaned
</code></pre>
|
<p><code>tee</code>(1) is your friend. It sends its input to both the specified file and stdout. </p>
<p>Stick it between your pipes. For example:</p>
<pre><code>ls | tee /tmp/out1 | sort | tee /tmp/out2 | sed 's/foo/bar/g'
</code></pre>
| 8,921
|
<p>Is there an equivalent of svn's blame for Perforce on the command line? <code>p4 annotate</code> doesn't display usernames -- only changeset numbers (without ancestor history!).</p>
<p>I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility?</p>
|
<p>I'm not overly familiar with the blame command, but I assume that you are looking for who changes a particular line of code. The easiest way is to use Perforce's 'time lapse view' available from both p4win and p4v.</p>
<p>This tool uses annotate and some other commands to give you a view of the code line over time. You can see who modified what code, when it was inserted or removed from the codeline, etc. </p>
<p>It's not command line though. I checked briefly in the help and there doesnt' seem to be a way to launch the time lapse view directly from a p4win or p4v invocation. There might be though...I'll be checking further...</p>
<p>Edit: I checked with support, and you can launch the timelapse view through p4v as follows:</p>
<pre><code>p4v.exe -cmd "annotate //<path/to/file>"
</code></pre>
<p>HTH.</p>
|
<p>@alanw123: p4pr is close to what I'm looking for, but it doesn't cross branch boundaries:</p>
<pre><code>last if $type eq 'branch';
</code></pre>
<p>That was the main problem I had when I tried writing my own utility -- you can't (easily) tell how the lines map back to the file that was branched from.</p>
| 8,169
|
<p>I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one. </p>
<p>The graph contains labeled nodes and unlabeled directional edges.
The ideal output would be something like <a href="http://en.wikipedia.org/wiki/Image:6n-graf.svg" rel="noreferrer">this</a>. </p>
<p>Anybody know of anything pre-built than can help?</p>
|
<p>Definitely <a href="http://graphviz.org" rel="nofollow noreferrer">graphviz</a>. The image on the wikipedia link you are pointing at was made in graphviz. From its description page the graph description file looked like this:</p>
<pre><code>graph untitled {
graph[bgcolor="transparent"];
node [fontname="Bitstream Vera Sans", fontsize="22.00", shape=circle, style="bold,filled" fillcolor=white];
edge [style=bold];
1;2;3;4;5;6;
6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4;
2 -- 5;
}
</code></pre>
<p>If that code were saved into a file input.dot, the command they would have used to actually generate the graph would probably have been:</p>
<pre><code>neato -Tsvg input.dot > graph.svg
</code></pre>
|
<p>You might be able to pull this off with <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">Google's Chart API</a>. It is very easy to get started with.</p>
| 9,467
|
<p>I am trying to get simple jQuery to execute on my Content page with no luck below is what I am trying to do:</p>
<pre><code><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("hi");
});
</script>
</asp:Content>
</code></pre>
<p>I have also tried getting the following to work:</p>
<pre><code><asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
function onload()
{
$("#myDiv").css("border", "1px solid green");
}
</script>
<div id="myDive">
Hello
</div>
</asp:Content>
</code></pre>
|
<p>It may be that the JQuery file can't be found, try this for the script reference:</p>
<pre><code><script src="<%= Url.Content ("~/Scripts/jquery-1.2.6.js") %>" type="text/javascript"></script>
</code></pre>
<p>The Url.Content will build the correct path regardless of whether the app is running in the root or a sub-directory.</p>
<p>Also, if you've installed the hot-fix for the JS intellisense, you can use this in addition to the above:</p>
<pre><code><% if (false) { %>
<!-- Don't wrap this is a Url.Content call, it's like this so we get intellisense! -->
<script src="../../Scripts/jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
<% } %>
</code></pre>
<p><strong>Edit:</strong></p>
<p>Since the release of the RC 1 Refresh, there's been a know bug about placing elements with code blocks in the header, Philip Haacked has a nice <a href="http://haacked.com/archive/2009/01/27/controls-collection-cannot-be-modified-issue-with-asp.net-mvc-rc1.aspx" rel="noreferrer">article</a> about solving it...</p>
<p><strong>Edit 2:</strong></p>
<p>Apparently this has been fixed since RC 2 was released...</p>
<blockquote>
<p>• Code nuggets that are direct children of the head element do not cause an exception if the runat="server" attribute is added to them.</p>
</blockquote>
<p><strong>Edit 3:</strong></p>
<p>The hot-fix referenced earlier is only applicable to VS2008 and is available <a href="http://code.msdn.microsoft.com/KB958502/Release/ProjectReleases.aspx?ReleaseId=1736" rel="noreferrer">here</a> - check out the blog post by the VS Web Dev Team <a href="http://blogs.msdn.com/webdevtools/archive/2008/02/08/jscript-intellisense-working-with-jquery.aspx" rel="noreferrer">here</a> for details. VS2010 has it built in.</p>
|
<p>Try putting the javascript references in your Master Page. Then you don't have to worry about attempting to load the scripts multiple times.</p>
| 48,564
|
<p>everyone.</p>
<p>I'm a relative newcomer to 3D printing, so I don't know what constitutes an unacceptably bad spool of filament.</p>
<p>About 1/6 of the way into a roll of PETG (and maybe 4 hours into a 6-hour print), an over/under wrap brought things to a screeching halt. I aborted the print, then snipped the filament and started unspooling it, looking for more cross-wraps. I found a ton of them, along with a ton of kinks.</p>
<p>I stopped about 1/3 of the way into the spool, still finding kinks and cross-wraps, and said to heck with it. The only way to use it would have been to run the entire length onto another spool, carefully avoiding cross-wraps, and hope the kinks wouldn't affect the print quality.</p>
<p>I complained to the supplier but never even got a reply, so now I'm wondering if this is just one of those things I can expect from time to time. Any thoughts & opinions would be much appreciated.</p>
<p>Cheers,</p>
<p>Glasseyed</p>
|
<p>Filament should come off of the roll without overlapping itself. That being said depending on what you paid for it would determine if you should complain. Normally you get what you pay for. If you paid \$10 for it, I would think that is why it was so cheap, but if you paid >\$25 it should be nice stuff.</p>
|
<p>Knot happens when you loosen the filament yourself and then leave it like that or try to manually re-spool it.
To avoid this kind of situation as well as the curly filament coming off the spool and getting tangled there, try to not loosen it and also build or print a "spool guide" for your 3d printer: <a href="http://www.thingiverse.com/search/page:1?q=filament+spool+guide&sa=" rel="nofollow">http://www.thingiverse.com/search/page:1?q=filament+spool+guide&sa=</a></p>
| 194
|
<p>This is a program I'm writing (myself as opposed to copying someone else's and thus not learning) as part of the ObjectiveC and Cocoa learning curve. I want to draw simple shapes on a NSView (limiting it to ovals and rectangles for now). The idea is that I record each NSBezierPath to an NSMutableArray so I can also investigate/implement saving/loading, undo/redo. I have a canvas, can draw on it as well as 2 buttons that I use to select the tool. To handle the path I created another object that can hold a NSBezierPath, color values and size value for each object drawn. This is what I want to store in the array. I use mouseDown/Dragged/Up to get coordinates for the drawing path. However, this is where things go wonky. I can instantiate the object that is supposed to hold the path/color/etc. info but, when I try to change an instance variable, the app crashes with no useful message in the debugger. I'll try to keep my code snippets short but tell me if I need to include more. The code has also degenerated a little from me trying so many things to make it work.</p>
<p>Project: Cocoa document based app<br />
I have the following .m/.h files</p>
<ul>
<li><code>MyDocument:NSDocument</code> - generated by XCode</li>
<li><code>DrawnObject:NSObject</code> - deals with the drawn object i.e. path, color, type (oval/rect) and size</li>
<li><code>Canvas:NSView</code> - well, shows the drawing, deals with the mouse and buttons</li>
</ul>
<p>Canvas is also responsible for maintaining a <code>NSMutableArray</code> of <code>DrawnObject</code> objects.</p>
<p><code>DrawnObject.h</code> looks like this:
<code></p>
<pre>
#import <Foundation/Foundation.h>
//The drawn object must know what tool it was created with etc as this needs to be used for generating the drawing
@interface DrawnObject : NSObject {
NSBezierPath * aPath;
NSNumber * toolType;//0 for oval, 1 for rectangular etc....
float toolSize;
struct myCol{
float rd;
float grn;
float blu;
float alp;
} toolColor;
}
-(void)setAPath:(NSBezierPath *) path;
-(NSBezierPath *)aPath;
@property (readwrite,assign) NSNumber * toolType;
-(float)toolSize;
-(void)setToolSize:(float) size;
-(struct myCol *)toolColor;
-(void)setCurrentColor:(float)ref:(float)green:(float)blue:(float)alpha;
@end
</pre>
<p></code>
<code>Canvas.h</code> looks like this</p>
<pre>
#import
#import "drawnObject.h"
@interface Canvas : NSView {
NSMutableArray * myDrawing;
NSPoint downPoint;
NSPoint currentPoint;
NSBezierPath * viewPath;//to show the path as the user drags the mouse
NSNumber * currentToolType;
BOOL mouseUpFlag;//trying a diff way to make it work
BOOL mouseDrag;
}
-(IBAction)useOval:(id)sender;
-(IBAction)useRect:(id)sender;
-(IBAction)showTool:(id)sender;
-(NSRect)currentRect;
-(NSBezierPath *)createPath:(NSRect) aRect;
-(void)setCurrentToolType:(NSNumber *) t;
-(NSNumber *)currentToolType;
@end
</pre>
<p>In the <code>Canvas.m</code> file there are several functions to deal with the mouse and NSView/XCode also dropped in <code><br />-(id)initWithFrame:(NSRect)frame</code> and <code>-(void)drawRect:(NSRect)rect</code> Originally I use <code>mouseUp</code> to try to insert the new <code>DrawnObject</code> into the array but that caused a crash. So, now I use two <code>BOOL</code> flags to see when the mouse was released (clunky but I'm trying....)in <code>drawRect</code> to insert into the array. I've included the method below and indicated where it causes the app to fail:</p>
<pre>
- (void)drawRect:(NSRect)rect { //This is called automatically
// Drawing code here.
//NSLog(@"Within drawRect tool type is %d", [self currentTool]);
NSRect bounds = [self bounds];
NSRect aRect = [self currentRect];
viewPath = [self createPath:aRect];
//the createPath method uses the tool type to switch between oval and rect bezier curves
if(mouseUpFlag==YES && mouseDrag==YES){
mouseDrag=NO;
//Create a new drawnObject here
DrawnObject * anObject = [[DrawnObject alloc]init];//- WORKS FINE UP TO HERE
NSLog(@"CREATED NEW drawnObject");
[anObject setAPath:viewPath]; //- INSTANT APP DEATH!!!!
NSLog(@"Set a path in drawnObject");
[anObject setToolType:[[NSNumber alloc]initWithInt:5]];
NSLog(@"Set toolType in DrawnObject");
[anObject setToolType:currentToolType];
[myDrawing addObject:anObject];
NSLog(@"Added Object");
}
[[NSColor colorWithCalibratedRed:0.0 green:0.9 blue:0.0 alpha:0.5]set];
[NSBezierPath fillRect:bounds];
[[NSColor lightGrayColor]set];
[viewPath stroke]; //This is so the user can see where the drawing is being done
//Now, draw the paths in the array
[[NSColor blueColor]set];
for(DrawnObject * indexedObject in myDrawing){
[[indexedObject aPath] stroke];//This will do the actual drawing of ALL objects
}
}
</pre>
<p>I guess this has something to do with object scope or something but I just can not figure it out. As I said, as I've tried things the code has sort of undergone an metamorphosis, sadly not for the better. Like those BOOLS etc.</p>
<p><strong> HELP! Any clever people out there, point me in the right direction please!</strong></p>
<p>ADDED THIS ON:</p>
<pre><code>
-(NSBezierPath *)createPath:(NSRect) aRect
{
NSBezierPath * tempPath;
//I need to know what tool
switch(0){ //temporary - this would use the toolType as a selector
case 0:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
case 1:
tempPath = [NSBezierPath bezierPathWithRect:aRect];
break;
default:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
}
return tempPath;
}
</code></pre>
|
<p>You said your init method was:</p>
<pre><code>-(void)init {
[super init];
//set default color = black
toolColor.rd=1.0;
toolColor.grn=1.0;
toolColor.blu=1.0;
toolColor.alp=1.0;
//set default size
toolSize=0.8;
//set default toolType
toolType=0;
//oval
NSLog(@"Init %@",self);
}
</code></pre>
<p>This is <strong><em>definitely</em></strong> wrong; read up on how to create an init method in the Obj-C guide or by reading sample code. Here's what it should look like:</p>
<pre><code>-(id)init {
if (self = [super init]) {
//set default color = black
toolColor.rd=1.0;
toolColor.grn=1.0;
toolColor.blu=1.0;
toolColor.alp=1.0;
//set default size
toolSize=0.8;
//set default toolType
toolType=0;
//oval
NSLog(@"Init %@",self);
}
return self;
}
</code></pre>
<p>By not returning anything from -init, you were preventing the object's creation. Good luck! :-)</p>
<p><strong>Edit:</strong> Ashley beat me to it...</p>
|
<p>What do you mean by “crash”?</p>
<p>Does anything appear in the Debugger Console (⇧⌘R)?</p>
<p>Does a stack trace appear in the Debugger window?</p>
<p>If there's a stack trace, where in your code does it crash?</p>
| 42,084
|
<p>I need a way to build C++ code from UML diagrams and vice versa. </p>
<p>Should be simple too hopefully. I don't mind paying too much.</p>
|
<p>You could try <a href="http://www.sparxsystems.com.au/products/ea/index.html" rel="nofollow noreferrer">Sparx Enterprise Architect</a> but the code quality would be average, not excellent.</p>
<p>I am not aware of any great automatic code generators for C++</p>
<p>Prices start from $135</p>
|
<p>Visio also supports this.</p>
| 26,176
|
<p>We are deciding the naming convention for tables, columns, procedures, etc. at our development team at work. The singular-plural table naming <em>has already been decided</em>, we are using singular. We are discussing whether to use a prefix for each table name or not. I would like to read suggestions about using a prefix or not, and why.</p>
<p>Does it provide any security at all (at least one more obstacle for a possible intruder)? I think it's generally more comfortable to name them with a prefix, in case we are using a table's name in the code, so to not confuse them with variables, attributes, etc. But I would like to read opinions from more experienced developers.</p>
|
<p>I prefer prefixing tables and other database objects with a short name of the application or solution.</p>
<p>This helps in two potential situations which spring to mind:</p>
<ol>
<li><p>You are less likely to get naming conflicts if you opt to use any third-party framework components which require tables in your application database (e.g. asp net membership provider).</p></li>
<li><p>If you are developing solutions for customers, they may be limited to a single database (especially if they are paying for external hosting), requiring them to store the database objects for multiple applications in a single database.</p></li>
</ol>
|
<p>If you're worried about mixing up your table names, employ a hungarian notation style system in your code. Perhaps "s" for string + "tn" for table name:</p>
<pre><code> stnUsers = 'users';
stnPosts = 'posts';
</code></pre>
<p>Of course, the prefix is up to you, depending on how verbose you like your code... <code>strtblUsers, strtblnmeUsers, thisisthenameofatableyouguysUsers...</code></p>
<p>Appending a prefix to table names does have some benefits, especially if you don't hardcode that prefix into the system, and allow it to change per installation. For one, you run less risk of conflicts with other components, as Ian said, and secondly, should you wish, you could have two or instances of your program running off the same database.</p>
| 41,974
|
<p>I've created a model for executing worker tasks in a server application using a thread pool associated with an IO completion port such as shown in the posts below:</p>
<p><a href="http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx" rel="noreferrer">http://weblogs.asp.net/kennykerr/archive/2008/01/03/parallel-programming-with-c-part-4-i-o-completion-ports.aspx</a></p>
<p><a href="http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx" rel="noreferrer">http://blogs.msdn.com/larryosterman/archive/2004/03/29/101329.aspx</a></p>
<p>Are there any classes in boost that can help with this programming model?</p>
|
<p>Not really, at least, not last time I looked. I mean, boost::thread_group might make things marginally tidier in places, but not so as would make much of a difference, I don't think.</p>
<p>Boost's thread support seems marginally useful when writing something that's cross-platform, but given that what you're writing is going to be Win32-specific anyway (due to the use of IOCPs) there doesn't really seem to be much benefit from that.</p>
|
<p><a href="http://www.cs.wustl.edu/~schmidt/ACE.html" rel="nofollow noreferrer">ACE</a> has some reactors that you can use to model things around your IOCPs. Some of these could have been added to boost, but boost makes building them pretty easy. </p>
| 5,773
|
<p>I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:</p>
<pre><code><list>
<activity>swimming</activity>
<activity>running</activity>
<list>
</code></pre>
<p>Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:</p>
<pre><code><html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$activities = = $xmldoc->firstChild->firstChild;
if($activities!=null){
while(activities!=null){
echo $activities->textContent.'<br/>';
activities = activities->nextSibling.
}
}
?>
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text' name='activity'/>
<input type='submit' value='send'/>
</form>
</body>
</html
</code></pre>
<p>and here's the code for insert.php:</p>
<pre><code><?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
</code></pre>
<p>The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.</p>
|
<p>is your code block copy and pasted from your existing files? if so i see two potential issues:</p>
<pre><code><form name='input' action'insert.php' method='post'> // should be:
<form name="input" action="insert.php" method="post">
</code></pre>
<p>note: you're missing <code>action</code><strong>=</strong><code>"insert.php"</code>, which would cause the form to just reload itself without submitting, which is the behaviour you describe.</p>
<p>secondly, make sure you have write permission to "sample.xml". you can confirm if you're actually writing anything:</p>
<pre><code>print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';
</code></pre>
|
<p>I think I know what is the problem with your code. You should not write like that: <code><?xml-stylesheet type="text/xsl" href="sample.xsl" ?></code>
The right code is:</p>
<pre><code><?xml:stylesheet type="text/xsl" href="sample.xsl" ?>
</code></pre>
| 23,644
|
<p>Can someone provide a regular expression for parsing name/value pairs from a string? The pairs are separated by commas, and the value can optionally be enclosed in quotes. For example:</p>
<pre><code>AssemblyName=foo.dll,ClassName="SomeClass",Parameters="Some,Parameters"
</code></pre>
|
<ul>
<li><p><strong>No escape:</strong></p>
<pre><code>/([^=,]*)=("[^"]*"|[^,"]*)/
</code></pre></li>
<li><p><strong>Double quote escape for both key and value:</strong></p>
<pre><code>/((?:"[^"]*"|[^=,])*)=((?:"[^"]*"|[^=,])*)/
key=value,"key with "" in it"="value with "" in it",key=value" "with" "spaces
</code></pre></li>
<li><p><strong>Backslash string escape:</strong></p>
<pre><code>/([^=,]*)=("(?:\\.|[^"\\]+)*"|[^,"]*)/
key=value,key="value",key="val\"ue"
</code></pre></li>
<li><p><strong>Full backslash escape:</strong></p>
<pre><code>/((?:\\.|[^=,]+)*)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^,"\\]+)*)/
key=value,key="value",key="val\"ue",ke\,y=val\,ue
</code></pre></li>
</ul>
<p><strong>Edit:</strong> Added escaping alternatives.</p>
<p><strong>Edit2:</strong> Added another escaping alternative.</p>
<p>You would have to clean up the keys/values by removing any escape-characters and surrounding quotes.</p>
|
<p>This is how I would do it if you can use <code>Perl 5.10</code>.</p>
<pre>
qr/
(?<key>
(?:
[^=,\\]
|
(?&escape)
)++ # Prevent null keys
)
\s*+
=
\s*+
(?<value>
(?"ed)
|
(?:
[^=,\s\\]
|
(?&escape)
)++ # Prevent null value ( use quotes for that )
)
(?(DEFINE)
(?<escape>\\.)
(?<quoted>
"
(?:
(?&escaped)
|
[^"\\]
)*+
"
)
)
/x
</pre>
<p>The elements would be accessed through <code>%+</code>.</p>
<p><em><a href="http://perldoc.perl.org/perlretut.html" rel="nofollow noreferrer"><code>perlretut</code></a> was very helpful in creating this answer.</em></p>
| 20,309
|
<p>How to Programmatically Inject JavaScript in PDF files?</p>
<p>Can it be done without Adobe Professional?</p>
<hr>
<p>My goal is: I want to show up the print dialog immediately when I open the PDF. </p>
<p>I know that this can be done with JavaScript code embedded in the document.</p>
|
<p>If you're developing in Java have a look at iText: <a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">http://www.lowagie.com/iText/</a>
I think it supports what you are looking for.</p>
<p>There are also some .Net versions around: <a href="http://www.ujihara.jp/iTextdotNET/en/" rel="nofollow noreferrer">http://www.ujihara.jp/iTextdotNET/en/</a></p>
|
<p>I've done studing the <a href="http://www.adobe.com/devnet/acrobat/pdfs/PDF32000_2008.pdf" rel="nofollow noreferrer">PDF Specifications</a>.</p>
<p>Turns out that the PDF file format isn't that hard.</p>
<p>It has a nice feature that ables to modify the document just by appending new content in the end of the file.</p>
<p>If you are trying to do the same thing... don't be affraid! go and look at the specs.</p>
| 25,774
|
<p>I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the UID:</p>
<pre><code>$id = tempnam (".", "");
unlink($id);
$id = substr($id, 2);
</code></pre>
<p>This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string.</p>
<p>Is there any better way to do this, most preferably without any external dependencies?</p>
<p>Thanks much!</p>
|
<pre><code>string uniqid ([ string $prefix [, bool $more_entropy ]] )
</code></pre>
<p>Gets a prefixed unique identifier based on the current time in microseconds.</p>
<pre><code>USAGE: $id = uniqid(rand(), true);
</code></pre>
|
<p>uniqid() is what you're looking for in most practical situations.</p>
<p>You can make it even more "uniq" by adding a large random number after it.</p>
| 21,859
|
<p>This is my first real question of need for any of those Gridview experts out there in the .NET world.</p>
<p>I an creating a Gridview from codebehind and I am holding a bunch of numerical data in the columns. Although, I do add the comma in the number fields from codebehind. When I load it to the Gridview, I have the sorting ability turned on, BUT the gridview chooses to ALPHA sort rather than sorting numerically because I add in those commas.</p>
<p>So I need help. Anyone willing to give this one a shot? I need to change some of my columns in the gridview to numerical sort rather than the alpha sort it is using.</p>
|
<p>If you do end up implementing your own comparer and sorting them as strings, the algorithm for treating numbers 'properly' is called Natural Sorting. Jeff wrote a pretty good entry on it here:<br>
<a href="https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow noreferrer">Sorting for Humans : Natural Sort Order</a></p>
<p>You can find a pretty good implementation in C# here:<br>
<a href="http://www.codeproject.com/KB/string/NaturalSortComparer.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/string/NaturalSortComparer.aspx</a></p>
|
<p>Depending on exactly how you are doing sorting you could use one of the above methods, or you could return to the DB and get the sorting done there if the columns are actually a number type, then add your decoration to it later.</p>
| 10,513
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content">Resizing an iframe based on content</a> </p>
</blockquote>
<p>I'm loading an iFrame and want the parent to automatically change the height based upon the height of the iFrame's content.</p>
<p>To simply things, all pages belong to the same domain, so I shouldn't run into cross-site scripting issues.</p>
|
<p>On any other element, I would use the <code>scrollHeight</code> of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.</p>
<p>Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the <code>offsetHeight</code>:</p>
<pre><code>function setHeight() {
parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}
</code></pre>
<p>And attach that to run with the iframe-body's <code>onLoad</code> event.</p>
|
<p>Actually - Patrick's code sort of worked for me as well. The correct way to do it would be along the lines of this:</p>
<p>Note: there's a bit of jquery ahead:</p>
<pre><code>
if ($.browser.msie == false) {
var h = (document.getElementById("iframeID").contentDocument.body.offsetHeight);
} else {
var h = (document.getElementById("iframeID").Document.body.scrollHeight);
}
</code></pre>
| 30,692
|
<p>How can I get a list of the IP addresses or host names from a local network easily in Python?</p>
<p>It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.</p>
<p><strong>Edit:</strong> By local I mean all <strong>active</strong> addresses within a local network, such as <code>192.168.xxx.xxx</code>.</p>
<p>So, if the IP address of my computer (within the local network) is <code>192.168.1.1</code>, and I have three other connected computers, I would want it to return the IP addresses <code>192.168.1.2</code>, <code>192.168.1.3</code>, <code>192.168.1.4</code>, and possibly their hostnames.</p>
|
<p>If by "local" you mean on the same network segment, then you have to perform the following steps:</p>
<ol>
<li>Determine your own IP address</li>
<li>Determine your own netmask</li>
<li>Determine the network range</li>
<li>Scan all the addresses (except the lowest, which is your network address and the highest, which is your broadcast address).</li>
<li>Use your DNS's reverse lookup to determine the hostname for IP addresses which respond to your scan.</li>
</ol>
<p>Or you can just let Python execute nmap externally and pipe the results back into your program.</p>
|
<p>One of the answers in <a href="https://stackoverflow.com/questions/166506/finding-local-ip-addresses-in-python">this question</a> might help you. There seems to be a platform agnostic version for python, but I haven't tried it yet.</p>
| 25,391
|
<p>I've never used a printer with auto bed leveling, but my understanding is that most or all of them don't actually level anything, but rather compensate for the unlevel bed in firmware by transforming the coordinates. It seems to me this would necessarily introduce aliasing artifacts in all your prints by making it so that line widths are no longer a whole number of microsteps - I immediately observed such an effect on top/bottom skin when I tried to use steps-per-mm tweaking in firmware to compensate for a dimensional error rather than fixing the mechanical source of the error, and concluded that it was a dead-end approach.</p>
<p>If the auto-leveling firmware only makes adjustments with the Z motor as it moves, rather than transforming all three coordinates, it seems like that would be mostly or entirely mitigated, but with slight errors in dimensional accuracy dependent on how tilted the bed actually is.</p>
<p>Do any of the printers with (or add-on kits for) auto bed leveling actually level the bed mechanically, with servos attached to the adjustment knobs? Why isn't an approach like that more common?</p>
|
<p>Automatic bed levelling is not magic; it still requires you to level the bed properly (as level as possible). The upside of automatic bed levelling is that it compensates for small deviations like a slightly slanted surface or a (somewhat large) dent in the surface (as long it is probed and can be digitized by the firmware). It will keep the nozzle at a distance to the bed that it maintains proper distance to the bed for the filament to adhere properly (first layer adherence is key for successful prints). The slight imperfections are smeared out over about 10 mm (set in the firmware), this way you do not need transformations for the whole print (so if you deliberately make the bed very skew, the print will follow the Z axis, not the direction perpendicular to the bed).</p>
<p>While systems to level or align the bed exist, it is not very practical and expensive as it requires more parts, that is why it is not commonly used. Apart from the suggested printer in <a href="/a/10408">this answer</a>, printers with e.g. 4 ball screw Z movement lead screws exist (mostly printers for companies, not for use at home); ball screws are way more expensive, but also way more accurate than trapezoidal lead screws. A low accuracy is preferable as such systems generally have no guiding linear rods (as that would mean that you fix the plane/alignment of the build platform!).</p>
|
<p>The only 'consumer' approach to this would be providing adjustment feedback to the user, after the bed has been probed to determine an optimal position so that most of the bed is in the same plane.</p>
<p>This seems to me like a 'free' enhancement, but users don't seem to be overly worried by the distortions introduced (or perform the calibrations manually already).</p>
| 1,381
|
<p>I have create a WCF service and am utilising netMsmqBinding binding.</p>
<p>This is a simple service that passes a Dto to my service method and does not expect a response. The message is placed in an MSMQ, and once picked up inserted into a database.</p>
<p>What is the best method to make sure no data is being lost.</p>
<p>I have tried the 2 following methods:</p>
<ol>
<li><p>Throw an exception</p>
<p>This places the message in a dead letter queue for manual perusal. I can process this when my strvice starts</p>
</li>
<li><p>set the receiveRetryCount="3" on the binding</p>
<p>After 3 tries - which happen instantanously, this seems to leave the message in queue, but fault my service. Restarting my service repeats this process.</p>
</li>
</ol>
<p>Ideally I would like to do the follow:</p>
<p>Try process the message</p>
<ul>
<li>If this fails, wait 5 minutes for that message and try again.</li>
<li>If that process fails 3 times, move the message to a dead letter queue.</li>
<li>Restarting the service will push all messages from the dead letter queue back into the queue so that it can be processed.</li>
</ul>
<p>Can I achieve this? If so how?
Can you point me to any good articles on how best to utilize WCF and MSMQ for my given sceneria.</p>
<p>Any help would be much appreciated. Thanks!</p>
<p><strong>Some additional information</strong></p>
<p>I am using MSMQ 3.0 on Windows XP and Windows Server 2003.
Unfortunately I can't use the built in poison message support targeted at MSMQ 4.0 and Vista/2008.</p>
|
<p>I think with MSMQ (avaiable only on Vista) you might be able to to do like this:</p>
<pre><code><bindings>
<netMsmqBinding>
<binding name="PosionMessageHandling"
receiveRetryCount="3"
retryCycleDelay="00:05:00"
maxRetryCycles="3"
receiveErrorHandling="Move" />
</netMsmqBinding>
</bindings>
</code></pre>
<p>WCF will immediately retry for ReceiveRetryCount times after the first call failure. After the batch has failed the message is moved
to the retry queue. After a delay of RetryCycleDelay minute, the message moved from the retry queue to the endpoint queue and the batch is retried. This will be repeated
MaxRetryCycle time. If all that fails the message is handled according to receiveErrorHandling which can be move
(to poison queue), reject, drop or fault</p>
<p>By the way a good text about WCF and MSMQ is the chapther 9 of Progammig WCF book from Juval Lowy</p>
|
<p>Unfortunately I'm stuck on Windows XP and Windows Server 2003 so that isn't an option for me. - (I will re-clarify that in my question as I found this solution after posting and realised i couldn't use it)</p>
<p>I found that one solution was to setup a custom handler which would move my message onto another queue or poison queue and restart my service.
This seemed crazy to me. Imagine my Sql Server was down how often the service would be restarted.</p>
<p>SO what I've ended up doing is allowing the Line to fault and leave messages on the queue.
I also log a fatal message to my system logging service that this has happened.
Once our issue is resolved, I restart the service and all the messages start getting processed again.</p>
<p>I realised re-processing this message or any other will all fail, so why the need to move this message and the others to another queue. I may as well stop my service, and start it again when all is operating as expected.</p>
<p>aogan, you had the perfect answer for MSMQ 4.0, but unfortunately not for me</p>
| 10,779
|
<p>I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.</p>
<p>How can this be accomplished? Ive included a sample of my current code below.</p>
<p>sample.aspx</p>
<pre><code><asp:textbox id=foo runat=server />
<asp:requiredfieldvalidator id=val runat=server controltovalidate=foo />
<asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') />
</code></pre>
<p>sample.aspx.vb</p>
<pre><code>Sub Page_Load()
If Page.IsPostback() Then
Page.Validate()
If Page.IsValid Then
'process page here'
End If
End If
End Sub
</code></pre>
<p>Thanks for any help.</p>
|
<p>This seems to be a very common problem.</p>
<p>The workaround:</p>
<p>Validate the page first, then call <code>confirm</code>, as shown <a href="http://www.codedigest.com/CodeDigest/73-Fire-Validator-Controls-Before-JavaScript-Confirm-Box-Fires-in-ASP-Net-Page.aspx" rel="noreferrer">here</a> and <a href="http://www.stevekinsey.com/2007/06/04/onclientclick-and-form-validation-controls/" rel="noreferrer">here</a>.
This does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit <code>onclick</code>.</p>
<p>How to make this work properly, i.e. Validate the page first (and only once), then show the <code>confirm</code> box, I do not yet know.</p>
<p>Edit: <a href="http://www.dotnetjohn.com/articles.aspx?articleid=39" rel="noreferrer">Here</a>'s a useful suggestion:</p>
<blockquote>
<p>What ASP.NET does behind the scenes
when validation controls exist, is add
an autogenerated onClick event for
each button. This OnClick event would
supercede the custom OnClick event. So to
overcome this I did the following:</p>
<ol>
<li>add CausesValidation = False </li>
<li>added Validate() and IsValid code to the onClick event
behind the page to simulate the now
missing autogenerated validation code
behind the button.</li>
</ol>
</blockquote>
<p>Edit 2: A complete example</p>
<pre><code><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}" CausesValidation="false" />
</code></pre>
|
<p>You should validate the page on the client itself.</p>
<pre><code>function validate()
{
Page_ClientValidate();
if (Page_IsValid)
// do your processing here
return Page_IsValid;
}
</code></pre>
<p>This method can be called on the "onClientClick" event of the button and in the code-behind, you can if the page is valid and do the processing if the client-side validation is successful.</p>
<p>So, on the click event of the button, you can do - </p>
<pre><code>protected void SubmitButton_Click(object sender, EventArgs e)
{
if (!this.isValid)
return;
// do the processing here
}
</code></pre>
| 16,928
|
<p>I have a Rails app with some basic models. The website displays data retrieved from other sources. So I need to write a Ruby script that creates new instances in my database. I know I can do that with the test hooks, but I'm not sure that makes sense here.</p>
<p>I'm not sure what this task should look like, how I can invoke it, or where it should go in my source tree (lib\tasks?).</p>
<p>For example, here's my first try:</p>
<pre><code>require 'active_record'
require '../app/models/mymodel.rb'
test = MyModel.new
test.name = 'test'
test.save
</code></pre>
<p>This fails because it can't get a connection to the database. This makes sense in a vague way to my newbie brain, since presumably Rails is doing all the magic work behind the scenes to set all that stuff up. So how do I set up my little script?</p>
|
<p>You can load the entire rails environment in any ruby script by simply requiring environment.rb:</p>
<pre><code>require "#{ENV['RAILS_ROOT']}/config/environment"
</code></pre>
<p>This assumes the RAILS_ROOT environment variable is set, see my comment for other ways of doing this.</p>
<p>This has the added bonus of giving you all the nice classes and objects that you have in the rest of your rails code.</p>
<p>To kick off your processes it sounds like cron will do what you want, and I would also add a task to your capistrano recipe that would add your script to the crontab to periodically get the data from the external source and update your DB. This can easily be done with the <a href="http://cronedit.rubyforge.org/" rel="noreferrer">cronedit</a> gem.</p>
<p>The cron approach does have some drawbacks, mostly overhead and control, for other more sophisticated options see <a href="http://wiki.rubyonrails.org/rails/pages/HowToRunBackgroundJobsInRails" rel="noreferrer">HowToRunBackgroundJobsInRails</a> from the rails wiki.</p>
|
<p>Nice Joyent write up of using rake to run rails tasks from a cron job - <a href="http://wiki.joyent.com/accelerators:kb:rails:cron" rel="nofollow noreferrer">http://wiki.joyent.com/accelerators:kb:rails:cron</a></p>
| 37,434
|
<p>A product that I am working on collects several thousand readings a day and stores them as 64k binary files on a NTFS partition (Windows XP). After a year in production there is over 300000 files in a single directory and the number keeps growing. This has made accessing the parent/ancestor directories from windows explorer very time consuming. </p>
<p>I have tried turning off the indexing service but that made no difference. I have also contemplated moving the file content into a database/zip files/tarballs but it is beneficial for us to access the files individually; basically, the files are still needed for research purposes and the researchers are not willing to deal with anything else. </p>
<p>Is there a way to optimize NTFS or Windows so that it can work with all these small files? </p>
|
<p>NTFS performance severely degrades after 10,000 files in a directory. What you do is create an additional level in the directory hierarchy, with each subdirectory having 10,000 files.</p>
<p>For what it's worth, this is the approach that the SVN folks took in <a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#fsfs-sharding" rel="noreferrer">version 1.5</a>. They used 1,000 files as the default threshold.</p>
|
<p>Consider pushing them to another server that uses a filesystem friendlier to massive quantities of small files (Solaris w/ZFS for example)?</p>
| 14,128
|
<p>What's the best way to automate testing the UI in an Asp.net Page?</p>
|
<p><a href="http://wtr.rubyforge.org/" rel="nofollow noreferrer">Watir</a> or <a href="http://sourceforge.net/projects/watin/" rel="nofollow noreferrer">Watin</a> are a great place to start.</p>
<p>More info <a href="http://www.hanselman.com/blog/WATIRForNETWatiNApproaches08ReleaseAndAutomatingIEFromPowerShell.aspx" rel="nofollow noreferrer">here</a></p>
|
<p>Not sure about the "best" way, that's probably quite a loaded question...</p>
<p>One way is to use the Web Tests in the Test edition of Visual Studio, see <a href="http://msdn.microsoft.com/en-us/library/ms182536(VS.80).aspx" rel="nofollow noreferrer">MSDN documentation.</a>
Also here's a <a href="http://blogs.vertigosoftware.com/teamsystem/archive/2006/03/09/Simple_Web_Testing_with_Team_Test_Edition.aspx" rel="nofollow noreferrer">simple tutorial.</a></p>
| 11,986
|
<p>In FogBugz 6, how do I represent the concepts of a "feature" versus a "task"? As <a href="http://www.joelonsoftware.com/articles/fog0000000245.html" rel="nofollow noreferrer">defined by Joel Spolsky</a>, the owner of Fog Creek Software (which makes FogBugz), a feature is essentially a user-visible capability. To estimate the time to implement a feature, the developer should break the implementation into short tasks (2 days max) to ensure they think about each step.</p>
<p>FogBugz has only cases. I can't tell whether they're supposed to correspond to features or tasks. <a href="http://www.fogcreek.com/FogBugz/learnmore.html?section=PredictShipDates#hist_EnteringFeatures" rel="nofollow noreferrer">Some FogBugz documentation</a> indicates that each case is a task, which is fine except there is no way to group all the tasks for a given feature together. This is especially odd given that, before FogBugz 6, Joel advocated using a spreadsheet with that grouped all the tasks for each feature. But his own software doesn't appear to meaningfully support that grouping.</p>
<p>I realize that the Joel article I reference includes a disclaimer pointing to a later article. However, the later article does not settle this issue, in fact it doesn't discuss features versus tasks at all, which is surprising given how well Joel advocates for those concepts in the first article.</p>
|
<p><a href="https://stackoverflow.com/questions/88455/how-do-i-represent-features-v-tasks-in-fogbugz-6/406118#406118">Responding to AviD's comment/question to Joel</a>:</p>
<blockquote>
<p>So, if you have 10 new features coming
in the next version, with each feature
needing 5 tasks to implement, you
recommend creating 10 releases? And
how do I define that these are the
features/"releases" that are to be
included in the upcoming release?</p>
</blockquote>
<p>Here is how we dealt with this specific problem in our development process:</p>
<ol>
<li>First, we made a regular release schedule: monthly internal releases and quarterly external releases. This schedule never changes but task assignment / feature completion does. This is hugely important in terms of simplifying our inter-human communication: don't try to argue with the calendar.</li>
<li>Major features ("10 new features" in your example) are turned into cases (e.g., case 101 to case 110).</li>
<li>Each task that is a sub-component of a major feature also gets created as a sub-case with a description of what makes this chunk of work an important part of the larger picture. Previously, in Fogbugz 6, we used the "See also" feature by allowing it to search the text for us ("This is a sub-component of case 101" for example). This was effectively the same thing but less aesthetic.</li>
<li>Now that we've broken down the work to its finest level of usefulness, we bring the actual developers into the discussion. Each task and major feature is individually assigned to a particular developer.</li>
<li>The developer determines when they can get their assigned work done by picking the appropriate internal release date that they think they can commit to. </li>
<li>At this point, we have a rough sketch of what will get done for each release. Further refinements continue as the working people actually estimate the hours that they'll need to do the work, enabling evidence-based scheduling, etc. </li>
</ol>
<p>For AviD's question, though, he would have the release-assignment problem solved by step 5 above.</p>
<p>However, I think point 6 is the most interesting as that's where you really get a solid schedule. For example, if developers are having trouble estimating a larger task, they break it down into sub-cases even further. Notice how my assessment of "finest level of usefulness" can differ (perhaps greatly) from the person who really needs to get the work done. </p>
<p>This is also a time when a developer can reach out to someone else and say "I can do most of this but it would really help if person X could help me with this little piece Y." This is actually where I get most of my development tasking: I personally sit in multiple places during this process, from large-scale planning meetings to little fiddly tasks that no-one else has time to do.</p>
<p><em>PS: Making it a personal goal to get this answer rated higher than Joel's.... ;-)</em></p>
<p><em>PPS: My original response is now overcome by events since Fogbugz 7 has lovely sub-tasks. Program managers love those reports.</em></p>
|
<p>haha, that article has a disclaimer, but I understand what you are saying.</p>
<p>We use Fogbugz and the only 'Feature' that I am aware of is under category and I don't think you can associated it with sub-tasks.</p>
<p>You can type in 'Case N' is the feature for this task if you just wanted to reference it in the case text.</p>
<p>That kind of stuff sound like is lies more in the project management domain instead of software used to track bugs. </p>
| 11,406
|
<p>This works, but is it the proper way to do it???</p>
<p>I have a custom server control that has an [input] box on it. I want it to kinda mimic the ASP.NET TextBox, but not completely. When the textbox is rendered i have a javascript that allows users to select values that are then placed in that input box.</p>
<p>I have a public text property on the control. In the get/set i get/set the viewstate for the control - that part is easy, but when the control is populated via the javascript, the Text get is not actually called, what is the proper way to set this exposed property using JavaScript (or even if the user just types in the box) ?</p>
<p>Edit:
In the OnInit i ensure the state is maintained by reaching into the form values.</p>
<pre><code> protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (HttpContext.Current.Request.Form["MyInputBoxValue"] != "")
{
ViewState["MyInputBoxValue"]
= HttpContext.Current.Request.Form["MyInputBoxValue"];
}
}
</code></pre>
<p>Then to get the value actually back in place in the HtmlTextWrite, i do this:</p>
<pre><code>protected override void RenderContents(HtmlTextWriter output)
{
// There is an input control here and i set its value property
// like this using the Text internal defined.
output.Write("<input value=" + Text + ">.....
}
</code></pre>
<p>thanks</p>
|
<p>I find using IStateManager works the best. </p>
<p>For example:</p>
<pre><code>partial class MyControl : System.Web.UI.UserControl, IStateManager
{
[Serializable()]
protected struct MyControlState
{
public bool someValue;
public string name;
}
protected MyControlState state;
public bool someValue {
get { return state.someValue; }
set { state.someValue = value; }
}
public bool IsTrackingViewState {
get { return true; }
}
protected override void LoadViewState(object state)
{
if ((state != null) && state is MyControlState) {
this.state = state;
}
}
protected override object SaveViewState()
{
return state;
}
protected override void TrackViewState()
{
base.TrackViewState();
}
}
</code></pre>
<p>getDefaultState() would just load some sane defaults into a new state struct. state gets tracked in the viewstate of the page, and ASP will take care of bring it in/out for you.</p>
<p>(above code ported from VB and not checked, hopefully I didn't make any errors but it should get the point across anyways)</p>
|
<p>If you need to maintain state on postback, you must provide your own methods
of recording what the user has done with your control on the client side
and either update the server control later on the server with
the changes, or redo the changes on the client side when the page refreshes. </p>
| 27,153
|
<p>In our application, we are using RMI for client-server communication in very different ways:</p>
<ol>
<li>Pushing data from the server to the client to be displayed.</li>
<li>Sending control information from the client to the server.</li>
<li>Callbacks from those control messages code paths that reach back from the server to the client (sidebar note - this is a side-effect of some legacy code and is not our long-term intent).</li>
</ol>
<p>What we would like to do is ensure that all of our RMI-related code will use only a known specified inventory of ports. This includes the registry port (commonly expected to be 1099), the server port and any ports resulting from the callbacks.</p>
<p>Here is what we already know:</p>
<ol>
<li>LocateRegistry.getRegistry(1099) or Locate.createRegistry(1099) will ensure that the registry is listening in on 1099.</li>
<li>Using the UnicastRemoteObject constructor / exportObject static method with a port argument will specify the server port.</li>
</ol>
<p>These points are also covered in this <a href="http://forums.sun.com/thread.jspa?threadID=370039&messageID=1566073" rel="noreferrer">Sun forum post</a>. </p>
<p>What we don't know is: how do we ensure that the client connections back to the server resulting from the callbacks will only connect on a specified port rather than defaulting to an anonymous port?</p>
<p>EDIT: Added a longish answer summarizing my findings and how we solved the problem. Hopefully, this will help anyone else with similar issues.</p>
<p>SECOND EDIT: It turns out that in my application, there seems to be a race condition in my creation and modification of socket factories. I had wanted to allow the user to override my default settings in a Beanshell script. Sadly, it appears that my script is being run significantly after the first socket is created by the factory. As a result, I'm getting a mix of ports from the set of defaults and the user settings. More work will be required that's out of the scope of this question but I thought I would point it out as a point of interest for others who might have to tread these waters at some point....</p>
|
<p>You can do this with a custom RMI Socket Factory. </p>
<p>The socket factories create the sockets for RMI to use at both the client and server end so if you write your own you've got full control over the ports used. The client factories are created on the server, Serialized and then sent down to the client which is pretty neat.</p>
<p><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/rmi/socketfactory/" rel="nofollow noreferrer">Here's a guide at Sun telling you how to do it.</a></p>
|
<p>I've been having various problems implementing an RMI Server/Client architecture, with Client Callbacks. My scenario is that both Server and Client are behind Firewall/NAT. In the end I got a fully working implementation. Here are the main things that I did:</p>
<h2>Server Side , Local IP: 192.168.1.10. Public (Internet) IP 80.80.80.10</h2>
<p>On the Firewall/Router/Local Server PC open port 6620.
On the Firewall/Router/Local Server PC open port 1099.
On the Router/NAT redirect incoming connections on port 6620 to 192.168.1.10:6620
On the Router/NAT redirect incoming connections on port 1099 to 192.168.1.10:1099</p>
<p>In the actual program:</p>
<pre><code>System.getProperties().put("java.rmi.server.hostname", IP 80.80.80.10);
MyService rmiserver = new MyService();
MyService stub = (MyService) UnicastRemoteObject.exportObject(rmiserver, 6620);
LocateRegistry.createRegistry(1099);
Registry registry = LocateRegistry.getRegistry();
registry.rebind("FAManagerService", stub);
</code></pre>
<h2>Client Side, Local IP: 10.0.1.123 Public (Internet) IP 70.70.70.20</h2>
<p>On the Firewall/Router/Local Server PC open port 1999.
On the Router/NAT redirect incoming connections on port 1999 to 10.0.1.123:1999</p>
<p>In the actual program:</p>
<pre><code>System.getProperties().put("java.rmi.server.hostname", 70.70.70.20);
UnicastRemoteObject.exportObject(this, 1999);
MyService server = (MyService) Naming.lookup("rmi://" + serverIP + "/MyService ");
</code></pre>
<p>Hope this helps.
Iraklis</p>
| 8,073
|
<p>Lasty, I tried to implements an hybrid structure in Java, something that looks like:</p>
<pre><code>public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
</code></pre>
<p>Where HasKey is the following interface:</p>
<pre><code>public interface HasKey<K> {
public K getKey();
}
</code></pre>
<p>Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.</p>
<p>Do you see a nicer solution?</p>
<p>In response to the first comments, here is my goal:</p>
<blockquote>
<p>Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value.
At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.</p>
</blockquote>
|
<p>What are you trying to accomplish? <code>Map</code> already exposes its keys as a <code>Set</code> via its [keySet()](<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.html#keySet())</a> method. If you want a reliable iteratior order, there's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html" rel="nofollow noreferrer">LinkedHashMap</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html" rel="nofollow noreferrer">TreeMap</a>.</p>
<p>UPDATE: If you want to ensure that a value has only been inserted once, you can extend one of the classes I mentioned above to create something like a <code>SingleEntryMap</code> and override the implementation of <code>put(K key, V value)</code> to do a uniqueness check and throw an Exception when the value has already been inserted.</p>
<p>UPDATE: Will something like this work? (I don't have my editor up, so this may not compile)</p>
<pre><code>public final class KeyedSets<K, V> implements Map<K,Set<V>> {
private final Map<K, Set<V>> internalMap = new TreeMap<K, Set<V>>;
// delegate methods go here
public Set<V> getSortedSuperset() {
final Set<V> superset = new TreeSet<V>();
for (final Map.Entry<K, V> entry : internalMap.entrySet()) {
superset.addAll(entry.getValue());
}
return superset;
}
}
</code></pre>
|
<p>I would say that something that is meant to be sometimes used as a Map and sometimes as a Set should implement Map, since that can be viewed as a set of keys or values as well as a mapping between keys and values. That is what the Map.containsKey() and Map.containsValue() methods are for.</p>
| 9,617
|
<p>I've found syntax highlighters that highlight pre-existing code, but I'd like to do it as you type with a WYSIWYG-style editor. I don't need auto-completed functions, just the highlighting.</p>
<p>As a follow-up question, what is the WYSIWYG editor that stackoverflow uses?</p>
<p>Edit: Thanks to the answer below, I found two that look like they might suit my needs:
<a href="http://www.cdolivet.net/editarea/" rel="nofollow noreferrer">EditArea</a> and <a href="http://codepress.sourceforge.net/" rel="nofollow noreferrer">CodePress</a></p>
<p>EDIT: See this question also:<br>
<a href="https://stackoverflow.com/questions/379185/free-syntax-highlighting-editor-control-in-javascript">https://stackoverflow.com/questions/379185/free-syntax-highlighting-editor-control-in-javascript</a></p>
|
<p>Here is a really interesting article about how to write one: (Even better, he gives the full source to a JavaScript formatter and colorizer.)</p>
<p><a href="http://marijn.haverbeke.nl/codemirror/story.html" rel="noreferrer">Implementing a syntax-higlighting JavaScript editor in JavaScript</a>
or
A brutal odyssey to the dark side of the DOM tree</p>
<blockquote>
<p>How does one do decent syntax
highlighting? A very simple scanning
can tell the difference between
strings, comments, keywords, and other
code. But this time I wanted to
actually be able to recognize regular
expressions, so that I didn't have any
blatant incorrect behaviour anymore.</p>
</blockquote>
<p>Importantly, it handles regex correctly. Also of interest is that he used a continuation passing style lexer/parser instead of the more typical lex (or regex) based lexers that you'll see in the wild.</p>
<p>As a bonus he discusses a lot of real-world issues you'll run into when working with JavaScript in the browser.</p>
|
<p>I dont program a lot of javascript but JSEclipse has been pretty helpful for me in the past. It comes as an Eclipse plug-in.</p>
<p>I've been using it for years for free</p>
<p><a href="http://www.interaktonline.com/products/eclipse/jseclipse/overview/" rel="nofollow noreferrer">http://www.interaktonline.com/products/eclipse/jseclipse/overview/</a></p>
<p>I also rely heavily on FireBug for Firefox whenever I deal with Javascript</p>
| 8,688
|
<p>I am the .Net specialist in a consultancy with many difference flavors of developers using many different languages and frameworks. Because everyone is pretty much trying to push their own agendas with our different clients in terms of what technology to propose, I'm constantly finding myself in the classic arguments with them all about "why" .Net may be a better technology solution for a given clients requirements. </p>
<p>Often time here, the debate comes down to the issue of performance. Usually the areas that are argued about here consist of costs, maintainability, and performance. I have a hard time arguing about cost because in general open-source technologies are usually cheaper, and although and can usual put a good word in for .Net in terms of total cost of ownership (It seems to be pretty easy to convince people that .Net applications have relative low costs for maintainability if the application architecture has been thoughtfully designed), we will really only push .Net here if the client understands and is indifferent about the costs associated with Microsoft licensing. In terms of maintainability, like I mentioned before, the other developers here realize how much a difference it can make when an application is thoughtfully designed. I have had around 8 years of experience programming .Net solutions and I'm pretty confident in my ability to present to a client all the features and tool sets that .Net provides to give an application a long, and easy to maintain life span.</p>
<p>So again, what it usually boils down to is an argument over performance. Up until now, I have worked for companies that already used Microsoft development technologies to developer their applications so while I have <em>discussed</em> performance with others in the past I have never been a position where I have had to <em>convince</em> performance. My other co-workers are always boasting about these different website that they go to that show improved performance for open-source web applications. This all being said, what I would like to know from everybody here is where do you usually go to get your information about how may some .Net web applications have out performed other technologies?</p>
<p>Thanks in advance for the advice,</p>
<p>-Matt</p>
|
<p>when you call settimeout, it returns you a variable "handle" (a number, I think)</p>
<p>if you call settimeout a second time, you should first </p>
<pre><code>clearTimeout( handle )
</code></pre>
<p>then:</p>
<pre><code>handle = setTimeout( ... )
</code></pre>
<p>to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div's id, or anything you want), so that if there's a previous settimeout with the same "string", it clears it for you automatically before setting it again, </p>
<p>You would use an array (i.e. dictionary/hashmap) to associate strings with handles.</p>
<pre><code>var timeout_handles = []
function set_time_out( id, code, time ) /// wrapper
{
if( id in timeout_handles )
{
clearTimeout( timeout_handles[id] )
}
timeout_handles[id] = setTimeout( code, time )
}
</code></pre>
<p>There are of course other ways to do this .. </p>
|
<p>you can always overwrite the buttons onclick to return false. example:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="UTF-8">
<head>
<title>Javascript example</title>
<script type="text/javascript">
var count = 0;
function annoy() {
document.getElementById('testa').onclick = function() { return false; };
setTimeout(function() {
alert('isn\'t this annoying? ' + count++);
document.getElementById('testa').onclick = window.annoy;
}, 1000);
}
</script>
</head>
<body>
<h2>Javascript example</h2>
<a href="#" onClick="annoy()" id="testa">Should Only Fire Once</a><br />
</body>
</html>
</code></pre>
| 40,670
|
<p>Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.</p>
<p>Problem 1 :</p>
<p><strong>Product of everything except current</strong> </p>
<p>Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]</p>
<p>For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.</p>
<p>IMPORTANT: Your algorithm must run in linear time.</p>
<p>Problem 2 : ( the topic was in one of Jeff posts )</p>
<p><strong>Shuffle card deck evenly</strong></p>
<ol>
<li><p>Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).</p></li>
<li><p>Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()</p></li>
<li><p>What is the complexity of your algorithm (as a function of the number n of cards in the deck)?</p></li>
<li><p>Explain how you would test that the cards are evenly shuffled by your method (black box testing).</p></li>
</ol>
<p>P.S. I had two hours to code the solutions</p>
|
<p>First question: </p>
<pre><code>int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
</code></pre>
<p>Worst case this program will step through 3 vectors once.</p>
|
<p>Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.</p>
| 8,009
|
<p>I need a type which can contain a position of an object in a 3D environment - my house.</p>
<p>I need to know the floor it is on, and the x and Y coordinates on that floor.</p>
<p>The System.Windows.Point(int, int) only represent a two-dimensional space, but does .NET have a type for three-dimensional space?</p>
<p>I realize that I could do something like</p>
<pre><code>List<int, Point<int, int>>
</code></pre>
<p>but I would like to have just a simple type instead. Something like:</p>
<pre><code>3DPoint<int, int, int>
</code></pre>
<p>Does the .NET Framework have this?</p>
|
<p>In managed Direct3D there is a vector3 type that describes a point in space. It would be trivial to implement one yourself.</p>
<pre><code>public struct Vector3
{
public float x;
public float y;
public float z;
}
</code></pre>
|
<p>I don't think there is built in functionality like that. </p>
<p>But check out this CodeProject article <a href="http://www.codeproject.com/KB/vb/3D_Graphics_-_Net.aspx" rel="nofollow noreferrer">3D Geometry Library (Basic Classes) and 3D Drawing using VB.Net</a></p>
| 40,093
|
<p>i am trying to use an ASP conditional here:</p>
<pre><code>if (Request.Cookies("username")) and
(Request.Cookies("password")) <> ""
Then
</code></pre>
<p>And i keep getting this error:</p>
<blockquote>
<p>Type mismatch: '[string: ""]'</p>
</blockquote>
<p>Any ideas what I am getting that?</p>
|
<p>try</p>
<pre><code>if (Request.Cookies("username") <> "") and (Request.Cookies("password") <> "") Then
</code></pre>
|
<p>Actually, I would do the following..</p>
<pre><code>if (!string.IsNullOrEmpty(Request.Cookies("username")) &&
!string.IsNullOrEmpty(Request.Cookies("password")))
{
// Do your stuff, here :)
}
</code></pre>
<p>Get into the habit of using <code>string.IsNullOrEmpty</code> for testing variables and <code>string.Empty</code> for setting values, if u don't want a string to be <code>null</code>.</p>
| 45,145
|
<p>I just had a conversation with my lead developer who disagreed that unit tests are all that necessary or important. In his view, functional tests with a high enough code coverage should be enough since any inner refactorings (interface changes, etc.) will not lead to the tests being needed to be rewritten or looked over again.</p>
<p>I tried explaining but didn't get very far, and thought you guys could do better. ;-) So...</p>
<p>What are some good reasons to unit test code that functional tests don't offer? What dangers are there if all you have are functional tests?</p>
<p><strong>Edit #1</strong> Thanks for all the great answers. I wanted to add that by functional tests I don't mean only tests on the entire product, but rather also tests on modules within the product, just not on the low level of a unit test with mocking if necessary, etc. Note also that our functional tests are automatic, and are continuously running, but they just take longer than unit tests (which is one of the big advantages of unit tests).</p>
<p>I like the brick vs. house example. I guess what my lead developer is saying is testing the walls of the house is enough, you don't need to test the individual bricks... :-)</p>
|
<p>Off the top of my head</p>
<ul>
<li>Unit tests are repeatable without effort. Write once, run thousands of times, no human effort required, and much faster feedback than you get from a functional test</li>
<li>Unit tests test small units, so immediately point to the correct "sector" in which the error occurs. Functional tests point out errors, but they can be caused by plenty of modules, even in co-operation.</li>
<li>I'd hardly call an interface change "an inner refactoring". Interface changes tend to break a lot of code, and (in my opinion) force a new test loop rather than none.</li>
</ul>
|
<p>If you use a pure Extreme Programing / Agile Development methodology the Unit tests are always required as they are the requirements for development.</p>
<p>In pure XP/Agile one makes all requirements based on the tests which are going to be performed to the application</p>
<ul>
<li>Functional tests - Generate functional requirements.</li>
<li>Unit tests - Generate functions or object requirements.</li>
</ul>
<p>Other than that Unit testing can be used to keep a persistent track of function requirements. </p>
<p><strong>i.e.</strong> If you need to change the working way of a function but the input fields and output keep untouched. Then unit testing is the best way to keep tracking of possible problems as you only need to run the tests.</p>
| 22,035
|
<p>Is it possible to obtain the maximum column length for a VARCHAR, CHAR etc?</p>
|
<p>Here's a way which avoids touching the database:</p>
<ul>
<li>Using Reflection, get the property of the entity class that corresponds to the column in question.</li>
<li>Then, retrieve the System.Data.Linq.Mapping.Column attribute of the property.</li>
<li>Then, parse the DbType property of this attribute (eg <strong>NVarChar(255) NOT NULL</strong>) to get the column length.</li>
</ul>
|
<p>In pure T-SQL you can use this query:</p>
<pre><code>select max_length from sys.columns as c inner join sys.objects o on c.object_id = o.object_id where o.name = 'myTable' and c.name = 'myColumn'
</code></pre>
<p>For linq-to-sql you need it rewrite into linq.</p>
| 32,777
|
<p>I am working on a windows form application. How do i use the find method of a datatable to find a row if the datatable has a compound key?</p>
<p>Table Structure
Col A, Col B, Col C</p>
<p>Col A and Col B make up the compound key.
I want to find the row where the value in Col A is 6 and Col B is 5</p>
|
<p>When you "set" the Primary key of the datatable, the parameter value is an array of DataColumns... </p>
<p>if your datatable is in variable dt...,</p>
<pre><code>dt.PrimaryKey = new DataColumn[] {dt.Columns["ColA"], dt.Columns["ColB"]};
</code></pre>
<p>Then pass an array of object values to the Find() method</p>
<pre><code>object[] keyVals = new object[] {6, 5};
DataRow dr = dt.Rows.Find(keyVals);
</code></pre>
<p>or, just</p>
<pre><code>DataRow dr = dt.Rows.Find(new object[] {6, 5});
</code></pre>
|
<p>When you "set" the Primary key of the datatable, the parameter value is an array of DataColumns... </p>
<p>if your datatable is in variable dt...,</p>
<pre><code>dt.PrimaryKey = new DataColumn[] {dt.Columns["ColA"], dt.Columns["ColB"]};
</code></pre>
<p>Then pass an array of object values to the Find() method</p>
<pre><code>object[] keyVals = new object[] {6, 5};
DataRow dr = dt.Rows.Find(keyVals);
</code></pre>
<p>or, just</p>
<pre><code>DataRow dr = dt.Rows.Find(new object[] {6, 5});
</code></pre>
| 40,633
|
<p>Is there a public/government web service that I can call to find out what the national holidays are for a given year? (For the US and/or any country in the world.)</p>
<p>Edit: Does anybody have a set of formulas to calculate US holidays? (C# would be my language of choice if there is a choice.)</p>
|
<p>There's a web service at <a href="http://www.holidaywebservice.com" rel="noreferrer">http://www.holidaywebservice.com</a> which will provide dates of holidays for the USA, Republic of Ireland, England and Scotland. They also sell a DLL and source code.</p>
<p>As for details of algorithms, you could do worse than check out the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0521702380" rel="noreferrer" rel="nofollow noreferrer">Calendrical Calculations</a> book (third edition), which is a really fascinating read for all matters calendrical, and includes sample LISP code for their calendar algorithms.</p>
|
<p>Some parsing may be required, and it's not 100% complete, but you can use <a href="http://en.wikipedia.org/wiki/List_of_holidays_by_country" rel="nofollow noreferrer">wikipedia</a>.</p>
| 8,469
|
<p>How can I get a query which uses an OR in the WHERE clause to split itself into two queries with a UNION during compilation? If I manually rewrite it, the query using the UNION is 100x faster than the single query, because it can effectively use different indices in each query of the union. Is there any way I can make the optimizer use this approach?</p>
<p>I have a query that looks something like this:</p>
<pre><code>select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
where conditions1
and ((@param1 is null and cond3a) or (cond3b))
</code></pre>
<p>Where columnlist, joincond2, joincond3, and conditions1 are all longer expressions. The kicker is that only one of the conditions in the OR is ever true.</p>
<p>I first thought I could just rewrite it to do the union, but then I am repeating columnlist, joincond2, joincond3, and conditions1, which is 20 or so lines of SQL that might need a lot of maintenance in the future. Is there a hint I can supply or some better way to write the WHERE clause? Thanks in advance.</p>
|
<p>You can group</p>
<pre><code>select columnlist
from table1
join table2 on joincond2
join table3 on joincond3
</code></pre>
<p>into a view, and then use union.</p>
<p>but if you can migrate to sql2005/8,
you can use common table expression.</p>
<pre><code>with cte ( columnlist )
as (
select columnlist
from table1
join table2 on joincond2
join table3 on joincond3 )
select columnlist from cte where ...
union
select columnlist from cte where ...
</code></pre>
|
<p>Try adding OPTION (RECOMPILE) to the query. If it's in a stored procedure then add WITH RECOMPILE to that as well. It may be that the first time that you run the query SQL Server comes up with a plan and caches it but then the second time through it's still using the old (and now poor) query plan.</p>
<p>You will take a minor hit because it will need to recompile every time you use the query, but it will be minuscule in comparison to the use of a poor plan.</p>
<p>EDIT: I've read that using WITH RECOMPILE in a stored procedure in SQL 2000 doesn't always work properly. The bug was supposedly fixed in SQL 2005. I've never encountered the bug personally though, so I don't know what the exact deal is with it. Give it a try though.</p>
| 48,658
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.