input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
asp.net : IIS Service Unavailable <p>When I attempt to update the code on a IIS webserver by replacing the old code with my new code, I receive 503 Service Unavailable replys when attempting to access any of the replaced pages on the server. </p>
<p>What is the cause of this failure and what steps can I take to correct such errors? </p>
<p>Thanks!</p>
|
<p>I would do a few things:</p>
<p>Check the windows event logs for any web related errors.</p>
<p>Check the IIS logs to see if there is anything odd with the requests.</p>
<p>Double check the permissions of all the new files, make sure they match the files that do work.</p>
<p>Perform an IISReset after you deployed.</p>
<p>Make sure your virtual directory, or sub folders are set up correctly in IIS and didn't change in the deployment.</p>
|
Paver 0.8.1 compatibility with python 2.6 <p>Does anyone manage to bootstrap its development area using paver with python 2.6 ?</p>
<p>I have install python 2.6, install paver with easy_install-2.6, everything looks fine.
But when I try to launch the bootstrap method it raises an urllib2.HTTPError (: HTTP Error 404: Not Found) while trying to download <a href="http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c8-py2.6.egg" rel="nofollow">http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c8-py2.6.egg</a>.
I have tryed to add the correct setuptools EGG file (which is 0.6c9) in the support-files directory, bootstrap.py find the EGG file, but doesn't seem to use it because it still try to download the 0.6c8 version which is no more available.</p>
<p>Any ideas how to solve this issue ?</p>
<p>Thanks in advance </p>
<p>Bertrand</p>
|
<p>You should try newer version. =) <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">http://www.blueskyonmars.com/projects/paver/</a></p>
|
Do you validate your URL variables? <p>When you're passing variables through your site using GET requests, do you validate (regular expressions, filters, etc.) them before you use them?</p>
<p>Say you have the URL <a href="http://www.example.com/i=45&p=custform" rel="nofollow">http://www.example.com/i=45&p=custform</a>. You know that "i" will always be an integer and "p" will always contain only letters and/or numbers. Is it worth the time to make sure that no one has attempted to manipulate the values and then resubmit the page?</p>
|
<p>Yes. Without a doubt. Never trust user input.</p>
<p>To improve the user experience, input fields can (and IMHO should) be validated on the client. This can pre-empt a round trip to the server that only leads to the same form and an error message.</p>
<p>However, input must <strong>always</strong> be validated on the server side since the user can just change the input data manually in the GET url or send crafted POST data.</p>
<p>In a worst case scenario you can end up with an <a href="http://unixwiz.net/techtips/sql-injection.html" rel="nofollow">SQL injection</a>, or even worse, a <a href="http://www.cgisecurity.com/articles/xss-faq.shtml" rel="nofollow">XSS</a> vulnerability.</p>
<p>Most frameworks already have some builtin way to clean the input, but even without this it's usually very easy to clean the input using a combination of regular exceptions and lookup tables.</p>
<ul>
<li>Say you know it's an integer, use int.Parse or match it against the regex "^\d+$".</li>
<li>If it's a string and the choices are limited, make a dictionary and run the string through it. If you don't get a match change the string to a default.</li>
<li>If it's a user specified string, match it against a strict regex like "^\w+$"</li>
</ul>
|
How do I create a keyboard hook with a different thread in C#? <p>I'm creating a low level keyboard hook in c# using SetWindowsHookEx, question is how can I make the on keyboard event function run on a thread other from the main thread? Also I currently don't have a thread other then the main thread, so how can I create one that will halt until a keyboard hook event will occur?</p>
|
<p>Here is the code for the <a href="http://forum.cheatengine.org/viewtopic.php?t=192699&sid=d25bb4a9d48a3518bba28ec63d6510a2" rel="nofollow">C# Keyboard hook</a>.</p>
<p>You just need to call Hook.CreateHook(METHODNAMEHERE); in a new Thread (see the Thread class).</p>
|
PHP/PDO and SQL Server connection and i18n issues <p>In our web-app we use PHP5.2.6 + PDO to connect to a SQL Server 2005 database and store Russian texts.</p>
<p>Database collation is <code>Cyrillic_General_CI_AS</code>, table collation is <code>Cyrillic_General_CI_AS</code>, column type is <code>NVARCHAR(MAX)</code>.</p>
<p>We tried connecting to a database using two following schemes, both causing different problems.</p>
<ol>
<li><p><em>PDO mssql:</em></p>
<pre><code>$dbh = new PDO ('mssql:host='.$mssql_server.';dbname='.$mssql_db, $mssql_login, $mssql_pwd);
</code></pre>
<p>in which case a result of a simple query like that:</p>
<pre><code>SELECT field1 FROM tbl1 WHERE id=1
</code></pre>
<p>shows <code>field1</code> data truncated to 255 bytes.</p></li>
<li><p><em>PDO odbc:</em> </p>
<pre><code>$dbh = new PDO ('odbc:DSN=myDSN;UID='.$mssql_login.';PWD='.$mssql_pwd);
</code></pre>
<p>in which case a result of the same query shows full not truncated data but with question marks instead of Russian symbols. </p></li>
</ol>
<p><hr /></p>
<p>Notes:</p>
<ul>
<li>In the SQL Management Studio data is not truncated and Russian symbols are displayed properly as well.</li>
<li>We have Windows 2003 Enterprise Edition SP2</li>
</ul>
<p>So what should we choose as a connection method and how to fix corresponding issues?</p>
|
<p>Try executing <code>SET NAMES "charset"</code> after you connect.</p>
<p>I don't know what the charset to match <code>Cyrillic_General_CI_AS</code> is, but try "Cyrillic"?</p>
|
bind Linux to Active Directory using kerberos <p>We are trying to bind a Linux machine (debian 4.0) to W2k3 AD. We have configured kerberos properly so that we can get TGTs. And users authenticate properly. However, PAM seems to be the sticky wicket. For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell. The default environment is configured properly and PAM even creates the Homedir properly. As a reference we were loosely following:</p>
<p>https://help.ubuntu.com/community/ActiveDirectoryHowto</p>
|
<p>If you're confident everything but PAM works correctly, I suggest passing the debug option to pam_krb5.so to see if that gives a clue to what's happening.</p>
<p>I'd also suggest verifying that nss-ldap is set up correctly using </p>
<pre><code>getent passwd avalidusername
</code></pre>
|
Microsoft ReportViewer: Session Expired Errors <p>The project is ASP.NET 2.0, I have never been able to reproduce this myself, but I get emails informing me it happens to clients many times a week, often a few times in a row.</p>
<p>Here is the full error:</p>
<p>Exception Details: </p>
<blockquote>
<p>Microsoft.Reporting.WebForms.AspNetSessionExpiredException: ASP.NET session has expired</p>
</blockquote>
<p>Stack Trace: </p>
<blockquote>
<p>[AspNetSessionExpiredException: ASP.NET session has expired]
at Microsoft.Reporting.WebForms.ReportDataOperation..ctor()
at Microsoft.Reporting.WebForms.HttpHandler.GetHandler()
at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Session Objects:75de8e1d65ff40d1ba666d940af5b118: Microsoft.Reporting.WebForms.ReportHierarchy
5210064be1fa4d6abf5dd5e56b262974: Microsoft.Reporting.WebForms.ReportHierarchy</p>
</blockquote>
|
<p>We had the same problem. So far, we only found it when the session expired but they used the back button in a browser that does aggressive caching, which is fine. But the ReportViewer tried to to a refresh even though the main page did not. So, we just added some hacky Global.asax error handling:</p>
<pre><code>protected void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError().GetBaseException();
if (exc is Microsoft.Reporting.WebForms.AspNetSessionExpiredException)
{
Server.ClearError();
Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.PathAndQuery), true);
}
}
</code></pre>
|
ASP.NET xsd dataset where do I put it <p>I am trying to convert an ASP.NET website into a web application project. The conversion has gone ok I think apart from previously I had 2 xsd files in the App_Code folder. I believe this folder is not used in web applications projects, so where would I put xsd files now.</p>
|
<p>I don't think you have to put them anyplace in particular. For the purposes of organization you could create a data directory. If the project is small enough, I leave it in the root.</p>
|
Generic, annotation-driven event notification frameworks <p>While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead. </p>
<p>For an example, see <a href="http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.2.0.GA/userguide_en/html_single/index.html#api.listener">JBossCache 2.2</a>. The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).</p>
<p>Here's a sample from the JBossCache docs:</p>
<pre><code>@CacheListener
public class MyListener {
@CacheStarted
@CacheStopped
public void cacheStartStopEvent(Event e) {
switch (e.getType()) {
case Event.Type.CACHE_STARTED:
System.out.println("Cache has started");
break;
case Event.Type.CACHE_STOPPED:
System.out.println("Cache has stopped");
break;
}
}
@NodeCreated
@NodeRemoved
@NodeVisited
@NodeModified
@NodeMoved
public void logNodeEvent(NodeEvent ne) {
log("An event on node " + ne.getFqn() + " has occured");
}
</code></pre>
<p>}</p>
<p>The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.</p>
<p>So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?</p>
|
<p>You can already do this today with <a href="http://eventbus.org">EventBus</a>.</p>
<p>Following example is from <a href="http://eventbus.org/confluence/display/EventBus/Getting+Started">EventBus Getting Started guide</a>. Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time.</p>
<pre><code>public StatusBar extends JLabel {
public StatusBar() {
AnnotationProcessor.process(this);
}
@EventSubscriber(eventClass=StatusEvent.class)
public void updateStatus(StatusEvent statusEvent) {
this.setText(statusEvent.getStatusText();
}
}
</code></pre>
<p>A similar project is <a href="https://elf.dev.java.net/">ELF (Event Listener Framework)</a> but it seems to be less mature.</p>
<p>I'm currently researching about event notification frameworks on <a href="http://spring-java-ee.blogspot.com/2009/12/publish-subscribe-event-driven.html">Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev</a> and the followup articles.</p>
|
Lock Active Directory accounts programmatically <p>I have to lock user accounts in Active Directory programmatically in C#. </p>
<p>Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account).</p>
<p>Now I tried to lock the account by providing incorrect credentials (see below), but this doesn't work either.</p>
<pre><code>int retries = 0;
while (!adsUser.IsAccountLocked && retries < MAX_LOCK_RETRIES)
{
retries++;
try
{
new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache();
}
catch (Exception)
{
/* ... */
}
adsUser.GetInfo();
}
</code></pre>
<p>Any ideas?</p>
|
<p>Make sure the account you're using to disable the account has sufficient privileges to disable accounts. See <a href="http://msdn.microsoft.com/en-us/library/ms696026(VS.85).aspx" rel="nofollow">this example</a> from Microsoft.</p>
|
Compiler could not choose an overload between interface and exception <p>Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.</p>
<p>Detais are following:</p>
<pre><code>//exception overloads:
public FilterXmlParseException(string message, Exception innerException)
: base(message, innerException) { }
public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...}
//Usage:
XmlReader reader = ...
IXmlLineInfo lineinfo = (IXmlLineInfo)reader;
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
//ok
throw new FilterXmlParseException("<Filter> element expected", lineinfo);
</code></pre>
<p>And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception</p>
|
<p>The line:</p>
<pre><code>//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
</code></pre>
<p>because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implements this interface, but the compiler has no way to know it.</p>
|
How do I add an MSAccess connection to CodeIgniter or CakePHP? <p>I'm trying to use a Microsoft Access database for a demo project that I'm thinking of doing in either CodeIgniter or CakePHP. Ignoring the possible folly of using Microsoft Access, I haven't been able to figure out precisely how the connection string corresponds to the frameworks' database settings. In straight PHP, I can use this code to connect to an Access database:</p>
<pre><code>$db_connection = odbc_connect(
"DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=\\path\\to\\db.mdb",
"ADODB.Connection", "", "SQL_CUR_USE_ODBC"
);
</code></pre>
<p>How do those strings correspond to the Code Igniter db settings? This doesn't seem to be quite working:</p>
<pre><code>$db['access']['hostname'] = "{Microsoft Access Driver (*.mdb)}";
$db['access']['username'] = "ADODB.Connection";
$db['access']['password'] = "";
$db['access']['database'] = "\\path\\to\\db.mdb";
$db['access']['dbdriver'] = "odbc";
$db['access']['dbprefix'] = "";
$db['access']['pconnect'] = TRUE;
$db['access']['db_debug'] = TRUE;
$db['access']['cache_on'] = FALSE;
$db['access']['cachedir'] = "";
$db['access']['char_set'] = "utf8";
$db['access']['dbcollat'] = "utf8_general_ci";
</code></pre>
|
<p>Try setting up a DSN and changing to the following:</p>
<pre><code>$db['access']['hostname'] = "<dsn name>";
$db['access']['username'] = "";
$db['access']['password'] = "";
$db['access']['database'] = "<dsn name>";
</code></pre>
<p>There's also a section in the CodeIgniter documentation that addresses connection strings:</p>
<p><a href="http://codeigniter.com/user_guide/database/connecting.html" rel="nofollow">http://codeigniter.com/user_guide/database/connecting.html</a></p>
|
How do I find out when the Spring.NET root context has loaded? <p>I have a web service running, and it uses Spring.NET for it's IoCness. One of the classes needs to do some stuff when it loads (I'm using <code>AfterPropertiesSet</code>) and "some stuff" involves a call to <code>ContextRegistry.GetContext()</code>. The problem is this code in the <code>ContextRegistry</code> class:</p>
<pre><code>if (rootContextCurrentlyInCreation)
{
throw new InvalidOperationException("root context is currently in creation. You must not call ContextRegistry.GetContext() from e.g. constructors of your singleton objects");
}
</code></pre>
<p>How can I have that object register itself to be notified once the context is fully created?</p>
|
<p>if possible, remove that call to <code>ContextRegistry.GetContext()</code>. That is a sign of bad design anyway because it couples your code very closely to the container - which I think we all agree shouldn't be the case.</p>
<p>What exactly are you trying to do?</p>
<p><strong>P.S</strong>: I'd also like to suggest you post Spring for .NET relevant questions to our <a href="http://forum.springframework.net/" rel="nofollow">community forums</a> - it is more likely to get your questions answered there.</p>
|
IE8 loses cookies when opening a new window after a redirect <p>I'm using Internet Explorer 8 beta 2. </p>
<ol>
<li><p>Client performs POST on <a href="http://alpha/foo">http://alpha/foo</a></p></li>
<li><p>Server responds with redirect to <a href="http://beta/bar">http://beta/bar</a></p></li>
<li><p>Client performs GET on <a href="http://beta/bar">http://beta/bar</a></p></li>
<li><p>Server responds with redirect to <a href="http://beta/baz">http://beta/baz</a> and sets cookie</p></li>
<li><p>Client performs GET on <a href="http://beta/baz">http://beta/baz</a> <em>including cookie</em></p></li>
<li><p>Server provides response</p></li>
<li><p>User selects "Open in new window" on a link in the page</p></li>
<li><p>Client performs GET on <a href="http://beta/link">http://beta/link</a>, <em>without cookie!</em></p></li>
</ol>
<p>If in step 7 the user just clicks the link, the cookie <em>is</em> passed correctly. If there is no redirect, the cookie is passed correctly even if the user selects "Open in new window".</p>
<p>Is there a way to convince IE8 to pass the cookie in step 8?</p>
<p>(Edit: I believe this is a bug in IE8 beta 2, so I've <a href="http://www.microsoft.com/communities/newsgroups/list/en-us/default.aspx?mid=f90dfed8-42e3-499a-9a0b-4eefa66efccc&dg=microsoft.public.internetexplorer.beta">raised it on the IE beta newsgroup</a>. Workaround suggestions welcome.)</p>
|
<p>I believe that IE8 uses a separate process for each window. If you're using session cookies, the new process will start with a fresh session and therefore won't be able to submit the session cookies received by the other process. Can you try using persistent cookies and see what happens?</p>
<p>From <a href="http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie" rel="nofollow">http://www.microsoft.com/windows/internet-explorer/beta/readiness/developers-existing.aspx#lcie</a></p>
<blockquote>
<p>Loosely-coupled Internet Explorer
(LCIE) is an architectural effort to
improve the browser by separating its
components and loosening their
interdependence: most notably, it is
an attempt to isolate the Internet
Explorer frame and its tabs into
separate processes. In Internet
Explorer 8, this isolation will bring
about improved performance and
scalability, as well as more potent
methods to recover from problems like
disk or system failure.</p>
</blockquote>
|
Correct behavior for interface methods that can't be implemented <p>If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do?</p>
<p>For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements <a href="http://java.sun.com/javase/6/docs/api/java/util/Map.html" rel="nofollow">java.util.Map</a> by wrapping some immutable object and exposing it's data as key/value pairs. In this case the methods put and putAll don't make sense as I have no way to modify the underlying object. So the question is what should those methods do?</p>
|
<p>Any method that cannot be implemented according to the semantics of the interface should throw an <a href="http://java.sun.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html" rel="nofollow">UnsupportedOperationException</a>.</p>
|
Creating local users on remote windows server using c# <p>Provided I have admin access, I need a way to manage (Create, modify, remove) local accounts in a remote machine from an ASP.NET client.</p>
<p>I'm clueless in how to approach this. Is WMI a possibility (System.Management namespace)?
Any pointers?</p>
|
<p>Give this a try:</p>
<pre><code>DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://ComputerName" & ",computer", "AdminUN", "AdminPW");
DirectoryEntry user = directoryEntry.Children.Add("username", "user");
user.Invoke("SetPassword", new object[] { "password"});
ser.CommitChanges();
</code></pre>
<p>If you do need to go the Active Directory route, you can change the directoryEntry path string to something like this: LDAP://CN=ComputerName,DC=MySample,DC=com</p>
|
Isn't saying "C/C++" wrong? <p>I've seen a lot of questions around that use improperly the expression "C/C++".
The reasons in my opinion are: </p>
<ul>
<li>Newbie C and C++ programmers probably don't understand the difference between the two languages.</li>
<li>People don't really care about it since they want a generic, quick and "dirty" answer</li>
</ul>
<p>While C/C++ could sometimes be interpreted as "either C or C++", I think it's a big error. C and C++ offer different approaches to programming, and even if C code can be easily implemented into C++ programs I think that referring to two separate languages with that single expression ( C/C++ ) is wrong.<br /></p>
<p>It's true that some questions can be considered either as C or C++ ones, anyway.
What do you think about it?</p>
|
<p>C/C++ is a holdout from the early days of C++, where they were much more similar than they were today. It's something that wasn't really wrong at first, but is getting more-so all the time.</p>
<p>The basic structure is similar enough that most simple questions do still work between the two, though. There is an entire Wikipedia article on this topic: <a href="http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B">http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B</a></p>
<p>The biggest fallacy that comes from this is that because someone is well-versed in C, they will be equally good at C++.</p>
|
CSS - Is there a way to get rid of the selection rectangle after clicking a link? <p>Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely?</p>
|
<p>Do you mean the dotted outline of a target?</p>
<p>Try:</p>
<pre><code>:focus {
outline: 0;
}
</code></pre>
<p>This would remove all focus outlines. IT's essentially the same as onclick in JavaScript terms. You might prefer to apply this to <code>a:focus</code>.</p>
|
How can you make use of the add-in framework in .NET 3.0? <p>There are some updates with .NET 3.0 concerning how to create and use add-ins for your own applications. I read about some "<em>pipeline</em>" you have to create for the communication between add-in and host-application but couldn't find further information about it.</p>
<p>How would you made an add-in functionality in an application with .NET 3.0/3.5?</p>
<p><strong>Additional information if necessary</strong>: The host application is made with WPF and some general functionality. Each add-in should add a own register-tab to a given container with their own content (buttons, textfields, ...) and methods to extend the host-application.</p>
<p>Thanks in advance!</p>
|
<p>In addition to <a href="http://stackoverflow.com/questions/179680/how-can-you-make-use-of-the-add-in-framework-in-net-30#179727">Daniels</a> codeplex link, Jason He also has a nice wee series on using the System.AddIn namespace when developing Paint.NET starting here -</p>
<p><a href="http://blogs.msdn.com/zifengh/archive/2007/01/04/addin-model-in-paint-net-1-introduction.aspx" rel="nofollow">http://blogs.msdn.com/zifengh/archive/2007/01/04/addin-model-in-paint-net-1-introduction.aspx</a></p>
|
Would you use C++/CLI if supported like C# & VB.NET? <p>I've always had a thing for C++/CLI. Maybe because not many developers use it... or just because it's different.</p>
<p>Suppose Microsoft fully supported C++/CLI as they do VB.NET and C# (ie. LINQ, WPF, etc.). Would you use it? </p>
<p>If not, why?</p>
|
<p>I <em>do</em> use it. Even with the relative lack of tool support, it still beats raw P/Invoke for dealing with Win32. </p>
<p>As for LINQ, i don't really care to see too much more hacked into the C++ language. LINQ is usable enough as-is - if they're gonna enhance the compiler, they should work on C++ 0x support...</p>
|
Get the name of a class as a string in C# <p>Is there a way to take a class name and convert it to a string in C#? </p>
<p>As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.</p>
<p>Thus, is there a way that I could do this:</p>
<pre><code>class Foo
{
}
tblBar.Include ( Foo.GetType().ToString() );
</code></pre>
<p>I don't think I can do GetType() without an instance. Any ideas?</p>
|
<p>You can't use <code>.GetType()</code> without an instance because <code>GetType</code> is a method.</p>
<p>You can get the name from the type though like this:</p>
<pre><code>typeof(Foo).Name
</code></pre>
<p>And as pointed out by Chris, if you need the assembly qualified name you can use</p>
<pre><code>typeof(Foo).AssemblyQualifiedName
</code></pre>
|
is there something like alternate data streams on any linux filesystem? <p>On Windows NTFS there is a nice but mostly unused feature called
"Alternate Data Streams" (ADS) which I recently used in a hobby-dev project.</p>
<p>On Mac HFS+ there is also a similarly nice but mostly unused feature called "named forks".</p>
<p>I am thinking of porting this project to Linux, but I do not know if any Filesystem on linux has such a feature?</p>
|
<p>The problem with ADS is that Windows will "lose" those ADS streams the second that it moves to any non-NTFS filesystem. It does not consider those streams important, so oftentimes they are not kept around. You'll find they aren't accessible or disappear when over a network share, when burned to CD, put on a USB drive, etc... </p>
<p>The long and short of it is, unless you have a very narrow focus for your application (always on NTFS), I would avoid ADS streams altogether.</p>
|
Integrating with Great Plains, best way? <p>I can't find much information around the web about it. Has anyone used both eConnect and the Dynamics web services to interact (read/write) with Great Plains. I am looking for the pros and cons of both approaches.</p>
<p>This product will be installed and configured on various sites, so ease of configuration is really important. I usually hate to mess with IIS.</p>
<p>Should be able to target GP 9 and 10.</p>
<p>Thank you</p>
|
<p>Use the Great Plains Connector - full info here <a href="http://help.boomi.com/display/BOD/Great+Plains+Connector?showChildren=false" rel="nofollow">http://help.boomi.com/display/BOD/Great+Plains+Connector?showChildren=false</a></p>
<p>and here for pro-cons/limitations etc.:</p>
<p><a href="http://www.articlesbase.com/software-articles/great-plains-customization-how-to-integrate-legacy-application-with-dynamics-gp-452580.html" rel="nofollow">http://www.articlesbase.com/software-articles/great-plains-customization-how-to-integrate-legacy-application-with-dynamics-gp-452580.html</a></p>
<p>and of course from the horse's mouth:
<a href="http://msdn.microsoft.com/en-us/library/ms994230.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms994230.aspx</a></p>
|
Problem with width of auto-generated columns in DataGrid <p>Maybe world peace would be easier, but I have a problem with the widths of auto generated columns when a DataGrid has no rows. The column headings all squeeze up with no spacing between them. I've tried adding the following CSS to no avail:</p>
<pre><code>td.gridHeader
{
padding-left:20px;
padding-right: 20px;
}
</code></pre>
|
<p>I beleive headings are rendered as <th> not <td>. </p>
<pre><code>th.gridHeader
{
padding-left:20px;
padding-right: 20px;
}
</code></pre>
<p>I also assume you have applied <HeaderStyle CssClass="gridHeader" /> in the DataGrid markup. I didn't think people used DataGrids anymnore? or is it actually a GridView ? </p>
|
Convert UTC/GMT time to local time <p>We are developing a C# application for a web-service client. This will run on Windows XP PC's.</p>
<p>One of the fields returned by the web service is a DateTime field. The server returns a field in GMT format i.e. with a "Z" at the end.</p>
<p>However, we found that .NET seems to do some kind of implicit conversion and the time was always 12 hours out.</p>
<p>The following code sample resolves this to some extent in that the 12 hour difference has gone but it makes no allowance for NZ daylight saving.</p>
<pre><code>CultureInfo ci = new CultureInfo("en-NZ");
string date = "Web service date".ToString("R", ci);
DateTime convertedDate = DateTime.Parse(date);
</code></pre>
<p>As per <a href="http://www.timeanddate.com/worldclock/city.html?n=22">this date site</a>:</p>
<blockquote>
<p>UTC/GMT Offset </p>
<p>Standard time zone: UTC/GMT +12 hours<br>
Daylight saving time: +1 hour<br>
Current time zone offset: <strong>UTC/GMT +13 hours</strong> </p>
</blockquote>
<p>How do we adjust for the extra hour? Can this be done programmatically or is this some kind of setting on the PC's?</p>
|
<p>For strings such as <code>2012-09-19 01:27:30.000</code>, <code>DateTime.Parse</code> cannot tell what time zone the date and time are from.</p>
<p><code>DateTime</code> has a <em>Kind</em> property, which can have one of three time zone options:</p>
<ul>
<li>Unspecified</li>
<li>Local</li>
<li>Utc</li>
</ul>
<p><strong>NOTE</strong> <em>If you are wishing to represent a date/time other than UTC or your local time zone, then you should use <a href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx"><code>DateTimeOffset</code></a>.</em></p>
<hr>
<p>So for the code in your question:</p>
<pre><code>DateTime convertedDate = DateTime.Parse(dateStr);
var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified
</code></pre>
<p>You say you know what kind it is, so tell it.</p>
<pre><code>DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(dateStr),
DateTimeKind.Utc);
var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
</code></pre>
<p>Now, once the system knows its in UTC time, you can just call <code>ToLocalTime</code>:</p>
<pre><code>DateTime dt = convertedDate.ToLocalTime();
</code></pre>
<p>This will give you the result you require.</p>
|
How can I find out when a picture was actually taken in C# running on Vista? <p>In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem.</p>
<p>In Vista it instead returns the date that the picture is copied from the camera.</p>
<p>How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".</p>
|
<p>Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10x as fast on my machine.</p>
<pre><code> //we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
private static Regex r = new Regex(":");
//retrieves the datetime WITHOUT loading the whole image
public static DateTime GetDateTakenFromImage(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (Image myImage = Image.FromStream(fs, false, false))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
}
</code></pre>
<p>And yes, the correct id is 36867, not 306.</p>
<p>The other open source projects below should take note of this. it is a HUGE perfprmance hit when processing thousands of files!</p>
|
Editing tables with MSHTML <p>Is there a way to create/edit a table using MSHTML without resorting to editing the underlying HTML?</p>
|
<p>If you want to automate this you can manipulate the DOM by adding rows and cells and tables if need to the document.</p>
<p>One the tables and rows are there the user can edit them like any other part of the document.</p>
|
Visual Designer errors, when there are no errors <p>I get errors when viewing forms and there are not any. I can close VS and reopen and it is fine. What cases this? Can it be fixed without closing?</p>
|
<p>Verify none of your custom user controls has any code errors.</p>
<p>Also try starting up Visual Studios using <strong>devenv /resetskippkgs</strong> from the command prompt.
It will reset packages if there is an error in loading.</p>
|
What are the limits of ruby on rails? <p>I have a memory of talking to people who have got so far in using Ruby on Rails and then had to abandon it when they have hit limits, or found it was ultimately too rigid. I forget the details but it may have had to do with using more than one database.</p>
<p>So what I'd like is to know is what features/requirements fall outside of Ruby on Rails, or at least requires such contortions that it is better to use another more flexible framework, even though you may have to lose some elegance or write extra boilerplate code. </p>
|
<p>Rails (not ruby itself) is proud to be "Opinionated Software".</p>
<p>What this means in practice is that the authors of rails have a certain target audience in mind (themselves basically) and aim rails specifically at that. If X feature isn't needed for that target audience, it doesn't get added.</p>
<p>Off the top of my head, things that rails explicitly doesn't support that people may care about:</p>
<ol>
<li>Foreign keys in databases</li>
<li>Connections to multiple DB's at once</li>
<li>SOAP web services (since rails 2.0)</li>
<li>Connections to multiple database <em>servers</em> at once</li>
</ol>
<p>That said, it is very easy to extend rails with plugins, and there are plugins which add all of the above functionality to rails, and a lot more, so I wouldn't really count these as limits.</p>
<p>The only other caveat is that rails is <em>built</em> around the idea of creating CRUD web applications using MVC. If you're trying to do something which is NOT a CRUD web app (like twitter, which is actually a messaging system, or if you are insane and want to use a model like ASP.NET webforms) then you will also encounter problems. In this case you're better off not using rails, as you're essentially trying to build a boat out of bicycle parts.</p>
<p>In all likelihood, the problems you will run into that can't just be fixed with a quick plugin or a day or 2 of coding are all inherent problems with the underlying C Ruby runtime (memory leaks, green threads, crap performance, etc).</p>
|
Are C++ Templates just Macros in disguise? <p>I've been programming in C++ for a few years, and I've used STL quite a bit and have created my own template classes a few times to see how it's done.</p>
<p>Now I'm trying to integrate templates deeper into my OO design, and a nagging thought keeps coming back to me: They're just a macros, really... You could implement (rather UGLY) auto_ptrs using #defines, if you really wanted to.</p>
<p>This way of thinking about templates helps me understand how my code will actually work, but I feel that I must be missing the point somehow. Macros are meant evil incarnate, yet "template metaprogramming" is all the rage.</p>
<p>So, what ARE the real distinctions? and how can templates avoid the dangers that #define leads you into, like</p>
<ul>
<li>Inscrutable compiler errors in
places where you don't expect them?</li>
<li>Code bloat? </li>
<li>Difficulty in tracing code?</li>
<li>Setting Debugger Breakpoints?</li>
</ul>
|
<p>Macros are a text substitution mechanism.</p>
<p>Templates are a functional turing-complete language that is executed at compile time and is integrated into the C++ type system. You can think of them as a plugin mechanism for the language.</p>
|
Obtain file path of C# save dialog box <p>I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later. </p>
<p>Can anybody tell me how to obtain the file path from the save dialog box to use it later?</p>
|
<p>Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.</p>
<pre><code>SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 1;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
}
</code></pre>
|
How to display DateTime with an abbreviated Time Zone? <p>I am aware of the <a href="http://msdn.microsoft.com/en-us/library/system.timezone(VS.80).aspx">System.TimeZone</a> class as well as the many uses of the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tostring(VS.80).aspx">DateTime.ToString()</a> method. What I haven't been able to find is a way to convert a DateTime to a string that, in addition to the time and date info, contains the three-letter Time Zone abbreviation (in fact, much the same way StackOverflow's tooltips for relative time display works).</p>
<p>To make an example easy for everyone to follow as well as consume, let's continue with the StackOverflow example. If you look at the tooltip that displays on relative times, it displays with the full date, the time including seconds in twelve-hour format, an AM/PM designation, and then the three-letter Time Zone abbreviation (in their case, Coordinated Universal Time). I realize I could easily get GMT or UTC by using the built-in methods, but what I really want is the time as it is locally — in this case, on a web server.</p>
<p>If our web server is running Windows Server 2k3 and has it's time zone set to CST (or, until <a href="http://en.wikipedia.org/wiki/Daylight_saving_time#Terminology">daylight saving</a> switches back, CDT is it?), I'd like our ASP.NET web app to display DateTimes relative to that time zone as well as formatted to display a "CST" on the end. I realize I could easily hard-code this, but in the interest of robustness, I'd really prefer a solution based on the server running the code's OS environment settings.</p>
<p>Right now, I have everything but the time zone abbreviation using the following code:</p>
<pre><code>myDateTime.ToString("MM/dd/yyyy hh:mm:ss tt")
</code></pre>
<p>Which displays:</p>
<p>10/07/2008 03:40:31 PM</p>
<p>All I want (and it's not much, promise!) is for it to say:</p>
<p>10/07/2008 03:40:31 PM CDT</p>
<p>I can use System.TimeZone.CurrentTimeZone and use it to correctly display "Central Daylight Time" but... that's a bit too long for brevity's sake. Am I then stuck writing a string manipulation routine to strip out white-space and any non-uppercase letters? While that might work, that seems incredibly hack to me...</p>
<p><a href="http://www.google.com/search?hl=en&safe=off&q=C%23+time+zone+abbreviation&btnG=Search">Googling</a> and looking around on here did not produce anything applicable to my specific question.</p>
|
<p>Here's my quick hack method I just made to work around this.</p>
<pre><code>public static String TimeZoneName(DateTime dt)
{
String sName = TimeZone.CurrentTimeZone.IsDaylightSavingTime(dt)
? TimeZone.CurrentTimeZone.DaylightName
: TimeZone.CurrentTimeZone.StandardName;
String sNewName = "";
String[] sSplit = sName.Split(new char[]{' '});
foreach (String s in sSplit)
if (s.Length >= 1)
sNewName += s.Substring(0, 1);
return sNewName;
}
</code></pre>
|
Mixed syntax for control structures generating syntax errors <p>I'm refactoring some PHP code and discovered that certain nested combinations of </p>
<pre><code>if () :
</code></pre>
<p>and </p>
<pre><code>if () {
</code></pre>
<p>generate syntax errors. Not that I would normally mix the two, but I like to do frequent syntax checks as I'm writing code and I kept getting a syntax error because of this.</p>
<p>Example - generates syntax error:</p>
<pre><code>if ( $test == 1 ) :
if ( $test2 == 'a' ) {
if ( $test3 == 'A' ) {
} else {
}
}
else :
echo 'test2';
endif;
</code></pre>
<p>Example - does NOT generate syntax error:</p>
<pre><code>if ( $test == 1 ) :
if ( $test2 == 'a' ) :
if ( $test3 == 'A' ) :
else :
endif;
endif;
else :
echo 'test2';
endif;
</code></pre>
<p>Could someone please explain to me why the first block of code is generating an error? </p>
|
<p>This is a wild guess since I am not familiar with the grammar of PHP. But here goes:</p>
<p>The problem is the second <code>else</code>. The parser can't see if this <code>else</code> is belonging to the first or the second if (counting from the beginning). In your second example there is an <code>endif</code> making the second <code>if</code>-block be terminated so there it can do the parse. Perhaps this is the famous 'dangling-else' problem in disguise?</p>
|
How do you deal with connection strings when deploying an ASP.NET site? <p>Right now our test and production databases are on the same server, but with different names. Deploying has meant editing Web.config to change all the connection strings for the correct database. A step which I forget all too frequently... </p>
<p>We've finally created a new database server for testing, and I'm moving the databases over... but now the server will be different and we'll still need to deal with connection string issues. </p>
<p>I was thinking of managing it via a hosts file, but the thought of switching that on my desktop machine whenever I need to test against production data seems cumbersome at best.</p>
<p>So I'm just wondering if there's a better way out there. Something that would build with a "production" web config for deployment would be ideal...</p>
|
<p>Use a <a href="http://weblogs.asp.net/scottgu/archive/2008/01/28/vs-2008-web-deployment-project-support-released.aspx" rel="nofollow">Web Deployment Project</a> and update the wdproj file (it's just an MSBuild file) with some post build tasks to output the correct .config file. I keep a web.config and web.release.config then use this in the wdproj file:</p>
<pre><code><Target Name="AfterBuild">
<Copy Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " SourceFiles="$(SourceWebPhysicalPath)\web.release.config" DestinationFiles="$(OutputPath)\web.config" />
<Delete Files="$(OutputPath)\web.release.config" />
</Target>
</code></pre>
<p><a href="http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx" rel="nofollow">More information</a></p>
<p>A simpler solution some like is using <a href="http://weblogs.asp.net/fmarguerie/archive/2007/04/26/using-configsource-to-split-configuration-files.aspx" rel="nofollow">configSource property of appSettings and connectionStrings</a> and then never overwriting that file on the production server.</p>
|
Is there a master list of the Big-O notation for everything? <p>Is there a master list of the Big-O notation for everything? Data structures, algorithms, operations performed on each, average-case, worst-case, etc.</p>
|
<p><a href="http://xlinux.nist.gov/dads/" rel="nofollow">Dictionary of Algorithms and Data Structures</a> is a fairly comprehensive list, and includes complexity (Big-O) in the algorithms' descriptions. If you need more information, it'll be in one of the linked references, and there's always Wikipedia as a fallback.</p>
|
Using Office Ribbon in a Word Processor <p>I heard Microsoft allows use of commercially available Office UI controls, with the exception of competing products, such as a word processor or spreadsheet app, etc.</p>
<p>How true is that?</p>
<p>Also, if it is not true, do you know of any <em>free</em> Ribbon controls?</p>
|
<p>You should look at <a href="http://blogs.msdn.com/jensenh/archive/2006/11/21/licensing-the-2007-microsoft-office-user-interface.aspx" rel="nofollow">Jensen Harris' blog entry about licensing the Office user interface</a> which explains it in great detail. However I believe the relevant point here is:</p>
<blockquote>
<p>There's only one limitation: if you
are building a program which directly
competes with Word, Excel, PowerPoint,
Outlook, or Access (the Microsoft
applications with the new UI), you
can't obtain the royalty-free license.</p>
</blockquote>
|
Doesn't the ability to cast defeat the purpose of typed variables? <p>So, I'm working under the assumption that we have typed languages because we make a lot of mistakes... so typing is one way to have the compiler do a lot of checks for us and help us out a bit (please let me know if it is my assumptions that's incorrect).</p>
<p>However, if we introduce casting to a typed language, don't we re-introduce most the problems we had when were not able to type variables?</p>
<p>I'm also aware that my assumption isn't the only reason why we type variables. Please share some of the other reasons why we have typed languages.</p>
|
<p>The bottom line is that <strong>strong typing lets the compiler check things for you</strong> and <strong>casting lets you override the strong typing when necessary.</strong></p>
|
string symbol manipulation in batch files? <p>Is there a way to take substrings of a string with .bat/.cmd files?</p>
<p>For example given the string "hello.txt" is there a way to strip the .txt?</p>
<p>EDIT: Also is there a more general way to do this, not under the assumption that it is a file name or file path?</p>
|
<p>If this is a file passed as a parameter, you can use %~n1, like this:</p>
<pre><code>test.bat
----------
echo %~n1 %~n2
c:\> test.bat myfile.txt my.long.file.bat
myfile my.long.file
</code></pre>
<p>If you know the length of the string you can use the substring operator:</p>
<pre><code>echo %variable:0,4% => "test.txt" => "test"
</code></pre>
<p>And to get everything EXCEPT the last 4 characters:</p>
<pre><code>echo %variable:~0,-4% => "file...name.txt" => "file...name"
</code></pre>
<ul>
<li><a href="http://www.batchfiles.co.nr/" rel="nofollow">BatchFiles Website (kind advanced)</a></li>
<li><a href="http://forums.afterdawn.com/thread_view.cfm/514228" rel="nofollow">Decent forum post</a></li>
<li><a href="http://groups.google.com/group/alt.msdos.batch.nt/msg/923423bf3143fcdd?pli=1" rel="nofollow">Another Good Post</a></li>
</ul>
|
Makefile If-Then Else and Loops <p>Can someone explain how to use if-then statements and for loops in Makefiles? I can't seem to find any good documentation with examples.</p>
|
<p><strong>Conditional Forms</strong> </p>
<p>Simple </p>
<pre><code>conditional-directive
text-if-true
endif
</code></pre>
<p>Moderately Complex </p>
<pre><code>conditional-directive
text-if-true
else
text-if-false
endif
</code></pre>
<p>More Complex </p>
<pre><code>conditional-directive
text-if-one-is-true
else
conditional-directive
text-if-true
else
text-if-false
endif
endif
</code></pre>
<p><strong>Conditional Directives</strong> </p>
<p>If Equal Syntax </p>
<pre><code>ifeq (arg1, arg2)
ifeq 'arg1' 'arg2'
ifeq "arg1" "arg2"
ifeq "arg1" 'arg2'
ifeq 'arg1' "arg2"
</code></pre>
<p>If Not Equal Syntax </p>
<pre><code>ifneq (arg1, arg2)
ifneq 'arg1' 'arg2'
ifneq "arg1" "arg2"
ifneq "arg1" 'arg2'
ifneq 'arg1' "arg2"
</code></pre>
<p>If Defined Syntax </p>
<pre><code>ifdef variable-name
</code></pre>
<p>If Not Defined Syntax </p>
<pre><code>ifndef variable-name
</code></pre>
<p><strong>foreach Function</strong> </p>
<p>foreach Function Syntax </p>
<pre><code>$(foreach var, list, text)
</code></pre>
<p>foreach Semantics<br>
For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.</p>
|
asp.net output data from DB without any html markup <p>I'm new to jquery and asp.net so please forgive if this is an obvious question. I'm using a jquery autocomplete plugin which requires that the page it looks up asynchronously for data is in this format as pure text only:</p>
<p>product1|price1<br>
product2|price2<br>
product3|price3</p>
<p>WITHOUT ANY OTHER HTML MARKUP. Any other html tags seems to cause problems.
Normally for a page like that I would use a repeater and some standard database calls and output the 2 fields. This however creates html tags.</p>
<p>How can I output this data as text only with no other markup whatsoever?</p>
|
<p>If you have a bare page with no master page referenced a repeater shouldn't produce any html. Make sure in the HTML view you only have:</p>
<pre><code><asp:Repeater ID="outRepeater" runat="server">
- your template here
</asp:Repeater>
</code></pre>
<p>An alternative would be to add a new Handler to your project which is a class that implements the IHttpHandler interface. This would allow you to output your code directly. This would end up looking like:</p>
<pre><code>public class MyOutputHandler : IHttpHandler {
public bool IsReusable { return false; }
public void ProcessRequest(HttpContext context) {
context.Response.Write("product1|price1");
}
}
</code></pre>
<p>If you have added this to a project as a new Handler (from add items) it should have a .ashx extension. Otherwise you'll need to register it in your web.config with its type and filename.</p>
|
CString maximum length <p>What is the maximum length in characters a CString object can hold?</p>
|
<p>Up to your available memory or INT_MAX-1 (whichever is less).</p>
|
What is the best encryption library in C/C++? <p>What is the best encryption library in C/C++ In terms of: </p>
<ul>
<li>entropy </li>
<li>quality </li>
<li>ease of use</li>
<li>readability</li>
<li>portability </li>
<li>performance</li>
</ul>
<p>What's your favorite and why do you like it? </p>
|
<p>We've used <a href="http://www.openssl.org/">OpenSSL</a> with good success. Portable, standards compliant and easy to use.</p>
|
How do I change read/write mode for a file using Emacs? <p>If a file is set to read only mode, how do I change it to write mode and vice versa from within Emacs?</p>
|
<blockquote>
<p>M-x toggle-read-only</p>
</blockquote>
<p>On my Windows box, that amounts to Alt-x to bring up the meta prompt and typing "toggle-read-only" to call the correct elisp function.</p>
<p>If you are using the default keyboard bindings, </p>
<blockquote>
<p>C-x C-q </p>
</blockquote>
<p>(which you read aloud as "Control-X Control-Q") will have the same effect. Remember, however, given that emacs is essentially infinitely re-configurable, your mileage may vary.</p>
<p><em>Following up from the commentary:</em> you should note that the writeable status of the buffer does not change the writeable permission of the file. If you try to write out to a read only <em>file</em>, you'll see a confirmation message. However, if you own the file, you can write out your changes <em>without</em> changing the permissions on the file.</p>
<p>This is very convenient if you'd like to make a quick change to a file without having to go through the multiple steps of add write permission, write out changes, remove write permission. I tend to forget that last step, leaving potentially critical files open for accidental changes later on.</p>
|
Object Initializer syntax to produce correct Json <p>I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.</p>
<p>Given this data:</p>
<pre><code>var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");
</code></pre>
<p>And this code: ** Which is not correct and is what needs to be fixed!! **</p>
<pre><code>var shaped = data.Select(c =>
new { c = c }
).ToList();
serializer.Serialize(shaped,sb);
string desiredResult = sb.ToString();
</code></pre>
<p>I would like <code>desiredResult</code> to be:</p>
<pre><code>{
"One": "One",
"Two": "Two",
"Three": "Three"
}
</code></pre>
<p>but it is currently:</p>
<p><code>{ "c" : "One" },{ "c" : "Two" }</code>, etc. </p>
<p>One problem is that on the left side of the object initializer I want the value of <code>c</code>, not <code>c</code> itself...</p>
|
<p>In json, the "c" in "c" : "One" is the property name. And in the C# world, you can't create property names on the fly (ignoring System.ComponentModel).</p>
<p>Basically, I don't think you can do what you want.</p>
|
Can you allocate a very large single chunk of memory ( > 4GB ) in c or c++? <p>With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them?</p>
<p>Why???
I'm working on processing some openstreetmap xml data and these files are huge. I'm currently streaming them in since I can't load them all in one chunk but I just got curious about the upper limits on malloc or new. </p>
|
<p>Short answer: Not likely</p>
<p>In order for this to work, you absolutely would <strong>have</strong> to use a 64-bit processor.
Secondly, it would depend on the Operating System support for allocating more than 4G of RAM to a single process.</p>
<p>In theory, it would be possible, but you would have to read the documentation for the memory allocator. You would also be more susceptible to memory fragmentation issues.</p>
<p>There is good information on <a href="http://www.microsoft.com/whdc/system/kernel/wmm.mspx">Windows memory management</a>.</p>
|
Best way to add full web search to my site? <p>I need to add full web search to my site. I need something like Google Custom Search but with no ads and it has to be free. Any recommendation of a web service or open source project that can index my site and allow me to search it will be helpful.</p>
<p>My site is made in ruby on rails, if that helps.</p>
<p>I'll make this question community-wiki so you can edit my bad English. I think many people can benefit from this question.</p>
|
<p>Check out Lucene. It's an open source search engine that will certainly be a fun learning experience to implement on your own site. It was originally designed by the Excite folks, I do believe.</p>
|
How can I cache a calculated column in rails? <p>I have a tree of active record objects, something like:</p>
<pre><code>class Part < ActiveRecord::Base
has_many :sub_parts, :class_name => "Part"
def complicated_calculation
if sub_parts.size > 0
return self.sub_parts.inject(0){ |sum, current| sum + current.complicated_calculation }
else
sleep(1)
return rand(10000)
end
end
end
</code></pre>
<p>It is too costly to recalculate the complicated_calculation each time. So, I need a way to cache the value. However, if any part is changed, it needs to invalidate its cache and the cache of its parent, and grandparent, etc.</p>
<p>As a rough draft, I created a column to hold the cached calculation in the "parts" table, but this smells a little rotten. It seems like there should be a cleaner way to cache the calculated values without stuffing them along side the "real" columns.</p>
|
<p>I suggest using association callbacks.</p>
<pre><code>class Part < ActiveRecord::Base
has_many :sub_parts,
:class_name => "Part",
:after_add => :count_sub_parts,
:after_remove => :count_sub_parts
private
def count_sub_parts
update_attribute(:sub_part_count, calculate_sub_part_count)
end
def calculate_sub_part_count
# perform the actual calculation here
end
end
</code></pre>
<p>Nice and easy =)</p>
|
Encrypted database query <p>I've just found out about Stack Overflow and I'm just checking if there are ideas for a constraint I'm having with some friends in a project, though this is more of a theoretical question to which I've been trying to find an answer for some time.</p>
<p>I'm not much given into cryptography but if I'm not clear enough I'll try to edit/comment to clarify any questions.</p>
<p>Trying to be brief, the environment is something like this:</p>
<ul>
<li><p>An application where the front-end as access to encrypt/decrypt keys and the back-end is just used for storage and queries.</p></li>
<li><p>Having a database to which you can't have access for a couple of fields for example let's say "address" which is text/varchar as usual.</p></li>
<li><p>You don't have access to the key for decrypting the information, and all information arrives to the database already encrypted.</p></li>
</ul>
<p>The main problem is something like this, how to consistently make queries on the database, it's impossible to do stuff like "where address like '%F§YU/´~#JKSks23%'". (IF there is anyone feeling with an answer for this feel free to shoot it).</p>
<p>But is it ok to do <code>where address='±!NNsj3~^º-:'</code>? Or would it also completely eat up the database? </p>
<p>Another restrain that might apply is that the front end doesn't have much processing power available, so already encrypting/decrypting information starts to push it to its limits. (Saying this just to avoid replies like "Exporting a join of tables to the front end and query it there".)</p>
<p>Could someone point me in a direction to keep thinking about it?</p>
<hr>
<p>Well thanks for so fast replies at 4 AM, for a first time usage I'm really feeling impressed with this community. (Or maybe I'm it's just for the different time zone)</p>
<p>Just feeding some information:</p>
<p>The main problem is all around partial matching. As a mandatory requirement in most databases is to allow partial matches. The main constraint is actually <strong>the database owner would not be allowed to look inside the database for information</strong>. During the last 10 minutes I've come up with a possible solution which extends again to possible database problems, to which I'll add here:</p>
<p>Possible solution to allow semi partial matching:</p>
<ul>
<li>The password + a couple of public fields of the user are actually the key for encrypting. For authentication the idea is to encrypt a static value and compare it within the database.</li>
<li>Creating a new set of tables where information is stored in a parsed way, meaning something like: "4th Street" would become 2 encrypted rows (one for '4th' another for 'Street'). This would already allow semi-partial matching as a search could already be performed on the separate tables.</li>
</ul>
<p>New question:</p>
<ul>
<li>Would this probably eat up the database server again, or does anyone think it is a viable solution for the partial matching problem?</li>
</ul>
<p><em>Post Scriptum: I've unaccepted the answer from Cade Roux just to allow for further discussion and specially a possible answer to the new question.</em></p>
|
<p>You can do it the way you describe - effectively querying the hash, say, but there's not many systems with that requirement, because at that point the security requirements are interfering with other requirements for the system to be usable - i.e. no partial matches, since the encryption rules that out. It's the same problem with compression. Years ago, in a very small environment, I had to compress the data before putting it in the data format. Of course, those fields could not easily be searched.</p>
<p>In a more typical application, ultimately, the keys are going to be available to someone in the chain - probably the web server.</p>
<p>For end user traffic SSL protects that pipe. Some network switches can protect it between web server and database, and storing encrypted data in the database is fine, but you're not going to query on encrypted data like that.</p>
<p>And once the data is displayed, it's out there on the machine, so any general purpose computing device can be circumvented at that point, and you have perimeter defenses outside of your application which really come into play.</p>
|
Database Null <p>I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status). </p>
<p>Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".</p>
<p>Thanks!</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx" rel="nofollow">Nullable Types</a> are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types.</p>
<p>Pseudo code to read the fields:</p>
<pre><code>decimal? dValue; // default value is null
if(decimalValueExists)
{
dValue = <value read from text file>
}
</code></pre>
<p>When you say multiple methods - I assume these are overloaded methods to be able to add optional fields (so n optional fields means n more methods)</p>
<p>You can avoid writing those methods by writing single method. Suppose you have one required field and one optional field:</p>
<pre><code>public class MyFields
{
decimal req1;
decimal? opt1; // optional field 1
}
</code></pre>
<p>Then define the web service method to use it:</p>
<pre><code>[WebMethod]
void MyWSMethod(MyFields myFields)
{/* code here will ultimately call InsertMyFields */}
void InsertMyFields(MyFields myFields)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "AddMyFields";
command.CommandType = CommandType.StoredProcedure;
// Add the required input parameter
SqlParameter parameter1 = new SqlParameter();
parameter1.ParameterName = "@ReqField1";
parameter1.SqlDbType = SqlDbType.NVarChar;
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = myFields.req1;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter1);
// Add the optional parameter and set its properties.
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@OptField1";
parameter2.SqlDbType = SqlDbType.NVarChar;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter2);
//.. rest of the code
}
}
</code></pre>
<p>If the nullable type has a value, <a href="http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx" rel="nofollow">Null Coalescing Operator</a> will set the value or else it will set the other value that you specify (DBNull.Value in our case).</p>
|
Delphi Project Needing runtime Packages, even with runtime Packages off <p>My Delphi7 project will not run on my clients computer if i don't have a few of the runtime packages in the path. eg rtl70.bpl</p>
<p>I have <I>Build with runtime packages</I> unticked, so shouldn't they be complied into the exe?</p>
<p>Edit: the Project uses Jedi Packages (TJvPlugin) and running the program with out any plugin installed works fine. As Soon as i add a Plugin, the bpl not found errors reappear. Seems like ill have to live with the extra packages. </p>
|
<p>It has been a while, but it seems like there was something where you needed to (1) check build with runtime packages, and then that enables some other editor (maybe list of packages to use), and you (2) make a change there. (3) Then do a full build, and then (4) remove the runtime packages check and do another (5) full build. It is important to do a full build each time. </p>
|
Percentages of subtotal in a report <p>I am using Report Designer in VS 2008. Is there a way to display the percentages of a subtotal in a crosstab report?</p>
|
<p>I'm assuming you want something that looks like this:</p>
<pre><code>ITEM_ID | AMOUNT | % OF TOTAL
-----------------------------------
1 | 20 | 10%
2 | 30 | 15%
3 | 40 | 20%
4 | 50 | 25%
5 | 60 | 30%
</code></pre>
<p>The value of your Amount column, by default, should contain an expression like:<br />
<strong><code>=Fields!Amount.Value</code></strong></p>
<p>So the value of a percentage column would contain the expression:<br />
<strong><code>=(Fields!Amount.Value / Sum(Fields!Amount.Value) * 100) & "%"</code></strong></p>
|
Python style: multiple-line conditions in IFs <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
|
<p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Also, don't forget the whitespace is more flexible than you might think:</p>
<pre><code>if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Both of those are fairly ugly though.</p>
<p>Maybe lose the brackets (the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements">Style Guide</a> discourages this though)?</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
</code></pre>
<p>This at least gives you some differentiation.</p>
<p>Or even:</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>I think I prefer:</p>
<pre><code>if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>Here's the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements">Style Guide</a>, which (since 2010) recommends using brackets.</p>
|
What's a good and stable C++ tree implementation? <p>I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is
stl compatible if at all possible.</p>
<p>For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here.</p>
<p>Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within.
So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable. </p>
|
<p>Take a look at <a href="http://tree.phi-sci.com/">this</a>.</p>
<p>The tree.hh library for C++ provides an STL-like container class for n-ary trees, templated over the data stored at the nodes. Various types of iterators are provided (post-order, pre-order, and others). Where possible the access methods are compatible with the STL or alternative algorithms are available.</p>
<p>HTH</p>
|
Thread synchronization question (in java) <p>my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing <strong>task1</strong>) and a Thread t2 (for <strong>task2</strong>).
I want then to do a specific task, <strong>task3</strong> when both other tasks (1 & 2) are over. Naturally I can't tell which of <strong>task1</strong> and <strong>task2</strong> will finish first...</p>
<p>Which would be for you the simplest (and safest) way to code this ?</p>
<p>Thank you for your help</p>
|
<p>You've got several options:</p>
<ol>
<li>If task3 is on a separate thread AND task1 and task2 threads are exclusive to their tasks (no thread pooling) and finish when the task finish, you can use {T1.join(); T2.join();} to wait for both threads. Pros: Easy. Cons: The situation is rarely that simple.</li>
<li>If task3 is on a separate thread, you could use java.util.concurrent.CountDownLatch shared between all threads. Task 3 will wait for the latch while task1 and task2 will decrease it. Pros: quite easy, oblivious to the environment. Cons: require T3 to be created before it's really needed.</li>
<li>If task3 should only be created AFTER task1 and task2 are finished (no separate thread for it until after task1 and task2 finishes), you'd have to build something a bit more complex. I'd recommend either creating your own ExecutorService that take a condition n addition to the future and only executes the future when the condition changes, or creating a management service that will check conditions and submit given futures based on these conditions. Mind, this is of the top of my head, there might be simpler solutions. Pros: resources-friendly. Cons: complex.</li>
</ol>
|
Is there a documented way to set the iPhone orientation? <p>I have an app where I would like to support device rotation in certain views but other don't particularly make sense in Landscape mode, so as I swapping the views out I would like to force the rotation to be set to portrait.</p>
<p>There is an undocumented property setter on UIDevice that does the trick but obviously generates a compiler warning and could disappear with a future revision of the SDK.</p>
<pre><code>[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationPortrait];
</code></pre>
<p>Are there any documented ways to force the orientation?</p>
<p><strong>Update:</strong> I thought I would provide an example as I am not looking for shouldAutorotateToInterfaceOrientation as I have already implemented that.</p>
<p>I want my app to support landscape and portrait in View 1 but only portrait in View 2. I have already implemented shouldAutorotateToInterfaceOrientation for all views but if the user is in landscape mode in View 1 and then switches to View 2, I want to force the phone to rotate back to Portrait.</p>
|
<p>This is long after the fact, but just in case anybody comes along who isn't using a navigation controller and/or doesn't wish to use undocumented methods:</p>
<pre><code>UIViewController *c = [[UIViewController alloc]init];
[self presentModalViewController:c animated:NO];
[self dismissModalViewControllerAnimated:NO];
[c release];
</code></pre>
<p>It is sufficient to present and dismiss a vanilla view controller.</p>
<p>Obviously you'll still need to confirm or deny the orientation in your override of shouldAutorotateToInterfaceOrientation. But this will cause shouldAutorotate... to be called again by the system.</p>
|
Issue with localizing html title of a page <p>I'm trying to localize my aspx pages. I'm done with content localization using L10n features provided by .net f/w, like resource files. But I'm finding it difficult to set local data in page titles. </p>
<p>Most of the browsers, including IE and FF, shows content on window title with some boxes (FF will show properly localized text in tab, IE doesn't even do that). But its working fine in safari (on windows). </p>
<p>When I did a research it seems like this issue exits ONLY for some of the languages. For example, the <a href="http://www.bbc.co.uk/hindi/" rel="nofollow">Hindi version of BBC</a> shows the title with boxes. But <a href="http://news.bbc.co.uk/hi/arabic/news/" rel="nofollow">Arabic version</a> shows the localized text in title.</p>
<p>Can somebody please tell me why this is happening? How we can solve this issue?</p>
<p>Note: My site is using Asp.net 2.0 / IIS</p>
|
<p>I suspect this is a typeface issue. The browser title bar and other window ornaments are usually rendered by your OS, not by the browser itself, so if you've configured Windows to use a typeface that doesn't support the additional character glyphs required for Hindi, Arabic, etc., then you'll get the boxes instead. Within your actual pages, you're probably using a typeface which does include support for all these extended characters, which is why you're only seeing the problem on the window titles.</p>
<p>Safari uses its own rendering engine for everything including the window chrome, which is why it doesn't look like a normal Windows app, and why your localized titles are working.</p>
<p>You might want to try changing your Windows "Active Title Bar" font (under Display Properties, Appearance, Advanced) to something like Arial which covers the full set of Unicode characters, and see if this resolves the problem? </p>
|
How do I unit test a custom ant task? <p>I am writing a custom ant task that extends Task. I am using the log() method in the task. What I want to do is use a unit test while deveoping the task, but I don't know how to set up a context for the task to run in to initialise the task as if it were running in ant.</p>
<p>This is the custom Task:</p>
<pre><code>public class CopyAndSetPropertiesForFiles extends Task {
public void execute() throws BuildException {
log("CopyAndSetPropertiesForFiles begin execute()");
log("CopyAndSetPropertiesForFiles end execute()");
}
}
</code></pre>
<p>This is the unit test code:</p>
<pre><code>CopyAndSetPropertiesForFiles task = new CopyAndSetPropertiesForFiles();
task.execute();
</code></pre>
<p>When the code is run as a test it gives a NullPointerException when it calls log.</p>
<pre><code>java.lang.NullPointerException
at org.apache.tools.ant.Task.log(Task.java:346)
at org.apache.tools.ant.Task.log(Task.java:334)
at uk.co.tbp.ant.custom.CopyAndSetPropertiesForFiles.execute(CopyAndSetPropertiesForFiles.java:40)
at uk.co.tbp.ant.custom.test.TestCopyAndSetPropertiesForFiles.testCopyAndSetPropertiesForFiles(TestCopyAndSetPropertiesForFiles.java:22)
</code></pre>
<p>Does anybody know a way to provide a context or stubs or something similar to the task?</p>
<p>Thanks,</p>
<p>Rob.</p>
<p>Accepted answer from Abarax. I was able to call task.setProject(new Project());
The code now executes OK (except no logging appears in th console - at least I can exercise the code :-) ).</p>
|
<p>Or better yet, decouple the task object itself from the logic (lets call it TaskImpl) inside the task - so that you can pass in your own dependencies (e.g., the logger). Then, instead of testing the task object, you test TaskImpl -> which you can pass in the logger, and any other weird bits and pieces it might need to do its job. Then unit testing is a matter of mocking the dependencies. </p>
|
computing performance <p>I need to find out the time a function takes for computing the performance of the application / function.
is their any open source Java APIs for doing the same ?</p>
|
<p>You're in luck as there are quite a few <a href="http://java-source.net/open-source/profilers" rel="nofollow">open source Java profilers</a> available for you.</p>
|
Help on Open source controls in commercial application <p>What are the implications of including a set of visual components released under a <a href="http://www.mozilla.org/MPL/MPL-1.1.html" rel="nofollow">Mozilla Public License</a> in a commercial application.</p>
<p>Do I have any obligations?</p>
|
<p>I've found pretty good analysis on MPL (and others) by Frank Hecker here:</p>
<p><a href="http://hecker.org/writings/setting-up-shop" rel="nofollow">http://hecker.org/writings/setting-up-shop</a> (search for "Mozilla Public License")</p>
<p>This pretty much sums it up:</p>
<blockquote>
<p>For MozPL-ed source code considered as
a set of source files, modifications
of the original source files are
considered to also fall under the
MozPL, as are new source files
incorporating extracts from the
original source files. Such modified
or new files are required to be
licensed under the same terms as the
original files, and in particular must
be made freely and publicly available
in source form.</p>
</blockquote>
<p>...</p>
<blockquote>
<p>Thus an open-source product initially
released under the MozPL may be
extended with proprietary code to
create new proprietary products, as
long as the proprietary code is
separate (i.e., in separate files) and
interacts with the open-source code
using a defined API.</p>
</blockquote>
<p>But as usual, read it carefully and consult your lawyers.</p>
|
Windows SharePoint Services vs. Microsoft Office SharePoint Server? <p>There's Windows SharePoint Services (WSS) and then there is Microsoft Office SharePoint Server (MOSS). MOSS considerably more expensive than WSS (which ships as part of Microsoft Server licensing).</p>
<p>My question is: what does MOSS do that makes it <i>worth</i> the extra cost? </p>
<p>..and does <a href="http://www.microsoft.com/Enterprisesearch/">Microsoft Search Server</a> not compete with the <a href="http://msdn.microsoft.com/en-us/library/ms563661.aspx">Business Data Cache</a> (BDC)?</p>
<p>Edit: The feature comparision page is helpful in illustrating the numerous features that MOSS has and WSS does not. By the looks of it, most of MOSS's feature set is Enterprise oriented. </p>
<p>How would you describe the differences (or additional benefits) of MOSS over WSS in a couple of sentences? In essence, what are the "big ticket" items in MOSS (and not in WSS)?</p>
|
<p>Don't assume that WSS is free in all deployment scenarios. We got a nice wake up call when we deployed WSS in a client-facing extranet configuration. One "main site" w/ a bunch of segregated, client sub-sites. Turns out we needed to buy an "intranet license" (can't remember the exact name) for the OS. This is different from the SharePoint internet connector - it actually lets you use Win 2003 w/ an unlimited number of internet users. Not hugely expensive, but it was a couple thousand dollars we weren't expecting on paying...</p>
|
SQL Server 2005 Performance: Distinct or full table in WHERE IN statement <p>We have two Tables:</p>
<ul>
<li>Document: id, title, document_type_id, showon_id</li>
<li>DocumentType: id, name</li>
<li>Relationship: DocumentType hasMany Documents. (Document.document_type_id = DocumentType.id)</li>
</ul>
<p>We wish to retrieve a list of all document types for one given ShowOn_Id. </p>
<p>We see two possiblities:</p>
<pre><code>SELECT DocumentType.*
FROM DocumentType
WHERE DocumentType.id IN (
SELECT DISTINCT Document.document_type_id FROM Document WHERE showon_id = 42
);
SELECT DocumentType.*
FROM DocumentType
WHERE DocumentType.id IN (
SELECT Document.document_type_id FROM Document WHERE showon_id = 42
);
</code></pre>
<p>Our question is: when and if is it better to use the DISTINCT to get the smaller record set versus retrieving the whole table and the IN statement walking the table to the first match. (We guess that's what it does ;-))</p>
<p>Is this different for different databases, is there a common answer?</p>
<p>Or is there a better way of doing it? (We are in .NET land)</p>
|
<p>You can use a join:</p>
<pre><code>SELECT DISTINCT DocumentType.*
FROM DocumentType
INNER JOIN Document
ON DocumentType.id=Document.document_type_id
WHERE Document.showon_id = 42
</code></pre>
<p>I think it's the best way to do it.</p>
|
Processing Linux SIGnals using Gambas <p>I would like to send a (as yet undetermined) SIGnal from a bash script to a Gambas program when a specific file has been changed. </p>
<p>How can I get my Gambas program to process this SIGnal?</p>
|
<p>If the documentation is anything to go by, this doesn't seem possible. However, I would suggest asking the same question on the Gambas mailing list (and/or link to this question on Stack Overflow). Please report back if you get an answer via the mailing list.</p>
|
Programmatically access currency exchange rates <p>I'm setting up an online ordering system but I'm in Australia and for international customers I'd like to show prices in US dollars or Euros so they don't have to make the mental effort to convert from Australian dollars.</p>
<p>Does anyone know if I can pull up to date exchange rates off the net somewhere in an easy-to-parse format I can access from my PHP script ?</p>
<p><hr /></p>
<p><strong>UPDATE:</strong> I have now written a PHP class which implements this. <a href="http://www.doctort.org/adam/general/currency-calculation-in-php.html">You can get the code from my website</a>.</p>
|
<p>You can get currency conversions in a simple format from yahoo:</p>
<p>For example, to convert from GBP to EUR:
<code>http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&f=sl1d1t1ba&e=.csv</code></p>
|
Default segment name in rails resources routing <p>I want to create a route in my rails application along the lines of</p>
<pre><code>/panda/blog
/tiger/blog
/dog/blog
</code></pre>
<p>where panda, tiger, and dog are all permalinks (for an animal class)</p>
<p>The normal way of doing this</p>
<pre><code>map.resources :animals do |animal|
animal.resource :blog
end
</code></pre>
<p>would create routes along the lines of</p>
<pre><code>/animals/panda/blog
/animals/tiger/blog
/animals/dog/blog
</code></pre>
<p>But i do not want the first segment, as it will always be the same. </p>
<p>I know I could do this by manual routing, but I want to know how to do using rails resources, as having animals and blogs is a requirement for me.</p>
|
<p>In rails 3.x, you can add <code>path => ""</code> to any <code>resource</code> or <code>resources</code> call to remove the first segment from the generated path.</p>
<pre><code>resources :animals, :path => ""
</code></pre>
<hr>
<pre><code>$ rake routes
animals GET / {:action=>"index", :controller=>"animals"}
POST / {:action=>"create", :controller=>"animals"}
new_animal GET /new(.:format) {:action=>"new", :controller=>"animals"}
edit_animal GET /:id/edit(.:format) {:action=>"edit", :controller=>"animals"}
animal GET /:id(.:format) {:action=>"show", :controller=>"animals"}
PUT /:id(.:format) {:action=>"update", :controller=>"animals"}
DELETE /:id(.:format) {:action=>"destroy", :controller=>"animals"}
</code></pre>
|
WHERE IN (array of IDs) <p>I have webservice which is passed an array of ints.
I'd like to do the select statement as follows but keep getting errors. Do I need to change the array to a string?</p>
<pre><code>[WebMethod]
public MiniEvent[] getAdminEvents(int buildingID, DateTime startDate)
{
command.CommandText = @"SELECT id,
startDateTime, endDateTime From
tb_bookings WHERE buildingID IN
(@buildingIDs) AND startDateTime <=
@fromDate";
SqlParameter buildID = new SqlParameter("@buildingIDs", buildingIDs);
}
</code></pre>
|
<p>You can't (unfortunately) do that. A Sql Parameter can only be a single value, so you'd have to do:</p>
<pre><code>WHERE buildingID IN (@buildingID1, @buildingID2, @buildingID3...)
</code></pre>
<p>Which, of course, requires you to know how many building ids there are, or to dynamically construct the query.</p>
<p>As a workaround*, I've done the following:</p>
<pre><code>WHERE buildingID IN (@buildingID)
command.CommandText = command.CommandText.Replace(
"@buildingID",
string.Join(buildingIDs.Select(b => b.ToString()), ",")
);
</code></pre>
<p>which will replace the text of the statement with the numbers, ending up as something like:</p>
<pre><code>WHERE buildingID IN (1,2,3,4)
</code></pre>
<ul>
<li>Note that this is getting close to a Sql injection vulnerability, but since it's an int array is safe. Arbitrary strings are <em>not</em> safe, but there's no way to embed Sql statements in an integer (or datetime, boolean, etc).</li>
</ul>
|
Serialization problem <p>The situation is like this : Main project A. and a class library B. <strong>A references B</strong></p>
<p>Project B has the classes that will be serialized. The classes are used in A. Now, the problem appears when from Project A I try to serialize the objects from B. An exception is thrown that says a class from A cannot be serialized. This is the strange part since in the classes in B I cant have a reference to those in A. (a circular dependency would be created).</p>
<p>How can I track down the problem ? because the exception method doesn't say where the Problem appeared ?</p>
<p><strong>Edit :</strong>
Ok, I found the problem with the help of <strong>Kent Boogaart's</strong> small app :D . I have a PropertyChanged listener in a class in project A that is not marked Serializable - and I don't want to mark it so. ( it would serialize that class to right ?)</p>
<p>I've solved the problem with the event by following this link : <a href="http://www.lhotka.net/weblog/CommentView,guid,776f44e8-aaec-4845-b649-e0d840e6de2c.aspx#commentstart" rel="nofollow">.NET 2.0 solution to serialization of objects that raise events</a>.
There still is a problem , but it's probably something similar.</p>
<p><strong>PS:</strong> Great tool from <strong>Kent Boogaart</strong></p>
|
<p>I have written a tool called <a href="http://kent-boogaart.com/blog/sertool" rel="nofollow">sertool</a> that will tell you what in your object graph cannot be serialized and how it is being referenced.</p>
|
SQL - state machine - reporting on historical data based on changeset <p>I want to record user states and then be able to report historically based on the record of changes we've kept. I'm trying to do this in SQL (using PostgreSQL) and I have a proposed structure for recording user changes like the following.</p>
<pre><code>CREATE TABLE users (
userid SERIAL NOT NULL PRIMARY KEY,
name VARCHAR(40),
status CHAR NOT NULL
);
CREATE TABLE status_log (
logid SERIAL,
userid INTEGER NOT NULL REFERENCES users(userid),
status CHAR NOT NULL,
logcreated TIMESTAMP
);
</code></pre>
<p>That's my proposed table structure, based on the data.</p>
<p>For the status field 'a' represents an active user and 's' represents a suspended user,</p>
<pre><code>INSERT INTO status_log (userid, status, logcreated) VALUES (1, 's', '2008-01-01');
INSERT INTO status_log (userid, status, logcreated) VALUES (1, 'a', '2008-02-01');
</code></pre>
<p>So this user was suspended on 1st Jan and active again on 1st of February.</p>
<p>If I wanted to get a suspended list of customers on 15th January 2008, then userid 1 should show up. If I get a suspended list of customers on 15th February 2008, then userid 1 should not show up.</p>
<p>1) Is this the best way to structure this data for this kind of query?</p>
<p>2) How do I query the data in either this structure or in your proposed modified structure so that I can simply have a date (say 15th January) and find a list of customers that had an active status on that date in SQL only? Is this a job for SQL?</p>
|
<p>This can be done, but would be a lot more efficient if you stored the end date of each log. With your model you have to do something like:</p>
<pre><code>select l1.userid
from status_log l1
where l1.status='s'
and l1.logcreated = (select max(l2.logcreated)
from status_log l2
where l2.userid = l1.userid
and l2.logcreated <= date '2008-02-15'
);
</code></pre>
<p>With the additional column it woud be more like:</p>
<pre><code>select userid
from status_log
where status='s'
and logcreated <= date '2008-02-15'
and logsuperseded >= date '2008-02-15';
</code></pre>
<p>(Apologies for any syntax errors, I don't know Postgresql.)</p>
<p>To address some further issues raised by Phil:</p>
<blockquote>
<p>A user might get moved from active, to suspended, to cancelled, to active again. This is a simplified version, in reality, there are even more states and people can be moved directly from one state to another.</p>
</blockquote>
<p>This would appear in the table like this:</p>
<pre><code>userid from to status
FRED 2008-01-01 2008-01-31 s
FRED 2008-02-01 2008-02-07 c
FRED 2008-02-08 a
</code></pre>
<p>I used a null for the "to" date of the current record. I could have used a future date like 2999-12-31 but null is preferable in some ways.</p>
<blockquote>
<p>Additionally, there would be no "end date" for the current status either, so I think this slightly breaks your query?</p>
</blockquote>
<p>Yes, my query would have to be re-written as</p>
<pre><code>select userid
from status_log
where status='s'
and logcreated <= date '2008-02-15'
and (logsuperseded is null or logsuperseded >= date '2008-02-15');
</code></pre>
<p>A downside of this design is that whenever the user's status changes you have to end date their current status_log as well as create a new one. However, that isn't difficult, and I think the query advantage probably outweighs this.</p>
|
Spring security: adding "On successful login event listener" <p>I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.</p>
|
<p>You need to define a Spring Bean which implements <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationListener.html">ApplicationListener</a>.</p>
<p>Then, in your code, do something like this:</p>
<pre class="lang-java prettyprint-override"><code>public void onApplicationEvent(ApplicationEvent appEvent)
{
if (appEvent instanceof AuthenticationSuccessEvent)
{
AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();
// ....
}
}
</code></pre>
<p>Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)</p>
|
Data from Google Analytics <p>So Google Analytics does not have an API that we can use to get our data, so is there an efficient way to programaticly fetch the data collected by Google, without logging it locally?</p>
<p>Edit:
I would prefer a Python or PHP solution but anything will work.</p>
|
<p>Google just announced that they're <a href="http://analytics.blogspot.com/2008/10/more-enterprise-class-features-added-to.html" rel="nofollow">making available a data export API for Google Analytics</a>. It sounds like that's exactly what you're looking for.</p>
<p>Per their announcement, the feature's currently in private beta, but I figure it'll be rolled out to all accounts in coming weeks/months. Depending on your needs, you may just want to wait, instead of building a short-term hackish solution.</p>
<p>If you're interested, I presume that the functionality's being rolled out first to members of the <a href="http://code.google.com/apis/analytics/docs/trustedTester.html" rel="nofollow">Google Analytics Trusted Tester</a> program.</p>
|
Alternative to Html.Button<T>? <p>I know the Html.Button has been moved to the Microsoft.Web.Mvc namespace, but I really miss the generic versions that used to exist in the early Previews. </p>
<p>All I want the Html.Button to do is to hit an action in my controller, but I'd rather not write the JavaScript in the onClickMethod argument.</p>
<p>In my previous project I just snagged the generic Html.Button code from a previous preview release, but that doesn't seem like the best approach as things progress. There were also Html.NavigateButton... where is that and why should I have to recreate it?</p>
<p>How is everybody else doing this?</p>
|
<p>The problem with the generic versions is that filters are allowed to change the actual name of the action away from the name of the method (like the [ActionName] attribute).</p>
|
How to JSON decode array elements in JavaScript? <p>I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.</p>
<p>But if I try to do a redirect or simply do an 'alert' on the link array element I get: </p>
<blockquote>
<p>function(){return JSON.encode(this);}</p>
</blockquote>
<p>As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.</p>
<p>After following some suggestions I've run <code>eval('(' + jsonObject + ')')</code> but it still returns the same output.</p>
<p>So how's this done ? </p>
|
<pre><code>var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
</code></pre>
<p><a href="http://api.jquery.com/jQuery.parseJSON/">See the jQuery API</a>.</p>
|
"TryParse / Parse like" pattern: what is the best way to implement it <p>This question is a follow-up from <a href="http://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful">How to indicate that a method was unsuccessful</a>. The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.</p>
<p>What is best:</p>
<pre><code>public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
</code></pre>
<p>or</p>
<pre><code>public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
</code></pre>
<p>I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example?</p>
|
<p>Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.</p>
<p>If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:</p>
<pre><code>public int DoSomething(string input)
{
int ret;
Exception exception = DoSomethingImpl(input, out ret);
if (exception != null)
{
// Note that you'll lose stack trace accuracy here
throw exception;
}
return ret;
}
public bool TrySomething(string input, out int ret)
{
Exception exception = DoSomethingImpl(input, out ret);
return exception == null;
}
private Exception DoSomethingImpl(string input, out int ret)
{
ret = 0;
if (input != "bad")
{
ret = 5;
return null;
}
else
{
return new ArgumentException("Some details");
}
}
</code></pre>
<p>Time this before you commit to it though!</p>
|
What is the best PHP lib/class to generate RSS/Atom <p>I have to produce RSS/Atom feed in various applications, and I want to know a good lib/class wich is able to produce both, and which already handle all common problems.</p>
<p>For example the one I used for year does not put the right format for date, so my feed is not well handled by several aggregators.</p>
<p>Thanks,
Cédric</p>
<p>Update :
Why I am looking for a lib? Because the one I used for years, which I had hacked a few, have a little problem. Maybe a specification is not correctly followed.
<a href="http://stackoverflow.com/questions/182615/why-my-rss-feed-duplicate-some-entries">http://stackoverflow.com/questions/182615/why-my-rss-feed-duplicate-some-entries</a></p>
|
<p>The <a href="http://www.phpclasses.org/package/4427-PHP-Generate-feeds-in-RSS-1-0-2-0-an-Atom-formats.html">PHP Universal Feed Generator</a> seems to be exactly what you're after - it has a simple, OO-based way of declaring a new feed and outputting it to your desired specification. </p>
<p>It also has built-in date format conversions as one of it's features.</p>
<blockquote>
<p>Features:</p>
<ul>
<li>Generates RSS 1.0, RSS 2.0 and ATOM 1.0 feeds</li>
<li>All feeds are are validated by feed validator.</li>
<li>Implements appropriate namespaces for different versions.</li>
<li>Automatically converts date formats.</li>
<li>Generates UUID for ATOM feeds.</li>
<li>Handles CDATA encoding for required tags.</li>
</ul>
<p>Supported versions:</p>
<ul>
<li>RSS 1.0 (which officially obsoleted RSS 0.90)</li>
<li>RSS 2.0 (which officially obsoleted RSS 0.91, 0.92, 0.93 and 0.94)</li>
<li>ATOM 1.0</li>
</ul>
</blockquote>
|
Should one use < or <= in a for loop <p>If you had to iterate through a loop 7 times, would you use:</p>
<pre><code>for (int i = 0; i < 7; i++)
</code></pre>
<p>or:</p>
<pre><code>for (int i = 0; i <= 6; i++)
</code></pre>
<p>There are two considerations:</p>
<ul>
<li>performance</li>
<li>readability </li>
</ul>
<p>For performance I'm assuming Java or C#. Does it matter if "less than" or "less than or equal to" is used? If you have insight for a different language, please indicate which.</p>
<p>For readability I'm assuming 0-based arrays.</p>
<p><strong>UPD:</strong> My mention of 0-based arrays may have confused things. I'm not talking about iterating through array elements. Just a general loop. </p>
<p>There is a good point below about using a constant to which would explain what this magic number is. So if I had "<code>int NUMBER_OF_THINGS = 7</code>" then "<code>i <= NUMBER_OF_THINGS - 1</code>" would look weird, wouldn't it. </p>
|
<p>The first is more <a href="http://en.wiktionary.org/wiki/idiomatic">idiomatic</a>. In particular, it indicates (in a 0-based sense) the number of iterations. When using something 1-based (e.g. JDBC, IIRC) I might be tempted to use <=. So:</p>
<pre><code>for (int i=0; i < count; i++) // For 0-based APIs
for (int i=1; i <= count; i++) // For 1-based APIs
</code></pre>
<p>I would expect the performance difference to be insignificantly small in real-world code.</p>
|
jQuery Tips and Tricks <h2>Syntax</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218129#2218129">Shorthand for the ready-event</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218135#2218135">Line breaks and chainability</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389474#389474">Nesting filters</a> by Nathan Long</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/552831#552831">Cache a collection and execute commands on the same line</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1519474#1519474">Contains selector</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Defining properties at element creation</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/3967325#3967325">Access jQuery functions as you would an array</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182666#182666">The noConflict function - Freeing up the $ variable</a> by Oli</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382853#382853">Isolate the $ variable in noConflict mode</a> by nickf</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2218120#2218120">No-conflict mode</a> by roosteronacid</li>
</ul>
<h2>Data Storage</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382834#382834">The data function - bind data to elements</a> by TenebrousX</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/5410587#5410587">HTML5 data attributes support, on steroids!</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504776#504776">The jQuery metadata plug-in</a> by Filip DupanoviÄ</li>
</ul>
<h2>Optimization</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1019899#1019899">Optimize performance of complex selectors</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/504732#504732">The context parameter</a> by lupefiasco</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389793#389793">Save and reuse searches</a> by Nathan Long</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/382922#382922">Creating an HTML Element and keeping a reference, Checking if an element exists, Writing your own selectors</a> by Andreas Grech</li>
</ul>
<h2>Miscellaneous</h2>
<ul>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/389906#389906">Check the index of an element in a collection</a> by redsquare</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/892617#892617">Live event handlers</a> by TM</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/696385#696385">Replace anonymous functions with named functions</a> by ken</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191139#191139">Microsoft AJAX framework and jQuery bridge</a> by Slace</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/922865#922865">jQuery tutorials</a> by egyamado</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/998547#998547">Remove elements from a collection and preserve chainability</a> by roosteronacid</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/191061#191061">Declare $this at the beginning of anonymous functions</a> by Ben</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1771311#1771311">FireBug lite, Hotbox plug-in, tell when an image has been loaded and Google CDN</a> by Colour Blend</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/182715#182715">Judicious use of third-party jQuery scripts</a> by harriyott</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1584927#1584927">The each function</a> by Jan Zich</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/1235178#1235178">Form Extensions plug-in</a> by Chris S</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/2750689#2750689">Asynchronous each function</a> by OneNerd</li>
<li><a href="http://stackoverflow.com/questions/182630/jquery-tips-and-tricks/4962433#4962433">The jQuery template plug-in: implementing complex logic using render-functions</a> by roosteronacid</li>
</ul>
|
<p><strong>Creating an HTML Element and keeping a reference</strong></p>
<pre><code>var newDiv = $("<div />");
newDiv.attr("id", "myNewDiv").appendTo("body");
/* Now whenever I want to append the new div I created,
I can just reference it from the "newDiv" variable */
</code></pre>
<p><br />
<strong>Checking if an element exists</strong></p>
<pre><code>if ($("#someDiv").length)
{
// It exists...
}
</code></pre>
<p><br />
<strong>Writing your own selectors</strong></p>
<pre><code>$.extend($.expr[":"], {
over100pixels: function (e)
{
return $(e).height() > 100;
}
});
$(".box:over100pixels").click(function ()
{
alert("The element you clicked is over 100 pixels height");
});
</code></pre>
|
Visual Print Design for .NET <p>I have a project that I'm working on and I need to be able to print out ID cards from the program. Are there any products out there that are reasonably priced so I can design a document for print and use it in .NET? I'm trying to avoid using System.Drawing from having to do it manually because when the company I work for needs to make changes to the ID card it will be a pain to change it later.</p>
|
<p>You could use Adobe Acrobat and one of the libraries out there for writing PDFs. That would let you design the document template in Adobe Acrobat, fill it out in code, and print it in code. There are some open source PDF writers and some commercial ones. The differences lie in the feature sets.</p>
<p>I've used <a href="http://www.codeproject.com/KB/printing/PDFWriter.aspx" rel="nofollow">PDFWriter</a> in the past.</p>
|
WorkFlow Unit Testing <p>How to unit test the windows workflows?</p>
|
<p>K. Scott Allen has posted <a href="http://odetocode.com/Blogs/scott/archive/2006/08/02/5492.aspx">this</a>, which provides an approach to unit testing custom activities (although he says that he is not satisfied). A similar approach is presented by Ron Jacobs <a href="http://blogs.msdn.com/rjacobs/archive/2008/08/26/unit-testing-workflows.aspx">here</a> and <a href="http://blogs.msdn.com/rjacobs/archive/2008/08/27/unit-testing-activities-with-windows-workflow-foundation.aspx">here</a>.</p>
<p>Another approach is presented by Maurice <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/06/02/unit-testing-custom-workflow-activities.aspx">here</a> and <a href="http://msmvps.com/blogs/theproblemsolver/archive/2008/06/11/unit-testing-asynchronous-workflow-activities.aspx">here</a> (he uses <a href="http://www.typemock.com/">TypeMock</a> as Will already <a href="http://stackoverflow.com/questions/182740/workflow-unit-testing#182888">mentioned</a>).</p>
|
Map a network drive to be used by a service <p>Suppose some Windows service uses code that wants mapped network drives and no UNC paths. How can I make the drive mapping available to the service's session when the service is started? Logging in as the service user and creating a persistent mapping will not establish the mapping in the context of the actual service.</p>
|
<p>Use this at your own risk. (I have tested it on XP and Server 2008 x64 R2)</p>
<p>For this hack you will need <a href="http://technet.microsoft.com/en-us/sysinternals/bb842062.aspx">SysinternalsSuite by Mark Russinovich</a>:</p>
<p><strong>Step one:</strong>
Open an elevated cmd.exe prompt (Run as administrator)</p>
<p><strong>Step two:</strong>
Elevate again to root using PSExec.exe:
Navigate to the folder containing SysinternalsSuite and execute the following command
<code>psexec -i -s cmd.exe</code>
you are now inside of a prompt that is <code>nt authority\system</code> and you can prove this by typing <code>whoami</code>. The <code>-i</code> is needed because drive mappings need to interact with the user</p>
<p><strong>Step Three:</strong>
Create the persistent mapped drive as the SYSTEM account with the following command
<code>net use z: \\servername\sharedfolder /persistent:yes</code></p>
<p>It's that easy!</p>
<p><strong>WARNING</strong>: You can only remove this mapping the same way you created it, from the SYSTEM account. If you need to remove it, follow steps 1 and 2 but change the command on step 3 to <code>net use z: /delete</code>.</p>
<p><strong>NOTE</strong>: The newly created mapped drive will now appear for ALL users of this system but they will see it displayed as "Disconnected Network Drive (Z:)". Do not let the name fool you. It may claim to be disconnected but it will work for everyone. That's how you can tell this hack is not supported by M$.</p>
|
Determine highest .NET Framework version <p>I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code. Looks like I can iterate the folders under <code>%systemroot%\Microsoft.NET\Framework</code>, but that seems kind of error prone. Is there a better way? Perhaps a registry key I can inspect? Thanks.</p>
|
<p>Use the <a href="http://en.wikipedia.org/wiki/Windows_Registry" rel="nofollow">Windows Registry</a> location <code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP</code>.</p>
|
C wrapper to remove users on command "ps" <p>I have one question maybe someone here can help me. If i do "ps aux --sort user" on linux console I have one list of users and their processes runing on the machine. My question is how do I remove the users name and print that list like this <strong>in a C program</strong>:</p>
<p>for example:</p>
<pre><code>(â¦)
--------------------------------------------------------------------------
user: APACHE
--------------------------------------------------------------------------
3169 0.0 1.2 39752 12352 ? S 04:10 0:00 /usr/sbin/httpd
--------------------------------------------------------------------------
user: VASCO
--------------------------------------------------------------------------
23030 0.0 0.1 4648 1536 pts/1 Ss 20:02 0:00 âbash
(â¦)
</code></pre>
<p>I print the user name then I print his processes... any ideas ?</p>
<p>thx</p>
|
<pre><code>ps aux --sort user | perl -npe 's/^(\w+)//g; if ($user ne $1) {$user=$1; print "user: " . uc($user) . "\n";}'
</code></pre>
|
What is returned when I call ToString() on an uninitialized char object property? <p>I have a c# object with a property called Gender which is declared as a char.</p>
<pre><code>private char _Gender;
public char Gender
{
get{ return _Gender; }
set{ _Gender = value; }
}
</code></pre>
<p>What string is returned/created when I call MyObject.Gender.ToString()?</p>
<p>I ask because I am calling a webservice (which accepts a string rather than a char) so I am doing a ToString on the property as I pass it over. I was expecting it to send an empty string if the char is not set.</p>
<p>However this doesn't appear to be the case, so the question is what is the string?</p>
|
<p>The default value of char is unicode 0, so I'd expect "\u0000" to be returned.</p>
|
How do I Update a GridView from a Page Method from code behind? <p>How do I update a Gridview on a aspx page from a webmethod?</p>
<p>Here is my code.</p>
<pre><code>[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
</code></pre>
<p>I can't use the "findcontrol" or the "this" methods so I need some help.</p>
|
<p>You can dynamically/programmatically build the GridView control. Then in your WebMethod, you can call RenderControl() method to retrieve the HTML content of the rendered GridView control. Return that content from the WebMethod and have the callback JavaScript function inject the HTML content into your placeholder element's innerHTML property.</p>
<p>Another option is to do your data binding on the client-side. So all the WebMethod has to do is pass back the data (excluding presentational markup), for example in a JSON-type format. Then you can use something like <a href="http://code.google.com/p/trimpath/wiki/JavaScriptTemplates" rel="nofollow">javascript templates</a> to render the grid with data. This approach takes GridView control completely out of the picture, but depending on your needs, it may be a viable option.</p>
|
Is this the best way to get unique version of filename w/ Python? <p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this?
Thanks!</p>
<pre><code>def unique_filename(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while os.path.isfile(file_name):
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
return file_name
</code></pre>
<p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
|
<p>One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.</p>
<p>To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):</p>
<pre><code>def unique_file(file_name):
counter = 1
file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext')
while 1:
try:
fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW)
return os.fdopen(fd), file_name
except OSError:
pass
file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1]
counter += 1
</code></pre>
<p><strong>[Edit]</strong> Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):</p>
<pre><code>def unique_file(file_name):
dirname, filename = os.path.split(file_name)
prefix, suffix = os.path.splitext(filename)
fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname)
return os.fdopen(fd), filename
>>> f, filename=unique_file('/home/some_dir/foo.txt')
>>> print filename
/home/some_dir/foo_z8f_2Z.txt
</code></pre>
<p>The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first.
You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.</p>
|
WCF Endpoint with Priority <p>I need WCF service with 3 endpoints </p>
<ol>
<li>High</li>
<li>Normal</li>
<li>Low</li>
</ol>
<p>Most of messages will come through Normal and Low Endpoints.
If Message on High will appear it have to be processed asap.</p>
<p>Does anyone knows how to do it ???</p>
|
<p>You should take a look at this great two part series from Michele Leroux Bustamante in MSDN Magazine:</p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc500646.aspx" rel="nofollow">Building a WCF Router, Part 1</a> and
<a href="http://msdn.microsoft.com/en-us/magazine/cc546553.aspx" rel="nofollow">Building a WCF Router, Part 2</a></p>
<p>Part 1, in particular, would be interesting to you:</p>
<blockquote>
<p>Sometimes it is useful to introduce an
intermediary or router service between
a client and a target service to
receive messages that flow between
them and perform additional activities
such as logging, <strong><em>priority routing</em></strong>,
online/offline routing, load
balancing, or to introduce a security
boundary. When such an intermediate
service is introduced, it becomes
necessary to tweak some addressing and
message filtering behaviors to
accommodate.</p>
</blockquote>
<p><strong><em>[my emphasis added]</em></strong></p>
<p>She also has the related <a href="http://www.dasblonde.net/downloads/routers.zip" rel="nofollow">source code</a> available on her <a href="http://www.dasblonde.net" rel="nofollow">blog</a>.</p>
|
Forking subprocesses in Perl unit tests stops prove; Test::Harness exiting <p>I have been trying to use the Perl utility/module "prove" as a test harness for some unit tests. The unit tests are a little more "system" than "unit" as I need to fork off some background processes as part of the test, Using the following...</p>
<pre><code>sub SpinupMonitor{
my $base_dir = shift;
my $config = shift;
my $pid = fork();
if($pid){
return $pid;
}else{
my $cmd = "$base_dir\/..\/bin\/monitor_real.pl -config $config -test";
close STDOUT;
exec ($cmd) or die "cannot exec test code [$cmd]\n";
}
}
sub KillMonitor{
my $pid = shift;
print "Killing monitor [$pid]\n";
kill(1,$pid);
}
</code></pre>
<p>However for some reason when I have my .t file spin up some extra processes it causes the test harness to hang at the end of the first .t file after all the tests have finished, rather than going on to the next file, or exiting if there is only one.</p>
<p>At first I wondered if it might be because I was killing of my sub-processes and leaving them defunct. So I added..</p>
<pre><code>$SIG{CHLD} = \&REAPER;
sub REAPER {
my $pid = wait;
$SIG{CHLD} = \&REAPER;
}
</code></pre>
<p>To the code. But that doesn't help. In fact on closed examination it turns out that my perl test file has exited and is now a defunct process and it is the prove wrapper script that has not reaped its child. In fact when I added a die() call at the end of my test script I got...</p>
<pre><code># Looks like your test died just after 7.
</code></pre>
<p>So my script exited but for some reason the harness isn't unraveling.</p>
<p>I did confirm that it is definitely my sub-processes that are upsetting it as when I disabled them while the tests failed the harness exited properly.</p>
<p>Is there anything I am doing wrong with the way I am starting up my processes that might upset the harness in some way?</p>
<p>Thanks</p>
<p>Peter</p>
|
<p><p>Note that you don't test whether <code>fork()</code> failed. You need to make sure <code>$pid</code> is <a href="http://perldoc.perl.org/functions/defined.html" rel="nofollow">defined</a> before assuming that "false" means "child."
<p>Because your <code>$cmd</code> contains shell metacharacters (spaces), Perl is actually using a shell when you call <code>exec()</code>. While your monitor is running, there's (1) Perl, (2) a child <code>sh -c</code>, and (3) a grandchild Perl running <code>monitor_real.pl</code>. What that means in particular is when you call <code>KillMonitor</code>, you're only killing the shell (because that's the PID you have) and not the monitor.
<p>You might also be interested in <a href="http://perldoc.perl.org/perlfaq8.html#How-do-I-fork-a-daemon-process%3f" rel="nofollow">How do I fork a daemon process?</a> from the Perl FAQ.</p>
|
Organization of JUnit tests in projects <p>What would you consider best practice for organizing JUnit tests in a project, and why? For example, do you keep your tests next to the classes they test? Do you put them in a separate but parallel package structure? Do you use a different organization strategy entirely?</p>
|
<p>I use a separate but parallel package structure for several reasons.</p>
<ol>
<li>It keeps tests organized the same way as the application code.
<li>I can easily build just the application files for distribution.
<li>Test code still has access to my application code.
<li>It's not as cluttered as having test code mixed with application code.
</ol>
|
How to tell if a URL parameter needs to be encoded in Java <p>I'm writing a Java app that is accepting URL parameter values that may or may not be encoded. I need an easy way to tell whether or not I need to encode the parameter string.</p>
<p>In other words, I want a function <code>boolean needsEncoding(String param)</code>, which will return true if I pass in the String "foo@test.com", and false if I pass in "foo%40test.com". The problem with this idea is that this is ambiguous. How would I know whether or not the "%" sign in the latter string should be encoded? One way to handle this is to modify my contract - require clients to pass in un-encoded strings so that I know I always need to encode them. Thoughts?</p>
|
<p>I thought I'd put this as a proposed answer so that people can vote:</p>
<p>One way to handle this is to modify my contract - require clients to pass in un-encoded strings so that I know I always need to encode them.</p>
|
Add ScriptManager to Page Programmatically? <p>I am developing a WebPart (it will be used in a SharePoint environment, although it does not use the Object Model) that I want to expose AJAX functionality in. Because of the nature of the environment, Adding the Script Manager directly to the page is not an option, and so must be added programmatically. I have attempted to add the ScriptManager control to the page in my webpart code.</p>
<pre><code>protected override void CreateChildControls()
{
if (ScriptManager.GetCurrent(Page) == null)
{
ScriptManager sMgr = new ScriptManager();
// Ensure the ScriptManager is the first control.
Page.Form.Controls.AddAt(0, sMgr);
}
}
</code></pre>
<p>However, when this code is executed, I get the following error message:</p>
<blockquote>
<p>"The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases."</p>
</blockquote>
<p>Is there another way to add the ScriptManager to the page from a WebPart, or am I going to have to just add the ScriptManager to each page (or master page) that will use the WebPart?</p>
|
<p>I was able to get this to work by using the Page's Init event:</p>
<pre><code>protected override void OnInit(EventArgs e)
{
Page.Init += delegate(object sender, EventArgs e_Init)
{
if (ScriptManager.GetCurrent(Page) == null)
{
ScriptManager sMgr = new ScriptManager();
Page.Form.Controls.AddAt(0, sMgr);
}
};
base.OnInit(e);
}
</code></pre>
|
Eclipse PDT and .yml file, cannot open? <p>I am using Symphony framework and I have the default sandbox inside the Eclipse IDE. When I double click schema.yml instead of open in Eclipse it requests Windows to select a program to choose. I am a Visual Studio guy and I do not understand why it doesn't open in Eclipse, what should I do?</p>
|
<p>Right click on the file, select OPEN WITH>Text Editor and it will open in the IDE</p>
|
Java Application Installers <p>I'm not looking for java-web-start, I'm looking for a thick-client application installation toolkit. I've got a stand-alone application that consists of several files (jar files, data files, etc) and would need to do some pretty standard installation tasks, like asking the user for target directories, have them locate some parts of their system - choose some of the per-machine or per-user configuration options and possibly try to detect some of the machine settings for them.</p>
<p>I'm looking for something which is like the MSI or other wizard driven installation applications. What's a good installer for Java? It would be ideal if it were cross-platform capable (Linux, Mac OSX and Windows).</p>
|
<p>Not an MSI-Installer but crossplatform: <a href="http://izpack.org/">izPack</a></p>
<p>It's xml-file based with it's own GUI or ant task (whtaever you prefer)</p>
|
How to get the most out of being a manual tester <p>As a student, I have just got my first co-op job as a manual tester. I know it is as intellectual and demanding a job as a coder, but I cannot help thinking the other way around. I love being a coder but it is my first job. So I am asking you for any advice on how I can get the most out of the manual <em>black-box</em> testing job, i.e how can I use it to improve my coding skills. Many thanks.</p>
|
<p>Automate the simple things you do frequently when manual testing. This doesn't always mean the actual testing, in most cases automated functional testing becomes harder and you get less for your time the further away you get from the code and the closer you get to the interface and the human brain. </p>
<p>So for example; when testing do you need to copy files and enter some values to run the software? Automate that. Do you need to have data populated in a database to help your tests? Automate that. Once simple stuff is automated and running smoothly you can tackle harder stuff. </p>
<p>Another bit of advice is to read and understand the source code commits that fix the bugs that you find if possible. You can learn a lot this way. </p>
|
Vista Window Focus Problem <p>I have an application that manages patient demographic information. Along with this data a user can scan a picture of a patient and assign that picture to a patient. When the user clicks the scan button a separate application is opened as a dialog in order to scan the image. When running this on XP everything worked fine. The imaging application loaded up fine and gained focus. On Vista however occasionally the imaging application will not gain focus and will popup behind the main application. When running full screen or through 2008 Application Server you cannot see the application, you only get a locked screen and it appears nothing has happened. Is there any way to change the window focus management on Vista to work the way XP did? I'm looking for a way to solve this without making changes to the actual application if possible.</p>
|
<p>I think you will have to make changes to your application to allow the imaging application to take the focus. I'm going to assume that your application launches the imaging application through <code>ShellExecute</code> or <code>CreateProcess</code>. If so, you can get the process handle of the launched process either through <code>SHELLEXECUTEINFO.hProcess</code> (for <code>ShellExecute</code>) or <code>PROCESS_INFORMATION.hProcess</code> (for <code>CreateProcess</code>). Immediately after launching the imaging application call the <a href="http://msdn.microsoft.com/en-us/library/ms632668(VS.85).aspx" rel="nofollow">AllowSetForegroundWindow</a> API:</p>
<pre><code>AllowSetForegroundWindow(GetProcessId(hProcess));
</code></pre>
<p>This will allow the imaging application to place its main window/dialog in the foreground when it's starting up.</p>
|
What do I need to do to upgrade an application to the latest Rails version? <p>I am currently using Rails 2.1.0 and want to upgrade to Rails 2.1.1. After issuing the following command </p>
<pre><code>gem update rails
</code></pre>
<p>I suppose that I need to change this line </p>
<pre><code>RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION
</code></pre>
<p>in environment.rb</p>
<p>What other actions should I take to ensure that my application is using the latest version? Are there some other files that need an update?</p>
|
<p>You'll also need to go into your application directory and run the following command:</p>
<p>rake rails:update</p>
<p>Then run your tests and make sure everything works.</p>
|
How to monitor MySQL space? <p>I downloaded a VM image of a web application that uses MySQL.</p>
<p>How can I monitor its space consumption and know when additional space must be added?</p>
|
<p>I have some great big queries to share:</p>
<p>Run this to get the Total MySQL Data and Index Usage By Storage Engine</p>
<pre><code>SELECT IFNULL(B.engine,'Total') "Storage Engine",
CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Data Size", CONCAT(LPAD(REPLACE(
FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Index Size", CONCAT(LPAD(REPLACE(
FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Table Size" FROM
(SELECT engine,SUM(data_length) DSize,SUM(index_length) ISize,
SUM(data_length+index_length) TSize FROM
information_schema.tables WHERE table_schema NOT IN
('mysql','information_schema','performance_schema') AND
engine IS NOT NULL GROUP BY engine WITH ROLLUP) B,
(SELECT 3 pw) A ORDER BY TSize;
</code></pre>
<p>Run this to get the Total MySQL Data and Index Usage By Database</p>
<pre><code>SELECT DBName,CONCAT(LPAD(FORMAT(SDSize/POWER(1024,pw),3),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Data Size",CONCAT(LPAD(
FORMAT(SXSize/POWER(1024,pw),3),17,' '),' ',SUBSTR(' KMGTP',pw+1,1),'B') "Index Size",
CONCAT(LPAD(FORMAT(STSize/POWER(1024,pw),3),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') "Total Size" FROM
(SELECT IFNULL(DB,'All Databases') DBName,SUM(DSize) SDSize,SUM(XSize) SXSize,
SUM(TSize) STSize FROM (SELECT table_schema DB,data_length DSize,
index_length XSize,data_length+index_length TSize FROM information_schema.tables
WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')) AAA
GROUP BY DB WITH ROLLUP) AA,(SELECT 3 pw) BB ORDER BY (SDSize+SXSize);
</code></pre>
<p>Run this to get the Total MySQL Data and Index Usage By Database and Storage Engine</p>
<pre><code>SELECT Statistic,DataSize "Data Size",IndexSize "Index Size",TableSize "Table Size"
FROM (SELECT IF(ISNULL(table_schema)=1,10,0) schema_score,
IF(ISNULL(engine)=1,10,0) engine_score,
IF(ISNULL(table_schema)=1,'ZZZZZZZZZZZZZZZZ',table_schema) schemaname,
IF(ISNULL(B.table_schema)+ISNULL(B.engine)=2,"Storage for All Databases",
IF(ISNULL(B.table_schema)+ISNULL(B.engine)=1,
CONCAT("Storage for ",B.table_schema),
CONCAT(B.engine," Tables for ",B.table_schema))) Statistic,
CONCAT(LPAD(REPLACE(FORMAT(B.DSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') DataSize,CONCAT(LPAD(REPLACE(
FORMAT(B.ISize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') IndexSize,
CONCAT(LPAD(REPLACE(FORMAT(B.TSize/POWER(1024,pw),3),',',''),17,' '),' ',
SUBSTR(' KMGTP',pw+1,1),'B') TableSize FROM (SELECT table_schema,engine,
SUM(data_length) DSize,SUM(index_length) ISize,
SUM(data_length+index_length) TSize FROM information_schema.tables
WHERE table_schema NOT IN ('mysql','information_schema','performance_schema')
AND engine IS NOT NULL GROUP BY table_schema,engine WITH ROLLUP) B,
(SELECT 3 pw) A) AA ORDER BY schemaname,schema_score,engine_score;
</code></pre>
<p>CAVEAT</p>
<p>In each query, you will see <code>(SELECT 3 pw)</code>. The pw stands for the Power Of 1024 to display the results.</p>
<ul>
<li><code>(SELECT 0 pw)</code> will Display the Report in Bytes</li>
<li><code>(SELECT 1 pw)</code> will Display the Report in KiloBytes</li>
<li><code>(SELECT 2 pw)</code> will Display the Report in MegaBytes</li>
<li><code>(SELECT 3 pw)</code> will Display the Report in GigaBytes</li>
<li><code>(SELECT 4 pw)</code> will Display the Report in TeraBytes</li>
<li><code>(SELECT 5 pw)</code> will Display the Report in PetaBytes (please contact me if you run this one)</li>
</ul>
<p>Here is a report query with a little less formatting:</p>
<pre><code>SELECT IFNULL(db,'Total') "Database",
datsum / power(1024,pw) "Data Size",
ndxsum / power(1024,pw) "Index Size",
totsum / power(1024,pw) "Total"
FROM (SELECT db,SUM(dat) datsum,SUM(ndx) ndxsum,SUM(dat+ndx) totsum
FROM (SELECT table_schema db,data_length dat,index_length ndx
FROM information_schema.tables WHERE engine IS NOT NULL
AND table_schema NOT IN ('information_schema','mysql')) AA
GROUP BY db WITH ROLLUP) A,(SELECT 1 pw) B;
</code></pre>
<p>Trust me, I made these queries over 4 years ago and still use them today.</p>
<h1>UPDATE 2013-06-24 15:53 EDT</h1>
<p>I have something new. I have changed the queries so that you do not have to set the <code>pw</code> parameter for different unit displays. Each unit display is calculated for you.</p>
<p>Report By Storage Engine</p>
<pre><code>SELECT
IFNULL(ENGINE,'Total') "Storage Engine",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT ENGINE,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
ENGINE,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT engine,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY ENGINE WITH ROLLUP
) AAA ) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
<p>Report By Database</p>
<pre><code>SELECT
IFNULL(DB,'Total') "Database",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT DB,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
DB,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT table_schema DB,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY DB WITH ROLLUP
) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
<p>Report By Database / Storage Engine</p>
<pre><code>SELECT
IF(ISNULL(DB)+ISNULL(ENGINE)=2,'Database Total',
CONCAT(DB,' ',IFNULL(ENGINE,'Total'))) "Reported Statistic",
LPAD(CONCAT(FORMAT(DAT/POWER(1024,pw1),2),' ',
SUBSTR(units,pw1*2+1,2)),17,' ') "Data Size",
LPAD(CONCAT(FORMAT(NDX/POWER(1024,pw2),2),' ',
SUBSTR(units,pw2*2+1,2)),17,' ') "Index Size",
LPAD(CONCAT(FORMAT(TBL/POWER(1024,pw3),2),' ',
SUBSTR(units,pw3*2+1,2)),17,' ') "Total Size"
FROM
(
SELECT DB,ENGINE,DAT,NDX,TBL,
IF(px>4,4,px) pw1,IF(py>4,4,py) pw2,IF(pz>4,4,pz) pw3
FROM
(SELECT *,
FLOOR(LOG(IF(DAT=0,1,DAT))/LOG(1024)) px,
FLOOR(LOG(IF(NDX=0,1,NDX))/LOG(1024)) py,
FLOOR(LOG(IF(TBL=0,1,TBL))/LOG(1024)) pz
FROM
(SELECT
DB,ENGINE,
SUM(data_length) DAT,
SUM(index_length) NDX,
SUM(data_length+index_length) TBL
FROM
(
SELECT table_schema DB,ENGINE,data_length,index_length FROM
information_schema.tables WHERE table_schema NOT IN
('information_schema','performance_schema','mysql')
AND ENGINE IS NOT NULL
) AAA GROUP BY DB,ENGINE WITH ROLLUP
) AAA) AA) A,(SELECT ' BKBMBGBTB' units) B;
</code></pre>
|
ASP.NET: How to convert <A> or HtmlAnchor to static text? <p>i have a repeater that will output a series of items:</p>
<pre><code><asp:repeater ... runat="Server">
<itemtemplate>
<a href="<%# GetItemLink(...) %>"><%# GetItemText %></a>
<itemtemplate>
<asp:repeater>
</code></pre>
<p>But some items will not have an associated link, so i don't want them to be clickable. i tried making it a <code>runat=server</code> <code>HtmlAnchor</code>, and set the <code>htmlAnchor.Disabled = true</code> for the items are should not actually have a link - but they can still be clicked (it just makes the text gray)</p>
<p>i know how i'd do it in the olden days:</p>
<pre><code><% If IsLink Then %>
<A href="<% =GetItemLink%">
<% End If %>
<% =GetItemText %>
<% If IsLink Then %>
</A>
<% End If %>
</code></pre>
<p>But that's the messy mixing code and html ASP way. What's the ASP.NET way?</p>
|
<p>Use an <asp:HyperLink > control, which displays the text normally if no link is supplied.</p>
<p><hr /></p>
<p>Edited to include example:</p>
<pre><code><asp:repeater ... runat="Server">
<itemtemplate>
<asp:HyperLink ... runat="server" NavigateUrl="<%# GetItemLink(...) %>"> <%# GetItemText %></asp:HyperLink>
<itemtemplate>
<asp:repeater>
</code></pre>
<p>In the above example, the anchor tag will be rendered to html regardless, but if the NavigateUrl attribute is an empty string, there will be no <code>href</code> at all and every browser I've ever used renders the text in a manner similar to spans (so look out for custom styles on <a >'s).</p>
|
Is there a Perl-compatible regular expression to trim whitespace from both sides of a string? <p>Is there a way to do this in one line?</p>
<pre><code>$x =~ s/^\s+//;
$x =~ s/\s+$//;
</code></pre>
<p>In other words, remove all leading and trailing whitespace from a string.</p>
|
<p>My first question is ... why? I don't see any of the single-regexp solutions to be any more readable than the regexp you started with. And they sure aren't anywhere near as fast.</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(:all);
my $a = 'a' x 1_000;
my @x = (
" $a ",
"$a ",
$a,
" $a"
);
cmpthese(-5,
{
single => sub {
for my $s (@x)
{
my $x = $s;
$x =~ s/^\s+|\s+$//g;
}
},
double => sub {
for my $s (@x)
{
my $x = $s;
$x =~ s/^\s+//;
$x =~ s/\s+$//;
}
},
trick => sub {
for my $s (@x)
{
my $x = $s;
s/^\s+//, s/\s+$// for $x;
}
},
capture => sub {
for my $s (@x)
{
my $x = $s;
$x =~ s/\A\s*(.*?)\s*\z/$1/
}
},
kramercap => sub {
for my $s (@x)
{
my $x = $s;
($x) = $x =~ /^\s*(.*?)\s*$/
}
},
}
);
</code></pre>
<p>gives results on my machine of:</p>
<pre>
Rate single capture kramercap trick double
single 2541/s -- -12% -13% -96% -96%
capture 2902/s 14% -- -0% -95% -96%
kramercap 2911/s 15% 0% -- -95% -96%
trick 60381/s 2276% 1981% 1974% -- -7%
double 65162/s 2464% 2145% 2138% 8% --
</pre>
<p><strong>Edit</strong>: runrig is right, but to little change. I've updated the code to copy the string before modification, which, of course, slows things down. I also took into account brian d foy's suggestion in another answer to use a longer string (though a million seemed like overkill). However, that also suggests that before you choose the trick style, you figure out what your string lengths are like - the advantages of trick are lessened with shorter strings. At all lengths I've tested, though, double wins. And it's still easier on the eyes.</p>
|
Has and belongs to many relationship with multiple databases <p>I have a situation where I have two models, companies and permissions, where companies is in a separate database from my permissions database. This is a has and belongs to many relationship because each company can have many permissions and each permission can belong to many companies.</p>
<p>The reason the two databases are split is because the company database runs a high demand production application and the permissions database controls the permissions for another application.</p>
<p>With rails, it looks for the join table in the same database as the primary table. For instance, if I do company.permissions, it looks in the company database for company_permissions. If I do permission.companies it looks in the permissions database.</p>
<p>What is the best solution to using a has and belongs to many relationship with multiple databases?</p>
|
<p>Interesting question. For the sake of my own reference, let me try to summarize the solution proposed in the <em>Rails Recipe</em> book in this question's context.</p>
<p>1) First add in <em>database.yml</em></p>
<pre><code>permissions:
adapter: mysql
database: permissions
username: root
password:
socket: /tmp/mysql.sock
</code></pre>
<p>2) Make Permission model to call external database</p>
<pre><code>class Permission < ActiveRecord::Base
establish_connection :permissions
end
</code></pre>
<p>3) Create (migrate) a <em>Permission Reference table</em> with <em>Permission Id</em> column</p>
<p>4) Use <em>PermissionReference</em> model as a link to <em>Permission</em> model</p>
<pre><code>class PermissionReference < ActiveRecord::Base
belongs_to :permission
has_and_belongs_to_many :companies,
:join_table => 'companies_permissions',
:foreign_key => 'permission_id'
end
</code></pre>
<p>5) Lastly associate Company to Permission</p>
<pre><code>class Company < ActiveRecord::Base
has_and_belongs_to_many :permissions,
:class_name => 'PermissionReference',
:join_table => 'companies_permissions',
:association_foreign_key => 'permission_id'
end
</code></pre>
<p>You might wanna consider refactoring by subclassing models that calls an external database</p>
<pre><code>class External < ActiveRecord::Base
self.abstract_class = true
establish_connection :permissions
end
class Permission < External
end
</code></pre>
|
What is the difference between a deep copy and a shallow copy? <p>What is the difference between a deep copy and a shallow copy?</p>
|
<p>Breadth vs Depth; think in terms of a tree of references with your object as the root node.</p>
<p>Shallow:</p>
<p><img src="http://upload.wikimedia.org/wikipedia/en/thumb/6/6c/Pre_shallow_deep_copy.svg/120px-Pre_shallow_deep_copy.svg.png" alt="Before Copy">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/3/3e/Shallow_copy_in_progress.svg/120px-Shallow_copy_in_progress.svg.png" alt="Shallow Copying">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/e/e1/Shallow_copy_done.svg/120px-Shallow_copy_done.svg.png" alt="Shallow Done"></p>
<p>The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.</p>
<p>Deep:</p>
<p><img src="http://upload.wikimedia.org/wikipedia/en/thumb/6/6c/Pre_shallow_deep_copy.svg/120px-Pre_shallow_deep_copy.svg.png" alt="Before Copy">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/5/5f/Deep_copy_in_progress.svg/120px-Deep_copy_in_progress.svg.png" alt="Deep Copying">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/0/00/Deep_copy_done.svg/120px-Deep_copy_done.svg.png" alt="Deep Done"></p>
<p>The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.</p>
|
ASP.NET session and storing objects that use COM interop <p>I'm working on an asp.net web site. We have to use com interop to interact with legacy vb6 activex components. The components in many cases rely on receiving a context object (which is itself a vb6 activex component) as a parameter. The context object is fairly costly to construct.</p>
<p>Therefore one idea is that a context object is constructed once and stored in asp.net session. However, if this object is just a .net wrapper around an activex component, is it wise or advisible to persist such an object in session?</p>
<p>Additionally the context object contains user specific information, so persisting using .net HttpRuntime Caching could be used, but would require a user specific key. </p>
<p>I understand the other limitations and things you need to be aware of with asp.net session, <a href="http://stackoverflow.com/questions/133236/aspnet-session">aspnet-session question</a>.</p>
<p>To ask the question a slightly different way: are their any issues or problems with storing an .net object that is just a wrapper around a com object? </p>
|
<p>I think you will very rapidly get problems with one request blocking another.</p>
<p>ASP.NET by default initialises COM on its threads to put the thread in a multi-threaded apartment. VB6 components were apartment-model at best. That means that when the MTA thread creates the component, it's put into the main STA if one already exists (which for ASP.NET worker processes, it won't) or a new thread is created specifically for the STA. It doesn't matter which MTA thread creates the component, the same STA is always used for the components that can't handle the MTA model. That means the same thread is used for every call to those components, so concurrent calls have to wait in line.</p>
<p>To tell ASP.NET to initialize COM for single-threaded components, which will at least cause the object to be created on the same thread as the executing page, add the <code>AspCompat</code> attribute to the <a href="http://msdn.microsoft.com/en-us/library/ydy4x04a.aspx" rel="nofollow">@Page</a> directive.</p>
<p>I would not cache the objects as they're very likely to have cross-thread issues when they're reused.</p>
|
How to get an error-code from a VB component into (serverside) JScript <p>I have an plain-old asp web site that makes a call to a method in a dll written in VB 6. This method sets an error code in the VB Err Object if something goes wrong. Now I want to access that error code and description set in the Err object from a javascript (where I do the call to the dll method). First: is it possible? Second: if it is possible, how can I do that? Thanks in advance!</p>
<p>My first idea was:</p>
<p><code></p>
<pre><code>Function MyFunc()
{
var obj = Server.CreateObject(âMyDll.MyClassâ);
try
{
obj.MyMethod();
}
catch(error)
{
// Here I want to get the error code and description from the VB Err object
}
}
</code></pre>
<p></code></p>
<p>However, when I try this, the error I get is wrong. (I tried to make a test-app which receives the same error.) I get an error-code which isn't the same in JavaScript as in VB.</p>
<p>Anyone know how this aught to be done?</p>
<p>/L</p>
|
<p>In your MyClass, add a property that holds the error info when an error event occurs, then you should be able to look at obj.MyErrorCode and find out what you need.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.