input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
.NET referenced assemblies - version numbers <p>I've recently taken over a project, and the original developer has gone. I'm now trying to install the app on a new server, and I've got a problem with dependent assembly versions.</p>
<p>The project is a reporting tool, with (unfortunately) a reference to Crystal. On my machine I have version 11.5.9500.313 of CrystalDecisions.CrystalReports.Engine.dll.</p>
<p>The NAnt script that does the build defines the references, including the Crystal dll, but does not define the version number.</p>
<p>When I build the app, using the NAnt script, and analyse the assembly with Reflector, the reference is for version 11.5.3300.0.</p>
<p>Can anyone explain where the version number of this reference comes from?</p>
| <p>It comes from the references in the vs. project file. Open the project file in a text editor and check it out. Anyway, to fix re-add the references in the visual studio.</p>
|
Why does Unity's RegisterInstance<...> cause Unity to return multiple instances? <p>Unity's documentation says of the RegisterInstance<> method that registers an instance so that <strong>that particular instance is returned everytime Resolve<> is called</strong>. </p>
<p>However, this example below shows that each time Resolve<> is called, <strong>a new instance of the type is returned</strong>.</p>
<p>Why is this?</p>
<pre><code>using System;
using System.Windows;
using Microsoft.Practices.Unity;
namespace TestUnity34
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Validator validator1 = new Validator();
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IValidator>(validator1);
Validator validatorCopied = validator1;
Console.WriteLine(validator1.GetHashCode()); //14421545
Console.WriteLine(validatorCopied.GetHashCode()); //14421545
Validator validator2 = container.Resolve<Validator>();
Console.WriteLine(validator2.GetHashCode()); //35567111
Validator validator3 = container.Resolve<Validator>();
Console.WriteLine(validator3.GetHashCode()); //65066874
}
}
interface IValidator
{
void Validate();
string GetStatus();
}
public class Validator : IValidator
{
public void Validate() { }
public string GetStatus() { return "test"; }
}
}
</code></pre>
| <p>You have configured your container with IValidator so you will have to resolve using IValidator instead of Validator:</p>
<pre><code>Validator validator1 = new Validator();
IUnityContainer container = new UnityContainer();
container.RegisterInstance<IValidator>(validator1);
Validator validatorCopied = validator1;
Console.WriteLine(validator1.GetHashCode());
Console.WriteLine(validatorCopied.GetHashCode());
IValidator validator2 = container.Resolve<IValidator>();
Console.WriteLine(validator2.GetHashCode());
IValidator validator3 = container.Resolve<IValidator>();
Console.WriteLine(validator3.GetHashCode());
</code></pre>
<p>Alternatively you can keep your registration using Validator but then you have to resolve using Validator as well:</p>
<pre><code>Validator validator1 = new Validator();
IUnityContainer container = new UnityContainer();
container.RegisterInstance<Validator>(validator1);
Validator validatorCopied = validator1;
Console.WriteLine(validator1.GetHashCode());
Console.WriteLine(validatorCopied.GetHashCode());
Validator validator2 = container.Resolve<Validator>();
Console.WriteLine(validator2.GetHashCode());
Validator validator3 = container.Resolve<Validator>();
Console.WriteLine(validator3.GetHashCode());
</code></pre>
|
OneWayToSource binding from readonly property in XAML <p>I'm trying to bind to a <code>Readonly</code> property with <code>OneWayToSource</code> as mode, but it seems this cannot be done in XAML:</p>
<pre><code><controls:FlagThingy IsModified="{Binding FlagIsModified,
ElementName=container,
Mode=OneWayToSource}" />
</code></pre>
<p>I get: </p>
<blockquote>
<p>The property 'FlagThingy.IsModified' cannot be set because it does not have an accessible set accessor.</p>
</blockquote>
<p><code>IsModified</code> is a readonly <code>DependencyProperty</code> on <code>FlagThingy</code>. I want to bind that value to the <code>FlagIsModified</code> property on the container. </p>
<p>To be clear: </p>
<pre><code>FlagThingy.IsModified --> container.FlagIsModified
------ READONLY ----- ----- READWRITE --------
</code></pre>
<p>Is this possible using just XAML?</p>
<hr>
<p><strong>Update:</strong> Well, I fixed this case by setting the binding on the container and not on the <code>FlagThingy</code>. But I'd still like to know if this is possible. </p>
| <p>Some research results for OneWayToSource...</p>
<p>Option # 1.</p>
<pre class="lang-cs prettyprint-override"><code>// Control definition
public partial class FlagThingy : UserControl
{
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());
}
</code></pre>
<pre class="lang-xml prettyprint-override"><code><controls:FlagThingy x:Name="_flagThingy" />
</code></pre>
<pre class="lang-cs prettyprint-override"><code>// Binding Code
Binding binding = new Binding();
binding.Path = new PropertyPath("FlagIsModified");
binding.ElementName = "container";
binding.Mode = BindingMode.OneWayToSource;
_flagThingy.SetBinding(FlagThingy.IsModifiedProperty, binding);
</code></pre>
<p>Option # 2</p>
<pre class="lang-cs prettyprint-override"><code>// Control definition
public partial class FlagThingy : UserControl
{
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());
public bool IsModified
{
get { return (bool)GetValue(IsModifiedProperty); }
set { throw new Exception("An attempt ot modify Read-Only property"); }
}
}
</code></pre>
<pre class="lang-xml prettyprint-override"><code><controls:FlagThingy IsModified="{Binding Path=FlagIsModified,
ElementName=container, Mode=OneWayToSource}" />
</code></pre>
<p>Option # 3 (True read-only dependency property)</p>
<p>System.ArgumentException: 'IsModified' property cannot be data-bound.</p>
<pre class="lang-cs prettyprint-override"><code>// Control definition
public partial class FlagThingy : UserControl
{
private static readonly DependencyPropertyKey IsModifiedKey =
DependencyProperty.RegisterReadOnly("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());
public static readonly DependencyProperty IsModifiedProperty =
IsModifiedKey.DependencyProperty;
}
</code></pre>
<pre class="lang-xml prettyprint-override"><code><controls:FlagThingy x:Name="_flagThingy" />
</code></pre>
<pre class="lang-cs prettyprint-override"><code>// Binding Code
Same binding code...
</code></pre>
<p>Reflector gives the answer:</p>
<pre class="lang-cs prettyprint-override"><code>internal static BindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, Binding binding, BindingExpressionBase parent)
{
FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata;
if (((fwMetaData != null) && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly)
{
throw new ArgumentException(System.Windows.SR.Get(System.Windows.SRID.PropertyNotBindable, new object[] { dp.Name }), "dp");
}
....
</code></pre>
|
Select item from a string of items <p>I have a string of email recipients in the format like this:</p>
<pre><code> DECLARE @recipients VARCHAR(MAX);
....
PRINT @recipients;
/* the result
person1@yahoo.com;person2@hotmail.com;person1@yahoo.com;...
*/
</code></pre>
<p>"SELECT DISTIECT ..." is a simple and powerful SQL statement, but it works against a table. Is there a simple way to select <strong>distinct</strong> recipient from the recipient list variable like FOR loop in C# or Ruby?</p>
<pre><code> FOR @recipient IN @recipients
BEGIN
-- send email to @recipient
END
</code></pre>
<p>By the way, I am using TSQL in SQL server 2005.</p>
| <p>Here's a solution for you that uses a temporary table.</p>
<pre><code>declare @emails varchar(2000)
set @emails = 'person1@yahoo.com;person2@hotmail.com;person1@yahoo.com;'
declare @results table (row int identity(1,1), email varchar(500))
while ((select charindex(';',@emails)) > 0)
begin
insert into @results select substring(@emails,1,charindex(';',@emails))
select @emails = substring(@emails,charindex(';',@emails)+1,len(@emails))
end
select distinct email from @results
</code></pre>
<p>The idea is to continously parse the email from the string, insert it into a temporary table, and remove the parsed email from the remaining string.</p>
<p>You can use loop through the temporary table afterward to send your individual emails.</p>
|
winforms newbie trying to get into wpf, looking for resources <p>I am brand new in the world of Wpf, and am thinking it's time to get into it for my next project. </p>
<p>I'm a hardcore Winforms guy. Many of my projects perform tons of custom drawing - for example drawing a virtual baseball strike zone and then drawing icons to represent pitches thrown by a pitcher or seen by a batter. The pitches are interactive - the user can select one or multiple pitches (click, shift-click, rectangle drag) and then play video of the selected pitches.</p>
<p>I also have applications where I draw custom objects and then allow the user to drag them around and place them on a blank canvas.</p>
<p>I am trying to learn how one would do these types of things in the Wpf world. I got my first "hello world" graphic program working today, where I overrode ArrangeOverride and drew some lines on a blank window. But I've been reading about UIElement classes and Adorners and want to make sure I'm doing things "the right way". Should all my pitches be their own UIElements, for example?</p>
<p>I'm wondering if someone can guide me to some sample code or a book or article to get me started. If I could see "the right way" to create a custom drawn object (of any complexity, a simple rectangle would be fine), have the user select it (highlighting it somehow to show that it's selected) and then have the user drag it around the Wpf window, I would be well on my way.</p>
| <p>I also come from a WinForms background and the best book I've found is "Windows Presentation Foundation Unleashed" by Adam Nathan. </p>
<p>Amazon: <a href="http://rads.stackoverflow.com/amzn/click/0672328917" rel="nofollow">http://www.amazon.com/Windows-Presentation-Foundation-Unleashed-WPF/dp/0672328917</a></p>
<p>It's a very XAML focused book. I feel is very important for a WinForms guy because you have to get out of the mindset that code controls your UI. XAML is kind in the WPF world and you need to get into the habbit of starting in XAML vs. code. </p>
|
How to get Unity's automatic injection to work on interface injected constructors? <p>The Unity documentation states:</p>
<blockquote>
<p><em>if a class that developers instantiate
using the Resolve method of the Unity
container has a constructor that
defines one or more dependencies on
other classes, <strong>the Unity container
automatically creates the dependent
object instance</strong> specified in
parameters of the constructor</em></p>
</blockquote>
<p>This is great, but most often I don't specify <strong><em>classes</em></strong> for injection but <strong><em>interfaces</em></strong>, so as to keep things decoupled.</p>
<p>So how can I take advantage of Unity's automatic injection when I .Resolve<> <strong>a class which specifies interface injection</strong> instead of class injection?</p>
<p>i.e. in the following code, how can I make it work when I change my Customer constructor to "<strong>public Customer(ILogger logger)</strong>"?</p>
<pre><code>using System;
using Microsoft.Practices.Unity;
namespace TestUnityInjection23
{
public class Program
{
static void Main(string[] args)
{
Customer customer1 = new Customer(new BasicLogger());
//Customer customer2 = new Customer(new AdvancedLogger()); //can't use this since Customer only accepts BasicLogger
UnityContainer container = new UnityContainer();
container.RegisterType<Customer>();
container.RegisterType<ILogger, BasicLogger>();
Customer customer3 = container.Resolve<Customer>();
Console.ReadLine();
}
}
public class Customer
{
public Customer(BasicLogger logger) //would like to have Customer depend on ILogger here so logger can be swapped out
{
logger.WriteToLog("creating the customer");
}
}
public interface ILogger
{
void WriteToLog(string text);
}
public class BasicLogger : ILogger
{
public void WriteToLog(string text)
{
Console.WriteLine(text);
}
}
public class AdvancedLogger : ILogger
{
public void WriteToLog(string text)
{
Console.WriteLine("*** {0} ***", text);
}
}
}
</code></pre>
| <p>I've never used Unity, but every other DI framework I know does that and I'm sure Unity must do that too. </p>
<p>Have you tried changing the Customer constructor and seeing if it works? Cos it should.</p>
|
Recent Windows Updates and Credentials <p>Hi I recently applied Windows Updates to my server and all of a sudden most of my applications which have credentials such as DefaultNetworkCredentials or hard-coded username/passwords have stopped working. I am unable to get these functioning... is this a known issue? Any work arounds? Thank you.</p>
| <p>Here is your approach:</p>
<ul>
<li>figure out what is not working</li>
<li>figure out what was installed during the update</li>
<li>figure out which of the updated components caused the problem</li>
<li>take steps to either roll-back the update or fix your application</li>
</ul>
|
WPF - Creating a custom ItemsControl <p>I'm looking into creating custom controls for WPF and I've found some reasonably useful blogs and such that vaguely go into enough detail but I'm still struggling a bit.</p>
<p>Basically, what I'm trying to create is something akin to the infamous 'Coda Slider' but i just don't know enough to get started properly. Can anyone either point me in the direction of someone/somewhere to give me the low-down on creating custom ItemControls or provide me with the basic information like what ItemsControl members i need to override?</p>
<p>All help would be graciously received.</p>
| <p>Building a <strong>custom WPF control</strong> is nothing more than writing a class and inheriting the class from a base class that is provided in WPF.</p>
<p><a href="http://nayyeri.net/blog/how-to-create-a-custom-wpf-control/" rel="nofollow">How to Create a Custom WPF Control</a></p>
|
Web site reports xxx does not exist in current context after upgrade to VS2008 Sp1 <p>I just upgraded to VS2008 Sp1, and I have a weird issue going on. I get a lot of errors from my code behind pages indicating that a control doesn't exist in the current context and I am also getting an errors that the pages do not have methods. </p>
<p>It seems like ide is trying to compile the c# code without compiling the aspx code.</p>
<p>The site runs fine via both IIS and Visual Web Developer, and in fact when I open up the code behind page, all the errors go away. Anyone have any idea why VS2008 SP1 is behaving this way? </p>
<p>I am using C#, and the Web Site project mode.</p>
| <p>Check to make sure you are targeting the correct version of the .NET Framework. You can view this in the properties of the Solution file.</p>
<p>VS2008 allows you to target multiple framework versions.</p>
<p>Also check the Web.config, I know there can be differences between VS Web Developer and VS Standard/Pro with the web config. Maybe copy a fresh web.config file into the project.</p>
|
Interactive services dialog detection in Windows Vista <p>I have installed cc.net 1.4.3 version on Windows Vista. But It keeps giving me Interactive services dialog detection when I execute tests. I even have disabled the interactive services from services panel. but still getting this.</p>
<p>Any idea how to get rid of this problem
regards
Sam</p>
| <p>No easy fix that you can do. The service is trying to pop up UI on the user desktop. In XP this worked because services and the first user log on both run in session 0. In Vista, services run in session 0 and the first user runs in session 1, so there is no way for a service to directly show UI to the user. This was due to security issues - search for Win32 Shatter Attack to get more details, but basically an untrusted user could send malformed window messages to the services, and in some cases could even cause arbitrary code execution.</p>
<p>You can disable it altogether by disabling the "Interactive Services Detection" service on the system. But you won't see notifications at all, and this will disable it for all interactive services. Best approach is to complain to the vendor to update their software for Vista.</p>
<p>EDIT: And the software is broken on XP when multiple users are logged on and the active user isn't in session 0.</p>
|
Extract substring from string with Regex <p>Imagine that users are inserting strings in several computers.</p>
<p>On one computer, the pattern in the configuration will extract some characters of that string, lets say position 4 to 5.
On another computer, the extract pattern will return other characters, for instance, last 3 positions of the string.</p>
<p>These configurations (the Regex patterns) are different for each computer, and should be available for change by the administrator, without having to change the source code.</p>
<p>Some examples:</p>
<pre><code> Original_String Return_Value
User1 - abcd78defg123 78
User2 - abcd78defg123 78g1
User3 - mm127788abcd 12
User4 - 123456pp12asd ppsd
</code></pre>
<p>Can it be done with Regex?
Thanks.</p>
| <p>Why do you want to use regex for this? What is wrong with:</p>
<pre><code>string foo = s.Substring(4,2);
string bar = s.Substring(s.Length-3,3);
</code></pre>
<p>(you can wrap those up to do a bit of bounds-checking on the length easily enough)</p>
<p>If you really want, you could wrap it up in a <code>Func<string,string></code> to put somewhere - not sure I'd bother, though:</p>
<pre><code>Func<string, string> get4and5 = s => s.Substring(4, 2);
Func<string,string> getLast3 = s => s.Substring(s.Length - 3, 3);
string value = "abcd78defg123";
string foo = getLast3(value);
string bar = get4and5(value);
</code></pre>
|
What are the advantages of using generics in method signatures? <p><strong>(Thanks everyone for the answers, <a href="http://stackoverflow.com/questions/659232/it-this-an-example-of-the-single-responsibility-principle">here is my refactored example</a>, in turn another StackOverflow question about the Single Responsibility Principle.)</strong></p>
<p>Coming from PHP to C#, this syntax was intimidating:</p>
<pre><code>container.RegisterType<Customer>("customer1");
</code></pre>
<p>until I realized it expresses the same thing as:</p>
<pre><code>container.RegisterType(typeof(Customer), "customer1");
</code></pre>
<p>as I demonstrate in the code below.</p>
<p>So <strong>is there some reason why generics is used here</strong> (e.g. throughout Unity and most C# IoC containers) other than it just being a cleaner syntax, i.e. you don't need the typeof() when sending the type?</p>
<pre><code>using System;
namespace TestGenericParameter
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
container.RegisterType<Customer>("test");
container.RegisterType(typeof(Customer), "test");
Console.ReadLine();
}
}
public class Container
{
public void RegisterType<T>(string dummy)
{
Console.WriteLine("Type={0}, dummy={1}, name of class={2}", typeof(T), dummy, typeof(T).Name);
}
public void RegisterType(Type T, string dummy)
{
Console.WriteLine("Type={0}, dummy={1}, name of class={2}", T, dummy, T.Name);
}
}
public class Customer {}
}
//OUTPUT:
//Type=TestGenericParameter.Customer, dummy=test, name of class=Customer
//Type=TestGenericParameter.Customer, dummy=test, name of class=Customer
</code></pre>
| <p>A primary reason is the type safety at compile time. If you are passing two <code>Type</code> objects you are placing the responsibility at the developer instead of the compiler.</p>
<p>This is also why many IoC containers utilizes it, as your compiler will complain if an concrete type isn't inheriting the abstract type.</p>
<pre><code>public void Register<TAbstract, TConcrete>() where TConcrete : TAbstract
{
}
</code></pre>
<p>This code will only work if <code>TConcrete</code> is implementing or inheriting <code>TAbstract</code>. If this method took two <code>Type</code> parameters, your method should validate this relationship.</p>
|
Passing stored procedure to sp_send_dbmail <p>I am using sp_send_dbmail in SQL Server 2008 to send out the results of a query. I moved the query into a proc and am trying to use the proc in the sp_send_dbmail prcedure like so:</p>
<pre><code>EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'myprofile',
@from_address = 'email@somedomain.com',
@reply_to = 'email@somedomain.com',
@recipients = 'email@differentdomain.com',
@importance = 'NORMAL',
@sensitivity = 'NORMAL',
@subject = 'My Subject',
@body = 'Here you go.',
@attach_query_result_as_file= 1,
--@query_result_header = 1,
@query_result_width = 1000,
@query_result_separator = '~',
@query_attachment_filename = 'myFile.txt',
@query = 'EXEC dbo.myProc'
</code></pre>
<p>I have also tried this using 4 part naming on the proc; with and without the 'EXEC', etc. It worked fine as a query, but I cannot seem to get it to work as a proc. Is this even possible?</p>
| <p>You need to add the database context:</p>
<pre><code>@execute_query_database = 'MyDatabaseName',
</code></pre>
<p>I just ran this with no problems against AdventureWorks2008:</p>
<pre><code>EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DBMail',
@recipients = 'mitch@domain.com',
@query = 'exec dbo.uspGetManagerEmployees 5' ,
@execute_query_database = 'AdventureWorks2008',
@subject = 'Work Order Count',
@attach_query_result_as_file = 1 ;
</code></pre>
|
PHP Get Rid of Nasty \n Squares <p>Hardest problem to explain:</p>
<pre><code>$lol = "hello";
$that = "* music
* books
* games
* asos
* cry";
$lol = str_replace("*", $line, $that);
$name = str_replace(" ", "-", $line);
$myFile = "output/$name.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $lol;
fwrite($fh, $stringData);
fclose($fh);
</code></pre>
<p>I'm running through a big list of $lol variables and generating a text file for each of them, you can see the template for the text files in $that where * will become whichever $lol is in the loop.</p>
<p>So if $lol = "softlayer" I would get a csv with</p>
<pre><code>softlayer music
softlayer books
softlayer games
etc..
</code></pre>
<p>Problem is when I open them in notepad they aren't the softlayer music, etc are all on the same line seperated by those horrible squares which mean 'new line'. And because of this the CSV's I'm generating are supposedly invalid according to the software I'm trying to use them with.</p>
<p>That was an absolutely horrible problem to explain so excuse me :)</p>
<p>Any help would be massively appreciated!</p>
| <p>In the mists of pre-history, the Windows Folk, Mac Folk, and Unix folk couldn't agree on what character(s) should denote the end of a line. On classic Mac OS, it was a carriage return (\r). On Unix, it was a newline (\n). On windows, it was a carriage return followed by a newline (\r\n).</p>
<p>Historically speaking, on old typewriters you had to do <strong>two things</strong> to get the head onto a new line. A carriage return (the big arm thing) would move the typewriter head back to the left side (or right side; shalom!) of the paper. However, the head would still be on the same line. You've have to engage a second mechanism (line feed or newline) to move the paper itself up a single line. </p>
<p>One of the reasons for the ASCII standard was to encode data that was going to be later printed out (via telegraph, teletype, etc.) so having both characters in the standard made sense. When it came time to decide on a standard for files whose primary purpose was to live in a computer, no one would could agree. The windows standard (\r\n) makes the most literal sense, but the Unix and Classic Mac standards (\n for Unix, \r for Classic Mac) saved a bit per-line, which was important in the early days.</p>
<p>This has caused confusion for decades, and will continue to cause confusion into the future. This is particularly true when using Unix tools in a windows environment. A lot of these tools assume a \n as a line ending. Additionally, it's possible your PHP source file is encoded with unix style line endings, which means a string separated over several lines is actually split up by \n newlines, and your program is behaving correctly.</p>
<p>Most modern text editors will figure out how a text file is encoded, and display the lines "as intended" by the author. Notepad doesn't work like that, and obeys what's literally in the text file.</p>
<p>Irrespective of all that, the following reg ex should normalize your line endings to what's standard on windows</p>
<pre><code>$stringData = preg_replace('/[\n\r]{1,2}$/',"\r\n",$stringData);
</code></pre>
<p>Alternately, you could construct your string to end with carriage-return/line-feed</p>
<pre><code>$string = "line 1\r\nline 2";
$string = "line 1\r\n".
"line 2\r\n";
</code></pre>
|
Visual SVN Specify URL with new port <p>Our SVN server was initially setup to run on port 443, we had to change it to run on port 8443 because it was causing conflicts with IIS.</p>
<p>My question is how do I change the repository URL of all my projects to point to the new address? </p>
| <p>select your projects folder click realocate in the subversion menu and add the new address</p>
|
RegisterDeviceNotification Returns NULL but notifications still recieved <p>I'm using RegisterDeviceNotification to watch for changes to a USB device, using the WM_DEVICECHANGE event. However, when I call RegisterDeviceNotification() it returns NULL for the notification handle, which should indicate that it failed. But GetLastError() returns ERROR_SUCCESS and the notifications actually go through.<br />
This causes real trouble when I, later on, need to UnRegister for notifications and then re-register. Since the handle it returned was NULL, I can't actually re-register. If I try, RegisterDeviceNotification() just hangs.</p>
<p>My code is as follows:</p>
<pre><code>DEV_BROADCAST_HANDLE devBrHdr;
::ZeroMemory( &devBrHdr,sizeof( DEV_BROADCAST_HANDLE ) );
devBrHdr.dbch_size = sizeof( DEV_BROADCAST_HANDLE );
devBrHdr.dbch_devicetype = DBT_DEVTYP_HANDLE;
devBrHdr.dbch_handle = m_hDriver;
m_hDevNotify = ::RegisterDeviceNotification( hWnd,&devBrHdr,DEVICE_NOTIFY_WINDOW_HANDLE );
</code></pre>
<p>m_hDriver is the Handle to the driver, which I opened earlier, upon connecting to the device (a USB barcode scanner).</p>
<p>Any ideas what I'm doing wrong here?</p>
| <ol>
<li><p>Make sure you are not making another Win32 API call between <code>RegisterDeviceNotification</code> and <code>GetLastError</code>.</p></li>
<li><p>Check the value of <code>devBrHdr.dbch_hdevnotify</code>. It should contain the same handle returned by <code>RegisterDeviceNotification</code>.</p></li>
<li><p>Was the <code>m_hDriver</code> value obtained from a call to <code>CreateFile</code>?</p></li>
</ol>
|
EntLib 4.0: Exception Handling Application Block <p>I'm just starting to use the Enterprise Library Exception Handling block.</p>
<p>It seems a little cumbersome. </p>
<p>Do I really have to do </p>
<pre><code> try
{
//Do something with a DirectoryInfo object
}
catch(DirectoryNotFoundException ex)
{
bool rethrow = ExceptionPolicy.Handle(ex, _exceptionPolicyName);
if(rethrow)
throw;
}
</code></pre>
<p>Everywhere I want to handle exceptions?</p>
<p>Or should I just wrap the top level in </p>
<pre><code> try
{
//Entrypoint code
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.Handle(ex, _exceptionPolicyName);
if(rethrow)
throw;
}
</code></pre>
<p>I was under the impression I could aspect this on with attributes?</p>
| <p>How many places do you need to handle exceptions?</p>
<p>This Application Block is mainly used for handling exceptions on the boundaries of layers. For instance, the top-level code of your Data Access Layer might use this so you can configure whether and how to log DAL exceptions, whether to wrap a non-DAL exception, etc. But your private, inner methods should not handle exceptions at all.</p>
<p>And no, EAL doesn't do attributes.</p>
|
Url Hash with Html Base Tag <h2>window.location.hash</h2>
<p>When using a link for a javascript action, I usually do something like this:</p>
<pre><code><a href="#">Link Text</a>
</code></pre>
<p>That way, when someone clicks the link before the page loads nothing terrible happens.</p>
<h2>Html Base Tag</h2>
<p>On my current project I use this same construct, but with a base tag:</p>
<pre><code><html>
<head>
<base href="http://example.com/" />
</head>
<body>
<a href="#">Link Text</a>
</body>
</html>
</code></pre>
<p>However, if the page url is:</p>
<pre><code>http://example.com/dir/page
</code></pre>
<p>clicking the link navigates to</p>
<pre><code>http://example.com/#
</code></pre>
<p>rather than</p>
<pre><code>http://example.com/dir/page#
</code></pre>
<p>How can I fix this?</p>
| <p>Either remove your <code>base</code> tag or change your <code>href</code> attributes to be fully qualified. What you are observing is the intended behavior when you mix <code>base</code> with <code>a</code> elements.</p>
|
Ruby on Rails ActiveRecord conditional validation (and more..) <p>I have a <strong>Product</strong> model which validates multiple attributes (including a Paperclip image attachment) like so:</p>
<pre><code>validates_presence_of :name
validates_format_of :name, :with => /^([a-zA-Z0-9\ \-]{3,128})$/i
...
has_attached_file :image
validates_attachment_presence :image
validates_attachment_content_type :image, :content_type => ["image/jpeg", "image/png", "image/gif"]
</code></pre>
<p>Everything is working fine. What I want now is to make an <em>(unobtrusive) hidden iframe in-place upload script</em> using javascript. My problem is that I cannot just upload the image without the rest of the data, because it will fail validation (no name present) and also I cannot send the rest of the form without the image (same thing, fails validation).</p>
<p>So basically what I need (and don't know how to achieve) is to conditionally apply the model validations according to what the action is currently in progress (uploading the image or editing other data). </p>
<p>I hope I was clear enough. Any help is appreciated. Thanks.</p>
| <p><a href="http://railscasts.com/episodes/41-conditional-validations" rel="nofollow">Railscasts</a> have a nice video screencast about conditional validations.</p>
|
Why is there a special new and delete for arrays? <p>What is wrong with using <code>delete</code> instead of <code>delete[]</code>?</p>
<p>Is there something special happening under the covers for allocating and freeing arrays?</p>
<p>Why would it be different from <code>malloc</code> and free?</p>
| <p>Objects created with <code>new[]</code> must use <code>delete[]</code>. Using delete is undefined on arrays.</p>
<p>With malloc and free you have a more simple situation. There is only 1 function that frees the data you allocate, there is no concept of a destructor being called either. The confusion just comes in because <code>delete[]</code> and delete look similar. Actually they are 2 completely different functions.</p>
<p>Using delete won't call the correct function to delete the memory. It should call delete[](void*) but instead it calls delete(void*). For this reason you can't rely on using delete for memory allocated with <code>new[]</code></p>
<p><a href="http://www.parashift.com/c%2B%2B-faq-lite/freestore-mgmt.html#faq-16.13">See this C++ FAQ</a></p>
<blockquote>
<p>[16.13] Can I drop the <code>[]</code> when
deleteing array of some built-in type
(char, int, etc)?</p>
<p>No!</p>
<p>Sometimes programmers think that the
<code>[]</code> in the <code>delete[] p</code> only exists so
the compiler will call the appropriate
destructors for all elements in the
array. Because of this reasoning, they
assume that an array of some built-in
type such as <code>char</code> or <code>int</code> can be
<code>delete</code>d without the <code>[]</code>. E.g., they
assume the following is valid code:</p>
<pre><code>void userCode(int n) {
char* p = new char[n];
...
delete p; // â ERROR! Should be delete[] p !
}
</code></pre>
<p>But the above code is wrong, and it
can cause a disaster at runtime. In
particular, the code that's called for
<code>delete p</code> is <code>operator delete(void*)</code>,
but the code that's called for
<code>delete[] p</code> is <code>operator
delete[](void*)</code>. The default behavior
for the latter is to call the former,
but users are allowed to replace the
latter with a different behavior (in
which case they would normally also
replace the corresponding new code in
operator <code>new[](size_t)</code>). If they
replaced the <code>delete[]</code> code so it
wasn't compatible with the delete
code, and you called the wrong one
(i.e., if you said <code>delete p</code> rather
than <code>delete[] p</code>), you could end up
with a disaster at runtime.</p>
</blockquote>
<p><strong>Why does delete[] exist in the first place?</strong></p>
<p>Whether you do x or y:</p>
<pre><code> char * x = new char[100];
char * y = new char;
</code></pre>
<p>Both are stored in char * typed variables. </p>
<p>I think the reason for the decision of delete, and delete[] goes along with a long list of decisions that are in favor of efficiency in C++. It is so that there is no enforced price to do a lookup of how much needs to be deleted for a normal delete operation. </p>
<p>Having 2 new and new[] seems only logical to have delete and delete[] anyway for symmetry. </p>
|
<h2> background-color is not changing with Jquery? <p>I have an h2 element with an id of title and I have the following script:</p>
<pre><code><script type="text/javascript">
$(document).ready(function(){
$("#title").css("background-color","red");
)};
</script>
</code></pre>
<p>The background-color is not changing though and I can't figure out why?</p>
<pre><code><html>
<head>
<title>Table Sorter</title>
<script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/js/jquery.tablsorter.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#title").css("background-color","red");
)};
</script>
</head>
<body>
<h2 id="title">Table Sorter</h2>
</body>
</html>
<script type="text/javascript">
$(document).ready(function()
{
$("#title").css("background-color","red");
$("#myTable").tablesorter();
}
);
</script>
</code></pre>
| <p>Replace</p>
<pre><code><link type="text/javascript" src="/js/jquery-1.3.2.min.js"/>
</code></pre>
<p>with</p>
<pre><code><script type="text/javascript" src="/js/jquery-1.3.2.min.js"></script>
</code></pre>
<p>You also have a syntax error in your jQuery function at the closing brackets. They should be</p>
<pre><code>$(document).ready(function(){
$("#title").css("background-color","red");
});
</code></pre>
<p>If that <em>still</em> does not fix your problem, then put an alert in there like this...</p>
<pre><code>$(document).ready(function(){
alert("Howdy!");
});
</code></pre>
<p>If you do not see the alert message, then your jQuery script is not loaded, which means the relative path in the SRC attribute is incorrect.</p>
|
Tools and tutorials for examining the gen 2 heap <p>So you're at that time in your project when looking at Performance monitor, wondering "why is my gen 2 heap so large??"</p>
<p>That's where I am, currently. I'm interested in tools and tutorials for examining the contents of the gen 2 heap (and, by extension, gen 1 and 0 and the LOH).</p>
| <p>You could try the <a href="http://memprofiler.com/OnlineDocs/default.htm?turl=introduction.htm" rel="nofollow">.NET Memory Profiler</a>. It has the ability to track <a href="http://memprofiler.com/OnlineDocs/default.htm?turl=heaputilizationtracker.htm" rel="nofollow">heap space utilization</a>.</p>
|
Java stack trace on Windows <p>I need to get a stack trace for a JVM process running on a client machine that uses windows.</p>
<p>The client has the JRE installed but not the JDK. </p>
<p>I want to use JStack but it is not installed and we can't install a JDK on the client's machine. I also tried using AdaptJ stack trace product from a Java Webstart Session but that didn't work because we remote in and get an error about not being the session that started the application at a specified PID.</p>
<p>Essentially I want a way to install JStack without installing the JDK.</p>
| <p>You probably want to use <a href="http://www.latenighthacking.com/projects/2003/sendSignal/">SendSignal</a>, which was designed for exactly this purpose.</p>
|
Does this Ruby code look up identifiers or the values associated with them? <p>I've been trying to understand this example Ruby code <a href="http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol" rel="nofollow">from a blog entry</a> which says it uses the symbols :DEFAULT, :say and :@message "to look up identifiers". But from what I can tell, it's not looking up the identifiers, but the values associated with those identifiers. I thought identifiers are names of variables, methods, etc. So the identifiers would be "<strong>DEFAULT</strong>", "<strong>say</strong>" and "<strong>message</strong>"? The output of the program is below.</p>
<p>Also, why would you need to look up an identifier?</p>
<pre><code>class Demo
# The stuff we'll look up.
DEFAULT = "Hello"
def initialize
@message = DEFAULT
end
def say() @message end
# Use symbols to look up identifiers.
def look_up_with_symbols
[Demo.const_get(:DEFAULT),
method(:say),
instance_variable_get(:@message)]
end
end
dem = Demo.new
puts dem.look_up_with_symbols
</code></pre>
<p>When I run the code I get this output:</p>
<pre><code>Hello
#<Method: Demo#say>
Hello
</code></pre>
| <p>The sample code uses symbols to get at three things: the value of the <code>DEFAULT</code> const (accessed via <code>:DEFAULT</code>), a method object (accessed via <code>:say</code>), and the value of an instance variable (accessed via <code>:@message</code>). None of the three objects were defined using a symbol, yet you can use symbols to access them.</p>
<p>It's a fairly trivial example. The larger point is that symbols can be used to refer to constants, methods, and instance variables, if for some reason you don't want to refer to them directly via their identifiers. I see this most often used in metaprogramming.</p>
|
Transaction implementation for a simple file <p>I'm a part of a team writing an application for embedded systems. The application often suffers from data corruption caused by power shortage. I thought that implementing some kind of transactions would stop this from happening. One scenario would include copying the area of a file before writing to some additional storage (transaction log). What are other possibilities?</p>
| <p>Databases use a variety of techniques to assure that the state is properly persisted.</p>
<ol>
<li><p>The DBMS often retains a replicated control file -- several synchronized copies on several devices. Two is enough. More if your're paranoid. The control file provides a few key parameters used to locate the other files and their expected states. The control file can include a "database version number".</p></li>
<li><p>Each file has a "version number" in several forms. A lot of times it's in plain form plus in some XOR-complement so that the two version numbers can be trivially checked to have the correct relationship, and match the control file version number.</p></li>
<li><p>All transactions are written to a transaction journal. The transaction journal is then written to the database files.</p></li>
<li><p>Before writing to database files, the original data block is copied to a "before image journal", or rollback segment, or some such.</p></li>
<li><p>When the block is written to the file, the sequence numbers are updated, and the block is removed from the transaction journal.</p></li>
</ol>
<p>You can read up on RDBMS techniques for reliability.</p>
|
How well does SVN work for Office 2007 documents? <p>I'm considering using our SVN repository to manage all our documents. We mostly use Office 2007 (docx, xlsx) files. I thought the x was for xml but opening these files in notepad reveals a binary format. </p>
<p>I'm looking to find out what people's experience is with using svn to manage these kinds of files. Someone told me that SVN isn't so great for binary files. </p>
| <p>They are xml, mostly, but they're in a zipped format. In other words, try renaming the file to .zip and check how it looks then.</p>
<p>And no, SVN won't work terribly well with that format. I mean, it will certainly be able to store them, but it won't be able to diff them, and parallel editing won't work either.</p>
<p>The real benefits of SVN is with parallel working on the files (ie. two people working on the same files at the same time) and merging the changes later. Binary files won't work with that.</p>
|
How can I migrate TFS source from one team project to another? <p>We've decided to go with a different template for our team project and want to move all of source under that team project. We are not concerned with migrating work items, but we would like to keep the version history of the source files, if possible. I tried the TFS to TFS migration tool on code plex and it seems to only move the most recent version of each source file over.</p>
<p>We are on TFS 2008 and the team projects are on the same server.</p>
<p>EDIT: It looks like the move function may work. I've seen some concerns posted about whether or not this moves all the history for a given file.</p>
| <p>If you do a move from within TFS, that should register as just another action to be saved in the history. Your other history should be kept intact, even when moving across projects.</p>
|
What is your favorite open source debugging tool? <p>I've been giving a talk recently on a plethora of Open Source (some are borderline open-source, I'll admit) debugging tools and the audiences have been making great additions to my list.</p>
<p>I'd like to gather the knowledge (and give credit) to the oft-brilliant StackOverflow crowd on this same question.</p>
<p>There are no WebService/Java/.Net/HTML/Perl constraints of programming languages to this question. So far, I've been pontificating about:</p>
<ol>
<li><a href="http://developer.apple.com/DOCUMENTATION/Darwin/Reference/ManPages/man1/fs%5Fusage.1.html" rel="nofollow">fs_usage</a> for finding what keeps writing to disk so much</li>
<li><a href="http://www.akadia.com/services/lsof%5Fintro.html" rel="nofollow">lsof</a> for debugging what ports or files are open</li>
<li><a href="http://www.tcpdump.org/" rel="nofollow">tcpdump</a>, <a href="http://www.wireshark.org/" rel="nofollow">wireshark</a>, <a href="http://www.baurhome.net/software/eavesdrop/" rel="nofollow">eavesdrop</a> for looking at your network traffic (malformed data?)</li>
<li><a href="http://getfirebug.com/" rel="nofollow">firebug</a> for debugging css, javascript, and page loading issues</li>
<li><a href="http://www.soapui.org/" rel="nofollow">SoapUI</a>, <a href="https://addons.mozilla.org/en-US/firefox/addon/2691" rel="nofollow">poster</a>, and for troubleshooting SOAP and RESTful web services</li>
<li><a href="http://www.eclipse.org/mat/" rel="nofollow">Eclipse Memory Analyzer</a> and <a href="https://visualvm.dev.java.net/" rel="nofollow">VisualVM</a> for Java memory usage and GC issues</li>
<li><a href="https://btrace.dev.java.net/" rel="nofollow">BTrace</a> for instrumenting Java code already deployed to production servers</li>
<li><a href="http://curl.haxx.se/" rel="nofollow">curl</a> for looking at raw HTML, sans browser redirects, and test-calling web services</li>
<li><a href="http://jakarta.apache.org/jmeter/" rel="nofollow">JMeter</a> for load testing webapps and other supported components that fail under stress</li>
</ol>
<p>What Open Source tools can you add to the list?</p>
| <p>For the gcc crowd, there's gdb and gprof. I've gotten a lot done with those two.</p>
|
Do I need to Dispose() or Close() an EventWaitHandle? <p>If I am using <code>EventWaitHandle</code> (or <code>AutoResetEvent</code>, <code>ManualResetEvent</code>) to synchronise between threads then do I need to call the <code>Close()</code> or <code>Dispose()</code> methods on that event handle when I am done with it?</p>
<p><code>EventWaitHandle</code> inherits from <code>WaitHandle</code>, which implements <code>IDisposable</code>. And FxCop complains if I don't implement <code>IDisposable</code> on any class that contains an <code>EventWaitHandle</code>. So this suggests that I do need to call it.</p>
<p>However none of these MSDN usage examples call <code>Dispose()</code> or <code>Close()</code>:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(VS.80).aspx">http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle(VS.80).aspx</a>
<a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.80).aspx">http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(VS.80).aspx</a>
<a href="http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(VS.80).aspx">http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(VS.80).aspx</a></p>
<p>Is this just an example of Microsoft ignoring their own advice?</p>
| <p>The disposable resource of an <code>EventWaitHandle</code> is actually a <code>SafeHandle</code> (wrapped in a <code>SafeWaitHandle</code>). <code>SafeHandle</code> implements a finalizer, which eventually makes sure the necessary resource is release, so it should be safe to let the garbage collector / finalizer thread handle it <em>in this case</em>. </p>
<p>However, it is always a good idea to explicitly call <code>Dispose()</code> when the resource is no longer needed. </p>
<p>The threading chapter in <a href="http://www.albahari.com/nutshell/">C# 3.0 in a Nutshell</a> states </p>
<blockquote>
<p>This practice is (arguably) acceptable
with wait handles because they have a
light OS burden (asynchronous
delegates rely on exactly this mechanism
to release their <code>IAsyncResult</code>'s wait
handle).</p>
</blockquote>
|
Where to specify flag for Base class use <p>I've got a base class called Request.cs</p>
<p>In this class I have the following private fields:</p>
<pre><code>protected string _requestURI = xxpConfig.xxEndpoint;
protected string _requestURIAuthBased = xxConfig.xxEndpoint + "?SessionID=";
</code></pre>
<p>endpoint is just a string such as "http://SomeThridPartyAPIURIEndPoint"</p>
<p>In this class I have a method called SendRequest.</p>
<p>Subclasses for example represent certain API calls:</p>
<p>UpdateCustomerRequest.cs (inherits Request.cs) DeleteCustomerRequest.cs (inherits Request.cs)</p>
<p>and so on.</p>
<p>the Request class has a method called SendRequest that takes the URI and does the work to send the API request.</p>
<p>Certain kinds of API calls require a sessionID to be passed and others don't. The only difference in the URI is an added param called sessionID.</p>
<p>So I'm trying to figure out the best and most efficient way to set the "flag" for each type of API call (subclass) as each may or may not require the auth formatted URI vs. the regular. So in my base class I could check whether I need to use the _requestURI vs. _requestURIAuthBased in my Request.SendMethod for the subclass that I'm going to be calling to make that API call.</p>
| <p>If I follow what you ask, the best way I can think of is to follow the model of the EventArgs class. All event handlers take an EventArgs object, however, sometime a derived class is passed:</p>
<pre><code> public class RequestArgs { }
public class Request
{ // ...
void virtual SendRequest(RequestArgs args);
}
// ----------------------------
public class UpdateArgs : RequestArgs
{
public string SessionID {get; set;}
}
class UpdateCustomerRequest : Request
{ // ...
void SendRequest(RequestArgs args)
{
UpdateArgs updateArgs = args as UpdateArgs ;
// :
}
}
</code></pre>
|
Should validation be done in Form objects, or the model? <p>This question is mainly geared towards Zend in PHP, although it certainly applies to other languages and frameworks, so I welcome everyone's opinion.</p>
<p>I've only recently been using the Zend framework, and while it's not perfect, I have had a pretty good time with it. One thing that drives me crazy, however, is that most of the examples I see of people using Zend do the v<a href="http://framework.zend.com/manual/en/zend.form.advanced.html" rel="nofollow">alidation in special form objects</a>, rather than in the model. I think this is bad practice because data can enter into the system in other ways beyond form input, which means that either validators have to be bent and twisted to validate other input, or validation must be done in a second place, and logic duplicated.</p>
<p>I've found some other posts and blogs out there with people who feel the same way I do, but the developers of Zend made this choice for a reason, and other people seem to use it without issue, so I wanted to get some feedback from the community here.</p>
<p>As I said, this mainly applies to Zend, although I think it's important to look at the issue as a whole, rather than working within the confines of the Zend framework, since Zend was designed so that you could use as much, or as little, as you wished.</p>
| <p>Well, the validation can be done at many different levels and usually none of them is "the best". Of course, the model can be populated with invalid data that do not come from the form, but we can also create forms whose data do not go to any model.</p>
<p>Moreover, the direct validation in models is unsually not integrated with our form rendering system, which causes problems if we want to show the error messages and re-populate the form with the user-entered data then.</p>
<p>Both of the solutions have their own pros and cons. It would be perfect to have a system that ensures us that the validation finally must be done at some level. If the form does not validate some data, then the model does and vice versa. Unfortunately, I haven't heard of such library, but I must note that the validators in the frameworks unsually are source-independent. You can pass the POST data to them, but the same can be done with the information retreived from a properly parsed CSV, MYSQL databases, etc.</p>
|
Why is it not advisable to have the database and web server on the same machine? <p>Listening to Scott Hanselman's interview with the Stack Overflow team (<a href="http://www.hanselminutes.com/default.aspx?showID=152">part 1</a> and <a href="http://www.hanselminutes.com/default.aspx?showID=153">2</a>), he was adamant that the SQL server and application server should be on separate machines. Is this just to make sure that if one server is compromised, both systems aren't accessible? Do the security concerns outweigh the complexity of two servers (extra cost, dedicated network connection between the two, more maintenance, etc.), especially for a small application, where neither piece is using too much CPU or memory? Even with two servers, with one server compromised, an attacker could still do serious damage, either by deleting the database, or messing with the application code. </p>
<p>Why would this be such a big deal if performance isn't an issue?</p>
| <ol>
<li>Security. Your web server lives in a DMZ, accessible to the public internet and taking untrusted input from anonymous users. If your web server gets compromised, and you've followed least privilege rules in connecting to your DB, the maximum exposure is what your app can do through the database API. If you have a business tier in between, you have one more step between your attacker and your data. If, on the other hand, your database is on the same server, the attacker now has root access to your data and server.</li>
<li>Scalability. Keeping your web server stateless allows you to scale your web servers horizontally pretty much effortlessly. It is <em>very</em> difficult to horizontally scale a database server.</li>
<li>Performance. 2 boxes = 2 times the CPU, 2 times the RAM, and 2 times the spindles for disk access. </li>
</ol>
<p>All that being said, I can certainly see reasonable cases that none of those points really matter. </p>
|
C# - How can I cut a string at its end to fit in a div? <p>I'm making a list of recent news. So, it will show something like this:</p>
<pre><code>- Take a look at the new Volks...
- John Doe is looking for a jo...
- Microsoft is launching the n...
</code></pre>
<p>So, the list above only shows me the title of the news and the length of each news is limited in 25 characters. But, this is not working well... for example, if you type 25 M's, it will explode my div.</p>
<p>I've been told that there is a way to calculate the length of the string and make it fit in a div automatically.</p>
<p>Does anyone know how to do it?</p>
<p>thanks!!</p>
| <p>"text-overflow: ellipsis" is what you want but not everybody supports it. <a href="http://www.blakems.com/archives/000077.html" rel="nofollow">More info here...</a></p>
|
How can I avoid a segmentation fault while resize a vector like this <p>I think it is a simple question for you....i am pretty new in c++.....</p>
<p>So i have a vector defined like this:</p>
<p><code>vector<vector<float> > big_vector;</code></p>
<p>I read a file and initialized this vector, then the big_wector has about 200,000 elements in it. each is a vector < float ></p>
<p>Then I wanted to modify the elements in big_vector, for some elements I need to resize them first,(e.g. from 0 to 300)</p>
<p><code>big_vector[i].resize(new_size);</code></p>
<p>When I ran the program, first it went well, after some modifications, a "segmentation fault" occurred at the line above.</p>
| <p>First you need to resize big_vector, so that it has some vectors to resize.</p>
<pre><code>int total_vectors = 100;
big_vector.resize(total_vectors);
for(int i = 0; i < total_vectors; ++i)
big_vector[i].resize(new_size);
</code></pre>
|
How do I list all tga files in a directory (non recursive) in Python? <p>How do I list all tga files in a directory (non recursive) in Python?</p>
| <p>If you are doing it based on file extension, you can do something like this:</p>
<pre><code>import os
directory = "C:/"
extension = ".tga"
list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)]
</code></pre>
<p>Obviously you can omit the lower() if you can garantee the case of the files. Also there is the excellent path.py (<a href="http://pypi.python.org/pypi/path.py">http://pypi.python.org/pypi/path.py</a>) module.</p>
<p>If you do not know the file extension you can use something like PIL (<a href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a>) to detect the file type by decoding the file.</p>
|
Django Admin Form for Many to many relationship <p>I have a many to many relationship between 2 tables Users an Domains.
I have defined this relationship in the Domains class.
So in the admin interface I see the Users when I am viewing Domains.
But I do not see Domains when I am viewing Users.
How can I achieve this.</p>
| <p>I know that this is an older thread, but this was the first result that came up on google and I thought a better answer was necessary. </p>
<p>Via <a href="https://code.djangoproject.com/ticket/897#comment:28">this django bug report</a> I found the best way to have your ManyToManyField show up on both models:</p>
<pre><code>class Test1(models.Model):
tests2 = models.ManyToManyField('Test2', blank=True)
class Test2(models.Model):
tests1 = models.ManyToManyField(Test1, through=Test1.tests2.through, blank=True)
</code></pre>
<p>I have tested it myself and was very pleased with the results.</p>
|
How to automate a process with the sqlite3.exe command line tool? <p>I'm trying to bulk load a lot of data ( 5.5 million rows ) into an SQLite database file.
Loading via INSERTs seems to be far too slow, so I'm trying to use the sqlite3 command line tool and the .import command.</p>
<p>It works perfectly if I enter the commands by hand, but I can't for the life of me work out how to automate it from a script ( .bat file or python script; I'm working on a Windows machine ).</p>
<p>The commands I issue at the command line are these:</p>
<pre><code>> sqlite3 database.db
sqlite> CREATE TABLE log_entry ( <snip> );
sqlite> .separator "\t"
sqlite> .import logfile.log log_entry
</code></pre>
<p>But nothing I try will get this to work from a bat file or python script.</p>
<p>I've been trying things like:</p>
<pre><code>sqlite3 "database.db" .separator "\t" .import logfile.log log_entry
echo '.separator "\t" .import logfile.log log_entry' | sqlite3 database.db
</code></pre>
<p>Surely I can do this somehow?</p>
| <p>Create a text file with the lines you want to enter into the sqlite command line program, like this:</p>
<pre>
CREATE TABLE log_entry ( );
.separator "\t"
.import logfile.log log_entry</pre>
<p>and then just call <code>sqlite3 database.db < commands.txt</code></p>
|
Is the "sender" in Button_Click(object sender... really the sender? <p>Ted Faison in a <a href="http://www.dotnetrocks.com/default.aspx?showNum=355" rel="nofollow">podcast on event-based software design</a> mentioned that "sender" and "self" objects in .NET, C++ and Java event statements such as:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
</code></pre>
<p>are a misnomer since e.g. in the above example "sender" is not really the object which produced the event but a proxy, since you wouldn't want to couple your applications that tightly. </p>
<p>Did I understand him incorrectly (since when I debug it, "sender" does indeed seem to be the original object).</p>
<p>Or is it that common event patterns in these languages (e.g. a common click handler) are tightly coupled but they <em>should</em> be more decoupled, e.g. in composite applications. </p>
<p>He also mentioned that e.g. you shouldn't make inherit from EventArgs since it leads to an explosion of classes, one per event, which only transport a few variables. Many times in his opinion, you can just send a string for instance. He mentioned that this opinion is the opposite of what Microsoft Patterns and Practices suggests.</p>
<p>Any thoughts on these areas?</p>
| <p>First - the 'sender' will hold a reference to the button you clicked. If you have multiple buttons all hooked to the same event, this is how you see which one of the buttons you hit (if you're not passing something in the event arguments to read this).</p>
<p>Also I do to some extend agree that writing new eventargs inheriting frmo EventArgs can lead to explosion of classes - so use with causion. I like just raising an EventArgs.Empty and then have the code catching the event explicit querying the object that raised the event for the data. What i mean is - once you catch the event, instead of reading the data from the event arguments you go to the object that raised the event and read those of its properties you are interrested in. This makes it easier to just read what you need, but ofcourse - you could find yourself in a situation where those properties changed between the event raised and you reading the properties.</p>
|
Unit Testing a 'SetDefaults()' method <p>I am in the process of learning to unit test. I have a 'domain object' that doesn't do much apart from hold state (i.e. 'Employee' without any business logic). It has a method SetDefaults() which just fills its state with reasonable values. A simple method.</p>
<p>But when I go to unit test this method all I can think of is to run the method then check that every field is what it should be. Like (in C#):</p>
<pre><code> [TestMethod()]
public void SetDefaultsTest()
{
Employee target = new Employee();
employee.SetDefaults();
Assert.AreEqual(employee.Name, "New Employee");
Assert.AreEqual(employee.Age, 30);
// etc.
}
</code></pre>
<p>It feels wrong to duplicate the entire functionality of SetDefaults() within my test. Should I just leave this method untested? The problem is that I'd like a test to ensure that when new properties are added to the class they are also added to the SetDefaults() method.</p>
| <p>Trivial getters and setters sometimes don't have unit tests written for them. If that's all that SetDefaults() does, it probably won't hurt to skip it.</p>
<p>One thing you would want to consider testing, though, is that none of the set properties of the <code>employee</code> instance are null after calling <code>SetDefaults()</code>:</p>
<pre><code>var nonNullProperties = new object[] { employee.Name, employee.Age, ... };
foreach (var property in nonNullProperties)
Assert.IsNotNull(property);
</code></pre>
<p>This makes sense, since you really just care that they <em>are</em> set to some default value, and not so much that they're a <em>specific</em> value.</p>
|
C# XML Serialization - Leading Question Marks <h2>Problem</h2>
<p>By leveraging some samples I found online <a href="http://www.dotnetjohn.com/articles.aspx?articleid=173">here</a>, I've written some XML serialization methods.</p>
<ul>
<li><strong>Method1:</strong> Serialize an Object and return: (a) the type, (b) the xml string</li>
<li><strong>Method2:</strong> Takes (a) and (b) above and gives you back the Object.</li>
</ul>
<p>I noticed that the xml string from the <strong>Method1</strong> contains a leading '?'. This seems to be fine when using <strong>Method2</strong> to reconstruct the Object. </p>
<p>But when doing some testing in the application, sometimes we got leading '???' instead. This caused the <strong>Method2</strong> to throw an exception while trying to reconstruct the Object.
The 'Object' in this case was just a simple int.</p>
<blockquote>
System.InvalidOperationException was unhandled
Message="There is an error in XML document (1, 1)."
Source="System.Xml"
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at XMLSerialization.Program.DeserializeXmlStringToObject(String xmlString, String objectType) in C:\Documents and Settings\...Projects\XMLSerialization\Program.cs:line 96
at XMLSerialization.Program.Main(String[] args) in C:\Documents and Settings\...Projects\XMLSerialization\Program.cs:line 49
</blockquote>
<p>Would anyone be able to shed some light on what might be causing this?</p>
<h2>Sample Code</h2>
<p>Here's sample code from the mini-tester I wrote while coding this up which runs as a VS console app. It'll show you the XML string. You can also uncomment the regions to append the extra leading '??' to reproduce the exception.</p>
<pre><code>
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace XMLSerialization
{
class Program
{
static void Main(string[] args)
{
// deserialize to string
#region int
object inObj = 5;
#endregion
#region string
//object inObj = "Testing123";
#endregion
#region list
//List inObj = new List();
//inObj.Add("0:25");
//inObj.Add("1:26");
#endregion
string[] stringArray = SerializeObjectToXmlString(inObj);
#region include leading ???
//int indexOfBracket = stringArray[0].IndexOf('<');
//stringArray[0] = "??" + stringArray[0];
#endregion
#region strip out leading ???
//int indexOfBracket = stringArray[0].IndexOf('<');
//string trimmedString = stringArray[0].Substring(indexOfBracket);
//stringArray[0] = trimmedString;
#endregion
Console.WriteLine("Input");
Console.WriteLine("-----");
Console.WriteLine("Object Type: " + stringArray[1]);
Console.WriteLine();
Console.WriteLine("XML String: " + Environment.NewLine + stringArray[0]);
Console.WriteLine(String.Empty);
// serialize back to object
object outObj = DeserializeXmlStringToObject(stringArray[0], stringArray[1]);
Console.WriteLine("Output");
Console.WriteLine("------");
#region int
Console.WriteLine("Object: " + (int)outObj);
#endregion
#region string
//Console.WriteLine("Object: " + (string)outObj);
#endregion
#region list
//string[] tempArray;
//List list = (List)outObj;
//foreach (string pair in list)
//{
// tempArray = pair.Split(':');
// Console.WriteLine(String.Format("Key:{0} Value:{1}", tempArray[0], tempArray[1]));
//}
#endregion
Console.Read();
}
private static string[] SerializeObjectToXmlString(object obj)
{
XmlTextWriter writer = new XmlTextWriter(new MemoryStream(), Encoding.UTF8);
writer.Formatting = Formatting.Indented;
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(writer, obj);
MemoryStream stream = (MemoryStream)writer.BaseStream;
string xmlString = UTF8ByteArrayToString(stream.ToArray());
string objectType = obj.GetType().FullName;
return new string[]{xmlString, objectType};
}
private static object DeserializeXmlStringToObject(string xmlString, string objectType)
{
MemoryStream stream = new MemoryStream(StringToUTF8ByteArray(xmlString));
XmlSerializer serializer = new XmlSerializer(Type.GetType(objectType));
object obj = serializer.Deserialize(stream);
return obj;
}
private static string UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(characters);
}
private static byte[] StringToUTF8ByteArray(String pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(pXmlString);
}
}
}
</code></pre>
| <p>When I've come across this before, it usually had to do with encoding. I'd try specifying the encoding when you serialize your object. Try using the following code. Also, is there any specific reason why you need to return a <code>string[]</code> array? I've changed your methods to use generics so you don't have to specify a type.</p>
<pre><code>private static string SerializeObjectToXmlString<T>(T obj)
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
settings.IndentChars = "\t";
settings.NewLineChars = Environment.NewLine;
settings.ConformanceLevel = ConformanceLevel.Document;
using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
{
xmls.Serialize(writer, obj);
}
string xml = Encoding.UTF8.GetString(ms.ToArray());
return xml;
}
}
private static T DeserializeXmlStringToObject <T>(string xmlString)
{
XmlSerializer xmls = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
return (T)xmls.Deserialize(ms);
}
}
</code></pre>
<p>If you still have problems, try using <code>Encoding.ASCII</code> in your code anywhere you see <code>Encoding.UTF8</code>, unless you have a specific reason for using UTF8. I'm not sure of the cause, but I've seen UTF8 encoding cause this exact problem in certain cases when serializing.</p>
|
Determine list of event handlers bound to event <p>I have a WinForms form that won't close. In OnFormClosing, e.Cancel is set to true. I am guessing that some object in my application has bound to the Closing or FormClosing event, and is blocking the close. To find out, I'd like to determine what delegates are bound to one of these events.</p>
<p>Is there a way to determine the list of handlers bound to an event? Ideally I would do this via the Visual Studio debugger, but can write code in the application to find the handlers if necessary. Understanding that an event is like a hidden private field, I've navigated through the Debugger to the "Non-Public Fields" for the "Windows.Forms.Form" ancestor of my form, but to no avail.</p>
| <p>In short, you're not meant to do this - but for debugging purposes...</p>
<p>An event is <strong>often</strong> backed by a private field - but not with controls; they use the <code>EventHandlerList</code> approach. You would have to access the form's protected <code>Events</code> member, looking for the object mapped to the (private) EVENT_FORMCLOSING object.</p>
<p>Once you have the <code>FormClosingEventHandler</code>, <code>GetInvocationList</code> should do the job.</p>
<p><hr /></p>
<pre><code>using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;
class MyForm : Form
{
public MyForm()
{ // assume we don't know this...
Name = "My Form";
FormClosing += Foo;
FormClosing += Bar;
}
void Foo(object sender, FormClosingEventArgs e) { }
void Bar(object sender, FormClosingEventArgs e) { }
static void Main()
{
Form form = new MyForm();
EventHandlerList events = (EventHandlerList)typeof(Component)
.GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(form, null);
object key = typeof(Form)
.GetField("EVENT_FORMCLOSING", BindingFlags.NonPublic | BindingFlags.Static)
.GetValue(null);
Delegate handlers = events[key];
foreach (Delegate handler in handlers.GetInvocationList())
{
MethodInfo method = handler.Method;
string name = handler.Target == null ? "" : handler.Target.ToString();
if (handler.Target is Control) name = ((Control)handler.Target).Name;
Console.WriteLine(name + "; " + method.DeclaringType.Name + "." + method.Name);
}
}
}
</code></pre>
|
Change the alpha value of a BufferedImage? <p>How do I change the global alpha value of a BufferedImage in Java? (I.E. make every pixel in the image that has a alpha value of 100 have a alpha value of 80)</p>
| <p>@Neil Coffey:
Thanks, I've been looking for this too; however, Your code didn't work very well for me (white background became black).</p>
<p>I coded something like this and it works perfectly:</p>
<pre><code>public void setAlpha(byte alpha) {
alpha %= 0xff;
for (int cx=0;cx<obj_img.getWidth();cx++) {
for (int cy=0;cy<obj_img.getHeight();cy++) {
int color = obj_img.getRGB(cx, cy);
int mc = (alpha << 24) | 0x00ffffff;
int newcolor = color & mc;
obj_img.setRGB(cx, cy, newcolor);
}
}
}
</code></pre>
<p>Where obj_img is BufferedImage.TYPE_INT_ARGB.</p>
<p>I change alpha with setAlpha((byte)125); alpha range is now 0-255.</p>
<p>Hope someone finds this useful. </p>
|
Delegating Control on change of a value/property <p>I'm trying to do something I've been historically available to do using Visual FoxPro (VFP). By use of a "SETALL()" function, I am able to do something like pertaining to a current form... this.SetAll( "someProperty", "toSomeNewValue" ) and it goes through and assigns the value to all controls. By creating my own custom property and an internal to VFP via "_assign", will cause these events to trigger. From THAT method, each control would take care of itself on the form, from enable/disable/visibility, editable, readonly, color, font, validation, etc, based on what I put in each individual control. </p>
<p>So, how would I do a similar thing in C#... Such as have a public property, or method, or delegate at the form level, such as "FormEditMode". Then, when I do something like this.FormEditMode = AddMode, all controls will be self-triggered to turn themselves on/off, enable/disable respectively instead of explicit calls for all controls on a given form.</p>
<p>Thanks</p>
| <p>I would just do something like this: </p>
<pre><code>this.Visible = false;
Controls.ForEach<Control>(c => c.Visible = false);
</code></pre>
<p>If you have GroupBoxes or other Controls that have Controls, you may want to put that into a recursive function: </p>
<pre><code>static void DoForEachControl(Control control, Action<Control> f)
{
control.Controls.ForEach<Control>(c =>
{
f(c);
DoForEachControl(c, f);
});
}
</code></pre>
<p>To get that ForEach you'll need something like this: </p>
<pre><code> public static class Extensions
{
public static void ForEach<T>(this IEnumerable source, Action<T> action)
{
foreach (var item in source)
{
action((T)item);
}
}
}
</code></pre>
|
WPF No Events from Controls in RichTextBox <p>I am using WPF and have a Table inside a RichTextBox control. I need to get the background colour of the table cell to change it gets the focus. My problem is that I can't get the GotFocus or any other events to fire for the TableCell.</p>
<pre><code><RichTextBox>
<FlowDocument>
<Table>
<Table.Columns>
<TableColumn />
</Table.Columns>
<TableRowGroup>
<TableRow>
<TableCell GotFocus="SelectionCell_GotFocus">
<Paragraph>1</Paragraph>
</TableCell>
</TableRow>
</TableRowGroup>
</Table>
</FlowDocument>
</RichTextBox>
</code></pre>
<p>The image below shows the table in the RichTextBox control. What I'd like to be able to do is change the background as the user moves between the table cells.</p>
<p><img src="http://img16.imageshack.us/img16/8151/wpftable.png" alt="alt text" /></p>
<p>Edit: After more investigation the issue is not confined to Table's in a RichTextBox, no control in a RichTextBox appears to be able to generate events. I placed a button into it and was not bale to get it to fire its Click event. It looks like the RichTextBox masks all events, hopefully there is a way to unmask them.</p>
| <p>The half answer is to set the IsDocumentEnabled property on the RichTextBox to true. That allows controls within it to be enabled as per <a href="http://social.msdn.microsoft.com/forums/en-US/wpf/thread/5372c48e-3040-4312-8263-59616e6728a8/" rel="nofollow">Embedded UI Elements in RichTextBox</a>. Unfortunately that still doesn't fire the event I need which is the GotFocus on a TableCell although it is possible to get the event to fire by putting a button in the cell and clicking on it. That bubbles the GotFocus event up the UI tree to the TableCell. I don't want a button in every cell though so time to look for an alternative solution.</p>
<pre><code><RichTextBox IsDocumentEnabled="True">
<FlowDocument>
<Table>
<Table.Columns>
<TableColumn />
</Table.Columns>
<TableRowGroup>
<TableRow>
<TableCell GotFocus="SelectionCell_GotFocus">
<BlockUIContainer>
<Canvas>
<Button Click="Button_Click">
Click
</Button>
</Canvas>
</BlockUIContainer>
</TableCell>
</TableRow>
</TableRowGroup>
</Table>
</FlowDocument>
</RichTextBox>
</code></pre>
|
How do you tell the Visual Studio project type from an existing Visual Studio project <p>Using Visual Studio 2005.</p>
<p>Is there anything in the .sln or .vcproj files (or anywhere else) that defines the project type / subtype? </p>
<p>Edit: What I mean is that when you create a project, you first choose a language (e.g. Visual C#), then a project type (e.g. Windows) and then a subtype (e.g. Console Application).</p>
<p>Where is this information stored within the VS files?</p>
| <p>In the project XML files:</p>
<p>Console applications contain:</p>
<pre><code><OutputType>Exe</OutputType>
</code></pre>
<p>WinForms applications contain:</p>
<pre><code><OutputType>WinExe</OutputType>
</code></pre>
<p>Library (.dll) projects contain:</p>
<pre><code><OutputType>Library</OutputType>
</code></pre>
<p>and do NOT contain a </p>
<pre><code><ProjectTypeGuids>
</code></pre>
<p>ASP.NET and WCF projects contain:</p>
<pre><code><ProjectTypeGuids>{603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
</code></pre>
<p>The GUIDs do something to define exactly what type of project it is. The ones above were taken from an ASP.NET app. They exist in WCF projects too, and flipping around the GUIDs can fool Vis Studio into changing the project type when you open it.</p>
|
How do I submit an HTML form to a Popup windows with resize disabled? <p>I had designed an HTML form with submit button. But instead of submit it to another page I want to submit to pop up windows where I can limit the size of the pop up windows say "320x240" hide all the toolbar, disable resize.</p>
| <p>Here's my go at it; this JavaScript snippet should go into the head of your page:</p>
<pre><code><script>
process = function()
{
window.open('about:blank', 'popup', 'width=320,height=240,resizeable=no');
document.login.setAttribute('target', 'popup');
document.login.setAttribute('onsubmit', '');
document.login.submit();
};
</script>
</code></pre>
<p>And this is a sample form for demonstration purposes:</p>
<pre><code><form action="handle.html" method="get" name="login" onsubmit="process(); return false;">
Username: <input type="text" name="username" id="username" /><br />
<input type="submit" />
</form>
</code></pre>
<p>Now, here's what's happening: first, we set up a form and give it an <code>onsubmit</code> attribute that tells it to run the function <code>process()</code> and <code>return false;</code> instead of submitting normally; from this point, that function takes over and creates a popup window, giving it a name, and some features (by all means, add any surplus ones you'd like), and then attention comes back to the form, where we now set the <code>target</code> attribute to the name of the window we just created.</p>
<p>We then have to clear that <code>onsubmit</code> that we set earlier, or this same exact thing will happen again, and that's certainly not what you want. Finally, we just have the form submitted again and it now passes all of its information to the popped window; from there, it's just getting <code>handle.html</code> (or whatever you end up calling your processing page) to do its work with the data.</p>
<p>Hope I've helped.</p>
|
Using Unmapped Class with NHibernate Named Query <p>I'm using a custom named query with NHibernate which I want to return a collection of Person objects. The Person object is not mapped with an NHibernate mapping which means I'm getting the following exception:</p>
<blockquote>
<p>System.Collections.Generic.KeyNotFoundException:
The given key was not present in the
dictionary.</p>
</blockquote>
<p>It's getting thrown when the Session gets created because it can't find the class name when it calls NHibernate.Cfg.Mappings.GetClass(String className). This is all fairly understandable but I was wondering if there was any way to tell NHibernate to use the class even though I haven't got a mapping for it?</p>
| <p>Why don't you use:</p>
<p><code>
query.SetResultTransformer(Transformers.AliasToBean(typeof(Person)));
</code></p>
<p>It will insert data from each column in your query into Person object properties using column alias as a property name.</p>
|
The Three Systems of Man - How do you build a Third System? <p>I've been thinking about the story of the Three Systems of Man from the book <a href="http://rads.stackoverflow.com/amzn/click/1555581234">The UNIX Philosophy</a>. For those of you who aren't familiar, it goes something like this:</p>
<ul>
<li>The First System of Man is the one he
builds when his back is against the
wall. It's klugey, hackish, and
doesn't it lend itself to new
features.</li>
<li>The Second System is designed by a
team of "experts" who insist they're
going to do it the Right Way this
time. The resulting system is slow,
bloated, late to ship, and over
budget.</li>
<li>The Third System is built by people
who have been burned one too many
times by the second system. It is
robust, scalable, and maintainable.</li>
</ul>
<p>Obviously the goal in software development is to write The Third System. The author's premise is that you cannot do so without first writing the other two systems. From that we get concepts like "Plan to throw one away" from <a href="http://en.wikipedia.org/wiki/The%5FMythical%5FMan-Month">The Mythical Man-Month</a>. In my limited software engineering career, I've worked on one second system and two first systems that both became The System due to inertia. It feels like there's never enough time or budget to do it right, but always plenty of time and money to do it over.</p>
<p>Has anyone here ever built or maintained a Third System? What steps did you take to get there? Can you really "plan to throw one away" in practice?</p>
| <p>I think the key to this is the difference between having the time and money, and experience. If you've built something before, been burned, built it again, got it wrong and then build it again, and you're that rare developer who just knows what works, then you'll get the 'Third System'. </p>
<p>Just having money, time, and a previous failure is not a recipe for success.</p>
|
Is there an HTML version of the ECMA-335 CLI Specification? <p>I'm currently writing a blog post about the internals of the CLI, and I try to cite where something gets said. Mainly in the Partition III docs.</p>
<p>I'm currently linking to the ECMA page for it, where there are a bunch of pdf- and zip-files, and making section references where they are needed; but I would really like to link directly to the sections in the text.</p>
<p>Does anyone know where I can find an HTML version of the specification? I've been all over MSDN, Mono and Google looking, but have thus-far come up empty.</p>
| <p><em>Edit: as pointed out in the comments, this is actually an older draft, I'm not sure if it is "close enough" for you to use, but I'm not having any luck finding the current version in HTML.</em></p>
<p>It's not going to be a pretty link, but this will probably do the job (Google's HTML version of a DOC file):</p>
<p><a href="http://74.125.95.132/search?q=cache:OkolnRjRgFIJ:download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%2520I%2520Architecture.doc" rel="nofollow">http://74.125.95.132/search?q=cache:OkolnRjRgFIJ:download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%2520I%2520Architecture.doc</a></p>
<p>You can link to specific sections by viewing the source and looking for <code><a name="____"></code> anchors at the section, they all seem to have it, for example:</p>
<p><a href="http://74.125.95.132/search?q=cache:OkolnRjRgFIJ:download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%2520I%2520Architecture.doc#_Toc100635553" rel="nofollow">http://74.125.95.132/search?q=cache:OkolnRjRgFIJ:download.microsoft.com/download/D/C/1/DC1B219F-3B11-4A05-9DA3-2D0F98B20917/Partition%2520I%2520Architecture.doc#_Toc100635553</a></p>
<p>Of course, you could always just save this HTML file to a server under your own control, if you don't want to have such a messy-looking link.</p>
|
Grails Eclipse plugin <p>I've seen various posts on SO criticising the Eclipse Grails plugin, and am wondering if anyone has found a way to work productively with Grails within Eclipse?</p>
<p>I had a look at the <a href="http://www.grails.org/Eclipse+IDE+Integration" rel="nofollow">Grails plugin page</a>, and the information there doesn't look very promising, particularly the conflicting advice regarding the 'Disable Groovy Compiler Generating Class Files' setting.</p>
| <p>The Grails Eclipse Tooling available in STS is now becoming mature. I'd recommend trying this if you are still looking for a good way to develop Grails apps in Eclipse.</p>
<p><a href="http://www.grails.org/STS+Integration">http://www.grails.org/STS+Integration</a></p>
|
How do you add a directory of java classes to a project? <p>I have a Java project I'm working on, and wish to include a directory full of classes. These are the "JEdit Syntax" classes, and come within two packages:</p>
<pre><code>org.syntax.jedit
org.syntax.jedit.tokenmarker
</code></pre>
<p>However, everywhere I look it tells me to "import the entire jar file". My problem is that there is no jar file, just a directory with a subdirectory, both filled with *.java files, each containing a class.</p>
<p>In Netbeans 6.5 I added a library by "Jar/Folder", and both appear in my new library I created, but when I go to import the two packages listed above, I get the error that "org.syntax.jedit does not exist (cannot find symbol)".</p>
<p>Can anyone show me what I'm doing wrong?</p>
<p>Thanks a ton.</p>
| <p>It sounds like you have tried to add the two packages to your classpath seperately - and at the wrong level.
If you are pointing at a folder, you have to point to the "root" folder of the package hierarchy - ie in this case the folder which is the parent of "org"
Then from there it will look down the package/folder hierarchy org/syntax/jedit to find your classes.</p>
<p>So if your files are in the directory "c:\mylib\src\main\java\org\syntax\jedit" then you need to point the compiler folder at "c:\mylib\src\main\java".
That should then find all the classes.</p>
|
How do I include .class files in my project in Eclipse? (Java) <p>Hey all. I am working on a project for school where we are given the .class file but not the source to include in our code. I am using Eclipse, and I want to include the file in my project so I can instantiate objects from it and use it. <p>The file is TokenizerImpl.class, and I want to use it like this:</p> <code>TokenizerImpl tokenizer = new TokenizerImpl(foo);</code></p>
<p>I put the file in my project folder, and Eclipse says that "TokenizeImpl cannot be resolved as a type", which I assume means it cannot find the class or source. I tried putting it in the "bin" folder of the project and got the same error. Google search and SO search didn't seem to answer this, so I will give it a shot. How do I do this, oh wise ones? </p>
<p>Edit: Oh dear, I found the problem was something else entirely. These solutions worked fine, but I just forgot to create the Tokenizer interface that TokenizerImpl implements. Doh. Thanks for all your help though, I did learn a lot about eclipse.</p>
| <p>You can add a directory containing the class files to the Eclipse project, only if it is inside one of your Eclipse projects, either in a generated directory or in one you have created.</p>
<p>This can be done by adding the class folder to the Java build path of the application. You can set this in the Project properties, by visiting Java Build Path -> Libraries -> Add Class Folder. Keep in mind, that you will have to specify the root folder containing the class files in their packages.</p>
<p>Therefore, if you wish to have the compiler access com.stackoverflow.Example.class present in the classes directory under project A (but not in the build path of project A), then you should add 'classes' as a class folder, and not classes/com/stackoverflow as a class folder.</p>
|
jQuery Simpletip plugin to use the title attribute <p>How can you make the <a href="http://craigsworks.com/projects/simpletip/" rel="nofollow">SimpleTip</a> plugin use each element's <code>title</code> attribute for the tooltip text when you're applying it to a group of elements?</p>
<pre><code>$('td[title]').simpletip({
content : << this element's title attribute >>
});
</code></pre>
| <p>I think this will work for you</p>
<pre><code>$('td[title]').each(function() {
$(this).simpletip({
content : $(this).attr('title')
});
});
</code></pre>
|
Combine PHP prepared statments with LIKE <p>Anyone know how to combine PHP prepared statements with LIKE? i.e. </p>
<p><code>"SELECT * FROM table WHERE name LIKE %?%";</code></p>
| <p>The % signs need to go in the variable that you assign to the parameter, instead of in the query.</p>
<p>I don't know if you're using mysqli or PDO, but with PDO it would be something like:</p>
<pre><code>$st = $db->prepare("SELECT * FROM table WHERE name LIKE ?");
$st->execute(array('%'.$test_string.'%'));
</code></pre>
<p><strong>EDIT :: For <code>mysqli</code> user the following.</strong></p>
<pre><code>$test_string = '%' . $test_string . '%';
$st->bind_param('s', $test_string);
$st->execute();
</code></pre>
|
Flash transparent background not working on Mac <p>Hi I just can't seem to get the background to be transparent on a Mac, see here: <a href="http://www.digiflipconcepts.com/smokinhot/templates/smokinhot/" rel="nofollow">http://www.digiflipconcepts.com/smokinhot/templates/smokinhot/</a></p>
<p>I'm using wmode=transparent. I've been searching google for ages and see that wmode is not very stable and that it will work if I use the 'embed' tag but it would not be valid code anymore.</p>
<p>Can anyone help?</p>
| <p>Seeing that your background position is static you could skip the transparent background and just add that part of the image in the flash. You will need to pull some other tricks to get the position exactly right across browsers, but it will work better and improve performance.</p>
|
How to take a screenshot of the Active Window in Delphi? <p>For full screenshots, I use this code:</p>
<pre><code>form1.Hide;
sleep(500);
bmp := TBitmap.Create;
bmp.Height := Screen.Height;
bmp.Width := Screen.Width;
DCDesk := GetWindowDC(GetDesktopWindow);
BitBlt(bmp.Canvas.Handle, 0, 0, Screen.Width, Screen.Height, DCDesk, 0, 0, SRCCOPY);
form1.Show ;
FileName := 'Screenshot_'+FormatDateTime('mm-dd-yyyy-hhnnss',now());
bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
ReleaseDC(GetDesktopWindow, DCDesk);
bmp.Free;
</code></pre>
<p>How can I convert that to take a screenshot of only the active window.</p>
| <ol>
<li>First of all you have to get the right window. As sharptooth already noted you should use <code>GetForegroundWindow</code> instead of <code>GetDesktopWindow</code>. You have done it right in your <a href="http://pastebin.com/m2e334a4a">improved version</a>.</li>
<li>But then you have to resize your bitmap to the actual size of the DC/Window. You haven't done this yet.</li>
<li>And then make sure you don't capture some fullscreen window!</li>
</ol>
<p>When I executed your code, my Delphi IDE was captured and as it is on fullscreen by default, it created the illusion of a fullscreen screenshot. (Even though your code is mostly correct)</p>
<p>Considering the above steps, I was successfully able to create a single-window screenshot with your code.</p>
<p>Just a hint: You can <code>GetDC</code> instead of <code>GetWindowDC</code> if you are only interested in the client area. (No window borders)</p>
<p><strong>EDIT:</strong> Here's what I made with your code:</p>
<p><strong>You should not use this code! Look at the improved version below.</strong></p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
const
FullWindow = True; // Set to false if you only want the client area.
var
hWin: HWND;
dc: HDC;
bmp: TBitmap;
FileName: string;
r: TRect;
w: Integer;
h: Integer;
begin
form1.Hide;
sleep(500);
hWin := GetForegroundWindow;
if FullWindow then
begin
GetWindowRect(hWin,r);
dc := GetWindowDC(hWin) ;
end else
begin
Windows.GetClientRect(hWin, r);
dc := GetDC(hWin) ;
end;
w := r.Right - r.Left;
h := r.Bottom - r.Top;
bmp := TBitmap.Create;
bmp.Height := h;
bmp.Width := w;
BitBlt(bmp.Canvas.Handle, 0, 0, w, h, DC, 0, 0, SRCCOPY);
form1.Show ;
FileName := 'Screenshot_'+FormatDateTime('mm-dd-yyyy-hhnnss',now());
bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
ReleaseDC(hwin, DC);
bmp.Free;
end;
</code></pre>
<p><strong>EDIT 2:</strong> As requested I'm adding a better version of the code, but I'm keeping the old one as a reference. You should seriously consider using this instead of your original code. It'll behave much nicer in case of errors. (Resources are cleaned up, your form will be visible again, ...) </p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
const
FullWindow = True; // Set to false if you only want the client area.
var
Win: HWND;
DC: HDC;
Bmp: TBitmap;
FileName: string;
WinRect: TRect;
Width: Integer;
Height: Integer;
begin
Form1.Hide;
try
Application.ProcessMessages; // Was Sleep(500);
Win := GetForegroundWindow;
if FullWindow then
begin
GetWindowRect(Win, WinRect);
DC := GetWindowDC(Win);
end else
begin
Windows.GetClientRect(Win, WinRect);
DC := GetDC(Win);
end;
try
Width := WinRect.Right - WinRect.Left;
Height := WinRect.Bottom - WinRect.Top;
Bmp := TBitmap.Create;
try
Bmp.Height := Height;
Bmp.Width := Width;
BitBlt(Bmp.Canvas.Handle, 0, 0, Width, Height, DC, 0, 0, SRCCOPY);
FileName := 'Screenshot_' +
FormatDateTime('mm-dd-yyyy-hhnnss', Now());
Bmp.SaveToFile(Format('C:\Screenshots\%s.bmp', [FileName]));
finally
Bmp.Free;
end;
finally
ReleaseDC(Win, DC);
end;
finally
Form1.Show;
end;
end;
</code></pre>
|
How to add native library to "java.library.path" with Eclipse launch (instead of overriding it) <p>I got a native library that needs to be added to <em>java.library.path</em>. With JVM argument <em>-Djava.library.path=path...</em> I can set the path as I want.</p>
<p>My problem is that my other library (pentaho reporting) searches fonts based on the default java.library.path (including system directories etc) and the manual setting overrides the default path..</p>
<p>So : how can I <strong>add</strong> a path entry to the default java.library.path instead of overriding it (which seems to be done with -Djava.library.path)? (I wouldn't want to add the default path by hand, which wouldn't be nice for the sake of deployment)</p>
<p>EDIT: Sorry for missing details; I'm working with Eclipse. (The deployment is done with JNLP and there I can use <em>nativelib</em> under <em>resources</em>)</p>
| <p>Had forgotten this issue... I was actually asking with Eclipse, sorry for not stating that originally.
And the answer seems to be too simple (at least with 3.5; probably with older versions also):</p>
<p>Java run configuration's Arguments : VM arguments:</p>
<pre><code>-Djava.library.path="${workspace_loc:project}\lib;${env_var:PATH}"
</code></pre>
<p>Must not forget the quotation marks, otherwise there are problems with spaces in PATH.</p>
|
ruby-aaws Get specific Album <p>I am trying to get a specific music cd from Amazon using ruby-aaws. </p>
<pre><code>il = ItemSearch.new( 'Music', { 'Artist' => artist_title,
'Title' => album_name } )
rg = ResponseGroup.new( 'Large' )
req = Request.new(AMAZON_KEY_ID, AMAZON_ASSOCIATES_ID, 'de')
resp = req.search( il, rg, 5)
</code></pre>
<p>But this fails. It only seems to work when I search for artist <em>or</em> title, not both at the same time. What am I making wrong? If I construct the url by hand, it works prefectly, but I really don't want to parse the xml manually myself.</p>
| <p>I've had a bit of a look at the code of <code>ruby-aaws</code>. It looks like you should be able to set <code>$DEBUG</code> to <code>true</code> before calling any of the <code>ruby-aaws</code> methods/classes and see what URLs are being requested. If there are any discrepancies between your handcrafted URL and the one being generated by <code>ruby-aaws</code>, this might give you some clues.</p>
|
elisp functions as parameters and as return value <p>I have the following code </p>
<pre><code>(defun avg-damp(f)
#'(lambda(x) (/ (+ (funcall f x) x) 2.0)))
</code></pre>
<p>A call </p>
<pre><code>(funcall (avg-damp #'(lambda(v) (* v v))) 10)
</code></pre>
<p>returns 55.0 (the correct value) in SBCL but crashes with the following stack in emacs lisp</p>
<pre><code>Debugger entered--Lisp error: (void-variable f)
(funcall f x)
(+ (funcall f x) x)
(/ (+ (funcall f x) x) 2.0)
(lambda (x) (/ (+ ... x) 2.0))(10)
funcall((lambda (x) (/ (+ ... x) 2.0)) 10)
eval((funcall (avg-damp (function ...)) 10))
eval-last-sexp-1(nil)
eval-last-sexp(nil)
call-interactively(eval-last-sexp)
</code></pre>
<p>How can I make it work in Emacs lisp?</p>
| <p>This style of programming does not work in plain Emacs Lisp. Emacs Lisp uses dynamic binding and languages like Scheme and Common Lisp are using lexical binding. Your code exposes the difference. See: <a href="http://www.gnu.org/software/emacs/elisp/html_node/Extent.html" rel="nofollow">Extent in Emacs Lisp</a></p>
<p>See also this question: <a href="http://stackoverflow.com/questions/593383/how-do-i-do-closures-in-emacs-lisp">How do I do closures in Emacs Lisp?</a> and the 'solution' with lexical-let. lexical-let is an extension for Emacs Lisp in the "cl" package.</p>
<p>See also: since Emacs 24.1 there is optional <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Lexical-Binding.html" rel="nofollow">lexical binding</a>. Learn how to use it: <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Using-Lexical-Binding.html#Using-Lexical-Binding" rel="nofollow">using lexical binding</a>. </p>
|
Layering a WCF Service the right way <p>My question is more of an architectural nature, less involved with the actual implementation.</p>
<p>I have build an API based on WCF, but can't really decide on how to separate the PL from the BL. I have made my service thin, so that it holds only a minimum of implementation, something like:</p>
<pre><code>public TagItemResponse TagItem(TagItemRequest request)
{
return (new ItemTagRequestProcessor()).GetResponse(request);
}
</code></pre>
<p>Than of course the first question arises, in what layer do the RequestProcessors belong? I think it would be wrong to call them a facade, but at the same time, they have nothing to do with presentation. As for now, i decided that they nevertheless belong in the PL. The processor methods take my DTO's (DataContracts) as input, validate the request message (base class), authenticate (base class) and eventually return a single DTO response, like so:</p>
<pre><code>protected override void Process(TagItemRequest request, TagItemResponse response, Host host)
{
var profile = ProfileFacade.GetProfile(host, request.Profile);
var item = ItemFacade.GetItemId(host, request.Item);
var tags = new List<Tag>();
foreach (var name in request.Tags)
{
var tag = TagFacade.GetTag(profile, name);
ItemFacade.TagItem(item, tag);
tags.Add(tag);
}
ItemFacade.UntagItem(item, tags);
}
</code></pre>
<p>Now I ask myself, why do i need the facade classes 1:1 related to my business objects. For example i have a HostFacade that acts as a layer between the hostDAO and the processors. It, however, holds very little logic, it merely handles the DAO calls. </p>
<pre><code>public static Host GetHost(HostDTO dto)
{
return HostDAO.GetHostByCredentials(dto.Username, dto.Password);
}
</code></pre>
<p>Question: I might as well merge the processors and the facades, right?</p>
<p>I've read many articles/books on the subject, but i still can't settle on the 'right' way to go and tend to chose a different approach every time i face the issue. I wonder if a right approach even exists. </p>
<p>I've found f.ex. the doFactory example, where they talked to the DAO classes right from within the service implementation. I don't really like that, as most ServiceContract methods share some logic, and thus lend themselves well for use with shared base classes. </p>
<p>I've also found other examples where only the facades are called from within the services, but that seems to work well only for very fine-grained messages. My messages are 'fat' and composite in order to reduce the number of calls to the service as much as possible. My extra processing layer seems the be my real problem.</p>
<p>Probably there is no single answer as to how to correctly layer a WCF service, but hopefully there are some of you out there with an opinion that will either conform my instincts or shed some new light on the subject for me.</p>
<p>Thanx!</p>
<p>Geoffrey</p>
| <p>First, I assume that by PL you mean presentation layer, not persistence layer?</p>
<p>When implementing a layered application design, the main question should always be: can I replace the implementation of a lower layer without impacting the implementation of the layer(s) above.</p>
<p>This is usually best illustrated by the persistence layer. If you switch from SQL Server 2008 to MySQL for example, the persistence layer changes (of course). But are changes in the business layer also necessary? For example, does the business layer catch SqlException instances that are only thrown by SqlClient? In a good design, the business layer needs no changes at all.</p>
<p>The same principle should apply to the separation between business layer and presentation layer.</p>
<p>In your example, I would say that the <code>ItemTagRequestProcessor</code> should not be in the presentation layer. First, it has nothing to do with presentation, second, the implementation of processing a request is not a concern for the presentation layer. Compare it with a web application, presenting a <code>TagItemResponse</code> to a client is the concern of the web (presentation) layer. Retrieving an instance of <code>TagItemResponse</code> is the concern of a layer below the presentation layer.</p>
<p>Deciding whether to have a facade between your business layer and persistence layer is difficult. I usually do not implement a facade because it adds an extra (usually unnecessary) layer of indirection. Besides, I do not see a problem in calling persistence layer methods directly from business layer methods. If only you take the same principle into account: can you change the persistence layer implementation without affecting the business layer implementation.</p>
<p>Kind regards,</p>
<p>Ronald Wildenberg</p>
|
WPF - UserControl default Content attribute <p>I'm creating a UserControl and I just can't remember the name of the attribute which you use to decorate the property which you want to act as the default content property. </p>
<p>To give a concrete example, say i have a property called 'Title' which i can set using property syntax like this - </p>
<pre><code><local:myControl Title="the title"/>
</code></pre>
<p>But the consumer of the control may want to use element syntax like this - </p>
<pre><code><local:myControl> the Title </local:myControl>
</code></pre>
<p>I KNOW there is an attribute which I need to add to the Title property with to enable this support but I've forgotten what it is and can't find it anywhere.</p>
<p>Could anyone refresh my memory for me? Also, I'm looking for a similar attribute to act on CustomControls inheriting from ItemsControl.</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.markup.contentpropertyattribute.aspx">ContentPropertyAttribute</a></p>
|
CollectionViewSource Filter not refreshed when Source is changed <p>I have a WPF ListView bound to a CollectionViewSource. The source of that is bound to a property, which can change if the user selects an option.</p>
<p>When the list view source is updated due to a property changed event, everything updates correctly, but the view is not refreshed to take into account any changes in the CollectionViewSource filter. </p>
<p>If I attach a handler to the Changed event that the Source property is bound to I can refresh the view, but this is still the old view, as the binding has not updated the list yet.</p>
<p>Is there a decent way to make the view refresh and re-evaluate the filters when the source changes?</p>
<p>Cheers</p>
| <p>A bit late perhaps, but this may help other users so I'll post anyway...</p>
<p>Updating the CollectionView.Filter based on a PropertyChanged event is not supported by the framework.
There are a number of solutions around this.</p>
<p>1) Implementing the IEditableObject interface on the objects inside your collection, and calling BeginEdit and EndEdit when changing the property on which the filter is based.
You can read more about this on the Dr.WPF's excellent blog here : <a href="http://drwpf.com/blog/2008/10/20/itemscontrol-e-is-for-editable-collection/">Editable Collections by Dr.WPF</a></p>
<p>2) Creating the following class and using the RefreshFilter function on the changed object.</p>
<pre><code>public class FilteredObservableCollection<T> : ObservableCollection<T>
{
public void RefreshFilter(T changedobject)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, changedobject, changedobject));
}
}
</code></pre>
<p>Example:</p>
<pre><code>public class TestClass : INotifyPropertyChanged
{
private string _TestProp;
public string TestProp
{
get{ return _TestProp; }
set
{
_TestProp = value;
RaisePropertyChanged("TestProp");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
FilteredObservableCollection<TestClass> TestCollection = new FilteredObservableCollection<TestClass>();
void TestClass_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "TestProp":
TestCollection.RefreshFilter(sender as TestClass);
break;
}
}
</code></pre>
<p>Subscribe to the PropertyChanged event of the TestClass object when you create it, but don't forget to unhook the eventhandler when the object gets removed, otherwise this may lead to memory leaks</p>
<p>OR</p>
<p>Inject the TestCollection into the TestClass and use the RefreshFilter function inside the TestProp setter.
Anyhow, the magic here is worked by the NotifyCollectionChangedAction.Replace which updates the item entirely.</p>
|
How to implement conditional formatting in a GridView <p>I have a GridView on my aspx page which displays a collection of objects defined by the following class</p>
<pre><code>public class Item
{
public string ItemName{get; set;}
public object ItemValue{get; set;}
}
</code></pre>
<p>Then in my aspx markup I have something like this</p>
<pre><code><asp:GridView ID="MyTable" runat="server">
<Columns>
<asp:BoundField DataField="ItemName" />
<asp:BoundField DataField="ItemValue" />
</Columns>
</asp:GridView>
</code></pre>
<p>What I want to know is:<br/><i>
Is there a way to use conditional formatting on the ItemValue field, so that if the object is holding a string it will return the string unchanged, or if it holds a DateTime it will displays as DateTime.ToShortDateString().</i></p>
| <p>Not sure if you can use a BoundField, but if you change it to a TemplateField you could use a formatting function like in <a href="http://www.vbforums.com/showthread.php?t=545143">this link</a>.</p>
<p>ie something like</p>
<pre><code><%# FormatDataValue(DataBinder.Eval(Container.DataItem,"ItemValue")) %>
</code></pre>
<p>Then in your codebehind, you can add a Protected Function</p>
<pre><code>Protected Function FormatDataValue(val as object) As String
'custom enter code hereformatting goes here
End Function
</code></pre>
<p>Or you could do something in the OnRowCreated event of the gridview, like in <a href="http://www.netomatix.com/development/gridviewformatcolumn.aspx">this link</a></p>
<pre><code><asp:GridView ID="ctlGridView" runat="server" OnRowCreated="OnRowCreated" />
</code></pre>
<p>this function is conditional formatting based on whether or not the datavalue is null/is a double</p>
<pre><code>protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
Object ob = drv["ItemValue"];
if (!Convert.IsDBNull(ob) )
{
double dVal = 0f;
if (Double.TryParse(ob.ToString(), out dVal))
{
if (dVal > 3f)
{
TableCell cell = e.Row.Cells[1];
cell.CssClass = "heavyrow";
cell.BackColor = System.Drawing.Color.Orange;
}
}
}
}
}
</code></pre>
|
C++ Transformer scripting <p>Im looking to see if there are any pre-existing projects that do this.</p>
<p>Generally, I need something that will load in a c++ file and parse it and then based on a set of rules in script, transform it, say to add headers, reformat, or remove coding quirks for example, turning const int parameters in functions to int parameters, etc Or perhaps something that would generate a dom of some sorts based on the c++ file fed in that could be manipulated and written out again.</p>
<p>Are there any such projects/products out there free or commercial?</p>
| <p><a href="http://blog.mozilla.com/tglek/" rel="nofollow">Taras Glek</a> of Mozilla has been working on the <a href="https://developer.mozilla.org/en/Dehydra" rel="nofollow">dehydra tool</a>, based on <a href="http://www.eecs.berkeley.edu/~smcpeak/elkhound/" rel="nofollow">Elkhound</a> and scripted using JavaScript to transform the Mozilla codebase to fit with XPCOM and garbage collector changes.</p>
|
jFeed - sucess function not being executed (jQuery plugin) <p>I have the following Javascript code, where feed is a valid url to an rss feed.</p>
<pre><code>jQuery(function() {
jQuery.getFeed({
url:feed,
success: function(feed){
alert(feed);
}
});
});}
</code></pre>
<p>when i run this the alert never shows up. using firebug i can see the connection being made and the response from the feed.</p>
<p><strong><em>Note: i know this is a security issue and some browsers block it, this isnt the case at hand because i have worked around that issue and the browser no longer blocks the connection</em></strong></p>
<p>EDIT : for some reason i cant make the comment show up so here:</p>
<p>The call isnt being proxyed by a script at the moment, since this is a test im just overriding browser security settings with:</p>
<pre><code>netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
</code></pre>
| <p>With the information you give, we can see that your call is correct. The problem is probably somewhere else. In suggest that you dig in jFeed source code and disable feed parsing in $.ajax success method:</p>
<pre><code> $.ajax({
type: 'GET',
url: options.url,
data: options.data,
dataType: 'xml',
success: function(xml) {
var feed = xml; // <== was "var feed = new JFeed(xml);"
if(jQuery.isFunction(options.success)) options.success(feed);
}
});
</code></pre>
<p>If your alert pops up, it's a feed parsing problem. In this case, you can check that the xml is correct and submit it here for further investigation.</p>
<p><hr/></p>
<p>I've run some tests and checked jQuery code. You said that you worked around the browser security problem: I guess that you installed on you server a proxy script that will download the rss file from the distant server and then transmit it to your ajax request (because the browser will block ajax calls to a server different from the one your page is on). When making an ajax call with dataType : 'xml', jQuery expects that the content type of the response to contain the string "xml":</p>
<pre><code>var ct = xhr.getResponseHeader("content-type"),
xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
</code></pre>
<p>Here are my questions:</p>
<ul>
<li>Did you use a script as proxy script as I suppose ?</li>
<li>Does this script set the content-type to something containing xml ?</li>
</ul>
<p>Here is a minimalistic php sample shipped with jFeed:</p>
<pre><code><?php
header('Content-type: application/xml');
$handle = fopen($_REQUEST['url'], "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
</code></pre>
|
Changing values in Web.config with a Batch file or in .NET code <p>I have a web.config file on my computer.</p>
<p>There are alot of things i need to change and add in the file.
<em>(I am actually working with my SharePoint web.config file)</em></p>
<p>Can i do this with a Batch file, if so how would i do it.
Or how would i do it using VB.NET or C# code?</p>
<p>Any ideas guys?</p>
<p>Edit: i need to create a program to alter a web.config of lets say i web.config laying on my deskop and not the actual web.config of my project</p>
<p>Regards
Etienne</p>
| <p>You can modify it from C# code, for example:</p>
<pre><code>Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
{
appSettingsSection.Settings["foo"].Value = "bar";
config.Save();
}
</code></pre>
<p>where foo is the key and bar the value of the key to set, obviously. To remove a value, use Settings.Remove(key);</p>
<p>See the <a href="http://msdn.microsoft.com/en-us/library/ms151456.aspx" rel="nofollow">msdn documentation </a>for more information about the OpenWebConfiguration method and more.</p>
|
Handling multiple records in a MS SQL trigger <p>I am having to use triggers in MSSQL for the first time, well triggers in general. Having read around and tested this myself I realise now that a trigger fires per command and not per row inserted, deleted or updated.</p>
<p>The entire thing is some statistics for an advertising system. Our main stat table is rather large and doesn't contain the data in a way that makes sense in most cases. It contains one row per advert clicked, viewed and etc. As a user one is more inclined to want to view this as day X has Y amount of clicks and Z amount of views and so forth. We have done this purely based on a SQL query so far, getting this sort of report from the main table, but as the table has grown so does the time for that query to execute. Because of this we have opted for using triggers to keep another table updated and hence making this a bit easier on the SQL server.</p>
<p>My issue is now to get this working with multiple records. What I have done is to create 2 stored procedures, one for handling the operation of an insert, and one for a delete. My insert trigger (written to work with a single record) then graps the data off the Inserted table, and sends it off to the stored procedure. The delete trigger works in the same way, and (obviously?) the update trigger does the same as a delete + an insert.</p>
<p>My issue is now how to best do this with multiple records. I have tried using a cursor, but as far as I have been able to read and see myself, this performs really badly. I have considered writing some "checks" as well - as in checking to see IF there are multiple records in the commands and then go with the cursor, and otherwise simply just avoid this. Anyhow, here's my solution with a cursor, and im wondering if there's a way of doing this better?</p>
<pre><code>CREATE TRIGGER [dbo].[TR_STAT_INSERT]
ON [iqdev].[dbo].[Stat]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Date DATE
DECLARE @CampaignId BIGINT
DECLARE @CampaignName varchar(500)
DECLARE @AdvertiserId BIGINT
DECLARE @PublisherId BIGINT
DECLARE @Unique BIT
DECLARE @Approved BIT
DECLARE @PublisherEarning money
DECLARE @AdvertiserCost money
DECLARE @Type smallint
DECLARE InsertCursor CURSOR FOR SELECT Id FROM Inserted
DECLARE @curId bigint
OPEN InsertCursor
FETCH NEXT FROM InsertCursor INTO @curId
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @Date = [Date], @PublisherId = [PublisherCustomerId], @Approved = [Approved], @Unique = [Unique], @Type = [Type], @AdvertiserCost = AdvertiserCost, @PublisherEarning = PublisherEarning
FROM Inserted
WHERE Id = @curId
SELECT @CampaignId = T1.CampaignId, @CampaignName = T2.Name, @AdvertiserId = T2.CustomerId
FROM Advert AS T1
INNER JOIN Campaign AS T2 on T1.CampaignId = T2.Id
WHERE T1.Id = (SELECT AdvertId FROM Inserted WHERE Id = @curId)
EXEC ProcStatInsertTrigger @Date, @CampaignId, @CampaignName, @AdvertiserId, @PublisherId, @Unique, @Approved, @PublisherEarning, @AdvertiserCost, @Type
FETCH NEXT FROM InsertCursor INTO @curId
END
CLOSE InsertCursor
DEALLOCATE InsertCursor
END
</code></pre>
<p>The stored procedure is rather big and intense and I do not think there's a way of having to avoid looping through the records of the Inserted table in one way or another (ok, maybe there is, but I'd like to be able to read the code too :p), so I'm not gonna bore you with that one (unless you like to think otherwise). So pretty much, is there a better way of doing this, and if so, how?</p>
<p>EDIT: Well after request, here's the sproc</p>
<pre><code>CREATE PROCEDURE ProcStatInsertTrigger
@Date DATE,
@CampaignId BIGINT,
@CampaignName varchar(500),
@AdvertiserId BIGINT,
@PublisherId BIGINT,
@Unique BIT,
@Approved BIT,
@PublisherEarning money,
@AdvertiserCost money,
@Type smallint
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF @Approved = 1
BEGIN
DECLARE @test bit
SELECT @test = 1 FROM CachedStats WHERE [Date] = @Date AND CampaignId = @CampaignId AND CustomerId = @PublisherId
IF @test IS NULL
BEGIN
INSERT INTO CachedStats ([Date], CustomerId, CampaignId, CampaignName) VALUES (@Date, @PublisherId, @CampaignId, @CampaignName)
END
SELECT @test = NULL
DECLARE @Clicks int
DECLARE @TotalAdvertiserCost money
DECLARE @TotalPublisherEarning money
DECLARE @PublisherCPC money
DECLARE @AdvertiserCPC money
SELECT @Clicks = Clicks, @TotalAdvertiserCost = AdvertiserCost + @AdvertiserCost, @TotalPublisherEarning = PublisherEarning + @PublisherEarning FROM CachedStats
WHERE [Date] = @Date AND CustomerId = @PublisherId AND CampaignId = @CampaignId
IF @Type = 0 -- If click add one to the calculation
BEGIN
SELECT @Clicks = @Clicks + 1
END
IF @Clicks > 0
BEGIN
SELECT @PublisherCPC = @TotalPublisherEarning / @Clicks, @AdvertiserCPC = @TotalAdvertiserCost / @Clicks
END
ELSE
BEGIN
SELECT @PublisherCPC = 0, @AdvertiserCPC = 0
END
IF @Type = 0
BEGIN
UPDATE CachedStats SET
Clicks = @Clicks,
UniqueClicks = UniqueClicks + @Unique,
PublisherEarning = @TotalPublisherEarning,
AdvertiserCost = @TotalAdvertiserCost,
PublisherCPC = @PublisherCPC,
AdvertiserCPC = @AdvertiserCPC
WHERE [Date] = @Date AND CustomerId = @PublisherId AND CampaignId = @CampaignId
END
ELSE IF @Type = 1 OR @Type = 4 -- lead or coreg
BEGIN
UPDATE CachedStats SET
Leads = Leads + 1,
PublisherEarning = @TotalPublisherEarning,
AdvertiserCost = @TotalAdvertiserCost,
AdvertiserCPC = @AdvertiserCPC,
PublisherCPC = @AdvertiserCPC
WHERE [Date] = @Date AND CustomerId = @PublisherId AND CampaignId = @CampaignId
END
ELSE IF @Type = 3 -- Isale
BEGIN
UPDATE CachedStats SET
Leads = Leads + 1,
PublisherEarning = @TotalPublisherEarning,
AdvertiserCost = @TotalAdvertiserCost,
AdvertiserCPC = @AdvertiserCPC,
PublisherCPC = @AdvertiserCPC,
AdvertiserOrderValue = @AdvertiserCost,
PublisherOrderValue = @PublisherEarning
WHERE [Date] = @Date AND CustomerId = @PublisherId AND CampaignId = @CampaignId
END
ELSE IF @Type = 2 -- View
BEGIN
UPDATE CachedStats SET
[Views] = [Views] + 1,
UniqueViews = UniqueViews + @Unique,
PublisherEarning = @TotalPublisherEarning,
AdvertiserCost = @TotalAdvertiserCost,
PublisherCPC = @PublisherCPC,
AdvertiserCPC = @AdvertiserCPC
WHERE [Date] = @Date AND CustomerId = @PublisherId AND CampaignId = @CampaignId
END
END
END
</code></pre>
<p>After help, here's my final result, posted in case others have a similiar issue</p>
<pre><code>CREATE TRIGGER [dbo].[TR_STAT_INSERT]
ON [iqdev].[dbo].[Stat]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
-- insert all missing "CachedStats" rows
INSERT INTO
CachedStats ([Date], AdvertId, CustomerId, CampaignId, CampaignName)
SELECT DISTINCT
CONVERT(Date, i.[Date]), i.AdvertId, i.[PublisherCustomerId], c.Id, c.Name
FROM
Inserted i
INNER JOIN Advert AS a ON a.Id = i.AdvertId
INNER JOIN Campaign AS c ON c.Id = a.CampaignId
WHERE
i.[Approved] = 1
AND NOT EXISTS (
SELECT 1
FROM CachedStats as t
WHERE
[Date] = CONVERT(Date, i.[Date])
AND CampaignId = c.Id
AND CustomerId = i.[PublisherCustomerId]
AND t.AdvertId = i.AdvertId
)
-- update all affected records at once
UPDATE
CachedStats
SET
Clicks =
Clicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
),
UniqueClicks =
UniqueClicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.[Unique] = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
),
[Views] =
[Views] + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 2
),
UniqueViews =
UniqueViews + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.[Unique] = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 2
),
Leads =
Leads + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.[Unique] = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] IN (1,3,4)
),
PublisherEarning =
CachedStats.PublisherEarning + ISNULL((
SELECT SUM(PublisherEarning) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
), 0),
AdvertiserCost =
CachedStats.AdvertiserCost + ISNULL((
SELECT SUM(AdvertiserCost) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
), 0),
PublisherOrderValue =
PublisherOrderValue + ISNULL((
SELECT SUM(PublisherEarning) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 3
), 0),
AdvertiserOrderValue =
AdvertiserOrderValue + ISNULL((
SELECT SUM(AdvertiserCost) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 3
), 0),
PublisherCPC =
CASE WHEN (Clicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
)) > 0 THEN
(CachedStats.PublisherEarning + ISNULL((
SELECT SUM(PublisherEarning) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
), 0)) -- COST ^
/ (
Clicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
)
) --- Clicks ^
ELSE
0
END,
AdvertiserCPC =
CASE WHEN (Clicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
)) > 0 THEN
(CachedStats.AdvertiserCost + ISNULL((
SELECT SUM(AdvertiserCost) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
), 0)) -- COST ^
/ (
Clicks + (
SELECT COUNT(*) FROM Inserted s
WHERE s.Approved = 1
AND s.PublisherCustomerId = i.PublisherCustomerId
AND CONVERT(Date, s.[Date]) = CONVERT(Date, i.[Date])
AND s.AdvertId = i.AdvertId
AND s.[Type] = 0
)
) --- Clicks ^
ELSE
0
END
FROM
Inserted i
WHERE
i.Approved = 1 AND
CachedStats.Advertid = i.AdvertId AND
CachedStats.[Date] = Convert(Date, i.[Date]) AND
CachedStats.CustomerId = i.PublisherCustomerId
SET NOCOUNT OFF
END
</code></pre>
<p>It looks slightly different now because I had to index it per advertisement too - but thanks alot for the help - sped everything up from 30hour+ to 30 sec to generate the CachedStats from my own development Stat table :)</p>
| <p>The trick with these kinds of situations is to turn the sequential operation (for each record do <em>xyz</em>) into a set-based operation (an UPDATE statement).</p>
<p>I have analyzed your stored procedure and merged your separate UPDATE statements into a single one. This single statement can then be transformed into a version that can be applied to all inserted records at once, eliminating the need for a stored procedure and thereby the need for a cursor.</p>
<p>EDIT: Below is the code that we finally got working. Execution time for the whole operation went down from "virtually forever" (for the original solution) to something under one second, according to the OP's feedback. Overall code size also decreased quite noticeably.</p>
<pre><code>CREATE TRIGGER [dbo].[TR_STAT_INSERT]
ON [iqdev].[dbo].[Stat]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
-- insert all missing "CachedStats" rows
INSERT INTO
CachedStats ([Date], AdvertId, CustomerId, CampaignId, CampaignName)
SELECT DISTINCT
CONVERT(Date, i.[Date]), i.AdvertId, i.PublisherCustomerId, c.Id, c.Name
FROM
Inserted i
INNER JOIN Advert a ON a.Id = i.AdvertId
INNER JOIN Campaign c ON c.Id = a.CampaignId
WHERE
i.Approved = 1
AND NOT EXISTS (
SELECT 1
FROM CachedStats
WHERE Advertid = i.AdvertId AND
CustomerId = i.PublisherCustomerId AND
[Date] = CONVERT(DATE, i.[Date])
)
-- update all affected records at once
UPDATE
CachedStats
SET
Clicks = Clicks + i.AddedClicks,
UniqueClicks = UniqueClicks + i.AddedUniqueClicks,
[Views] = [Views] + i.AddedViews,
UniqueViews = UniqueViews + i.AddedUniqueViews,
Leads = Leads + i.AddedLeads,
PublisherEarning = PublisherEarning + ISNULL(i.AddedPublisherEarning, 0),
AdvertiserCost = AdvertiserCost + ISNULL(i.AddedAdvertiserCost, 0),
PublisherOrderValue = PublisherOrderValue + ISNULL(i.AddedPublisherOrderValue, 0),
AdvertiserOrderValue = AdvertiserOrderValue + ISNULL(i.AddedAdvertiserOrderValue, 0)
FROM
(
SELECT
AdvertId,
CONVERT(DATE, [Date]) [Date],
PublisherCustomerId,
COUNT(*) NumRows,
SUM(CASE WHEN Type IN (0) THEN 1 ELSE 0 END) AddedClicks,
SUM(CASE WHEN Type IN (0) AND [Unique] = 1 THEN 1 ELSE 0 END) AddedUniqueClicks,
SUM(CASE WHEN Type IN (2) THEN 1 ELSE 0 END) AddedViews,
SUM(CASE WHEN Type IN (2) AND [Unique] = 1 THEN 1 ELSE 0 END) AddedUniqueViews,
SUM(CASE WHEN Type IN (1,3,4) AND [Unique] = 1 THEN 1 ELSE 0 END) AddedLeads,
SUM(PublisherEarning) AddedPublisherEarning,
SUM(AdvertiserCost) AddedAdvertiserCost,
SUM(CASE WHEN Type IN (3) THEN PublisherOrderValue ELSE 0 END) AddedPublisherOrderValue,
SUM(CASE WHEN Type IN (3) THEN AdvertiserOrderValue ELSE 0 END) AddedAdvertiserOrderValue
FROM
Inserted
WHERE
Approved = 1
GROUP BY
AdvertId,
CONVERT(DATE, [Date]),
PublisherCustomerId
) i
INNER JOIN CachedStats cs ON
cs.Advertid = i.AdvertId AND
cs.CustomerId = i.PublisherCustomerId AND
cs.[Date] = i.[Date]
SET NOCOUNT OFF
END
</code></pre>
<p>The operations involving the <code>CachedStats</code> table will greatly benefit from one multiple-column index over <code>(Advertid, CustomerId, [Date])</code> (as confirmed by the OP).</p>
|
Getting a column definition by name in wpf <p>For example:</p>
<pre><code><Grid Name="TestGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Name="TestColumnName" Width="*" />
</Grid.ColumnDefinitions>
</Grid>
</code></pre>
<p>I would like to be able to access the column definition in code using the name 'TestColumnName'.</p>
| <p>Use the x:Name property instead of Name :)</p>
|
How can I eval environment variables in Perl? <p>I would like to evaluate an environment variable and set the result to a variable:</p>
<pre><code>$x=eval($ENV{EDITOR});
print $x;
</code></pre>
<p>outputs:</p>
<pre><code>/bin/vi
</code></pre>
<p>works fine.</p>
<p>If I set an environment variable QUOTE to \' and try the same thing:</p>
<pre><code>$x=eval($ENV{QUOTE});
print $x;
</code></pre>
<p>outputs:</p>
<p>(nothing)</p>
<pre><code>$@ set to: "Can't find a string terminator anywhere before ..."
</code></pre>
<p>I do not wish to simply set <code>$x=$ENV{QUOTE};</code> as the eval is also used to call a script and return its last value (very handy), so I would like to stick with the eval(); Note that all of the Environment variables eval'ed in this manner are set by me in a different place so I am not concerned with malicious access to the environment variables eval-ed in this way.</p>
<p>Suggestions?</p>
| <p>Well, of course it does nothing. </p>
<p>If your ENV varaible contains text which is half code, but isn't and you give the resulting string to something that <b>eval</b>uates that code as Perl, of <strong>course</strong> it's not going to work.</p>
<p>You only have 3 options: </p>
<ol>
<li>Programmatically process the string so it doesn't have invalid syntax in it </li>
<li>Manually make sure your ENV variables are not rubbish </li>
<li>Find a solution not involving <b>eval</b> but gives the right result. </li>
</ol>
<p>You may as well complain that </p>
<pre><code> $x = '
</code></pre>
<p>Is not valid code, because that's essentially what's occurring. </p>
<h2>Samples of Fixing the value of 'QUOTE' to work</h2>
<pre><code># Bad.
QUOTE="'" perl -wWe 'print eval $ENV{QUOTE}; print "$@"'
# Can't find string terminator "'" anywhere before EOF at (eval 1) line 1.
# Bad.
QUOTE="\'" perl -wWe 'print eval $ENV{QUOTE}; print "$@"'
# Can't find string terminator "'" anywhere before EOF at (eval 1) line 1.
# Bad.
QUOTE="\\'" perl -wWe 'print eval $ENV{QUOTE}; print "$@"'
# Can't find string terminator "'" anywhere before EOF at (eval 1) line 1.
# Good
QUOTE="'\''" perl -wWe 'print eval $ENV{QUOTE}; print "$@"'
# '
</code></pre>
|
How to efficiently scale and crop images in an ASP.NET app? <p>We're having problems with an ASP.NET application which allows users to upload, and crop images. The images are all scaled to fixed sizes afterwards. We basically run out of memory when a large file is processed; it seems that the handling of JPEG is rather inefficient -- we're using System.Drawing.BitMap. Do you have any general advice, and perhaps some pointers to a more efficient image handling library? What experiences do you have?</p>
| <p>I had the same problem, the solution was to use System.Drawing.Graphics to do the transformations and dispose every bitmap object as soon as I was finished with it. Here's a sample from my library (resizing) :</p>
<pre><code> public Bitmap ApplyTo(Bitmap bitmap)
{
using (bitmap)
{
Bitmap newBitmap = new Bitmap(bitmap, CalculateNewSize(bitmap));
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
graphics.SmoothingMode =
SmoothingMode.None;
graphics.InterpolationMode =
InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality =
CompositingQuality.HighQuality;
graphics.DrawImage(
bitmap,
new Rectangle(0, 0, newBitmap.Width, newBitmap.Height));
}
return newBitmap;
}
}
</code></pre>
|
Combining joint probabilities <p>I am trying to work out the expression for a probability distribution (related to bioinformatics), and am having trouble combining the information about a random variable from two different sources. Essentially, here is the scenario:
There are 3 discrete random variables X, A & B. X depends on A and B. A and B are related only through X, i.e. A and B are independent given X. Now, I have derived the expressions for:
P(X, A) and P(X, B). I need to calculate P(X, A, B) - this is not a straightforward application of the chain rule.</p>
<p>I can derive P(X | A) from the first expression since P(A) is available. B is never observed independently of A, P(B) is not readily available - at best I can approximate it by marginalizing over A, but the expression P(A, B) does not have a closed form so the integration is tricky.</p>
<p>Any thoughts on how P(X, A, B) can be derived, without discarding information? Many thanks in advance.</p>
<p>Amit</p>
| <p>What you're dealing with here is an undirected acyclic graph. A is conditionally independent of B given X, but X depends (I assume directly) on A and B. I'm a little confused about the nature of your problem, i.e. what form your probability distributions are specified in, but you could look at <a href="http://en.wikipedia.org/wiki/Belief%5Fpropagation" rel="nofollow">belief propagation.</a></p>
|
Would you use the S#arp Architecture in a new commercial project? <p>The <a href="http://code.google.com/p/sharp-architecture/">S#arp Architecture</a> seems really cool, but do you think it's still too new to make the commitment to it in an important new project? (Let's assume the project appears to be a good fit for it at first glance.)</p>
<p>It all <em>seems</em> very good, I'm just concerned that the new project I'm working on is using all the newer technologies - WCF, ASP.NET MVC etc - and that if I add one more infant technology I'm going to end up with lots of problems and not enough technical skill or community support to figure them out...</p>
<p>It's just so hard to resist that demanding boy inside me: <em>I wanna have the newest stuff!</em></p>
<p><em>(Disclaimer: I'm very new to the S#arp Architecture, so I'm mostly basing my optimistic opinion of it on the stated goals of the project, articles, bits of sample code etc.)</em></p>
| <p><a href="http://fancydressoutfitters.co.uk">http://fancydressoutfitters.co.uk</a> was built using:</p>
<ul>
<li>Sharp Architecture (ASP.NET MVC, NHibernate, Fluent NHibernate), </li>
<li>Spark View Engine</li>
<li>AutoMapper</li>
<li>NHibernate Validator</li>
<li>xVal Validation Framework</li>
<li>N2CMS</li>
<li>PostSharp</li>
<li>Solr & SolrNet</li>
</ul>
<p>and it worked very well indeed. We documented a lot of our learnings from this project as blogs which you can find here: <a href="http://delicious.com/howardvanrooijen/fdo-casestudy">http://delicious.com/howardvanrooijen/fdo-casestudy</a></p>
<p>We also decided that we wanted to give back to the various Open Source Communities who helped us, so we created a new Sharp Architecture Showcase Application called Who Can Help Me? The source is available from <a href="http://whocanhelpme.codeplex.com">http://whocanhelpme.codeplex.com</a> and a live demo can be found at <a href="http://who-can-help.me">http://who-can-help.me</a></p>
|
How do I change the ForeColor of a GroupBox without having that color applied to every child control as well? <p>I need to change the group box text to a specific color without changing the color of what is inside the group box. </p>
<p>The following code sets the <code>ForeColor</code> of the <code>GroupBox</code> to pink but this settings cascades to all the child controls as well:</p>
<pre><code>groupbox.ForeColor = Color.Pink
</code></pre>
<p>How do I change the <code>ForeColor</code> of a <code>GroupBox</code> without having that color applied to every child control as well?</p>
| <p>You could iterate through all the controls in the GroupBox and set their respective ForeColor properties:</p>
<pre><code>groupBox1.ForeColor = Color.Pink;
foreach (Control ctl in groupBox1.Controls) {
ctl.ForeColor = SystemColors.ControlText;
}
</code></pre>
|
How to change the pop-up position of the jQuery DatePicker control <p>Any idea how to get the DatePicker to appear at the end of the associated text box instead of directly below it? What tends to happen is that the text box is towards the bottom of the page and the DatePicker shifts up to account for it and totally covers the text box. If the user wants to type the date instead of pick it, they can't. I'd rather have it appear just after the text box so it doesn't matter how it adjusts vertically.</p>
<p>Any idea how to control the positioning? I didn't see any settings for the widget, and I haven't had any luck tweaking the CSS settings, but I could easily be missing something.</p>
| <p>Here's what I'm using:</p>
<pre><code>$('input.date').datepicker({
beforeShow: function(input, inst)
{
inst.dpDiv.css({marginTop: -input.offsetHeight + 'px', marginLeft: input.offsetWidth + 'px'});
}
});
</code></pre>
<p>You may also want to add a bit more to the left margin so it's not right up against the input field.</p>
|
Hierarchical RSS Feeds <p>Is it possible to create an RSS feed with a multi-level hierarchy, sort of like a directory structure? Is this allowed per the RSS spec?
If this is possible, does anyone know of what limitations there might be? As in, are there any particular readers that would not support it?
My main concern here is that I want to create an RSS feed to use with the "Live Bookmarks" feature in many browsers, but be able to maintain the directory feel.</p>
<p>I'm not concerned with the code to generate the RSS, though an example of what the RSS xml would look like would be appreciated.</p>
| <p>It's not possible per the <a href="http://cyber.law.harvard.edu/rss/rss.html" rel="nofollow">Rss Spec</a>, and if you attempt to do so i'm afraid that a lot of browsers will not recognize rss format.</p>
|
Android SMS Content (content://sms/sent) <p>I'm having a problem reading the SMS messages from the device.
When acquiring a content provider for the URI '<code>content://sms/inbox</code>',
everything is fine, I can read the "person" column to find the foreign key
into the people table and ultimately reach the contact and their
name.</p>
<p>However, I also want to traverse the sent messages too. When reading
from 'content://sms/sent', the person field always appears to be 0. Is
this the correct field to be reading to locate the recipient data for
the sent message? If so - any idea why mine is always 0?</p>
<p>All my testing has been done in the emulator and I've created 3
contacts. I've sent messages to those contacts from the emulator in
the normal manner you'd send a message.</p>
<p>Just to reiterate, I can see the 4 sent messages and read the
associated body text. My problem is that I can't seem to read the
"person" ID and hence I can't work out who the recipient is.</p>
<p>Any help would be greatly appreciated.</p>
<p>Many thanks,</p>
<p>Martin.</p>
| <p>Use the address column. I guess the person column is ignored because people can send SMSs to phone numbers that are not in the contacts list.</p>
<pre><code>// address contains the phone number
Uri phoneUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, address);
if (phoneUri != null) {
Cursor phoneCursor = getContentResolver().query(phoneUri, new String[] {Phones._ID, Contacts.Phones.PERSON_ID}, null, null, null);
if (phoneCursor.moveToFirst()) {
long person = phonesCursor.getLong(1); // this is the person ID you need
}
}
</code></pre>
|
Palette Animation in OpenGL <p>I am making an old-school 2d game, and I want to animate a specific color in my texture.</p>
<p>Only ways I know are:</p>
<ol>
<li>opengl shaders.</li>
<li>animating one color channel only.</li>
<li>white texture under the color-animated texture.</li>
</ol>
<p>But I don't want to use shaders, I want to make this game as simple as possible, not many extra openGL functions etc..</p>
<p>And the color channel animating doesnt fit this because I need all color channels in my textures.</p>
<p>Currently I am doing it with 2 textures: white texture under the other texture, translated the specific pixel color into transparent, then I change white texture color with glColor3f() function to what ever I want, and I see the "palet animation" on that specific color.</p>
<p>But that style sounds pretty hacky, so I am wondering if there is some better trick to this?</p>
| <p>While I am unfamiliar with the palette texture extension I still recommend using a fragment shader for this sort of effect. It is almost trivial to do a color-key replacement with a shader, versus the other methods you mentioned, and will be way faster than writing the palette functionality yourself.</p>
<p>Here's an example GLSL fragment shader that would replace the color white in a texture for whatever color is passed in.</p>
<pre><code>uniform vec4 fvReplaceColor;
uniform sampler2D baseMap;
varying vec2 Texcoord;
void main( void )
{
vec4 fvBaseColor = texture2D( baseMap, Texcoord);
if(fvBaseColor == vec4(1.0, 1.0, 1.0, 1.0))
fvBaseColor = fvReplaceColor;
gl_FragColor = fvBaseColor;
}
</code></pre>
<p>Yes, it does take a little bit extra to set up shader, but but what it sounds like you are trying to do I feel it's the best approach.</p>
|
Is EJB inheritance through different EJB modules possible? <p>Is it possible to have an entity class which inherits from another (abstract) entity class from another ejb module?</p>
<p>EclipseLink for example doesn't create the depending columns in database table of the subclass. It simply ignores the (abstract) superclass entity.</p>
| <p>The annotation @Entity didn't work in my project but the annotation @MappedSuperclass which is also part of JPA 1.0 now works very well.</p>
<p>Sorry for that maybe stupid question. ;-)</p>
|
Why can't I enter text in Winform hosted in ATL dialog? <p>I am working on embedding winform controls into an ATL dialog (see <a href="http://stackoverflow.com/questions/642082/how-to-embed-windows-form-in-unmanaged-atl-gui">here</a> for how I did so far).</p>
<p>Now I have encountered a rather strange problem.<br />
For some reason, the text fields in my winforms display fine, but I am unable to change the text in them by typing on the keyboard.</p>
<p>However, I can copy and paste text from elsewhere into the text field and it is then treated as normal input (event for text change is fired etc.).</p>
<p>How do I get the text fields to behave normally and allow text input via keyboard?<br />
Any hints?</p>
| <p>There's something wrong with your message loop. TranslateMessage() is the likely candidate, that's the one that generates WM_CHAR messages from a WM_KEYDOWN message.</p>
|
javascript form - bypassing default behaviour for ajax <p>I am trying to use the following code below. What I want is to get the value of which radio button is selected, sent back to the javascript method. Any variation I try seems to fail.</p>
<pre><code><html>
<head>
<style type="text/css">
body { background-color: black; color: white; }
</style>
<script type="text/javascript">
function handleClick(event)
{
alert(this.textBox1.value);
event.preventDefault(); // disable normal form submit behavior
return false; // prevent further bubbling of event
}
</script>
</head>
<body">
<form name="myform">
<div>
<input type="radio" name="test1" value="Cheese">
<input type="radio" name="test2" value="Grapes">
<input type="radio" name="test3" value="Crackers">
</div>
<input type="submit" onsubmit=JavaScript:handleClick(value) value="Update"/>
</form>
</body>
</html>
</code></pre>
| <p>Your code is cut of but I think that you want to do something like this:</p>
<pre><code><html>
<head>
<script type="text/javascript">
function alertThing() {
alert(document.getElementsByName('textBox1')[0].value);
return false;
}
</script>
</head>
<body>
<form action="myPage.php" method="post" onsubmit="return alertThing();">
<input type="text" name="textBox1" value="hello" />
<input type="submit" value="Submit the form!" />
</form>
</body>
</html>
</code></pre>
<p>This will alert the value but it will not submit the form. Hope I helped you!</p>
<p>//Linus Unnebäck</p>
|
Convention over configuration with Spring MVC using ControllerClassNameHandlerMapping? <p>Following the directions from <a href="http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-coc" rel="nofollow">Spring Source</a> and the book Spring in Action, I am trying to set up Spring MVC in a way that minimizes xml configuration. However according to Spring Source this is how you set up the ControllerClassNameHandlerMap</p>
<pre><code><bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean id="viewShoppingCart" class="x.y.z.ViewShoppingCartController">
<!-- inject dependencies as required... -->
</bean>
</code></pre>
<p>Which strikes me as being completely useless, as it is actually simpler to use the handlers to just set the beans manually, as it is about the same amount of XML.</p>
<p>Now the book Spring in Action makes it sound like all you need is the first line from that code block to use the ControllerClassNameHandlerMapping, which would make it far more useful. However, I have not yet been able to get this to work.</p>
<p>Can anyone with Spring experience help me out?</p>
| <p>There are actually two different things going on here: </p>
<ol>
<li>the mapping between URLs and controllers </li>
<li>the definition of controllers as Spring beans</li>
</ol>
<p>For #1, if you define the ControllerClassNameHandlerMapping as you've done, that takes care of the URL-to-controller mapping. E.g., <a href="http://example.com/context/home">http://example.com/context/home</a> -> HomeController</p>
<p>For #2, you can define the controller beans as you've done. Or you can go down the path of using the Spring 2.5-style annotations for @Controllers and auto-wiring, which eliminates the need for XML bean definitions. Or not, the choice is up to you.</p>
<p>What you avoid by using ControllerClassNameHandlerMapping is having to explictly map all your potential URLs to Controllers. We have used this successfully.</p>
<p>One other thing you might want to use is the DefaultRequestToViewNameTranslator:</p>
<pre><code><!-- Generates view names based on the request url (e.g. "/home.htm" => "home", "/user/list.htm" => "user/list", etc.) -->
<bean id="viewNameTranslator" class="org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator"/>
</code></pre>
<p>We also use the UrlBasedViewResolver:</p>
<pre><code><!-- Maps view names to tiles view definitions files. E.g., "home" => "home", etc. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
</code></pre>
|
Anonymous Generics - Where would I use this? <p>I recently discovered a trick using casting by example to instantiate a generic with an anonymous type.</p>
<p><a href="http://brendanjerwin.com/blog/2009/03/19/anonymous-generics/" rel="nofollow">http://brendanjerwin.com/blog/2009/03/19/anonymous-generics/</a></p>
<p>So, its a neat trick, but when would it be used? Any ideas?</p>
| <p>The primary place I use this trick is for creating a collection container for anonymous types. </p>
<pre><code>public static List<T> CreateListOfAnonymous<T>(T unused) {
return new List<T>();
}
</code></pre>
<p>Usage:</p>
<pre><code>public void Foo() {
var list = CreateListOfAnonymous(new { Name = String.Empty, Age = 42 });
list.Add(new { Name = "foo", Age = 28 });
}
</code></pre>
|
Whats the best way to get data from other websites programmatically? "amazon offers for example" <p>I want to build a small application which will go to some websites and read specific data from these website, i want the application to be generic as i can so it work on any website i want later.
So there is a good way to parse website using .net?</p>
| <p>I have been told that a good toolkit for doing screen scraping in .NET is <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">HTML Agility Pack</a>.</p>
<p>You should be aware that it's always very hard to make a screen scraping solution stable, or general-purpose as you describe.</p>
<p>Also see other answers to this question: <a href="http://stackoverflow.com/questions/646484/screen-scraping-regular-expressions-or-xquery-expressions">http://stackoverflow.com/questions/646484/screen-scraping-regular-expressions-or-xquery-expressions</a></p>
|
C# Synchronized object - duplicate code with writing accessors <p>I like to use objects which sync itself using a private object which is locked when the property is changed.
Is there any generic way to achieve this?
My code looks always like this for each property (with one locker object)</p>
<pre><code>private Object locker = new Object();
private int x;
public int X
{
get {return x;}
set{
lock(locker){x=value;}
}
</code></pre>
<p>Is thee an easier way to achieved thread-safe modification of properties.</p>
| <p>Your code shouldn't look like that - you should lock on the <em>get</em> as well. Otherwise threads fetching data may not get the most recent value, for complicated memory model reasons.</p>
<p>But no, I don't know of any ways around this. You could do odd stuff with lambda expressions and extension methods, but it would be overkill IMO.</p>
<p>You should also strongly consider whether you <em>really</em> want the individual properties to be thread-safe. It may be the right thing to do - but I find that usually I don't need most types to be thread-safe. Only a few types need to directly know about threading, and they then take out appropriate locks while they're using the object, rather than the object doing the locking itself. It does depend on what you're doing though.</p>
<p>Another alternative for some cases is to use immutable types - that's nice when you can do it, although if you need one thread to see the changes made in another you'll need <em>some</em> sort of volatility or synchronization.</p>
|
ASP.NET Server Side Viewstate <p>I have read some approaches to storing viewstate on the server:</p>
<p><a href="http://aspalliance.com/72%5FServer%5FSide%5FViewstate" rel="nofollow">Here is one</a></p>
<p><a href="http://www.clanmonroe.com/Blog/archive/2008/08/05/efficient-server-side-view-state-persistence.aspx" rel="nofollow">Here is another</a></p>
<p>But they are sort of complicated. I am looking for a way to persist an object without having to serialize it. I could use session state, but if a user opens more than one window, there could be overwrites of the object. </p>
<p>Is there a simple solution to this?</p>
| <blockquote>
<p>I am looking for a way to persist an object without having to serialize it.</p>
</blockquote>
<p>Be careful with that. This will have a dramatic impact on the memory use of your site, and memory use is often the biggest impediment to scalability.</p>
|
Testing/Debugging website running on iis 6.0 and 7.0 with an xp development environment? <p>Considering iis 6.0 and above can't run on xp what options have i available?</p>
<p>Remote debugging (using a win 2k3 host) i'm aware of but i might not have the facilities available very easily</p>
| <p>I'm not sure of your exact situation (availability of OS licenses, specifically), but you could consider virtualization. I've used VirtualBox ( <a href="http://www.virtualbox.org/" rel="nofollow">http://www.virtualbox.org/</a> ) and I've heard that MS Virtual PC ( <a href="http://www.microsoft.com/Windows/products/winfamily/virtualpc/default.mspx" rel="nofollow">http://www.microsoft.com/Windows/products/winfamily/virtualpc/default.mspx</a> ) is pretty good for the MS Operating Systems.</p>
<p>I'll note that I have not done exactly what you are specifying. I suspect, however, that once IIS was running in the VM, you'd be able to do "remote" debugging to the VM. Also note that you'd need fair hardware to run both the virtualized OS as well as your main host/development OS. </p>
|
Query several EAV attributes in separate columns <p>I am facing issues trying to write a query. (this is slightly modified from my previous question)</p>
<p>My tables are laid out as follows:</p>
<pre><code> tblTicketIssues.TicketID
tblTicketIssues.RequesterID
tblPersonnelProfile.PersonnelID
tblPersonnelProfile.FirstName
tblPersonnelProfile.LastName
tblTicketAttribute.TicketID
tblTicketAttribute.Attribute
tblTicketAttribute.AttributeValue
</code></pre>
<p>I have to display the following fields:</p>
<pre><code> TicketID, RequesterFullName, UrgentPriorityID, MediumPriorityID,
LowPrioritytID
</code></pre>
<p>This is the part that is challenging:</p>
<p>If tblTicketAttribute.Attribute= "Urgent" then the value from tblTicketAttribute.AttributeValue is displayed in UrgentPriority column</p>
<p>If tblTicketAttribute.Attribute= "Medium" then the value from tblTicketAttribute.AttributeValue is displayed in MediumPriority column</p>
<p>If tblTicketAttribute.Attribute= "Low" then the value from tblTicketAttribute.AttributeValue is displayed in LowPriority column</p>
<p>If tblTicketAttribute.Attribute= "Closed" then
<p>The values in tblTicketAttribute.Attribute include "Urgent", "Medium", "Low", "Over30", "Over60", "Over90", "Closed"</p>
<p>I don't need to display all records. Only "Urgent", "Medium" & "Low".</p>
| <p>I'm not 100% sure that I understand, but I think this satisfies what you're asking for. Note that this was assuming that the database is MySQL, you didn't specify. The syntax of the IF() and CONCAT() may be slightly different if it's something else.</p>
<p><em>EDIT: updated query as per Csharp's "answer" below. <code>MAX</code>-ing the name is a bit of a hack.</em></p>
<pre><code>SELECT t.TicketID,
MAX(CONCAT(p.FirstName, ' ', p.LastName)) AS RequesterFullName,
MAX(IF(a.Attribute = 'Urgent', a.AttributeValue, NULL)) AS UrgentPriorityID,
MAX(IF(a.Attribute = 'Medium', a.AttributeValue, NULL)) AS MediumPriorityID,
MAX(IF(a.Attribute = 'Low', a.AttributeValue, NULL)) AS LowPriorityID
FROM tblTicketIssues AS t
LEFT JOIN tblPersonnelProfile AS p ON p.PersonnelID = t.RequesterID
LEFT JOIN tblTicketAttribute AS a ON a.TicketID = t.TicketID
WHERE a.Attribute IN ('Urgent', 'Medium', 'Low')
GROUP BY t.TicketID;
</code></pre>
|
Slow performance of SqlDataReader <p>I've query executing ~2 secs in MSSMS (returning 25K of rows)</p>
<p>Same query used in .NET (sqlReader) exetuting few minutes!</p>
<p>I've also tried to execute only reader </p>
<p>(commented all code in while loop just leaving reader.Read() ) - still same!</p>
<p>Any idea what's up?</p>
| <p>I would set up a trace in SQL Server Profiler to see what SET options settings the connection is using when connecting from .NET code, and what settings are being used in SSMS. By SET options settings, I mean</p>
<pre><code>ARITHABORT
ANSI_NULLS
CONCAT_NULL_YIELDS_NULL
//etc
</code></pre>
<p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/ms190707%28SQL.90%29.aspx" rel="nofollow">MSDN</a> for a table of options</p>
<p>I have seen the problem before where the options were different (in that case, <code>ARITHABORT</code>) and the performance difference was huge.</p>
|
How to test if a C# Hashtable contains a specific key/value pair? <p>I'm storing a bunch of supposedly-unique item IDs as a key and the file locations as the value in a hash table while traversing a table. While I am running through it, I need to make sure that they key/location pair is unique or throw an error message. I have the hashtable set up and am loading the values, but am not sure what to test:</p>
<pre><code>Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
//what goes here? Would be contains item["Path"] as the value for the key)
{
//throw error
}
}
</code></pre>
| <p>Try this:</p>
<pre><code>Hashtable check_for_duplicates = new HashTable();
foreach (object item in items)
{
if (check_for_duplicates.ContainsKey(item["ItemID"]) &&
check_for_duplicates[item["ItemID"]].Equals(item["Path"]))
{
//throw error
}
}
</code></pre>
<p>Also, if you're using .NET 2.0 or higher, consider using Generics, like this:</p>
<pre><code>List<Item> items; // Filled somewhere else
// Filters out duplicates, but won't throw an error like you want.
HashSet<Item> dupeCheck = new HashSet<Item>(items);
items = dupeCheck.ToList();
</code></pre>
<p>Actually, I just checked, and it looks like HashSet is .NET 3.5 only. A Dictionary would be more appropriate for 2.0:</p>
<pre><code>Dictionary<int, string> dupeCheck = new Dictionary<int, string>();
foreach(Item item in items) {
if(dupeCheck.ContainsKey(item.ItemID) &&
dupeCheck[item.ItemID].Equals(item.Path)) {
// throw error
}
else {
dupeCheck[item.ItemID] = item.Path;
}
}
</code></pre>
|
Need to write a ruby script to create a csv file of the data on the website <p>There is a website which gives me the information of pin codes of a particular state for example <a href="http://www.indiapost.gov.in/pin/pinsearch.aspx" rel="nofollow">indian postal website</a>, gives the details when I select the state in the drop down.</p>
<p>I need to write the script in ruby which would create the CSV file with all the data for a particular state. </p>
<p>Today is my first day on ruby and not sure how to approach this. Any help in the right direction would be appreciated.</p>
<p>Thanks</p>
| <p>You should be interested in the FasterCSV gem</p>
<p><a href="http://fastercsv.rubyforge.org/" rel="nofollow">http://fastercsv.rubyforge.org/</a></p>
<pre><code>gem install fastercsv
</code></pre>
<p>And then, something like that:</p>
<pre><code>require 'fastercsv'
FasterCSV.open("temp.csv", "w") do |csv|
csv << ["line1row1", "line1row2"]
csv << ["line2row1", "line2row2"]
# ...
end
</code></pre>
|
oracle 10g - Monitor large row deletions <p>how can i monitor rows being deleted(say 20 rows)?
consider, i am a dba and monitoring an oracle database.. i have to get an alert if someone deletes more than 20 rows.. i should avoid a trigger since it is costly.. is there any other way around? </p>
<p>how can i parse the redo log and trap the sql that might have caused a bulk row delete?
my scenario is, as soon as a bulk row delete happens, the DBA should be intimated.. any other way other than trigger? i ve been using a trigger and I am looking for a way to avoid triggers..</p>
| <p>What were you hoping to do if such a deletion occurs? Unless you've saved the deleted rows somewhere (which would require a trigger) you can't get them back, nor can you even know what they were.</p>
<p>If deleting rows is a problem and recovery is likely to be needed, don't allow rows to be deleted: add a "deleted" column and set its value in an UPDATE rather than a DELETE (or add a trigger.)</p>
<p>Alternatively, maybe you could find a way to parse the redo logs? I've never tried, but I imagine it's possible given enough effort.</p>
<p>Personally, I think I'd:</p>
<ol>
<li>re-examine the "need" to know about deletions and if I can't change that,</li>
<li>overcome my fear of triggers.</li>
</ol>
|
Oracle Deadlock when Hibernate application loading data for readonly use <p>We are experiencing an Oracle Deadlock (org.hibernate.util.JDBCExceptionReporter - ORA-00060: deadlock detected while waiting for resource) error. It has been suggested that the issue is with a process that is performing readonly operations using Hibernate while another process is performing an update on the same row.</p>
<p>The readonly process in question is configured using Hibernate and Spring. We have not explicitly defined a transaction for the service. While that may not be ideal - I fail to see why Hibernate would try to get an exclusive lock on a row when no save/update operations were performed - only a get/load.</p>
<p>So my question is: Does Hibernate, when no explicit transaction management is defined, try to get a read/write lock on a row even if only a "load" of an object is performed. No Save/Update is performed.</p>
<p>Is it possible that defining a transaction around the service that is loading data, and then specifically saying READONLY on the transactionAttributes would cause Hibernate to ignore an already existing row lock and just load the data for readonly purposes?</p>
<p>Here are some code examples:</p>
<p>For loading the record we are using a HibernateDaoTemplate</p>
<pre><code>public class HibernatePurchaseOrderDataService extends HibernateDaoSupport implements PurchaseOrderDataService {
public PurchaseOrderData retrieveById(Long id) {
return (PurchaseOrderData)getHibernateTemplate().get(PurchaseOrderData.class, id);
}
}
</code></pre>
<p>The Spring configuration for the service calling this method is:</p>
<pre><code><bean id="orderDataService"
class="com.example.orderdata.HibernatePurchaseOrderDataService">
<property name="sessionFactory" ref="orderDataSessionFactory"/>
</bean>
<bean id="orderDataSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="hibernateDataSource"/>
<property name="hibernateProperties" ref="hibernateProperties"/>
<property name="mappingResources">
<list>
<value>com/example/orderdata/PurchaseOrderData.hbm.xml</value>
<value>com/example/orderdata/PurchaseOrderItem.hbm.xml</value>
</list>
</property>
</bean>
</code></pre>
<p>The actual deadlock is occurring on one of the PurchaseOrderItem records being loaded by the call to the load the PurchaseOrder.</p>
<p>Would this cause a deadlock if the record being loaded was locked by another process? And if so - would adding a transaction wrapper such as the one below solve the problem?</p>
<pre><code><bean id="txWrappedOrderDataService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="target" ref="orderDataService"/>
<property name="transactionAttributes">
<props>
<!-- all methods require a transaction -->
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
</code></pre>
<p>Update: The DataBase team has seen trace messages on the server that seem to indicate that our "readonly" process is actually writing to the database automatically. There are logged "UPDATE" commands that are performed on the exact columns we are reading from the database. It seems that Hibernate is automatically writing these records back out to the database (even though we aren't asking it to). That would probably explain why there is a deadlock.</p>
<p>Could this be because of a Session FLUSH or something similar? Looking more like the solution might be to use a transaction wrapper with readOnly on it...</p>
| <p>Involuntary updates might happen with hibernate when you use setters that manipulate the value they actually set. An example would be a setter for an String attribute that replaces a value of null with "". A likely candidate are also collections. Make sure setters don't replace the contained collection. If you replace a collection of an entity with a another collection containing the same contents, hibernate will not be able to realize that and update the full collection.</p>
|
What's the advantage of this indirect function call? <p>I found the following code in a library:</p>
<pre><code>class Bar {
public:
bool foo(int i) {
return foo_(i);
}
private:
virtual bool foo_(int i) = 0;
};
</code></pre>
<p>Now I'm wondering: Why would you use this indirection? Could there be any reasons why the above would be better than the simple alternative:</p>
<pre><code>class Bar {
public:
virtual bool foo(int i) = 0;
};
</code></pre>
| <p>This is the <a href="http://www.gotw.ca/publications/mill18.htm">Non-Virtual Interface Idiom</a> (NVI). That page by Herb Sutter has a good bit of detail about it. However, temper what you read there with what the C++ FAQ Lite says <a href="http://www.parashift.com/c%2B%2B-faq-lite/strange-inheritance.html#faq-23.3">here</a> and <a href="http://www.parashift.com/c%2B%2B-faq-lite/strange-inheritance.html#faq-23.4">here</a>.</p>
<p>The primary advantage of NVI is separating interface from implementation. A base class can implement a generic algorithm and present it to the world while its subclasses can implement the details of the algorithm through virtual functions. Outside users are shielded from changes in the algorithm details, especially if you later decide you want to do add pre- and post-processing code.</p>
<p>The obvious disadvantage is that you have to write extra code. Also, <code>private</code> virtual functions are confusing to a lot of people. Many coders mistakenly think you can't override them. Herb Sutter seems to like <code>private</code> virtuals, but IMHO it's more effective in practice to follow the C++ FAQ Lite's recommendation and make them <code>protected</code>.</p>
|
LastChildFill Not Working When Trying To Dock ItemsControl <p>I've got the following markup in a WPF UserControl: </p>
<pre><code><Border Name="_border" BorderThickness="4" BorderBrush="Blue">
<Canvas Name="_canvas" Background="Black" >
<DockPanel LastChildFill="True">
<ItemsControl Name="_itemsControl" Background="Bisque" AllowDrop="True" Height="100" Width="100"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemTemplate="{StaticResource pictureTemplate}"
ItemsPanel="{StaticResource panelTemplate}"
Drop="_itemsControl_Drop"
DragOver="_itemsControl_DragOver"
DragLeave="_itemsControl_DragLeave"
PreviewMouseLeftButtonDown="_itemsControl_PreviewMouseLeftButtonDown"
PreviewMouseMove="_itemsControl_PreviewMouseMove">
</ItemsControl>
</DockPanel>
</Canvas>
</Border>
</code></pre>
<p>I would like the ItemsControl to fill all of the available space, but it is not obeying the DockPanel's LastChildFill property. The Horizontal and Vertical "Stretch" values aren't helping either. What am I missing? </p>
| <p>Whats the size of your DockPanel? Try setting a background on your DockPanel for testing. </p>
<p>I don't think that you problem is with your ItemsControl not stretching to fill your DockPanel, but actually your DockPanel is not stretching to fit inside the Canvas Control. Canvas control and its children will not resize to fit thier parent.</p>
|
What's the deal with a leading underscore in PHP class methods? <p>While looking over various PHP libraries I've noticed that a lot of people choose to prefix some class methods with a single underscore, such as</p>
<pre><code>public function _foo()
</code></pre>
<p>...instead of...</p>
<pre><code>public function foo()
</code></pre>
<p>I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from.</p>
<p>My thought is that it's probably being carried over from PHP 4, before class methods could be marked as protected or private, as a way of implying "do not call this method from outside the class". However, it also occurred to me that maybe it originates somewhere (a language) I'm not familiar with or that there may be good reasoning behind it that I would benefit from knowing.</p>
<p>Any thoughts, insights and/or opinions would be appreciated.</p>
| <p>It's from the bad old days of Object Oriented PHP (PHP 4). That implementation of OO was pretty bad, and didn't include things like private methods. To compensate, PHP developers prefaced methods that were intended to be private with an underscore. In some older classes you'll see <code>/**private*/ __foo() {</code> to give it some extra weight.</p>
<p>I've never heard of developers prefacing all their methods with underscores, so I can't begin to explain what causes that.</p>
|
Sockets Authentication is failing using NegotiateStream <p>I've got a Socket that is connected that I use to get HTTP header responses. If I skip authentication, everything works fine (unless the page requires authentication). But when I step into this code, it always throws an IOException on the AuthenticateAsClient line. The message is: of "Unable to read data from the transport connection: The connection was closed." I've tried both DefaultCredentials and DefaultNetworkCredentials. </p>
<p>Any ideas as to what I am missing? What is causing the connection to close?</p>
<p>thanks</p>
<pre><code>if (Authenticate)
{
NetworkStream clientStream = new NetworkStream(webSocket, false);
NegotiateStream authStream = new NegotiateStream(clientStream);
NetworkCredential netcred = CredentialCache.DefaultNetworkCredentials;
try
{
authStream.AuthenticateAsClient(netcred,
String.Empty,
ProtectionLevel.None,
TokenImpersonationLevel.Identification);
if (!authStream.IsAuthenticated)
{
Console.WriteLine("Authentication failed");
ErrorText = "Authentication using default credentials failed";
return (HttpStatusCode)(-1);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ErrorText = ex.Message;
return (HttpStatusCode)(-1);
}
}
</code></pre>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.net.security.negotiatestream.aspx" rel="nofollow"><code>NegotiateStream</code></a> doesn't perform HTTP authentication:</p>
<blockquote>
<p>On Windows 95/98 systems, Windows NT LAN Manager (NTLM) is the protocol used for authentication. On other platforms the Kerberos protocol is used for authentication if both client and server support it; otherwise NTLM is used.</p>
</blockquote>
<p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx" rel="nofollow">WebClient</a> class which provides a <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.credentials.aspx" rel="nofollow">Credentials</a> and a <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.responseheaders.aspx" rel="nofollow">ResponseHeaders</a> property.</p>
|
Python: How do you login to a page and view the resulting page in a browser? <p>I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired.</p>
<pre><code>import urllib, urllib2, cookielib, webbrowser
username = 'userhere'
password = 'passwordhere'
url = 'http://example.com'
webbrowser.open(url, new=1, autoraise=1)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://example.com', login_data)
resp = opener.open('http://example.com/afterlogin')
print resp
webbrowser.open(url, new=1, autoraise=1)
</code></pre>
| <p>First off, when doing cookie-based authentication, you need to have a <a href="http://docs.python.org/library/cookielib.html#cookielib.CookieJar" rel="nofollow"><code>CookieJar</code></a> to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again.</p>
<p>After opening a login-page through python, and saving the cookie from a successful login, you should use the <a href="http://docs.python.org/library/cookielib.html#cookielib.MozillaCookieJar" rel="nofollow"><code>MozillaCookieJar</code></a> to pass the python created cookies to a format a firefox browser can parse. Firefox 3.x no longer uses the cookie format that MozillaCookieJar produces, and I have not been able to find viable alternatives.</p>
<p>If all you need to do is to retrieve specific (in advance known format formatted) data, then I suggest you keep all your HTTP interactions within python. It is much easier, and you don't have to rely on specific browsers being available. If it is absolutely necessary to show stuff in a browser, you could render the so-called 'hidden' page through urllib2 (which incidentally integrates very nicely with cookielib), save the html to a temporary file and pass this to the <a href="http://docs.python.org/library/webbrowser.html?highlight=webbrowser#webbrowser.open" rel="nofollow"><code>webbrowser.open</code></a> which will then render that specific page. Further redirects are not possible.</p>
|
Is it a good idea to let your users change their usernames? <p>I'm back and forth on the idea of letting the users on my site change their usernames, which would be displayed through out the site. On one side I want to give the users flexibility. But on the other, I don't want them to use this feature as a way to hide if they do something unwanted on the site. I know SO & Twitter lets you change your display name. Whats keeping someone from behaving bad on the site and then changing their name so they can continue behaving bad?</p>
<p>I need feed back on the pro's and con's.
Thanks!</p>
<p><strong>Update:</strong>
To clear things up a bit. I'm not using the user name as the primary internal account ID.
Each user gets a unique number. My question is not really about my system tracking the user its about how other users will be able to track each other. </p>
<p>If userA knows that userB is doing something bad and then userB changes his name to userC. Then userA will no longer know who he is.</p>
| <p>What do you mean with "do something bad and then change their name"? If you're implying that users can post content, for instance, with their name attached, and then change their name and the name attached to their posts won't change as well, then I think you need to reconsider your (database) architecture and ensure that a username is a single point of reference and all representations of that username change when someone changes their username.</p>
<p>Edit:
OK, sorry for misunderstanding. But if it's the case that you have a single point of reference, then changing your username is irrelevant to the problem. Let's say my username is Foo and I troll some thread somewhere, then change my name to Bar. As long as people can see what I've posted (eg. a post history page), then it doesn't matter whether I used to be called Foo or not, Bar is associated now with posts made before that were troll material. So perhaps you just need to create transparency, by making something like a post history overview on users' profiles? :)</p>
|
How does gesture recognition work? <p>In a multi-touch environment, how does gesture recognition work? What mathematical methods or algorithms are utilized to recognize or reject data for possible gestures?</p>
<p>I've created some retro-reflective gloves and an IR LED array, coupled with a Wii remote. The Wii remote does internal blob detection and tracks 4 points of IR light and transmits this information to my computer via a bluetooth dongle. </p>
<p>This is based off <a href="http://johnnylee.net/projects/wii/" rel="nofollow">Johnny Chung Lee's Wii Research</a>. My precise setup is exactly like the graduate students from the Netherlands displayed <a href="http://www.cs.rug.nl/~isenberg/VideosAndDemos/Vlaming2008PTI" rel="nofollow">here</a>. I can easily track 4 point's positions in 2d space and I've written my basic software to receive and visualize these points. </p>
<p><img src="http://i40.tinypic.com/x517yg.png" alt="alt text" /><img src="http://i42.tinypic.com/nao9x.png" alt="alt text" /><img src="http://i43.tinypic.com/65d1zp.png" alt="alt text" /></p>
<p>The Netherlands students have gotten a lot of functionality out of their basic pinch-click recognition. I'd like to take it a step further if I could, and implement some other gestures.</p>
<p>How is gesture recognition usually implemented? Beyond anything trivial, how could I write software to recognize and identify a variety of gestures: various swipes, circular movements, letter tracing, etc.</p>
| <p>Gesture recognition, as I've seen it anyway, is usually implemented using machine learning techniques similar to image recognition software. <a href="http://www.codeproject.com/KB/recipes/cmgblade.aspx" rel="nofollow">Here's a cool project on codeproject about doing mouse gesture recognition in c#</a>. I'm sure the concepts are quite similar since you can likely reduce the problem down to 2D space. If you get something working with this, I'd love to see it. Great project idea!</p>
|
C# Nested Try Catch statements or methods? <p>Simple best practice question.</p>
<p>Should you nest try catch statements or just use methods.</p>
<p>For instance, if you have a method that opens a file does work and closes the file, you would have the open and close outside the try catch, or rather the close in the finally block.</p>
<p>Now if your open method fails, the method would assert right? So should your wrap that in a try catch block or should that be called from another method, which in turn as a try catch block?</p>
| <p>In the context of a method that opens a file I would use a using statement vs a try catch. The using statement ensures that Dispose is called if an exception occurs. </p>
<pre><code>using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
</code></pre>
<p>does the same thing as:</p>
<pre><code>FileStream fs;
try
{
fs = new FileStream(file, FileMode.Open);
//do Stuff
}
finally
{
if(fs!=null)
fs.Dispose();
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.