input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Vimdiff current line compare <p>In Beyond Compare, the line you currently have selected is compared on top of each other at the bottom of the window. Is there any way to accomplish this in vimdiff?</p>
| <p>Short answer No. </p>
<p>Vim does not have a built in way to do that. You would have to write a plugin that would split two more windows on the bottom, re-size them to 1 line. I tried doing it manually but it didn't keep one of the windows in sync while scrolling.</p>
<p>My work around is to use <code>CTRL-W J</code> to move the window to the bottom and then <code>CTRL-W L</code> to bring it back to side by side comparison. </p>
<p>see <code>help: window-moving</code> for details</p>
|
How do you change the owner of a database in sql? <p>In management studio you can see the owner under properties but it won't let you change it. My guess is there's some stored procedure to change it and you can't do it through the gui.</p>
| <p>Surpisingly, it's called <a href="http://msdn.microsoft.com/library/ms178630.aspx"><code>sp_changedbowner</code></a>.</p>
<p>You can actually change it in <code>SQL Server Management Studio</code> under <code>Database / Properties / Files</code></p>
|
What Class for Serializable Multidimensional Arrays? <p><strong><em>EDIT: See Below</em></strong></p>
<p>I have a web service which uses a class of functions in order to return data used in various business processes (via InfoPath). </p>
<p>One of the functions takes a given SQLCommand object and executes it into a SQLDataReader. Now depending on the SQL command text used this may return one or many rows of one or many columns. So what is the best class for this function to return bearing in mind it needs to be serialized by the web service.</p>
<p>My existing code is:</p>
<pre><code> Dim array As New ArrayList
Try
conCMS.Open()
Dim rdr As SqlDataReader = cmdCurrent.ExecuteReader
While rdr.Read
If rdr.VisibleFieldCount > 1 Then
Dim complexType(rdr.VisibleFieldCount - 1) As String
For rowIndex As Integer = 0 To rdr.VisibleFieldCount - 1
complexType(rowIndex) = rdr(rowIndex)
Next
array.Add(complexType)
Else
array.Add(rdr(0))
End If
End While
conCMS.Close()
Return array
Catch ex As Exception
array.Add("ERROR " & ex.Message)
End Try
Return Nothing
</code></pre>
<p>Now I know this is not efficient code, but this a work in progress. </p>
<p>As you can probably see this is generating a string array to represent a row with more than one column, however this cannot be serialized by the web service.</p>
<p>So 2 things really;</p>
<ul>
<li>Some guidance on an effective type to use (without writing a serializable class of my own)</li>
<li>Some advice on improving the code going forward.</li>
</ul>
<p>Thanks in advance</p>
<p><strong><em>EDIT:</em></strong>
I have managed to get serialization to work by simply creating a nested arrayList as follows (doh!):</p>
<pre><code> If rdr.VisibleFieldCount > 1 Then
Dim complexType As New ArrayList
For rowIndex As Integer = 0 To rdr.VisibleFieldCount - 1
complexType.Add(rdr(rowIndex))
Next
array.Add(complexType)
Else
array.Add(rdr(0))
End If
</code></pre>
<p>However please let me know how this could be improved.</p>
| <p>If your code knows the schema of the returned data before the call, then you should return data in the same shape. Have a struct or class with properties of the appropriate type for each column of the returned data. For each row, create an instance of such a struct, and fill in the properties from the returned columns. Then add each instance to a strongly-typed list of that struct, a List(Of T). Then return the list.</p>
<p>OBTW, ArrayList was created before we had generics in .NET. Today, it's better to use strongly-typed collections and not ArrayList, which is basically List(Of <em>anything</em>).</p>
|
Winforms &TimeSpan - Which control works best? <p>I am building a form with winforms - and should add a view and editable time span value.
Which controls works best for this ?</p>
<p>A normal edit control shows the value correctly -> but it's not really nice for changing values </p>
<p>the normal date time picker doesn't work</p>
<p>the masked edit control doesn't have got any standard mask for this</p>
<p>Does anybody have a good idea for a control for this task ?</p>
| <p>I built one that had a TextBox coupled with a ComboBox to choose the units. The user control had range settings (value +-) and (time units). Based on the units picked, the text box was ranged checked - e.g., 1-7 days might be valid but if units were minutes, 1-60 minutes might be better.</p>
<p>I've done combinations of two ComboBoxes a NumericUpDown as well.</p>
<p>If you need time spans that are things like 3 days 4 hours 6 minutes, I'd probably opt for a user control with masked text box and range check the parts.</p>
<p>Typically, I opt for the first one, though.</p>
<p>Just my two cents.</p>
|
Mac OS X equivalent for TerminateProcess(GetCurrentProcess,0); <p>I am looking for a simple and uncatchable way to terminate the Mac port of my C++ application. In Windows I was using</p>
<pre><code>TerminateProcess(GetCurrentProcess, 0);
</code></pre>
<p>What's the equivalent command I can use with Mac OS X / XCode / GCC? </p>
| <p>Actually you want <code>_exit</code> if you want to have the same semantics as <code>TerminateProcess</code>. <code>exit</code> semantics are more closely aligned with <code>ExitProcess</code>.</p>
|
Inconsistent browser caching of session variables - any solutions? <p>Hi all<br />
Why are my session variables being dropped here?</p>
<p>I submit a form using the submit button and create session variables of the values to allow them to be carried to other pages. All's fine. If I now move back and forward between the form and form handler using the browser buttons (as some user sometime will probably do) Firefox and Opera recalls the session variables and can populate the form handler. IE and Safari however don't. What can I do about it?</p>
<p>Firefox would demonstrate the problem if I hadn't inserted the following in the header file earlier this morning:</p>
<pre><code>header("Cache-Control: no-cache");
header("Expires: -1");
</code></pre>
<p>I've read that the second header line - <code>header("Expires: -1");</code> - should also be the fix for IE but that seems not to be the case. IE8 / Safari still show the problem. Opera doesn't need this at all. If this is a reload problem what do I need to add to the header to force IE and Safari to reload?</p>
<p>Thanks</p>
| <p>Your session variables are not lost. Rather, what's happening is that, when going back, none of the browsers will reload the form from your server (with the defaults filled in from the session variables.) Some browsers, however, will be nice about it and remember themselves what values the form fields last had when that particular form was last submitted, and fill them in for you. IE will not.</p>
<p>In any case, it is good practice for forms to be submitted via POST, and for the server to respond to the POST by <strong>redirecting</strong> (HTTP 302) to the next page, instead of rendering the next page directly. By issuing the redirect, any attempt by the user to go back will ask him/her to confirm whether they really want the form resubmitted for a second time, which could be a bigger problem than just not having some pre-filled values on the form. I'm guessing here what your real inentions are, but if you really want the user to be able to submit multiple forms in a row (repetitive task), simply render the form again on the next page, after the redirect.</p>
|
How can I tail a remote file? <p>I am trying to find a good way to tail a file on a remote host. This is on an internal network of Linux machines. The requirements are:</p>
<ol>
<li><p>Must be well behaved (no extra process laying around, or continuing output)</p></li>
<li><p>Cannot require someone's pet Perl module.</p></li>
<li><p>Can be invoked through Perl.</p></li>
<li><p>If possible, doesn't require a custom built script or utility on the remote machine (regular linux utilities are fine)</p></li>
</ol>
<p>The solutions I have tried are generally of this sort</p>
<pre><code>ssh remotemachine -f <some command>
</code></pre>
<p>"some command" has been:</p>
<pre><code>tail -f logfile
</code></pre>
<p>Basic tail doesn't work because the remote process continues to write output to the terminal after the local ssh process dies.</p>
<pre><code>$socket = IO:Socket::INET->new(...);
$pid = fork();
if(!$pid)
{
exec("ssh $host -f '<script which connects to socket and writes>'");
exit;
}
$client = $socket->accept;
while(<$client>)
{
print $_;
}
</code></pre>
<p>This works better because there is no output to the screen after the local process exits but the remote process doesn't figure out that its socket is down and it lives on indefinitely.</p>
| <p>Have you tried</p>
<pre><code>ssh -t remotemachine <some command>
</code></pre>
<p>-t option from the ssh man page:</p>
<pre><code> -t Force pseudo-tty allocation. This can be used to execute
arbitrary screen-based programs on a remote machine, which
can be very useful, e.g. when implementing menu services.
Multiple -t options force tty allocation, even if ssh has no local tty.
</code></pre>
<p>instead of</p>
<pre><code> -f Requests ssh to go to background just before command execution.
This is useful if ssh is going to ask for passwords or passphrases,
but the user wants it in the background.
This implies -n. The recommended way to start X11 programs at a remote
site is with something like ssh -f host xterm.
</code></pre>
|
Using an ASP.NET server control in a SQL Server 2005 reporting .rdl file <p>How would I embed an ASP.NET server control on a SQL Server 2005 Reporting file (.rdl)? </p>
<p>I am using the design view to accomplish my task.</p>
| <p>Last time I checked you can't. You're limited to code that generates images, like bar codes.</p>
|
Silverlight Development - Service URL while developing locally <p>What is the correct pattern or method for developing a Silverlight application (which is the Silverlight project and Web Application in a single solution)? I mean, how do you add the Service Reference if the localhost port number will be constantly changing?</p>
<p>Thanks.</p>
| <p>Like this one:
<a href="http://forums.silverlight.net/forums/t/19021.aspx" rel="nofollow">http://forums.silverlight.net/forums/t/19021.aspx</a></p>
<p>Do not rely on the URL set in the ServiceReference.ClientConfig. Set your URL in the code. Change your WebSerivice Calling code to the following:</p>
<pre><code> var webService = new YourWebService.YourWebServiceClient() // This is the default constructor, url will be read from the clientconfig file.
Uri address = new Uri(Application.Current.Host.Source, "../YourService.svc"); // this url will work both in dev and after deploy.
var webService = new YourWebService.YourWebServiceClient("YourServiceEndPointName", address.AbsolutePath);
</code></pre>
|
What allows a Windows authentication username to work (flow) between 2 servers? <p>Typical ISP setup. One server is the web server, another is the DB SQL server. There is a local administrator account, let's say XYZ, created on both machines. So when I log in remotely, I am either WebServer\XYZ or DBServer\XYZ, depending where I log in.</p>
<p>Now, when I login to SQL Server SSMS on DBServer using Windows Authentication, and execute "SELECT SUSER_NAME()", I get DBServer\XYZ. That makes sense since it's picking up the fact that I logged in with those credentials.</p>
<p>Now, move over to the WebServer. I remotely login as WebServer\XYZ. I've installed the SQL client components there. When I launch SSMS, choose the DBServer, login with Windows Authentication, and execute "SELECT SUSER_NAME()", I somehow get DBSERVER\XYZ, instead of what I would assume should be WebServer\XYZ. </p>
<p>Somehow, the XYZ from the WebServer becomes the XYZ from the DBServer. Why is that? How does that happen? Surely, it can't just be because the names happen to be the same?</p>
<p>I've heard of trusted domains, but neither machine is a Domain Controller, so I don't have access to that info. How can I tell if it's trusted or not, without the GUI tools?</p>
<p>The reason I ask the question is because, I'm trying to implement the same thing on my XP laptop (using Virtual PC), so I can imitate the production environment, but I'm not having any luck. </p>
| <p>You <code>XYZ</code> accounts seem to have same passwords on both machines, and they are not a part of a domain.</p>
<p><code>WebServer</code> sends just <code>XYZ</code> as a username and answers all password challenges successfuly, as the passwords do match.</p>
<p><code>DbServer</code>, of course, thinks of you as of <code>DbServer/XYZ</code>, as it knows of no others.</p>
<p>Exactly same thing happens when you try to access one standalone machine from another one over <code>SMB</code>. If your usernames and password match, you succeed.</p>
|
Linq to Sql - Select from 1:Many <p>I'm new to using Linq and just started a side project to learn some of the basics. I'm currently using Linq to Sql and all my DB Table relationships worked very well. Currently I have a Client table and a Project table. Each Client can have 1 or more Projects. Therefore, as you'd expect each Client object has a collection of Project objects after Linq does its magic. </p>
<p>I'm using the below code and it works well, but I think there is a better way of doing it. I need to pass my method a ProjectID and then select that Project from the Client:</p>
<pre><code> private void PopulateStatusView(int projectID)
{
MyDataContext db = new MyDataContext();
var client = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"])
select u).SingleOrDefault();
if (client != null)
{
foreach (Project currentProject in client.Projects)
{
if (currentProject.id == projectID)
{
// Project Selected Here
statusProjectName.Text = currentProject.name;
}
}
}
else
{
// Session Expired
}
}
</code></pre>
<p>Can anyone let me know if there's a better solution rather than looping over each Project.</p>
<p>Thank you.</p>
| <p>To get the client which has the specific project ID:</p>
<pre><code>var client = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"]) &&
u.Projects.Any(x=>x.id == projectID)
select u).SingleOrDefault();
</code></pre>
<p>To get the project:</p>
<pre><code>var project = (from u in db.Clients
where u.id == Convert.ToInt32(Session["ClientID"]) &&
u.Projects.Any(x=>x.id == projectID)
select u.Projects.Where(x=>x.id == projectID).Single()).SingleOrDefault();
</code></pre>
|
Can I protect my ASP.NET application against decompilers? <ol>
<li>I know also that ASP.NET when published can be precompiled</li>
<li>I know that .NET applications are compiled to MSIL that are easily reverted to any .NET language through tools like Red Gate's .NET Reflector. </li>
<li>I want to develop and deliver an ASP.NET site where the buyer will host the site and but cannot have access to the code.</li>
</ol>
<p>There is any way to do that?</p>
| <p>In my experience people who are obfuscating their code donât produce code that is worth the trouble.</p>
|
How do I calculate the average direction of two vectors <p>I am writing and opengl based iphone app and would like to allow a user to translate around a view based on the direction that they move two fingers on the screen. For one finger I know I could just calculate the vector from the start position to the current position of the users finger and then find the unit vector of this to get just the direction, but I don't know how I would do this for two fingers, I don't think adding the components of the vectors and calculating the average would work so I'm pretty much stuck.</p>
| <p>Vector math works just like you think:</p>
<pre><code>v3 = (v1 + v2)/2
// so:
v3.x = (v1.x + v2.x) / 2;
// same for Y and Z
</code></pre>
|
C#: Casting types dynamically <p>I currently have this type of code:</p>
<pre><code>private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
if (MainObject is SomeClassType1)
{
SomeClassType1 HelpObject = (SomeClassType1)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
else if (MainObject is SomeClassType2)
{
SomeClassType2 HelpObject = (SomeClassType2)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
}
</code></pre>
<p>Assuming that SomeClassType1 and SomeClassType2 have the same set of properties that I want to assign (although they may differ in other ones), is it possible to dynamically cast MainObject to the appropriate type and then assign the value, without duplicating the code?
This is what I would like to see in the end:</p>
<pre><code>private void FillObject(Object MainObject, Foo Arg1, Bar Arg2)
{
Type DynamicType = null;
if (MainObject is SomeClassType1)
{
DynamicType = typeof(SomeClassType1);
}
else if (MainObject is SomeClassType2)
{
DynamicType = typeof(SomeClassType2);
}
DynamicType HelpObject = (DynamicType)MainObject;
HelpObject.Property1 = Arg1;
HelpObject.Property2 = Arg2;
}
</code></pre>
<p>And obviously C# complains about not being able to find DynamicType:</p>
<blockquote>
<p>The type or namespace name 'DynamicType' could not be found (are you missing a using directive or an assembly reference?)</p>
</blockquote>
<p>Is something like this possible in C# 2.0? If it's more messy than my current code, than I see no point in doing this, but I'm very interested to find out. Thanks!</p>
<p>EDIT: Just to clarify, I perfectly understand that implementing an interface is the most appropriate and probably correct solution. That said, I'm more interested in seeing how to I could do it without implementing an interface. Thanks for great replies!</p>
| <p>It looks like both of the types you care about implement the same two properties. In that case, what you want to do is define an interface for those properties:</p>
<pre><code>public interface IMyInterface
{
public Foo Property1 {get; set;}
public Bar Property2 {get;set;}
}
</code></pre>
<p>Then, make sure each of your classes tell the compiler that they implement that new interface. Finally, use a generic method with a type argument that is constrained to that interace:</p>
<pre><code>private void FillObject<T>(T MainObject, Foo Arg1, Bar Arg2)
where T : IMyInterface
{
MainObject.Property1 = Arg1;
MainObject.Property2 = Arg2;
}
</code></pre>
<p>Note that even with the extra code to declare the interface, these snippets still end up shorter than either one of the snippets you posted in the question, and this code is much easier to extend if the number of types you care about increases.</p>
|
Good resources for learning visual studio DSL tools? <p>Can anyone recommend any good resources (online or books) for learning how to use visual studio's domain specific language tools? I know the msdn site has some pretty good walk-throughs/tutorials but I am looking for something more detailed.</p>
| <p>I found the DSL tools lab found <a href="http://code.msdn.microsoft.com/DSLToolsLab">here</a> to be quite useful. You might also find the book "Domain-Specific Development with Visual Studio DSL Tools" (<a href="http://rads.stackoverflow.com/amzn/click/0321398203">here</a>) useful as well.</p>
<p>Finally, it has been my experience that although the DSL tools seem quite intimidating at the outset once you get started it's really quite easy to "learn the ropes".</p>
|
How can I install a certificate into the local machine store programmatically using c#? <p>I have a certificate generated via MakeCert. I want to use this certificate for WCF message security using PeerTrust. How can I programmatically install the certificate into the "trusted people" local machine certificate store using c# or .NET?</p>
<p>I have a CER file, but can also create a PFX.</p>
| <p>I believe that this is correct:</p>
<pre><code>X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(cert); //where cert is an X509Certificate object
store.Close();
</code></pre>
|
Dynamic/Conditional SQL Join? <p>I have data in a MSSQL table (TableB) where [dbo].tableB.myColumn changes format after a certain date... </p>
<p>I'm doing a simple Join to that table.. </p>
<pre><code>Select [dbo].tableB.theColumnINeed from [dbo].tableA
left outer join [dbo].tableB on [dbo].tableA.myColumn = [dbo].tableB.myColumn
</code></pre>
<p>However, I need to join, using different formatting, based on a date column in Table A ([dbo].tableA.myDateColumn). </p>
<p>Something like... </p>
<pre><code>Select [dbo].tableB.theColumnINeed from [dbo].tableA
left outer join [dbo].tableB on [dbo].tableA.myColumn =
IF [dbo].tableA.myDateColumn > '1/1/2009'
BEGIN
FormatColumnOneWay([dbo].tableB.myColumn)
END
ELSE
BEGIN
FormatColumnAnotherWay([dbo].tableB.myColumn)
END
</code></pre>
<p>I'm wondering if there's a way to do this.. or a better way I'm not thinking of to approach this.. </p>
| <pre><code>SELECT [dbo].tableB.theColumnINeed
FROM [dbo].tableA
LEFT OUTER JOIN [dbo].tableB
ON [dbo].tableA.myColumn =
CASE
WHEN [dbo].tableA.myDateColumn <= '1/1/2009' THEN FormatColumnOneWay([dbo].tableB.myColumn)
ELSE FormatColumnAnotherWay([dbo].tableB.myColumn)
END
</code></pre>
|
BufferedImage Rotation <p>What is the best way of rotating a bufferedimage about its center where the gradient is 1 degree?</p>
<p>I know there is AffineTransform, but that causes shearing and weird stretching or black spots that should be blank.</p>
<p><em>edit</em> The sizes of images I am dealing with are icon sizes, so typically 24x24 up to 48x48 pixels</p>
| <p>The quality of rotation for such a small angle will vary greatly with the size of the image. How big is your image?</p>
<p>[After the OP edited the question to indicate the size of the image]</p>
<p>IMO the image is too small for any meaningful rotation other than in multiples of 90 degrees (assuming its a square). I am afraid this needs to be done manually by a graphic designer to get the best possible quality.</p>
<p>[Another alternative]</p>
<p>Keep a high res version of the image around. Apply all your transformations to this image and then scale down to obtain an icon.</p>
|
c# Threads and display update <p>I have a Windows Form with a label and a picture box. To retreive an image from a web service I use a thread.</p>
<p>The user click on a button and first the label must be displayed and then new thread is started to retrieve the image. This is the code:</p>
<pre><code>private void menuItem1_Click(object sender, EventArgs e)
{
etiquetaCargando.Visible = true;
this.Invoke(new System.Threading.ThreadStart(RequestImage));
}
</code></pre>
<p>The problem is this: label etiquetaCargando doesn't appear.</p>
<p>I'm programming on Compact Framework.</p>
<p>What it's happening?</p>
<p>Thanks!</p>
| <p>The question is unclear, but by using Invoke, you are defeating the purpose of having the image request on a separate thread. (You might notice that your interface becomes unresponsive while the request is happening)</p>
<p>Instead, it is better to create a new thread object, start it, and then use the Invoke to set the image (after it has been retrieved), something along the lines of</p>
<pre><code>private void menuItem1_Click(object sender, EventArgs e)
{
etiquetaCargando.Visible = true;
Thread reqThread =
new Thread(new ThreadStart(RequestImage));
reqThread.Start();
}
private void RequestImage()
{
/* Get the image
...
*/
Invoke(SetTheImage, new object[] { theImage });
}
</code></pre>
<p>this assumes that you have a method SetTheImage which will actually do the job of displaying the image on your form.</p>
|
Why are .NET app.config load rules different for win2k3? <p>...and are there any other caveat for other platforms?</p>
<p>I create an app.config for a win forms project, for example Application.exe.</p>
<p>By default I expect that at runtime my application is going to look for a file called Application.exe.config.</p>
<p>But there seem to be exceptions to this, for example in a Windows Server 2003 environment an app will look for <strong>Application.config</strong>.</p>
<p><strong>The full path of the config file being searched for is different in Windows Server 2003, why is this?</strong></p>
<p>Where is the definition for these cosmic app.config loading rules? </p>
| <p>I don't have the details at hand, but I believe a service pack or point version of the .NET Framework allowed <code>ExeName.config</code> to be an option, and that is now still supported for backward compatibility, but more recent service packs have returned to defaulting to <code>ExeName.exe.config</code> for all systems.</p>
|
Assign on-click VBA function to a dynamically created button on Excel Userform <p>I'm creating buttons dynamically on an Excel userform with the following code:</p>
<pre><code>With Me.CurrentFrame.Controls.Add("Forms.CommandButton.1")
.Caption = "XYZ"
.name = "AButton"
.Font.Bold = True
.ForeColor = &HFF&
... blah blah blah
End With
</code></pre>
<p>I'd like to assign a function to run when these buttons are clicked, but I can't find a straightforward way to do this since there's no property as part of the button itself.</p>
<p>Is there a way to do this using the above idiom? Should I be going about this whole thing in a different way?</p>
| <p>You need to dynamically create code / event handlers for each button.</p>
<p>It take a bit of doing - see here: <a href="http://www.cpearson.com/excel/vbe.aspx" rel="nofollow">http://navpadexcel.blogspot.com/2006/11/httpwwwcpearsoncomexcelvbehtm.html</a></p>
<p>A better way might be to create a bunch of buttons on the form (as many as you think you'll need) ahead of time. Create the event handler code as well. Make them all hidden initially.</p>
<p>Then when your form opens you can dynamically change the button captions, make them visible and move them around. The event code you created initially will be linked to the activated buttons as expected.</p>
|
Flex databinding a function <p>Does anyone know how to programmatically bind a property to a function that isn't a getter? IE: I have a function that returns a translated string based on the identifier you pass it. How do I do this in AS3 rather than MXML? (reason being - I have a dynamic layout that I render based on XML and so have create and add all children programmatically).</p>
| <p>You can call a setter function using <code>BindingUtils.bindSetter()</code>. You can use this to call a setter function that calls your translation function and sets the return value to a specified place. Unfortunately you can't dynamically specify the host of the setter like you can with <code>BindingUtils.bindProperty()</code>.</p>
|
Delegates: Predicate Action Func <p>Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:</p>
<ul>
<li>Predicate</li>
<li>Action</li>
<li>Func</li>
</ul>
<p>What other delegates should a C# developer be aware of?</p>
<p>How often do you use them in production code?</p>
| <ul>
<li><p><code>Predicate</code>: essentially <code>Func<T, bool></code>; asks the question "does the specified argument satisfy the condition represented by the delegate?" Used in things like List.FindAll.</p></li>
<li><p><code>Action</code>: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.</p></li>
<li><p><code>Func</code>: Used <em>extensively</em> in LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.</p></li>
</ul>
<p>Other important delegates:</p>
<ul>
<li><p><code>EventHandler</code>/<code>EventHandler<T></code>: Used all over WinForms</p></li>
<li><p><code>Comparison<T></code>: Like <code>IComparer<T></code> but in delegate form.</p></li>
</ul>
|
Expose webservice information to SCOM / WMI <p>What would be the best way to expose information from an ASP.NET webservice to SCOM or WMI? I'm interested in basically exposing performance information so the service can be monitored: ie. get a metric of calls processed per hour, total calls per day, etc.</p>
<p><strong>EDIT:</strong> This would have to run under standard ASP.NET permissions</p>
| <p>You'll need to write a WMI provider to expose info to WMI - there's <a href="http://www.codeproject.com/KB/system/WMIProviderExtensions.aspx" rel="nofollow">an example on CodeProject</a>. An alternative, possibly simpler, would be to expose some custom performance counters as outlined <a href="http://www.ondotnet.com/pub/a/dotnet/2003/04/07/wmi.html?page=2" rel="nofollow">in this article</a>.</p>
|
Sorting a list based on string case <p>How can I sort a List by order of case e.g.</p>
<ul>
<li>smtp:user@domain.com</li>
<li>smtp:user@otherdomain.com</li>
<li>SMTP:user@anotherdomain.com</li>
</ul>
<p>I would like to sort so that the upper case record is first in the list e.g SMTP:user@anotherdomain.com.</p>
| <p>You can use StringComparer.Ordinal to get a case sensitive sorting:</p>
<pre><code> List<string> l = new List<string>();
l.Add("smtp:a");
l.Add("smtp:c");
l.Add("SMTP:b");
l.Sort(StringComparer.Ordinal);
</code></pre>
|
Is PHP allowed to modify .htaccess file in current folder? <p>I have a PHP web app located on <strong>shared hosting</strong>.
My goal is to modify .htaccess file from PHP code when the PHP page is running.
I need that .htaccess to insert a couple of mod_rewrite lines into it.</p>
<p>The problem is that on Windows+Apache I can dynamically modify .htaccess file
but the same code on Linux reports a problem when I try to access this file in any
way (copy or fopen):</p>
<p><code>"failed to open stream: Permission denied"</code></p>
<p>I have given .htaccess file 777 permissions - still no result.
WHat prevents me from doing this? How can I develop a workaround?</p>
<p>P.S.
My initial goal was to be able to add a new RewriteRule into .htaccess that maps a
newly added category_id with new category_name.</p>
<p>If it wasn't shared hosting, I would use something like RewriteMap (in main Apache config) and would be able to access the map file.</p>
<p>This is the first real limitation I've been unable to tackle with PHP+Apache, but I hope it's circuventable too.</p>
| <p>This seems like an overly-complex solution to just having a general "load category" page that takes the category name from the URL and loads the corresponding ID.</p>
<p>For example, if the URL is:</p>
<pre><code>http://yoursite.com/category/programming
</code></pre>
<p>I would remap that to something like:</p>
<pre><code>http://yoursite.com/category.php?name=programming
</code></pre>
|
NHibernate - What kind of association(s) is this? <p>I'm having some trouble getting NH to persist my object graph.</p>
<p>I have (something like) this:</p>
<pre><code>/*Tables*/
TABLE Parent
ParentID PK
LastEventID NULL
TABLE Event
EventID PK
ParentID FK NOT NULL
</code></pre>
<p><hr /></p>
<pre><code>//Model Classes
public class Parent
{
public List<Event> Events; //Inverse
//Denormalized bit
public Event LastEvent; //not inverse
}
public class Event
{
public Parent Parent; //Makes the association up there Inverse
}
</code></pre>
<p>I'm creating a new Parent, creating a new Event, adding the new Event
to Parent.Events and setting Parent.LastEvent to the new Event.</p>
<p>When I tell NH to save the Parent I get an error about a transient
object needing to be saved first. I assume its because the association
between Parent and Event is not clear.</p>
<p>The way the SQL needs to go is to insert the Parent with a null
LastEvent, then insert the Event, then update Parent.LastEvent.</p>
<p>So how do I get NH to do this?</p>
| <p>Without seeing your mapping schema, I'll have to guess.</p>
<p>Are you cascading your updates? From the <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/manipulatingdata.html#manipulatingdata-graphs" rel="nofollow" title="NHibernate Reference">reference</a>:</p>
<blockquote>
<p>To save or update all objects in a graph of associated objects, you must either</p>
<ul>
<li>Save(), SaveOrUpdate() or Update() each individual object OR</li>
<li>map associated objects using cascade="all" or cascade="save-update".</li>
</ul>
</blockquote>
<p>Assuming you don't already have this, does adding cascade="all" or cascade="save-update" to the side marked inverse="true" fix the problem?</p>
|
C++ linker problem with wrapper <p>I have a library opengl.lib which contains wrapper functions to all opengl functions. The functions are declared in their own namespace so that the wrapper functions can be named with the same name as the opengl functions. So inside a wrapper function, opengl function is called with ::gl***();</p>
<pre><code>opengl.h:
namespace OpenGL {
void glFunction();
}
opengl.cpp:
void OpenGL::glFunction() {
::glFunction();
}
</code></pre>
<p>Now the problem is that when I use this opengl.lib in my application and include my own "opengl.h", for some reason the real opengl functions get called directly and not my wrapper functions.</p>
<p>I have made sure that I have not included any real opengl.h so this must be some kind of linker issue. How can I resolve it? I have also the real opengl library in library path because otherwise I get linker errors in my opengl.lib as it uses the real opengl functions. So the real opengl library and my opengl.lib gets somehow mixed and linker decides to use the real opengl.lib instead of mine.</p>
<p>I know I can solve this by renaming my wrapper functions to something else but I would like to use the same names.</p>
<p>This question relates to my previous question <a href="http://stackoverflow.com/questions/565459/c-wrapper-with-same-name">http://stackoverflow.com/questions/565459/c-wrapper-with-same-name</a></p>
<p>I am using Visual C++ with optimization disabled.</p>
| <p>Are your wrappers thin enough that they are being inlined?</p>
|
Ajax Script Manager and Master Pages <p>I'm building a new website and want to use Ajax controls.</p>
<p>Do I need to put a ScriptManager control on both the MasterPage and on each content page? or Just on the MasterPage?(or just on the content page?)</p>
| <p>Content pages or MasterPages can only have one ScriptManager control on them. If you have a ScriptManager control on your MasterPage, you can drop a ScriptManagerProxy control onto your content pages to use any given specific ASP.NET AJAX functionality like this, for example:</p>
<pre><code><asp:Content ID="Content1" ContentPlaceHolderID="BodyContent" runat="server">
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/MyWebServices/YourCoolWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<%-- more content stuff goes here --%>
<asp:Content>
</code></pre>
|
Tools to reduce risk regarding password security and HDD slack space <p>Down at the bottom of <a href="http://www.schneier.com/essay-148.html" rel="nofollow">this essay</a> is a comment about a spooky way to beat passwords. Scan the entire HDD of a user including dead space, swap space etc, and just try everything that looks like it might be a password.</p>
<p><strong>The question:</strong> part 1, are there any tools around (A live CD for instance) that will scan an unmounted file system and zero everything that can be? (Note I'm <em>not</em> trying to find passwords)</p>
<p>This would include:</p>
<ul>
<li>Slack space that is not part of any file</li>
<li>Unused parts of the last block used by a file</li>
<li>Swap space</li>
<li>Hibernation files</li>
<li>Dead space inside of some types of binary files (like .DOC)</li>
</ul>
<p>The tool (aside from the last case) would not modify anything that can be detected via the file system API. I'm <em>not</em> looking for a block device find/replace but rather something that just scrubs everything that isn't part of a file.</p>
<p>part 2, How practical would such a program be? How hard would it be to write? How common is it for file formats to contain uninitialized data?</p>
<p>One (risky and costly) way to do this would be to use a file system aware backup tool (one that only copies the actual data) to back up the whole disk, wipe it clean and then restore it.</p>
| <p>I don't understand your first question (do you want to modify the file system? Why? Isn't this dead space exactly where you want to look?)</p>
<p>Anyway, <a href="http://phihag.de/2009/so/hddpass.c" rel="nofollow">here's an example of such a tool</a>:</p>
<pre><code>#include <stdio.h>
#include <alloca.h>
#include <string.h>
#include <ctype.h>
/* Number of bytes we read at once, >2*maxlen */
#define BUFSIZE (1024*1024)
/* Replace this with a function that tests the passwort consisting of the first len bytes of pw */
int testPassword(const char* pw, int len) {
/*char* buf = alloca(len+1);
memcpy(buf, pw,len);
buf[len] = '\0';
printf("Testing %s\n", buf);*/
int rightLen = strlen("secret");
return len == rightLen && memcmp(pw, "secret", len) == 0;
}
int main(int argc, char* argv[]) {
int minlen = 5; /* We know the password is at least 5 characters long */
int maxlen = 7; /* ... and at most 7. Modify to find longer ones */
int avlen = 0; /* available length - The number of bytes we already tested and think could belong to a password */
int i;
char* curstart;
char* curp;
FILE* f;
size_t bytes_read;
char* buf = alloca(BUFSIZE+maxlen);
if (argc != 2) {
printf ("Usage: %s disk-file\n", argv[0]);
return 1;
}
f = fopen(argv[1], "rb");
if (f == NULL) {
printf("Couldn't open %s\n", argv[1]);
return 2;
}
for(;;) {
/* Copy the rest of the buffer to the front */
memcpy(buf, buf+BUFSIZE, maxlen);
bytes_read = fread(buf+maxlen, 1, BUFSIZE, f);
if (bytes_read == 0) {
/* Read the whole file */
break;
}
for (curstart = buf;curstart < buf+bytes_read;) {
for (curp = curstart+avlen;curp < curstart + maxlen;curp++) {
/* Let's assume the password just contains letters and digits. Use isprint() otherwise. */
if (!isalnum(*curp)) {
curstart = curp + 1;
break;
}
}
avlen = curp - curstart;
if (avlen < minlen) {
/* Nothing to test here, move along */
curstart = curp+1;
avlen = 0;
continue;
}
for (i = minlen;i <= avlen;i++) {
if (testPassword(curstart, i)) {
char* found = alloca(i+1);
memcpy(found, curstart, i);
found[i] = '\0';
printf("Found password: %s\n", found);
}
}
avlen--;
curstart++;
}
}
fclose(f);
return 0;
}
</code></pre>
<p>Installation:</p>
<ol>
<li>Start a Linux Live CD</li>
<li>Copy the program to the file <code>hddpass.c</code> in your home directory</li>
<li>Open a terminal and type the following</li>
<li><code>su || sudo -s</code> # Makes you root so that you can access the HDD</li>
<li><code>apt-get install -y gcc</code> # Install gcc
# This works only on Debian/Ubuntu et al, check your system documentation for others</li>
<li><code>gcc -o hddpass hddpass.c</code> # Compile.</li>
<li><code>./hddpass /dev/</code><em>YOURDISK</em> # The disk is usually <code>sda</code>, <code>hda</code> on older systems</li>
<li>Look at the output</li>
</ol>
<p><a href="http://phihag.de/2009/so/hddpass-testscript.sh" rel="nofollow">Test</a> (copy to console, as root):</p>
<pre><code>gcc -o hddpass hddpass.c
</dev/zero head -c 10000000 >testdisk # Create an empty 10MB file
mkfs.ext2 -F testdisk # Create a file system
rm -rf mountpoint; mkdir -p mountpoint
mount -o loop testdisk mountpoint # needs root rights
</dev/urandom head -c 5000000 >mountpoint/f # Write stuff to the disk
echo asddsasecretads >> mountpoint/f # Write password in our pagefile
# On some file systems, you could even remove the file.
umount testdisk
./hdpass testdisk # prints secret
</code></pre>
<p>Test it yourself on an Ubuntu Live CD:</p>
<pre><code># Start a console and type:
wget http://phihag.de/2009/so/hddpass-testscript.sh
sh hddpass-testscript.sh
</code></pre>
<p>Therefore, it's relatively easy. As I found out myself, ext2 (the file system I used) overwrites deleted files. However, I'm pretty sure some file systems don't. Same goes for the pagefile.</p>
|
Web programming: Get rid of Javascript or convince me to dive into this mess <p>I'm looking for alternatives to client side Javascript in web programming, because for me this language just plain sucks. I mean I am indeed impressed of the capabilities jquery or other javascript-frameworks accomplish, but for myself programming in javascript is a pain in the rump. I would like to replace it without sacrifice functionality.</p>
<p>But I think there is no real alternative, at least I'm not aware of.</p>
<p>What is your recommendation? </p>
| <p>Javascript is an awesome beast when tamed. Learn it and love it. :)</p>
<p>I'm also not quite sure what your experiences are with jQuery, but I am a big fan of it because it lets you do what you want to do very, very, easily. Just hang in there.</p>
|
Asp.Net Absolute Path of a URL <p>To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :</p>
<pre><code>HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;
</code></pre>
<p>It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.</p>
<p>Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.</p>
<p>Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.</p>
| <p>I have used this in the past:</p>
<pre><code>// Gets the base url in the following format:
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme
+ "://"
+ HttpContext.Current.Request.Url.Authority
+ HttpContext.Current.Request.ApplicationPath;
</code></pre>
|
How to reload user profile from script file in PowerShell <p>I want to reload my user profile from a script file. I thought that dot sourcing it from within the script file would do the trick, but it doesn't work:</p>
<pre><code># file.ps1
. $PROFILE</code></pre>
<p>However, it does work if I dot source it from PowerShell's interpreter.</p>
<p><strong>Why do I want to do this?</strong></p>
<p>I run this script every time I update my profile and want to test it, so I'd like to avoid having to restart PowerShell to refresh the environment.</p>
| <p>If you want to globally refresh your profile from a script, you will have to run that script "dot-sourced". </p>
<p>When you run your script, all the profile script runs in a "script" scope and will not modify your "global" scope. </p>
<p>In order for a script to modify your global scope, it needs to be "dot-source" or preceded with a period.</p>
<pre><code>. ./yourrestartscript.ps1
</code></pre>
<p>where you have your profile script "dot-sourced" inside of "yourrestartscript.ps1". What you are actually doing is telling "yourrestartscript" to run in the current scope and inside that script, you are telling the $profile script to run in the script's scope. Since the script's scope is the global scope, any variables set or commands in your profile will happen in the global scope.</p>
<p>That doesn't buy you much advantage over running</p>
<pre><code>. $profile
</code></pre>
|
Detecting overwriting of ruby test methods <p>If you write a test class like</p>
<pre><code>class MyTest < Test::Unit::TestCase
def setup
end
def test_1
flunk
end
def test_1
assert true
end
end
</code></pre>
<p>the first test_1 is ignored. Although it looks like a stupid mistake, it can happen with copy and paste programming. Apart from running</p>
<pre><code>grep test test_me.rb | wc
</code></pre>
<p>and comparing that with how many tests test unit says has run, or using rcov or heckle, or running with -w, how can you detect such issues?</p>
<p>Also, is there any way of specifying that test methods shouldn't be overwritten?</p>
<p><strong>Edit</strong>: The method being tested had a parameter with 6 or so possible values, and the tester wanted to test each scenario. This was why copy and paste programming was used. The only alternative I can envisage for such a scenario is a a six-element array of parameters and expected values.</p>
| <p>You can take advantage of Ruby's <code>method_added</code> that gets called anytime a method is added to a class. You should be able to can something into a module that you include, but here is a simple example of doing it inside your test class.</p>
<pre><code>class MyTest < Test::Unit::TestCase
@@my_tests = []
def self.method_added(sym)
raise "#{sym} already defined!" if @@my_tests.include? sym
@my_tests << sym
end
def test_foo_1
end
def test_foo_2
end
def test_foo_1
end
end
</code></pre>
|
Google image search <p>In C#, how can I extract the URL's of any images found when performing a search with Google? I'm writing a little app to get the artwork for my ripped cd's. I played around with the Amazon service but found the results I received were erratic. I can't be bothered to learn the whole Amazon API just for this simple little app though, so thought I'd try Google instead.</p>
<p>So far, I've performed the search and got the result page's source, but I'm not sure how to extract the URL's from it. I know I have to use Regex but have no idea what expression to use. All the one's I've found seem to be broken. Any help would be appreciated.</p>
| <p>Try using the HTML Agility Pack. It works wonders on scraping content.</p>
<p>It lives <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">here</a> on Codeplex.</p>
<p>I used it to scrape a <a href="http://www.chrisballance.com/so" rel="nofollow">user ranking list</a> from so.com, and loved it.</p>
<p>It will let you select a node of html and then query subnodes using XSLT.</p>
|
Repeated Keyword Value in JSON <p>On <a href="http://json.org" rel="nofollow">JSON.org</a> the essential data structures that JSON represents are given as </p>
<ol>
<li>A collection of name/value pairs, and </li>
<li>An ordered list of values.</li>
</ol>
<p>I have not been able to find anywhere whether a second member having the same name as one already parsed into the current object should (a) throw an exception or (b) replace the existing member.</p>
<p>Is this specified anywhere?</p>
<p>What do existing parsers do with repeated names?</p>
<p>EDIT: I am looking to define correct behavior for my parser.</p>
| <p>JSON is simply a subset of the object literal notation of JavaScript and as such, is constrained by the same rules - the latest value for repeated keys will override any previously assigned value for that key, within the specific object. Think in terms of assigning a value to an object property; A later assignment will override an earlier one.</p>
<p>To demonstrate this, I have set up an <a href="http://jsbin.com/amane" rel="nofollow">example here</a>. The code is displayed on the page, and as can be seen, the messagebox has the name 'Barney' in it.</p>
<p>Code here -</p>
<pre><code>$(function() {
$('#myButton').click(function(e)
{
var myJsonString = "Person = {'firstName':'Fred','lastName':'Flintstone','firstName':'Barney'}";
eval("(" + myJsonString + ")");
alert(Person.firstName);
});
});
</code></pre>
<p>By the Way, I have used eval() here for ease of use. I would recommend using a JSON parser instead of eval() due to security issues.</p>
|
Best practice when using multiple libraries with overlapping classes <p>Consider the task: </p>
<ol>
<li>Read a polygon from a KML file using library A </li>
<li>Intersect it with another polygon using library B </li>
<li>Calculate its area using library C</li>
</ol>
<p>Each library has it's own Polygon class, and they are all equivalent. Which is the best practice when using all these classes? At the moment I first wrote this question I had implemented a method that converts a PolygonA instance into a PolygonB instance and vice-versa. But I wonder if it is the only way.</p>
<p><strong>Clarification</strong> All libraries are third-parties'</p>
| <p>I would either choose one polygon class and only use that class or build my own Polygon class to store all of them in.</p>
<p>At any rate, make sure your namespaces are aptly named so that you can differentiate between the two.</p>
<p>Why not merge the duplicated functionality?</p>
|
What is the fastest way to copy my array? <p>I'm doing some Wave file handling and have them read from disk into an array of bytes. I want to quickly copy portions from this byte array into another buffer for intermediate processing. Currently I use something like this:</p>
<pre><code>float[] fin;
byte[] buf;
//fill buf code omitted
for(int i=offset; i < size; i++){
fin[i-offset] = (float) buf[i];
}
</code></pre>
<p>I feel that this is a slow method, because there is as much computation going on in the for loop conditional and increment as there is over in the actual body. If there was a block copy avaliable in C# or some other way I can implement a block copy, that would be great. </p>
<p>Maybe it isn't too slow, but it sure looks like a lot of work to move some data over. Here "size" is between 2^10 and 2^14. I am then handing the "fin" off to a FFT library, so this is by no means the slowest part of the code, maybe I'm barking up the wrong tree.</p>
<p>EDIT UPDATE:
I realize that micro optimizations are not where someone should spend their time, and I realize that profiling is a better way to achieve speedups overall, but I know that this code is in a 'hot path' and must be completed in under a third of a second on varying end user architectures to minimize our hardware system requirements. Even though I know that the following FFT code will be much more time consuming, I am looking for speedups where I can get them. </p>
<p>Array.Copy sure looks nice, I didn't know about that before, and I consider this Q&A a success already!</p>
| <p>There is also:</p>
<pre><code>Array.Copy
Array.CopyTo
</code></pre>
<p>but whether these will be faster will require profiling.</p>
<p><em>But be warned</em> about focusing on micro-optimisations to the extent you miss the big picture, on modern PCs the effect of multi-level memory caching is likely to be greater than one approach or another to the copy.</p>
<p>Edit: Quick check in reflector: both of the above methods boil down to a common native implementation (good).</p>
<p>Note the docs for Array.Copy cover valid type conversions, a value -> value widening conversion like byte to float should be OK.</p>
|
Regular expression to get text inside parenthesis <p>I'm looking at a string and trying to get everything inside the pair of brackets.
The contents may change and the max and min may not exist in certain cirumstances.</p>
<pre><code>get(max(fieldname1),min(fieldname2),fieldname3)where(something=something) sort(fieldname2 asc)
</code></pre>
<p>The where() and sort() are not guaranteed to be there.<br />
There may be spaces between each set and [EDIT] the keywords may not always be the same.</p>
<pre><code>get(something) where(something)
get(something)where(something) sort(something)
</code></pre>
<p>What regex pattern should be used?
Effectively, it should return:</p>
<pre><code>Array (
[0] => max(fieldname1),min(fieldname2),fieldname3
[1] => something=something
[2] => fieldname2 asc
)
</code></pre>
<p>I realise that changing the first set of brackets to { or [ may solve the problem but I'm stubborn and want to do it this way by regex.</p>
<p>EDIT
The best I could come up with using preg_match_all()</p>
<pre><code>/[a-zA-Z0-9_]+\((.*?)\)/
</code></pre>
| <p>You better use a parser such as:</p>
<pre><code>$str = 'get(max(fieldname1),min(fieldname2),fieldname3)where(something=something) sort(fieldname2 asc)';
$array = array();
$buffer = '';
$depth = 0;
for ($i=0; $i<strlen($str); $i++) {
$buffer .= $str[$i];
switch ($str[$i]) {
case '(':
$depth++;
break;
case ')':
$depth--;
if ($depth === 0) {
$array[] = $buffer;
$buffer = '';
}
break;
}
}
var_dump($array);
</code></pre>
|
Problem running Java .war on Tomcat <p>I am following the tutorial here: </p>
<p><a href="http://nutch.sourceforge.net/docs/en/tutorial.html" rel="nofollow">http://nutch.sourceforge.net/docs/en/tutorial.html</a></p>
<p>Crawling works fine, as does the test search from the command line. </p>
<p>When I try to fire up tomcat after moving ROOT.war into place(and it unarchiving and creating a new ROOT folder during startup), I get a page with the 500 error and some errors in the Tomcat logs. </p>
<p>HTTP Status 500 - No Context configured to process this request</p>
<pre><code>2009-02-19 15:55:46 WebappLoader[]: Deploy JAR /WEB-INF/lib/xerces-2_6_2.jar to C:\Program Files\Apache Software Foundation\Tomcat 4.1\webapps\ROOT\WEB-INF\lib\xerces-2_6_2.jar
2009-02-19 15:55:47 ContextConfig[] Parse error in default web.xml
org.apache.commons.logging.LogConfigurationException: User-specified log class 'org.apache.commons.logging.impl.Log4JLogger' cannot be found or is not useable.
at org.apache.commons.digester.Digester.createSAXException(Digester.java:3181)
at org.apache.commons.digester.Digester.createSAXException(Digester.java:3207)
at org.apache.commons.digester.Digester.endElement(Digester.java:1225) ............ etc.
</code></pre>
<p>So it looks like the root of the error is default web.xml, not in the Log4JLogger - although I know very little about Java. I did not edit the web.xml in the tomcat dir. </p>
<p>Anyone know what is going on here? </p>
<p>versions/info:</p>
<p>nutch 0.9</p>
<p>Tomcat 4.1</p>
<p>jre1.5.0_08</p>
<p>jdk1.6.0_12</p>
<p>NUTCH_JAVA_HOME=C:\Program Files\Java\jdk1.6.0_12</p>
<p>JAVA_HOME=C:\Program Files\Java\jdk1.6.0_12</p>
| <p>In Java, applications sometimes rely on third party libraries. In this case, it appears that your Tomcat installation does not include one such library. Judging by the error you received, it appears that you are missing the <a href="http://commons.apache.org/logging/" rel="nofollow">Apache Commons Logging</a> library (a commonly used library in the Java world that just so happens to not come bundled with Tomcat).</p>
<p>The typical way to distribute a library in Java is via a JAR (Java Archive) file. Simply put, a JAR file is simply a bunch of Java classes that have been zipped into a file that has been renamed from *.zip to *.jar.</p>
<p>To obtain the Commons Logging JAR file, you can download it from the <a href="http://commons.apache.org/downloads/download_logging.cgi" rel="nofollow">Apache Commons download site</a>. You will want the binary version, not the source version. Should you happen to download version 1.1.1 (for example), you should unzip the <code>commons-logging-1.1.1-bin.zip</code> file. Inside, you will find a file named <code>commons-logging-1.1.1.jar</code>. Copy this JAR file to the <code>lib</code> directory wherever your Tomcat software is installed. You may be required to restart Tomcat before it notices this new file.</p>
<p>Hopefully, the next time you try to use the application, you may or may not receive yet another error indicating that yet another class cannot be found. In that case, I welcome you to the wonderful world of JAR hunting! :) Hopefully the application will not require too many libraries above and beyond Commons Logging, but we will see (considering you're trying to run Nutch, I can foresee it requiring <a href="http://www.apache.org/dyn/closer.cgi/lucene/java/" rel="nofollow">Lucene</a>, so be prepared for that).</p>
<p>Have fun with Nutch!</p>
|
jQuery Flexigrid Resize columns in IE7 broken <p>In firefox, column resizing works fine. But in ie7, it's broken. </p>
<p><a href="http://markmail.org/message/dyv44u5fjhgylu2r?q=ie7+resize+column+list:com.googlegroups.flexigrid" rel="nofollow">Here's a thread</a> about flexigrid broken from jquery 1.3, I've tried the suggested edits to the flexigrid code, didnt work.</p>
<p>We're currently using jquery 1.3, although i've tried 1.3.1 & 1.3.2, neither fixed the problem.</p>
<p>While inspecting the css in ie7, I noticed <code><div class="cDrag"></code> (the div that contains the styles for dragging columns) was way to the right of my grid.</p>
<p>Has anyone experienced anything similar?</p>
| <p>IE7 requires the following at the top of the page:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http:// www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</code></pre>
|
Can you create more than one element of a list at a time with a list comprehension in haskell? <p>So, for example, say I had a list of numbers and I wanted to create a list that contained each number multiplied by 2 and 3. Is there any way to do something like the following, but get back a single list of numbers instead of a list of lists of numbers?</p>
<pre><code>mult_nums = [ [(n*2),(n*3)] | n <- [1..5]]
-- this returns [[2,3],[4,6],[6,9],[8,12],[10,15]]
-- but we want [2,3,4,6,6,9,8,12,10,15]
</code></pre>
| <p>I find that extending the list comprehension makes this easier to read:</p>
<pre><code>[ m | n <- [1..5], m <- [2*n,3*n] ]
</code></pre>
<p>It might be helpful to examine exactly what this does, and how it relates to other solutions. Let's define it as a function:</p>
<pre><code>mult lst = [ m | n <- lst, m <- [2*n,3*n] ]
</code></pre>
<p>After a fashion, this <a href="http://haskell.org/onlinereport/exps.html#list-comprehensions" rel="nofollow">desugars</a> to</p>
<pre><code>mult' lst =
concatMap (\n -> concatMap (\m -> [m]) [2*n,3*n]) lst
</code></pre>
<p>The expression <code>concatMap (\m -> [m])</code> is wrapping <code>m</code> up in a list in order to immediately flatten it—it is equivalent to <code>map id</code>.</p>
<p>Compare this to @FunctorSalad's answer:</p>
<pre><code>mult1 lst = concatMap (\n -> [n*2,n*3]) lst
</code></pre>
<p>We've optimized away <code>concatMap (\m -> [m])</code>. </p>
<p>Now @vili's answer:</p>
<pre><code>mult2 lst = concat [ [(n*2),(n*3)] | n <- lst]
</code></pre>
<p>This desugars to:</p>
<pre><code>mult2' lst = concat (concatMap (\n -> [[2*n,3*n]]) lst)
</code></pre>
<p>As in the first solution above, we are unnecessarily creating a list of lists that we have to <code>concat</code> away.</p>
<p>I don't think there is a solution that uses list comprehensions, but desugars to <code>mult1</code>. My intuition is that Haskell compilers are generally clever enough that this wouldn't matter (or, alternatively, that unnecessary <code>concat</code>s are cheap due to lazy evaluation (whereas they're lethal in eager languages)). </p>
|
Permissions for web site users <p>I'm working on a web site where each user can have multiple roles/permissions such as basic logging in, ordering products, administrating other users, and so on. On top of this, there are stores, and each store can have multiple users administrating it. Each store also has it's own set of permissions.</p>
<p>I've confused myself and am not sure how best to represent this in a db. Right now I'm thinking:</p>
<p>users
roles
users_roles
stores
stores_users</p>
<p>But, should I also have stores_roles and stores_users_roles tables to keep track of separate permissions for the stores or should I keep the roles limited to a single 'roles' table? </p>
<p>I originally thought of having only a single roles table, but then what about users who have roles in multiple stores? I.e., if a user is given a role of let's say 'store product updating' there would need to be some method of determining which store this is referring to. A stores_users_roles table could fix this by having a store_id field, thus a user could have 'store product updating' and 'store product deletion' for store #42 and only 'store product updating' for store #84.</p>
<p>I hope I'm making sense here. </p>
<h2>Edit</h2>
<p>Thanks for the info everyone. Apparently I have some thinking to do. This is simply a fun project I'm working on, but RBAC has always been something that I wanted to understand better. </p>
| <p>This is probably obvious to you by now, but <a href="http://en.wikipedia.org/wiki/Role-based_access_control" rel="nofollow">role based access control</a> is <em>hard</em>. My suggestion is, don't try to write your own unless you want that one part to take up all the time you were hoping to spend on the 'cool stuff'.</p>
<p>There are plenty of flexible, thoroughly-tested authorization libraries out there implementing RBAC (sometimes mislabeled as ACL), and my suggestion would be to find one that suits your needs and use it. Don't reinvent the wheel unless you are a wheel geek.</p>
|
How can I create a Windows application that can run with a GUI *or* as a Windows service in C#? <p>I'd like to create an application using C# that...: </p>
<ul>
<li><p>Can be run as a Windows application, with a GUI (it'll indicate progress, status, etc.)</p>
<p>OR</p></li>
<li><p>Can be run as a Windows service, without a GUI</p></li>
</ul>
<p>Is it possible? Can someone get me started?</p>
<p>I guess the alternative is that I could create a Windows service, and then a separate GUI application which can poll the Windows service to fetch data from it (progress, status, etc.). </p>
<p>In that case... how can I fetch data from the Windows service from my GUI application? </p>
| <p>I'm doing something similar to what you're asking for. I have programmed it so that if you send the command line parameter "/form" to the executable, it will pop up a windows form instead of running as a service.</p>
<p>As far as running the background job itself, in both cases you will need to do some sort of threading (perhaps with a timer) to do the work and report status back to your form asynchronously. This would be a whole different discussion topic on creating threaded GUI apps.</p>
<p>The "form or service" code goes something like this:</p>
<pre><code>static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main(string[] args)
{
if (args.Length > 0 && args[0] == "/form")
{
var form = new MainForm();
Application.Run(form);
return;
}
var ServicesToRun = new ServiceBase[]
{
new BackgroundService()
};
ServiceBase.Run(ServicesToRun);
}
}
</code></pre>
|
Querying full DNS record <p>I do alot of programming in *nix using C gcc. I know how to do a basic gethostbyname(). BUt what if I wanted to pull down the entire DNS record. More to the point, is there a function that I'm missing that allows you to specify the specific record that you want to pull? Or will I need to do this manually through a UDP socket?</p>
| <p>No, there is no such function in standard C or POSIX (and even the gethostbyname function, contrary to what you may think, is not a function for querying DNS - it can use any other way to get the address, like /etc/hosts or mDNS, whatever).</p>
<p>You might want to look at some DNS-specific libraries, like <a href="http://nlnetlabs.nl/projects/ldns/doc/tutorial1_mx.html" rel="nofollow">ldns</a>, libbind or libdjbdns.</p>
|
CSS layout problem <p>At the top of <a href="http://chaletsdesbouleaux.com/" rel="nofollow">this webpage</a>, there are two elements in the main content area (white background): an image and a logo box.</p>
<p>The logo box is floated right and the image has a right-margin which is sufficiently large to accomodate the logo box and a little padding. However, if you make your browser window sufficiently narrow, the logo box slides underneath the image. What I would like to happen is that the horizontal space between the two decreases to a minimum of 6 pixels, and if the browser window is made any narrower, horizontal scrollbars appear.</p>
<p>Is there any way that I can achieve this without resorting to a completely 'frozen' layout, i.e. setting a fixed width on the main content area?</p>
<p>Thanks,
Don</p>
| <p>The css <code>min-width</code> property does what you want. Doesn't work in IE 6, though. For that some JavaScript can help out if it's really necessary.</p>
<p>Set the white DIV's <code>min-width</code> to the size of the image + the border.</p>
|
Submitting Data via GET with "Snoopy" in PHP <p>I'm trying to send data to a url via <code>GET</code> in PHP. I've decided to go with the <a href="http://sourceforge.net/projects/snoopy/" rel="nofollow">Snoopy Class</a> after receiving an answer to another question here. The thing is, I cannot seem to find very good documentation/examples for the methods in this class.</p>
<p>I see the <code>->httprequest()</code> method, but I don't see where I can add an array of values along with the request.</p>
<p>Anybody a bit more familiar able to lend a hand?</p>
| <pre class="lang-php prettyprint-override"><code>$vars = array( "fname" => "Jonathan", "lname" => "Sampson" );
$snoopy = new Snoopy();
$snoopy->httpmethod = "GET"; // is GET by default
$snoopy->submit( "http://www.example.com", $vars );
print $snoopy->results;
</code></pre>
|
Tips for profiling misbehaving Emacs Lisp? <p>I customize Emacs a lot. Recently, I added something to my .emacs configuration that sporadically pegs my CPU at 100%, but I really don't know what it is. </p>
<p>If I press C-g a bunch of times, eventually I'll get a message <em>below</em> the minibuffer asking me if I want to auto save my files and then if I want to abort emacs entirely. If I keep saying no and keeping pressing C-g, eventually I can get back to running emacs as normal. An hour or so later it will happen again.</p>
<p>I could keep going about like I am, commenting out various things I've added recently, restarting emacs, trying to narrow down the culprit, but it's slow going.</p>
<p><strong>Is there a way I can profile emacs directly to figure out what lisp function is hogging the CPU?</strong></p>
| <p>The suggestion of setting <code>debug-on-quit</code> to <code>t</code> so that you can find out what Emacs is up to is a good one. You can think of this as being a form of sampling profiling with a single sample: often a single sample is all you need.</p>
<hr>
<p><strong>Update:</strong> Starting with version 24.3, Emacs contains <em>two</em> profilers. There's a (new) sampling profiler in <code>profiler.el</code>, and an (old) instrumenting profiler in <code>elp.el</code>.</p>
<p>The sampling profiler is <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Profiling.html">documented here</a>. It's pretty straightforward to use:</p>
<blockquote>
<p>To begin profiling, type <code>M-x profiler-start</code>. You can choose to profile by processor usage, memory usage, or both. After doing some work, type <code>M-x profiler-report</code> to display a summary buffer for each resource that you chose to profile. When you have finished profiling, type <code>M-x profiler-stop</code>.</p>
</blockquote>
<p>Here's some example output from a <code>cpu+mem</code> profiler session with the <a href="https://github.com/gareth-rees/p4.el">Perforce/Emacs integration</a> that I maintain. I've expanded the topmost function (<code>progn</code>) in order to find out <a href="https://github.com/gareth-rees/p4.el/issues/112">where the CPU time and memory use is coming from</a>.</p>
<pre class="lang-none prettyprint-override"><code>Function Bytes %
- progn 26,715,850 29%
- let 26,715,850 29%
- while 26,715,850 29%
- let 26,715,850 29%
- cond 26,715,850 29%
- insert 26,715,850 29%
+ c-after-change 26,713,770 29%
+ p4-file-revision-annotate-links 2,080 0%
+ let 20,431,797 22%
+ call-interactively 12,767,261 14%
+ save-current-buffer 10,005,836 11%
+ while 8,337,166 9%
+ p4-annotate-internal 5,964,974 6%
+ p4-annotate 2,821,034 3%
+ let* 2,089,810 2%
</code></pre>
<p>You can see that the culprit is <code>c-after-change</code>, so it looks as though I could save a lot of CPU time and memory by <a href="https://github.com/gareth-rees/p4.el/commit/4e015793877a56c4ccb1bfbb6e2d278be7c078d8">locally binding <code>inhibit-modification-hooks</code> to <code>t</code> around this code</a>.</p>
<hr>
<p>You can also use the Emacs Lisp Profiler. This is rather under-documented: you'll have to read the comments in <code>elp.el</code> for the details, but basically you run <code>elp-instrument-package</code> to turn on profiling for all the functions with a given prefix, and then <code>elp-results</code> to see the results.</p>
<p>Here's some typical output after typing <code>M-x elp-instrument-package RET c- RET</code>, fontifying 4,000 lines of C, and then running <code>elp-results</code> (and using <code>elp-sort-by-function</code> to sort by call count):</p>
<pre class="lang-none prettyprint-override"><code>Function Name Call Count Elapsed Time Average Time
============================= ========== ============ ============
c-skip-comments-and-strings 107 0.0 0.0
c-valid-offset 78 0.0 0.0
c-set-offset 68 0.031 0.0004558823
c-end-of-macro 52 0.0 0.0
c-neutralize-CPP-line 52 0.0 0.0
c-font-lock-invalid-string 20 0.0 0.0
c-set-style-1 19 0.031 0.0016315789
...
</code></pre>
<p>In your particular case the profiler doesn't help immediately, because you don't know which package is at fault. But if you can make a guess (or use <code>debug-on-quit</code> to find it for sure) then the profiler can help you diagnose the problem in detail.</p>
|
Upgrading Reporting Services RLD 2005 --> 2008 <p>I ran the solution conversion for a bunch of reports I maintain, but a handful (about half a dozen) failed to convert. I managed to convert some by hand, but some are different enough that changing the RDL by hand is difficult. Is there a better way to fix these reports?</p>
| <p>Did you try to open those file into SQL Server Business Intelligence Development Studio and save it again ?</p>
|
What is the complexity of finding median and doing counts in MySQL? <p>I would like to know what the complexity of the following two operations are. The first case is a count where I order by a column that I have an index on and ask for the count of all values below or above a certain number like this:</p>
<pre><code>SELECT count(*) FROM tbl WHERE col1 > 10 ORDER BY col1;
</code></pre>
<p>The other case is concerning a median operation. By median I mean finding the (int)n/2's row value, where n is the number of rows in the table. An example of this could be the following (again there's an index on col1):</p>
<pre><code>SELECT median(col1) FROM tbl ORDER BY col1;
</code></pre>
<p>What is the worst case complexities of these cases?</p>
| <p>The <code>ORDER BY</code> clauses are unnecessary - or confusing, or both.</p>
<p><code>SELECT COUNT(*)</code> will return a single row (normally). Because you have a criterion on the search, the optimizer may have to do an index scan of col1 (if there is an index with col1 as the leading column of the index), or a table scan. That is an O(N) operation, where N is the number of rows in the table.</p>
<p><code>SELECT MEDIAN(col1)</code> will also return a single row (normally). It will be an O(N) operation, again using an index scan or a table scan.</p>
<p>The 'normally' qualifier is there because I'm not absolutely sure what the optimizer will do with the <code>ORDER BY</code> clauses. One possibility is that the optimizer will determine that it is redundant and ignore it. The other possibility is that it will somehow add the <code>col1</code> that you <code>ORDER BY</code> to the projection columns, include it in the other operations, and then remove it before returning results. However, that would run foul of mixing aggregates and non-aggregates without a <code>GROUP BY</code> clause - so I think the optimizer will ignore it, or reject the query. However, I've not done the experiment with MySQL.</p>
<p>FWIW, IBM Informix Dynamic Server (IDS) yields error -19828: ORDER BY column or expression must be in SELECT list in this context.</p>
<p>Without the ORDER BY clauses, the analysis above is accurate enough. Note that for SELECT COUNT(*) with no criteria, the server can often use metadata it keeps about the table to answer the query in O(1) time.</p>
|
Python-like list unpacking in C#? <p>In python, I can do something like this:</p>
<pre><code>List=[3, 4]
def Add(x, y):
return x + y
Add(*List) #7
</code></pre>
<p>Is there any way to do this or something similar in C#? Basically I want to be able to pass a List of arguments to an arbitrary function, and have them applied as the function's parameters without manually unpacking the List and calling the function explicitly specifying the parameters.</p>
| <p>Well, the closest would be reflection, but that is on the slow side... but look at <a href="http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx">MethodInfo.Invoke</a>...</p>
|
SQL script to aggregate column values <p>i'd appreciate some help putting together a sql script to copy data from one table to another. essentially what i need to do for each row in the source table is aggregate the column values and store them into a single column in the target table.</p>
<pre><code>TableA: ID, ColumnA, ColumnB, ColumnC
TableB: Identity, ColumnX
</code></pre>
<p>so, ColumnX needs to be something like 'ColumnA, ColumnB, ColumnC'.</p>
<p>in addition though, i need to keep track of each TableA.ID -> SCOPE_IDENTITY() mapping in order to update a third table.</p>
<p>thanks in advance!</p>
<p>EDIT: TableA.ID is not the same as TableB.Identity. TableB.Identity will return a new identity value on insert. so either i need to store the mapping in a temp table or update TableC with each insert into TableB.</p>
| <p>Here is a row-by-row processing example. This will provide you the results in a way where you can process each row at a time. Or you can use TableC at the end and do whatever processing you need to do.</p>
<p>However, it would be a lot faster if you added an extra column to TableB (Called TableA_ID) and just INSERTED the result into it. You would have instant access to TableA.ID and TableB.Identity. But without knowing your exact situation, this may not be feasible. (But you could always add the column and then drop it afterwards!)</p>
<pre><code>USE tempdb
GO
CREATE TABLE TableA (
ID int NOT NULL PRIMARY KEY,
ColumnA varchar(10) NOT NULL,
ColumnB varchar(10) NOT NULL,
ColumnC varchar(10) NOT NULL
)
CREATE TABLE TableB (
[Identity] int IDENTITY(1,1) NOT NULL PRIMARY KEY,
ColumnX varchar(30) NOT NULL
)
CREATE TABLE TableC (
TableA_ID int NOT NULL,
TableB_ID int NOT NULL,
PRIMARY KEY (TableA_ID, TableB_ID)
)
GO
INSERT INTO TableA VALUES (1, 'A', 'A', 'A')
INSERT INTO TableA VALUES (2, 'A', 'A', 'B')
INSERT INTO TableA VALUES (3, 'A', 'A', 'C')
INSERT INTO TableA VALUES (11, 'A', 'B', 'A')
INSERT INTO TableA VALUES (12, 'A', 'B', 'B')
INSERT INTO TableA VALUES (13, 'A', 'B', 'C')
INSERT INTO TableA VALUES (21, 'A', 'C', 'A')
INSERT INTO TableA VALUES (22, 'A', 'C', 'B')
INSERT INTO TableA VALUES (23, 'A', 'C', 'C')
GO
-- Do row-by-row processing to get the desired results
SET NOCOUNT ON
DECLARE @TableA_ID int
DECLARE @TableB_Identity int
DECLARE @ColumnX varchar(100)
SET @TableA_ID = 0
WHILE 1=1 BEGIN
-- Get the next row to process
SELECT TOP 1
@TableA_ID=ID,
@ColumnX = ColumnA + ColumnB + ColumnC
FROM TableA
WHERE ID > @TableA_ID
-- Check if we are all done
IF @@ROWCOUNT = 0
BREAK
-- Insert row into TableB
INSERT INTO TableB (ColumnX)
SELECT @ColumnX
-- Get the identity of the new row
SET @TableB_Identity = SCOPE_IDENTITY()
-- At this point, you have @TableA_ID and @TableB_Identity.
-- Go to town with whatever extra processing you need to do
INSERT INTO TableC (TableA_ID, TableB_ID)
SELECT @TableA_ID, @TableB_Identity
END
GO
SELECT * FROM TableC
GO
</code></pre>
<p><strong>SELECT * FROM TableA</strong></p>
<pre><code>ID ColumnA ColumnB ColumnC
----------- ---------- ---------- ----------
1 A A A
2 A A B
3 A A C
11 A B A
12 A B B
13 A B C
21 A C A
22 A C B
23 A C C
</code></pre>
<p><strong>SELECT * FROM TableB</strong></p>
<pre><code>Identity ColumnX
----------- ------------------------------
1 AAA
2 AAB
3 AAC
4 ABA
5 ABB
6 ABC
7 ACA
8 ACB
9 ACC
</code></pre>
<p><strong>SELECT * FROM TableC</strong></p>
<pre><code>TableA_ID TableB_ID
----------- -----------
1 1
2 2
3 3
11 4
12 5
13 6
21 7
22 8
23 9
</code></pre>
|
Get the diff of two MSWord doc files and output to html <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/90075/how-to-compare-two-word-documents">How to compare two word documents?</a> </p>
</blockquote>
<p>How can you get the diff of two word .doc documents programatically?
Where you can then take the resulting output and generate an html file of the result. (As you would expect to see in a normal gui diff tool)</p>
<p>I imagine if you grabed the docs via COM and converted the output to text you could provide <em>some</em> diff funcitonality. Thoughts?</p>
<p>Is there a way to do this without windows and COM?</p>
<p>(Perferably in python, but I'm open to other solutions)</p>
<p><strong>UPDATE</strong></p>
<p>Original question asking about msword diff tools was a duplicate of: (Thanks Nathan)</p>
<p><a href="http://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/">How to compare two word documents?</a></p>
| <p>Use this option in Word 2003: </p>
<blockquote>
<p><strong>T</strong>ools | Compare and Merge <strong>D</strong>ocuments</p>
</blockquote>
<p>Or this in Word 2007: </p>
<blockquote>
<p><strong>R</strong>eview | Co<b>m</b>pare</p>
</blockquote>
<p>It prompts you for a file with which to compare the file you're editing.</p>
<p><hr /></p>
<p>This question is a duplicate of <a href="http://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/">How to compare two word documents?</a>, and this answer is a duplicate of <a href="http://stackoverflow.com/questions/90075/how-to-compare-two-word-documents/90277#90277">my answer there</a>.</p>
|
Loading C# form into ActiveX control <p>Is it possible loading C# form (or C# application) into ActiveX control? I know how to load ActiveX control to C# form.... </p>
| <p>You can call a .Net form in VB6 (with Interop Forms Toolkit 2.0), and you can use VB6 to create an ActiveX so my guess is that it is possible.</p>
<p>I have also heard of ppl used forms created from .net-dlls and den using setparent-api and got it to act as a child to vb6-form.</p>
<p>All in all, yes it seems possible to load an C#-form in an activeX control.</p>
<p><strong>Interop Forms Toolkit 2.0: display .NET Winforms in VB6 Applications</strong>
<a href="http://hubpages.com/hub/Interop_Forms_Toolkit_20" rel="nofollow">http://hubpages.com/hub/Interop_Forms_Toolkit_20</a></p>
<p>And someone using SetParent, not a solution but from this its easy to google away to other solutions.
<a href="http://www.eggheadcafe.com/forumarchives/NETFrameworkinterop/Oct2005/post24062147.asp" rel="nofollow">http://www.eggheadcafe.com/forumarchives/NETFrameworkinterop/Oct2005/post24062147.asp</a></p>
|
How to give entry in the where clause when we use it in webpages? <p>According to the user's input I want to select the record from the database. This is my code:</p>
<p><code><pre>
<%
String jempid=request.getParameter("empid");
out.println(jempid);
int intempid=1223;
Connection conn=null;
String url="jdbc:mysql://localhost/employees";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection(url,"root","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from empdetails where empnum=jempid");
%>
</pre></code></p>
<p>It throws the following error</p>
<p>javax.servlet.ServletException: java.sql.SQLException: Unknown column 'jempid' in 'where clause</p>
| <p>It's a bad idea to construct SQL using string concatenation - you're just opening yourself up to a SQL injection attack -- ESPECIALLY considering that you're getting the value of "empid" directly from the request. Yikes!</p>
<p>A better approach is use a parametrized query such as below:</p>
<pre><code>PreparedStatement st=conn.prepareStatement("select * from empdetails where empnum=?");
st.setString(1, jempid);
ResultSet rs=st.executeQuery();
</code></pre>
<p>Also you should check that jempid is not null.</p>
|
AWK - My regexp won't respect case <p>I'm running Ubuntu 8.04 and my code looks like this...</p>
<pre><code> for (i=1;i<=n;i++)
{
if (arr[i] ~ /^[A-Z]{2,4}$/) printf(arr[i])
}
</code></pre>
<p>I quickly discovered that the {n} expression won't work in gawk without the --posix switch. Once enabled the expression works but it is case-insenitive matching AAAA and aaaa. What is going on here?</p>
| <p>The expression itself works for me:</p>
<pre><code>dfs:~# gawk --posix '/^[A-Z]{2,4}$/ {print "Yes"}'
AAAA
Yes
AA
Yes
TT
Yes
tt
YY
Yes
yy
</code></pre>
<p>Your problems may be caused by two things. Either you accidentally set the <code>IGNORECASE</code> awk variable or otherwise turned of <a href="http://www.gnu.org/software/gawk/manual/gawk.html#Case_002dsensitivity" rel="nofollow">case insensitive operation</a> (BTW <code>IGNORECASE</code> doesn't work with <code>--posix</code>, but does with <code>--re-interval</code>, which enables the braces in regular expressions too), or it is a classic problem of locale's collating sequence (because gawk does locale aware character comparison), which means the lowercase characters compare between some uppercase characters. Quote from the <a href="http://www.gnu.org/software/gawk/manual/gawk.html#Character-Lists" rel="nofollow">relevant part of the manual:</a></p>
<blockquote>
<p>Many locales sort characters in
dictionary order, and in these
locales, â[a-dx-z]â is typically not
equivalent to â[abcdxyz]â; instead it
might be equivalent to
â[aBbCcDdxXyYz]â, for example. To
obtain the traditional interpretation
of bracket expressions, you can use
the C locale by setting the LC_ALL
environment variable to the value âCâ.</p>
</blockquote>
|
Which linux distribution fits a new learner of linux programming? <p>As I come up with linux ,I found the commands are different in OpenSuse and Ubuntu.</p>
<p>Which of them is suitable to somebody who was new in linux and want to master the command</p>
<p>needed when programming and using linux?</p>
| <p>I got the impression that OpenSuSE did some things a little unconventionally (kdesu, gksu), but it's a fine (KDE) distro. I've found (K)Ubuntu is a little better for beginners since it has access to huge compiled package repositories, plus <a href="http://ubuntuforums.org/" rel="nofollow">the community</a> is unbeatable.</p>
<p>They're pretty similar for most things, including programming.</p>
|
How do I use different Fields in the same column in a DataGridView <p>I have a, probably unique situation in which I need to use a single column for two different alternating values.</p>
<p>My data has seperate columns for date and time. Not my choice, I have to live with it. Rows are displayed in "pairs" Row 1 and 2 are part of the same functional unit, but they are seperate rows in the database. In the grid, Row 1, column 1 has to use the date column while in row 2 column 1 is the time column. This repeats for eavery even and odd row. See ASCII drawing below.</p>
<p><strong>Is it possible to make a cell hidden on one row but not another, and then make both fields share a common column header?</strong> </p>
<p>I'm also open to using other grids if you know of one that makes this functionality easier to accomplish.</p>
<pre><code>-----------------------------------------------------------------
|Date/Time| ......
=================================================================
|1/1/2008 | .......
|10:00pm | .......
-----------------------------------------------------------------
|1/2/2008 | .......
|7:00pm | .......
-----------------------------------------------------------------
...
...
...
</code></pre>
| <p>If you have control over the data feed coming into your system, say a SQL Stored Procedure, what about something like this?</p>
<pre><code>SELECT
ROWID AS 'ID'
, MYDATE + MYTIME AS 'MYDATETIME'
FROM
MYTABLE
</code></pre>
<p>If you don't have control over the data source, I'd recommend using the on Row_Databound event and changing the text of the cell to meet your needs. This may mean you make cell 3 equal to cell 3 + cell 4 and then hide cell 4... But either way, the Row_Databound would probably be a good fit...</p>
<pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//ASSUMES COLUMN 2 IS DATE
//AND COLUMN 3 IS TIME
e.Row.Cells[2].Text = e.Row.Cells[2].Text + " " + e.Row.Cells[3].Text;
e.Row.Cells[3].Visible = false;
}
}
</code></pre>
|
Possible memory leak? <p>Okay, so I have two classes, call them A and B--in that order in the code. Class B instantiates class A as an array, and class B also has an error message char* variable, which class A must set in the event of an error. I created a third class with a pure virtual function to set the errorMessage variable in B, then made B a child of that third class. Class A creates a pointer to the third class, call it C--when B initializes the array of A objects, it loops through them and invokes a function in A to set A's pointer to C-- it passes "this" to that function, and then A sets the pointer to C to "this," and since C is B's parent, A can set C->errorMessage (I had to do all this because A and B couldn't simultaneously be aware of each other at compile time).</p>
<p>Anyways it works fine, however, and when I pass command line parameters to main(int,char**), it works unless I pass seven, eight, or more than twelve parameters to it... I narrowed it down (through commenting out lines) to the line of code, in A, which sets the pointer to C, to the value passed to it by B. This made no sense to me... I suspected a memory leak or something, but it seems wrong and I have no idea how to fix it... Also I don't get why specifically seven, eight, and more than twelve arguments don't work, 1-6 and 9-12 work fine.</p>
<p>Here is my code (stripped down)--</p>
<pre><code>//class C
class errorContainer{
public:
virtual ~errorContainer(){ }
virtual void reportError(int,char*)=0;
};
//Class A
class switchObject{
void reportError(int,char*);
errorContainer* errorReference;
public:
void bindErrorContainer(errorContainer*);
};
//Class A member function definitions
void switchObject::reportError(int errorCode,char* errorMessage){
errorReference->reportError(errorCode,errorMessage);
}
void switchObject::bindErrorContainer(errorContainer* newReference){
errorReference=newReference; //commenting out this line fixes the problem
}
//Class B
class switchSystem: public errorContainer{
int errorCode;
char* errorMessage;
public:
switchSystem(int); //MUST specify number of switches in this system.
void reportError(int,char*);
int errCode();
char* errMessage();
switchObject* switchList;
};
//Class B member function definitions
switchSystem::switchSystem(int swLimit){
int i;
switchList=new (nothrow) switchObject[swLimit];
for(i=0;i<swLimit;i++){
switchList[i].bindErrorContainer(this);
}
errorCode=0;
errorMessage="No errors.";
}
void switchSystem::reportError(int reportErrorCode,char* reportErrorMessage){
int len=0,i;
errorCode=reportErrorCode;
if(errorMessage){
delete[] errorMessage;
}
while(reportErrorMessage[len]!='\0'){
len++;
}
errorMessage=new char[len];
for(i=0;i<=len;i++){
errorMessage[i]=reportErrorMessage[i];
}
}
int switchSystem::errCode(){
return errorCode;
}
char* switchSystem::errMessage(){
return errorMessage;
}
</code></pre>
<p>Anyone know what I've done wrong here?
It's bugging the crap out of me... I can't seem to fix it.</p>
<p>---EDIT---
okay, I have it set up the way I do so that I can use it like this in main()</p>
<pre><code>int main(int argc,char** argv){
switchSystem sw (2)
sw.switchList[0].argumentCount=2;
sw.switchList[1].argumentCount=0;
sw.switchList[0].identifier="a";
sw.switchList[1].identifier="switch";
sw.init(argc,argv);
if(sw.errCode()>0){
cout<< "Error "<< sw.errCode()<< ": "<< sw.errMessage()<< endl;
}
}
</code></pre>
<p>this program is supposed to read the command line arguments and handle user defined "switches"--like how most command line programs handle switches, but instead of testing for all of them at the beginning of main I wanted to try to write a class and some functions to do it for me--create a switchSystem object with the number of switches, set their identifiers, whether or not they take arguments, and then pass the command line arguments to "init()" to sort it out. Then test like, <pre>if(sw.isSet("switch")){ ... }</pre> etc.</p>
| <p>It seems scary that you:</p>
<ul>
<li>Mix dynamic memory with static string constants ("No errors.") in the same pointer.</li>
<li>Use an explicit <code>while</code>-loop to compute the string's length; have you not heard of <code>strlen()</code>?</li>
<li>Use such low-level C-like string processing, for no good reason ... What's wrong with <code>std::string</code>?</li>
<li>Don't properly account for the terminating '\0' in the string, when allocating space for it and copying it. The length is also not stored, leaving the resulting <code>char</code> array rather difficult to interpret.</li>
</ul>
|
Where to start as the new programmer working on a project <p>What process you guys follow when you join a new team/product or new job and start working on project there? There could be different answers :</p>
<ul>
<li>Start reading documentations.</li>
<li>Start debugging code.</li>
<li>Start fixing bugs.</li>
<li>Start doing small changes.</li>
</ul>
<p>I generally start debugging code , doing small changes.</p>
<p>May be there are some best ways that can be followed to get hands on with any new project.</p>
<p>Comments??</p>
| <p>First I would try to use the software myself for some time to get accustomed to what it is doing and how it is doing it. Then I would proceed by looking at the general architecture of the software (using the UML docs if there are any), then try to learn more about the some detail questions I might get during that process by look at actual source code. </p>
<p>Once I feel I have a good overview of all this, I would proceed to whatever is on the project team's to-do list (bug fixes, new features, etc). </p>
|
What is better, many small assemblies, or one big assembly? <p>All is in the title :)</p>
<p>Currently, we have a VS2005 solution with 20+ projets. Like</p>
<pre><code>MySolution
MySolution.Modules.Foo
MySolution.Modules.Bar
[insert many here]
MySolution.Modules.Baz
</code></pre>
<p>Can there be a harm to "merge" MySolution.Modules.* in one project ? All namespaces will be preserved, so no problem here.</p>
<p>But is there anything I didn't think about ?</p>
<p>Note : Currently, there can't be circular references : if MySolution.Modules.Foo references MySolution.Modules.Bar, MySolution.Modules.Bar can't reference MySolution.Modules.Foo. So we'll have to be careful not to create some.</p>
| <p>I have been in a couple of companies where having far too many projects has been a pain in various ways. I haven't yet been anywhere which had too <em>few</em> projects, although that's certainly possible.</p>
<p>Think about a project as a unit of reuse, amongst other things. Is any product going to need Foo but not Bar, or vice versa? If not, merge them together.</p>
<p>I like to keep different layers (presentation, business logic, data access) apart, and it's nice to have a common, product-agnostic utility library, but that's about it in many cases.</p>
<p>Oh, and keep tests in a different project to your production code, of course :)</p>
|
how do i use another identity to execute my code in asp.net provided i have a username and password <p>I'm building a small web based management app.
Within it I need to connect to different servers using different accounts via wmi.</p>
<p>What I want is to tell my app: you are now run by user1, do this and this.
And then I want to tell it: now you are user2, do this and this.</p>
<p>I guess, I'm not all that clear with my question, I'll refactor it.</p>
| <p>You would have to write a seperate piece of .Net code (some umanaged calls too) to perform impersonation of your user then call your code whilst impersonating that user. You can then restore the user account afterwards:</p>
<p>Apologies for the VB sample, but this would be easy to port to C#.</p>
<p><hr /></p>
<h2>VB Sample</h2>
<pre><code>Public Class UserImpersonation
Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Boolean
<DllImport("kernel32.dll")> _
Private Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
End Function
Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
Private Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
ByRef DuplicateTokenHandle As IntPtr) As Boolean
<PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
Public Shared Function ImpersonateUser(ByVal strDomain As String, ByVal strUserid As String, ByVal strPassword As String) As WindowsImpersonationContext
Dim tokenHandle As New IntPtr(0)
Dim dupeTokenHandle As New IntPtr(0)
Try
' Get the user token for the specified user, domain, and password using the
' unmanaged LogonUser method.
' The local machine name can be used for the domain name to impersonate a user on this machine.
Const LOGON32_PROVIDER_DEFAULT As Integer = 0
'This parameter causes LogonUser to create a primary token.
Const LOGON32_LOGON_INTERACTIVE As Integer = 2
tokenHandle = IntPtr.Zero
' Call LogonUser to obtain a handle to an access token.
Dim returnValue As Boolean = LogonUser(strUserid, strDomain, strPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, tokenHandle)
If returnValue = False Then
Dim ret As Integer = Marshal.GetLastWin32Error()
Throw New System.ComponentModel.Win32Exception(ret)
Else
' Use the token handle returned by LogonUser.
Dim newId As New WindowsIdentity(tokenHandle)
Dim ImpersonatedUser As WindowsImpersonationContext = newId.Impersonate()
Return ImpersonatedUser
End If
Catch ex As Exception
Console.WriteLine("UserImpersonation.impersonateUser Exception Occurred: " + ex.Message)
Return Nothing
End Try
' Free the tokens.
If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
CloseHandle(tokenHandle)
End If
End Function
Public Shared Function UndoImpersonate(ByVal WIC As WindowsImpersonationContext) As Boolean
Try
' Stop impersonating the user.
WIC.Undo()
Return True
Catch ex As Exception
Console.WriteLine(("Exception occurred. " + ex.Message))
Return False
End Try
End Function
End Class
</code></pre>
|
How to detect a string of data from xml in Xquery <p>I have an untyped XML column in Sql Server Database which holds values such as </p>
<pre><code> 1
<root><a>123</a></root>
<root>23d</root>
23
</code></pre>
<p>I was trying with the following query </p>
<pre><code>declare @x xml
set @x='1'
select @x.exist('xs:int(.)')
</code></pre>
<p>But here the problem is exist function will return 1 even if <code>@x='<root><a>12</a></root>'</code></p>
<p>I would like the output to '0' in such cases.</p>
<p>Is there a way out?</p>
| <p>The .exist() method returns 1 if the XQuery expression evaluates to non-null node list, otherwise it returns 0. So it'll return 1 every time in your example.</p>
<p>If I understand you correctly, you want it to return 1 when the value is just an integer, and 0 when it's XML?</p>
<p>In that case you need to do the following:</p>
<pre><code>declare @x xml
set @x='<root><a>12</a></root>'
select ISNUMERIC(CAST(@x.query('/') AS nvarchar))
</code></pre>
<p>This should return 0</p>
<pre><code>declare @x xml
set @x='12'
select ISNUMERIC(CAST(@x.query('/') AS nvarchar))
</code></pre>
<p>This should return 1</p>
|
Why is memory still accessible after std::map::clear() is called? <p>I am observing strange behaviour of std::map::clear(). This method is supposed to call element's destructor when called, however memory is still accessible after call to clear().</p>
<p>For example:</p>
<pre><code>struct A
{
~A() { x = 0; }
int x;
};
int main( void )
{
std::map< int, A * > my_map;
A *a = new A();
a->x = 5;
my_map.insert( std::make_pair< int, *A >( 0, a ) );
// addresses will be the same, will print 5
std::cout << a << " " << my_map[0] << " " << my_map[0]->x << std::endl;
my_map.clear();
// will be 0
std::cout << a->x << std::endl;
return 0;
}
</code></pre>
<p>The question is, why is variable <code>a</code> still accessible after its destructor was called by map::clear()? Do I need to write <code>delete a;</code> after calling <code>my_map.clear()</code> or is it safe to overwrite the contents of <code>a</code>?</p>
<p>Thanks in advance for your help,
sneg</p>
| <p>If you store pointers on a map (or a list, or anything like that) <strong>YOU</strong> are the responsible for deleting the pointers, since the map doesn't know if they have been created with new, or not. The clear function only invokes destructors if you don't use pointers.</p>
<p>Oh, and one more thing: invoking a destructor (or even calling delete) doesn't mean the memory can't be accessed anymore. It only means that you will be accessing garbage if you do.</p>
|
Repeater, Datalist in ASP vs PHP <p>Can anyone give me some suggestion please. In ASP we can use datalist and repeater control to repeate the rows but how can we do similar in PHP.</p>
<p>I am designing a private message page for the similair as inbox page.</p>
| <p>Use a loop construct. For example:</p>
<pre><code><?php foreach ($rows as $row): ?>
<tr>
<td><?php echo htmlspecialchars($row['id']); ?></td>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['email']); ?></td>
</tr>
<?php endforeach; ?>
</code></pre>
|
Are there any tools to do Migrations (a la Ruby) on Microsoft SQL Server (MSSQL)? <p>Are there any tools, or 'best practices' for creating Migrations on MSSQL? I have a Dev & Production database, and the Dev one often has new SPROCs created, and occasionally the structure is added to. I'd like to be able to write a set of scripts during each iteration which will update the Dev server, then execute all the scripts at release time to update Production. In ruby I can do this with migrations - is there an equivalent?</p>
| <p>There are a few:</p>
<ul>
<li><a href="http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer" rel="nofollow">Rails Migrations running on SQL Server</a></li>
<li><a href="http://www.rikware.com/RikMigrations.html" rel="nofollow">RikMigrations</a></li>
<li><a href="http://code.google.com/p/tarantino/" rel="nofollow">Tarantino</a></li>
<li><a href="http://code.google.com/p/migratordotnet/" rel="nofollow">Migrator.NET</a></li>
<li><a href="http://blog.eleutian.com/2008/04/25/AFirstLookAtMachineMigrations.aspx" rel="nofollow">Machine Migrations</a></li>
<li><a href="http://blog.wekeroad.com/2007/10/03/subsonic-migrate-me/" rel="nofollow">Subsonic Migrations</a></li>
<li><a href="http://dbdeploy.com/2007/09/25/dbdeploynet-v10-officially-released/" rel="nofollow">dbDeploy.NET</a></li>
<li><a href="http://wiki.github.com/enkari/fluentmigrator" rel="nofollow">Fluent Migrator</a></li>
</ul>
<p><a href="http://flux88.com/blog/net-database-migration-tool-roundup/" rel="nofollow">Source</a></p>
<p>For what it's worth, my favourite of these is Fluent Migrator.</p>
|
Change default SVN diffing tool <p>Following a blog, I created a batch file, wm.bat:</p>
<pre><code>"d:\svnroot\external\winmerge\WinMerge.exe" /B /WAIT "d:\svnroot\external\winmerge\WinMergeU.exe" /e /ub /dl %3 /dr %5 %6 %7
</code></pre>
<p>And I tried calling</p>
<pre><code>svn diff | wm
</code></pre>
<p>but that didn't work. So how do I integrate <a href="http://en.wikipedia.org/wiki/WinMerge" rel="nofollow">WinMerge</a> or similar utility with <code>svn diff</code>?</p>
<p>Extending on David's answer below, changing the default for Windows requires editing the configuration file located at (for Windows XP)</p>
<pre><code>C:\Documents and Settings\{username}\Application Data\Subversion\config
</code></pre>
<p>or (Windows Vista)</p>
<pre><code>C:\Users\{username}\AppData\Roaming\Subversion\config
</code></pre>
| <p>Ok, looking at the <a href="http://flimflan.com/blog/UsingWinMergeWithSubversion.aspx">original blog post</a>, this is what you want:</p>
<pre><code>svn diff --diff-cmd wm [optional-filename]
</code></pre>
<p>If you want to see what is actually happening here (i.e. what sort of parameters the <code>svn diff</code> passes to the nominated <code>diff-cmd</code>), you can just use <code>svn diff --diff-cmd echo</code> and see what it says:</p>
<pre><code>[~/src/gosmore-dev]$ svn diff --diff-cmd echo
Index: gosmore.cpp
===================================================================
-u -L gosmore.cpp (revision 13753) -L gosmore.cpp (working copy) .svn/text-base/gosmore.cpp.svn-base gosmore.cpp
</code></pre>
<p>Some quotes were removed above, but basically you can see that <code>svn diff</code> will pass </p>
<pre><code>-u -L "<left-label>" -L "<right-label>" <left-file> <right-file>
</code></pre>
<p>to your batch file. The batch file you have is used to turn these commands into the format that WinMerge understands.</p>
<p>More details and examples on how this all works are provided in the <a href="http://svnbook.red-bean.com/en/1.7/svn.advanced.externaldifftools.html">svn book</a>.</p>
<p>To make your batch file the default for <code>svn diff</code>, you need to add the following line in the <code>[helpers]</code> section in your local subversion config file (<code>~/.subversion/config</code> in Linux, I'm not sure where the config file is located in Windows) (see this <a href="http://stackoverflow.com/questions/569270/change-default-svn-diffing-tool/569281#569281">earlier SO question</a>)</p>
<pre><code>diff-cmd=wm.bat
</code></pre>
|
Vim search for a pattern and if occurs delete to end of line <p>I am trying to search a text file for a certain pattern. If this pattern occurs then it means that the rest of the line is not needed and therefore can be deleted.</p>
<p>I have tried using the following commands, but so far have been unsuccessful.</p>
<pre><code>:%s/{pattern}/d$
:g/{pattern}/d$
</code></pre>
<p>If anyone has any suggestions they would be greatly appreciated</p>
| <p>would <code>:%s/{pattern}.*//</code> work?</p>
|
SSL error RemoteCertificateNameMismatch <p>I am using WCF for the client to access service. I am trying to access the endpoint with TLS (https). I have certificates with both private and public keys. </p>
<p>If I have the end point of the service to have the host name same as the certificate name ("Issued To"), then i am able to access the service from the client. </p>
<p>If the names of the "issued to" and end point domain name are different i get the error "Could not establish trust relationship for the SSL/TLS secure channel with authority". I have added the certificates to "Trusted Root", "Personal" and "trusted People". In my service i have used "PeerOrChainTrust".</p>
<p>Please let me know if anybody has any idea on this.</p>
<p>Thanks,
Jan</p>
| <p>In that case, you need to define the trust policy for the server on client side,</p>
<p>Call SetCertPolicy once before you make any call to the services.</p>
<pre><code>using System.Net;
using System.Security.Cryptography.X509Certificates;
public static void SetCertPolicy()
{
ServicePointManager.ServerCertificateValidationCallback += RemoteCertValidate;
}
private static bool RemoteCertValidate( object sender, X509Certificate cert, X509Chain chain,
SslPolicyErrors error )
{
// trust any cert!!!
return true;
}
</code></pre>
|
Flex FileReference.download - is it possible to open associated application <p>When using FileReference.download() to retrieve a file from a server, I'd like to give the user the option to open the associated application directly rather than having to save it to disk first.</p>
<p>Is this possible in Flex 3? And, if so, how is it done!</p>
<p>Thanks,
Mark</p>
<p>ps. I've tried doing URLLoader.load(URLRequest) also, but no dice...</p>
| <p>Nope, you can't do that unfortunately. My guess is that this is due to security restrictions.</p>
|
Choking experienced while using the TCP/IP Adapter for BizTalk Server 2006 <p>I am using the TCP/IP Adapter for BizTalk Server 2006 which was obtained from codeplex: <a href="http://www.codeplex.com/BTSTCPIP" rel="nofollow">http://www.codeplex.com/BTSTCPIP</a> <br>
Once the application was deployed in production, we started to experience choking in the performance of the application. The more the requests, the more the performance degradation. <br>
Sometimes, it happens that the receive ports become non-responsive and we have to forcefully restart the host instances to temporarily let the services respond again but we experience the same problems again and again.
I would like to ask if any of you have used the same adapter and have you ever experienced the similar issues? If yes, how can we overcome theses issues.</p>
<p>Thanks.</p>
| <p>We experienced similar behaviour but it was a deeper systemic problem. Is the issue affecting other appplications? Is your DBA seeing excessive blocking in the database? Are your SQL Jobs running and/or failing? Are your backups processing at a regular interval? </p>
<p>I documented the problem we had <a href="http://www.implementsivillage.net/PermaLink,guid,ac3f65fa-0051-48a0-bb8b-f9e741c1a0d1.aspx" rel="nofollow">Here</a>.</p>
|
How do I choose web hosting? <p>I have a couple of personal web-based projects in the pipeline, and am unable to chose how to host them.</p>
<p>I have questions in the area of domain names and actual file hosting (which I believe are separate topics, though many companies provide both).</p>
<h2>Domain Names</h2>
<p>I have a domain name registered with Freeparking.co.uk, but they don't offer the kinds of services I think I need. Can I just transfer the domain name to somewhere else? Apart from anything the only thing they do is to host a page with a full-page frame on it, which I configure a URL for. Basic URL hiding, but that means that people can't bookmark specific pages in my websites.</p>
<h2>Hosting</h2>
<p>I wish to host ASP.NET applications (plural) using SQL Server 2005. What are the steps to choosing a hosting environment, and how do I connect the domain name to the hosting environment?</p>
| <p>Domain names are best kept separate from the hosting. Decent domain registrars let you freely define <em>name severs</em>, which in then give the IP address for the domain. Typically (but not necessarily) these name servers are provided by the hosting company. So, the steps are:</p>
<ol>
<li>Choose the hosting provider (sorry, I have don't recommendations on ASP hosting providers).</li>
<li>Configure the name servers so that at least the A record of yourdomain.com points to the ip of your server (this is often automatically done by the hosting company).</li>
<li>Configure your domain name at the registrar so that it refers to the the above mentioned name servers.</li>
</ol>
<p>Also the domain name registrar can provide the name server stuff, or you can use for example <a href="http://www.everydns.com/" rel="nofollow">EveryDNS</a>.</p>
|
Float 2 divs in a parent div and arrange such divs one below another <p>I am creating a web page with 3 columns. The middle column is where all the content goes. The content I want to enter has to be in the format of left aligned image, followed by some text next to the image. And this flows throughout the column with different images and corresponding text. Since my layout is a div based layout, I have put a main div (page_content )for the column. Then the heading (h4) and below the heading I have entered another div. This div in turn contains individual divs that are nested with div (class photo) for image and div (class lat_art) for text. The HTML code and CSS code has been given below. My issue is that the first image and text comes up, but subsequent get lined up vertically below the first text i.e occupies only the 50% of the div and floats right, pushing its corresponding text below it in the same 50% space. Should I specify a height for individual divs, probably the image is bigger than the text. But if I do that wonât my code become static. I want it to be dynamic. Please help. </p>
<h2>HTML Code </h2>
<pre><code><div id="page_content">
<h4 class="center_cap">LATEST ARTISTS</h4>
<!--Div for the content begins here-->
<div>
<!--Individual div begins here-->
<div >
<div class="photo">
<img src="Images/guitar.jpg" alt="guitar"/>
</div>
<div class="lat_art">
<span class="artist">ROCK ON</span>
<p>
Good news to all the fans of 'Rock On'. Concerts all around the world.
</p>
</div>
</div>
<!--Individual div ends here-->
<!--Individual div begins here-->
<div >
<div class="photo">
<img src="Images/guitar.jpg" alt="guitar"/>
</div>
<div class="lat_art">
<span class="artist">ROCK ON</span>
<p>
Good news to all the fans of 'Rock On'. Concerts all around the world.
</p>
</div>
</div>
</div>
<!--Div for the content ends here-->
</div>
</code></pre>
<h2>Code from external Stylesheet </h2>
<pre><code>.photo{
width:48%;
float:left;
padding-left:2px;
}
.lat_art{
width:50%;
float:right;
}
</code></pre>
| <p>It is really hard to follow because you are describing very much every other word is 'div'. Anyhow you described that you have three columns but If I understood correctly it is just the middle one you are asking about.</p>
<p>You want this format:</p>
<ul>
<li>picture to the left</li>
<li>Right of the picture you have a header</li>
<li>Under the header you have a lot of text that wraps around the picture</li>
</ul>
<p>Correct?</p>
<p>You problem is that you float, but you don't clear the float. This means that <strong>all</strong> content under it will be align according to the picture. What you need is to set clear:both after you don't want the content to wrap anymore. </p>
<p>I wroted a little example and tested it. CSS is inline to make the example short and simple.</p>
<pre><code><div>
<img src="pircture.png" style="float:left;height:400px;width:400px" />
<h4>My header</h4>
<p> A little content</p>
<div style="clear:both"></div>
</div>
</code></pre>
|
mod_rewrite - old parameter name to new name <p>Hi all I need a bit of getting a redirect working in mod_rewrite.</p>
<p>I need to redirect the following</p>
<pre><code>http://mysite.com/dictionary/find?word=test
</code></pre>
<p>to</p>
<pre><code>http://mysite.com/dictionary/find?w=test
</code></pre>
<p>I'm sure the solution is trivial enough but my knowledge of mod_rewrite and regular expressions is quite limited and I haven't been able to work out. This is what I have attempted so far to no avail.</p>
<pre><code>RewriteCond %{QUERY_STRING} word= [NC]
RewriteRule ^/(.*)word=(\w+)/$ /w=$1 [L]
</code></pre>
<p>Any help would be much appreciated. Thanks.</p>
| <p>This should be sufficient for you...</p>
<p>RewriteRule (?|&)word=(\w+) $1w=$2</p>
<p>this will replace it even if combined with other parameters.Your attempt to only process the querystring is interesting, I have never used that and cannot answer to if it's possible.</p>
<p>As a sidenote, turn on:</p>
<p>RewriteLog "/var/log/apache2/rewrite.log"<br />
RewriteLogLevel 2</p>
<p>for more useful feedback.</p>
|
How to keep track of thread progress in Python without freezing the PyQt GUI? <h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| <p>If you want to use signals to indicate progress to the main thread then you should really be using PyQt's QThread class instead of the Thread class from Python's threading module.</p>
<p>A simple example which uses QThread, signals and slots can be found on the PyQt Wiki:</p>
<p><a href="https://wiki.python.org/moin/PyQt/Threading,_Signals_and_Slots" rel="nofollow">https://wiki.python.org/moin/PyQt/Threading,_Signals_and_Slots</a></p>
|
Passing Unmanaged pointers in C++/CLI <p>I'm creating a C++/CLI wrapper DLL that depends on numerous C++ static libraries. Some of the function calls expect unmanaged pointers to be passed in. How do i pass them properly?</p>
<p>Also, other functions expect a "this pointer" to be passed in as a void*. What's the right way to pass "this"?</p>
<p><strong>Here's my class definition...</strong></p>
<pre><code>public ref class RTPClient
{
public:
RTPClient();
~RTPClient();
bool Connect();
void Disconnect();
private:
CIsmaClient* mClient;
};
</code></pre>
<p><strong>Here's my usage where the pointers in question are used...</strong></p>
<pre><code>RTPClient::RTPClient():
mClient(NULL)
{
CIsmaClient::Create(&mClient, NULL, &AllocBuffer, &GetDataPointer, this);
}
</code></pre>
<p><strong>The usage of &mClient and "this" cause the following compiler errors...</strong>
1>.\VBLoadSimulatorDll.cpp(40) : error C2664: 'CIsmaClient::Create' : cannot convert parameter 1 from 'cli::interior_ptr' to 'CIsmaClient **'
1> with
1> [
1> Type=CIsmaClient *
1> ]</p>
<p>1>.\VBLoadSimulatorDll.cpp(40) : error C2664: 'CIsmaClient::Create' : cannot convert parameter 5 from 'VBLoadSimulator::RTPClient ^const ' to 'VOID *'</p>
| <p>If you are passing a pointer to a managed class then it is easy to convert the ^ reference into a pointer but you must pin the managed object so that the GC doesn't move it about in memory (thus invalidating the pointer)</p>
<p>This is simple with <a href="http://msdn.microsoft.com/en-us/library/1dz8byfh(VS.80).aspx">pin_ptr</a></p>
<p>However your code is doing two things which won't work</p>
<pre><code>RTPClient::RTPClient():
mClient(NULL)
{
CIsmaClient::Create(
&mClient, // 1
NULL,
&AllocBuffer,
&GetDataPointer,
this); //2
}
</code></pre>
<p>1) You are trying to take the address of something on the managed heap (the location of the <em>pointer</em> to the pointer mClient is on the managed heap.</p>
<p>As such it can move in memory, thus the compiler supplier interior pointer (whose value is maintained over GC operations). This needs to be <a href="http://www.codeproject.com/KB/mcpp/pinnedpointers.aspx">pinned</a> and this will only work if the Create function does not expect to use the pointer after it's scope has ended (if it passes it anywhere else to store it this will lead to bugs).</p>
<p>2) You are passing a <a href="http://en.wikipedia.org/wiki/C%2B%2B/CLI">handle</a> (the funny hat symbol) rather than a pointer. (Read the wikipedia section on these they are a good overview) This is not (and cannot) be understood by the unmanaged code.</p>
<p>The only reason I can think of for this parameter in this context is as an explicit state variable passed to subsequent function callbacks (correct me if I'm wrong). 'this' in this context is NEVER going to work properly since this can move about in memory once the pin_ptr goes out of scope.</p>
<p>With that in mind here is a (partially) corrected implementation making it clear what can and can't be fixed.</p>
<pre><code>RTPClient::RTPClient():
mClient(NULL)
{
// make it clear you want the address of the instance variable
pin_ptr<CIsmaClient*> pinnedClient = &this->mClient;
CIsmaClient::Create(
pinnedClient, // fixed
NULL,
&AllocBuffer,
&GetDataPointer,
x /* pass something else in */); //2
}
</code></pre>
<p>If you supply more information on what the last parameter is used for I can suggest possible solutions</p>
|
External JS and browser <p>I have an external JS file that I include in my ASPX page. Whenever I make changes to the JS, I need to close the browser and reopen it to see the changes. I have tried Ctrl F5 to refresh the cached JS copy but that doesn't work in IE.</p>
<p>Is there some way to not restart the browser to see the updated changes?</p>
| <p>As others suggest, I would switch to Firefox for developing and keep IE only for testing. </p>
<p>If you want to keep developing on IE try the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=18359" rel="nofollow">Internet Explorer Developer Toolbar</a>. It offers some of the functionality of Firebug and you will have quick access to options for disabling the cache or clearing the cache for a specific domain, solving your caching problems.</p>
<p><img src="http://lh5.ggpht.com/_EuP0VgCBcqk/SZ7OqlxsyuI/AAAAAAAACV0/4cVa_syswwQ/s800/capturaIEDevToolbar.png" alt="Cache menu"></p>
|
Where is the best place to store global information in a WPF application? <p>I'm a former PHP developer now doing WPF/C# applications, and am having trouble understanding the best way to access global variables and how UserControls access the main Window, etc.</p>
<p>In the constructor of my Window1 class I load UserControls into an internal Dictionary, then dynamically load these into a DockPanel at runtime, which works great and keeps the internal state of each one.</p>
<pre><code>public Window1()
{
InitializeComponent();
List<string> userControlKeys = new List<string>();
userControlKeys.Add("Welcome");
userControlKeys.Add("News");
Type type = this.GetType();
Assembly assembly = type.Assembly;
foreach (string userControlKey in userControlKeys)
{
string userControlFullName = String.Format("{0}.Pages.{1}", type.Namespace, userControlKey);
UserControl userControl = (UserControl)assembly.CreateInstance(userControlFullName);
_userControls.Add(userControlKey, userControl);
}
//set the default page
btnWelcome.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
</code></pre>
<p><strong>Question</strong>: from within a UserControl how do I access my Dictionary in Window1?</p>
<ul>
<li>I can access the static Class Window1 but not its instantiation hence making a Getter for it gets me no further.</li>
<li>there are global attributes in C# but I can imagine there is a better, more OOP way</li>
<li>it just seems like I am looking at this in terms of web site / session variables, and thus missing a key concept of desktop development where "state is everywhere"</li>
</ul>
<p>Hope someone can shed some light on this.</p>
| <p>Try using a <a href="http://www.yoda.arachsys.com/csharp/singleton.html" rel="nofollow">singleton</a> object. The idea is to exploit the mechanics of static objects to achieve "global" variables but which are contained in a object for sanity management.</p>
|
Strange ListView selection behavior on Android <p>Got an activity that extends <code>ListActivity</code>.
The list is backed up by a custom adapter that extends <code>BaseAdapter</code>.</p>
<pre><code>getListView().setFocusable(true);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
</code></pre>
<p>I do a simple <code>(getSelectedItemPosition() == ListView.INVALID_POSITION)</code> check in <code>onPrepareOptionsMenu()</code> to disable the items that require an item to be selected.</p>
<p>Now, what I do after launching the activity (the action takes place
under emulator, ver.1.1) an what it looks like:</p>
<ol>
<li>Hit menu - the menu items are disabled - OK</li>
<li>Select an item with mouse wheel and hit menu - the items get enabled
-OK</li>
<li>Click anywhere outside the list, repeat 2). The items don't get
enabled - WTF?</li>
<li>Start from scratch, select an item hitting Del and moving mouse. The
result is the same as for 3.</li>
</ol>
<p>Why do these (3, 4) things keep happening to me? :)
TIA. </p>
| <p>Relying on the <code>selectedItemPosition</code> on a <code>ListView</code> can be a dangerous approach. In my experience if the List loses focus (by clicking something else) the <code>selectedItemPosition</code> gets set to <code>INVALID_POSITION</code>.</p>
<p>Basically if your item doesn't have that orange 'highlighted' look to it, count on the <code>selectedItemPosition</code> being null.</p>
<p>As an alternative you may want to remember the selected item by overriding the <code>onItemClick</code> and <code>onItemSelection</code> methods and saving the selected item's index, then use that to control your menu option availability.</p>
|
How to hide a WCF service from the public? <p>What measures can you take to 'hide' a WCF service from the public?</p>
<p>i.e. even if they know the URL, you don't expose the methods etc.</p>
| <p>I don't think you can if they have any idea what the specs for your contract are. If they don't, then they're just randomly guessing (as long as you don't expose metadata). Your best bet is to have an authentication function in your contract which must be called first and is necessary for subsequent calls to be allowed.</p>
|
What's the best way to communicate between view controllers? <p>Being new to objective-c, cocoa, and iPhone dev in general, I have a strong desire to get the most out of the language and the frameworks.</p>
<p>One of the resources I'm using is Stanford's CS193P class notes that they have left on the web. It includes lecture notes, assignments and sample code, and since the course was given by Apple dev's, I definitely consider it to be "from the horse's mouth".</p>
<p>Class Website:<br />
<a href="http://www.stanford.edu/class/cs193p/cgi-bin/index.php">http://www.stanford.edu/class/cs193p/cgi-bin/index.php</a></p>
<p>Lecture 08 is related to an assignment to build a UINavigationController based app that has multiple UIViewControllers pushed onto the UINavigationController stack. That's how the UINavigationController works. That's logical. However, there are some stern warnings in the slide about communicating between your UIViewControllers.</p>
<p>I'm going to quote from this serious of slides:<br />
<a href="http://cs193p.stanford.edu/downloads/08-NavigationTabBarControllers.pdf">http://cs193p.stanford.edu/downloads/08-NavigationTabBarControllers.pdf</a></p>
<p>Page 16/51:</p>
<blockquote>
<h1>How Not To Share Data</h1>
<ul>
<li>Global Variables or singletons
<ul>
<li>This includes your <strong>application delegate</strong></li>
</ul></li>
<li>Direct dependencies make your code less reusable
<ul>
<li>And more difficult to debug & test</li>
</ul></li>
</ul>
</blockquote>
<p>Ok. I'm down with that. Don't blindly toss all your methods that will be used for communicating between the viewcontroller into your app delegate and reference the viewcontroller instances in the app delegate methods. Fair 'nuff.</p>
<p>A bit further on, we get this slide telling us what we <em>should</em> do.</p>
<p>Page 18/51:</p>
<blockquote>
<h1>Best Practices for Data Flow</h1>
<ul>
<li>Figure out <strong>exactly</strong> what needs to be communicated</li>
<li><strong>Define input parameters</strong> for your view controller</li>
<li>For communicating back up the hierarchy, <strong>use loose coupling</strong>
<ul>
<li>Define a generic interface for observers (like delegation)</li>
</ul></li>
</ul>
</blockquote>
<p>This slide is then followed by what appears to be a place holder slide where the lecturer then apparently demonstrates the best practices using an example with the UIImagePickerController. I wish the videos were available! :(</p>
<p>Ok, so... I'm afraid my objc-fu is not so strong. I'm also a bit confused by the final line in the above quote. I've been doing my fair share of googling about this and I found what appears to be a decent article talking about the various methods of Observing/Notification techniques:<br />
<a href="http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html">http://cocoawithlove.com/2008/06/five-approaches-to-listening-observing.html</a></p>
<p>Method #5 even indicates delegates as an method! Except.... objects can only set one delegate at a time. So when I have multiple viewcontroller communication, what am I to do?</p>
<p>Ok, that's the set up gang. I know I can easily do my communication methods in the app delegate by reference's the multiple viewcontroller instances in my appdelegate but I want to do this sort of thing the <em>right</em> way.</p>
<p>Please help me "do the right thing" by answering the following questions:</p>
<ol>
<li>When I am trying to push a new viewcontroller on the UINavigationController stack, <strong>who</strong> should be doing this push. <strong>Which</strong> class/file in my code is the correct place?</li>
<li>When I want to affect some piece of data (value of an iVar) in one of my UIViewControllers when I am in a <strong>different</strong> UIViewController, what is the "right" way to do this?</li>
<li>Give that we can only have one delegate set at a time in an object, what would the implementation look like for when the lecturer says <em>"Define a generic interface for observers (like delegation)"</em>. A pseudocode example would be awfully helpful here if possible.</li>
</ol>
| <p>These are good questions, and its great to see that you're doing this research and seem concerned with learning how to "do it right" instead of just hacking it together.</p>
<p><strong><em>First</em></strong>, I agree with the previous answers which focus on the importance of putting data in model objects when appropriate (per the MVC design pattern). Usually you want to avoid putting state information inside a controller, unless it's strictly "presentation" data.</p>
<p><strong><em>Second</em></strong>, see page 10 of the Stanford presentation for an example of how to programmatically push a controller onto the navigation controller. For an example of how to do this "visually" using Interface Builder, take a look at <a href="http://www.invasivecode.com/iNVASIVE_CODE/Blog/Entries/2009/1/14_UINavigationController.html">this tutorial</a>.</p>
<p><strong><em>Third</em></strong>, and perhaps most importantly, note that the "best practices" mentioned in the Stanford presentation are much easier to understand if you think about them in the context of the "dependency injection" design pattern. In a nutshell, this means that your controller shouldn't "look up" the objects it needs to do its job (e.g., reference a global variable). Instead, you should always "inject" those dependencies into the controller (i.e., pass in the objects it needs via methods).</p>
<p>If you follow the dependency injection pattern, your controller will be modular and reusable. And if you think about where the Stanford presenters are coming from (i.e., as Apple employees their job is to build classes that can easily be reused), reusability and modularity are high priorities. All of the best practices they mention for sharing data are part of dependency injection.</p>
<p>That's the gist of my response. I'll include an example of using the dependency injection pattern with a controller below in case it's helpful.</p>
<p><strong>Example of Using Dependency Injection with a View Controller</strong></p>
<p>Let's say you're building a screen in which several books are listed. The user can pick books he/she wants to buy, and then tap a "checkout" button to go to the checkout screen. </p>
<p>To build this, you might create a BookPickerViewController class that controlls and displays the GUI/view objects. Where will it get all the book data? Let's say it depends on a BookWarehouse object for that. So now your controller is basically brokering data between a model object (BookWarehouse) and the GUI/view objects. In other words, BookPickerViewController DEPENDS on the BookWarehouse object.</p>
<p>Don't do this:</p>
<pre><code>@implementation BookPickerViewController
-(void) doSomething {
// I need to do something with the BookWarehouse so I'm going to look it up
// using the BookWarehouse class method (comparable to a global variable)
BookWarehouse *warehouse = [BookWarehouse getSingleton];
...
}
</code></pre>
<p>Instead, the dependencies should be injected like this:</p>
<pre><code>@implementation BookPickerViewController
-(void) initWithWarehouse: (BookWarehouse*)warehouse {
// myBookWarehouse is an instance variable
myBookWarehouse = warehouse;
[myBookWarehouse retain];
}
-(void) doSomething {
// I need to do something with the BookWarehouse object which was
// injected for me
[myBookWarehouse listBooks];
...
}
</code></pre>
<p>When the Apple guys are talking about using the delegation pattern to "communicate back up the hierarchy," they're still talking about dependency injection. In this example, what should the BookPickerViewController do once the user has picked his/her books and is ready to check out? Well, that's not really its job. It should DELEGATE that work to some other object, which means that it DEPENDS on another object. So we might modify our BookPickerViewController init method as follows:</p>
<pre><code>@implementation BookPickerViewController
-(void) initWithWarehouse: (BookWarehouse*)warehouse
andCheckoutController:(CheckoutController*)checkoutController
{
myBookWarehouse = warehouse;
myCheckoutController = checkoutController;
}
-(void) handleCheckout {
// We've collected the user's book picks in a "bookPicks" variable
[myCheckoutController handleCheckout: bookPicks];
...
}
</code></pre>
<p>The net result of all this is that you can give me your BookPickerViewController class (and related GUI/view objects) and I can easily use it in my own application, assuming BookWarehouse and CheckoutController are generic interfaces (i.e., protocols) that I can implement:</p>
<pre><code>@interface MyBookWarehouse : NSObject <BookWarehouse> { ... } @end
@implementation MyBookWarehouse { ... } @end
@interface MyCheckoutController : NSObject <CheckoutController> { ... } @end
@implementation MyCheckoutController { ... } @end
...
-(void) applicationDidFinishLoading {
MyBookWarehouse *myWarehouse = [[MyBookWarehouse alloc]init];
MyCheckoutController *myCheckout = [[MyCheckoutController alloc]init];
BookPickerViewController *bookPicker = [[BookPickerViewController alloc]
initWithWarehouse:myWarehouse
andCheckoutController:myCheckout];
...
[window addSubview:[bookPicker view]];
[window makeKeyAndVisible];
}
</code></pre>
<p>Finally, not only is your BookPickerController reusable but also easier to test. </p>
<pre><code>-(void) testBookPickerController {
MockBookWarehouse *myWarehouse = [[MockBookWarehouse alloc]init];
MockCheckoutController *myCheckout = [[MockCheckoutController alloc]init];
BookPickerViewController *bookPicker = [[BookPickerViewController alloc] initWithWarehouse:myWarehouse andCheckoutController:myCheckout];
...
[bookPicker handleCheckout];
// Do stuff to verify that BookPickerViewController correctly called
// MockCheckoutController's handleCheckout: method and passed it a valid
// list of books
...
}
</code></pre>
|
What causes Visual Basic Run-time error -2147319765 (8002802b) in Excel when an ActiveX control has been instanced? <p>I have created an ActiveX control using C++. I use Visual Basic code to instance the control in an Excel worksheet. I can only run the VB script once, subsequent runs cause the following runtime error when attempting to access the 'ActiveSheet' variable:</p>
<pre><code>Microsoft Visual Basic
Run-time error '-2147319765 (8002802b)':
Automation error
Element not found
</code></pre>
<p>I am trying to work out what causes this error and how I can fix it?</p>
<p>As an experiment I tried creating a simple ActiveX control generated by Visual Studio wizards (in both VS 2005 & 2008). I didn't add or modify any code in this test case. The simple test case still causes this error.</p>
<p>Other ActiveX controls in the system don't cause this error (eg I tried instancing 'Bitmap Image') from VB code.</p>
<p>This is the VB code (a macro that I recorded, but hand-coded VB has the same issue):</p>
<pre><code>Sub Macro1()
ActiveSheet.OLEObjects.Add(ClassType:="test.test_control.1" _
, Link:=False, DisplayAsIcon:=False).Select
End Sub
</code></pre>
<p>Can anyone give me an answer on this? Alternatively any pointers to resources that may help will be appreciated.</p>
<p>Thanks</p>
| <p>You have created an "unqualified" reference to an Excel application that you cannot release by utilizing a Global variable intended for VBA that should not be used in VB 6.0.</p>
<p>This is an unfortunate side-effect of using VB 6.0, but it is the only problem I know of using VB6, and it is easily fixed.</p>
<p>The problem in your case stems from using the 'ActiveSheet' global variable. When using VBA, this is fine, but when using VB 6.0, you must avoid this or else you create an Excel application that you cannot release. This approach will run fine the first time, but will cause all kinds of undefined behavior the <strong>second</strong> time your routine runs.</p>
<p>In your example, the code should do something like this:</p>
<pre><code>Sub Macro1()
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.ActiveSheet.OLEObjects.Add(ClassType:="test.test_control.1" _
, Link:=False, DisplayAsIcon:=False).Select
' Then when done:
xlApp.Quit()
xlApp = Nothing
End Sub
</code></pre>
<p>For a detailed discussion about how to handle this in general, see: </p>
<p>VB 6.0 Tutorial - Finding and Repairing Unqualified References
(<a href="http://www.xtremevbtalk.com/showthread.php?p=900556#post900556" rel="nofollow">http://www.xtremevbtalk.com/showthread.php?p=900556#post900556</a>)</p>
<p>For Microsoft documentation on this issue see:</p>
<p>Excel Automation Fails Second Time Code Runs (MSKB 178510)
(<a href="http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q178/5/10.asp" rel="nofollow">http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/q178/5/10.asp</a>)</p>
<p>Error or Unexpected Behavior with Office Automation When You Use Early Binding in Visual Basic (MSKB 319832)
(<a href="http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q319832&" rel="nofollow">http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q319832&</a>)</p>
<p><strong>Edit</strong>: <em>Note that using html 'a' tags were not working with these links for some reason. Someone might need to look into the parser?</em></p>
|
How to calculate distance from a GPX file? <p>I have a <a href="http://en.wikipedia.org/wiki/GPX_%28data_transfer%29">GPX file</a> with a GPS track. Now I want to calculate the distance I covered with this track.</p>
<p>What's the best way to calculate this?</p>
| <p>The traditional way of calculating the distance between two points (each pair of waypoints in your GPX file) is with the Haversine formula.</p>
<p>I have a SQL Server function that implements the algorithm. This should be easy to translate into other languages:</p>
<pre class="lang-sql prettyprint-override"><code>create function dbo.udf_Haversine(@lat1 float, @long1 float,
@lat2 float, @long2 float) returns float begin
declare @dlon float, @dlat float, @rlat1 float,
@rlat2 float, @rlong1 float, @rlong2 float,
@a float, @c float, @R float, @d float, @DtoR float
select @DtoR = 0.017453293
select @R = 3959 -- Earth radius
select
@rlat1 = @lat1 * @DtoR,
@rlong1 = @long1 * @DtoR,
@rlat2 = @lat2 * @DtoR,
@rlong2 = @long2 * @DtoR
select
@dlon = @rlong1 - @rlong2,
@dlat = @rlat1 - @rlat2
select @a = power(sin(@dlat/2), 2) + cos(@rlat1) *
cos(@rlat2) * power(sin(@dlon/2), 2)
select @c = 2 * atn2(sqrt(@a), sqrt(1-@a))
select @d = @R * @c
return @d
end
</code></pre>
<p>This returns the distance in Miles. For kilometers, replace the earth radius with it's km equivalent.</p>
<p><a href="http://mathforum.org/library/drmath/view/51879.html" rel="nofollow">Here</a> is a more in-depth explanation.</p>
<p>Edit: This function is fast enough and accurate enough for doing radius searches with a ZIP code database. It has been doing a great job on <a href="http://kofc.org/un/findCouncil/index.action" rel="nofollow">this site</a> for years (but it no longer does, as the link is broken now).</p>
|
Convert static files into MySQL entries <p>I am converting about 4000 text files that contain HTML into MySQL database entries. Seems like an easy way to do this would be to add a couple lines to the HTML to make them appear as XML files, then XSLT the XML into MySQL INSERT statements. (Building a CSV would also work, but less optimal IMHO). I've tried doing this but am having little luck getting my XSL to play nice. </p>
<p>I'm on a Windoze box but can SSH into my webhost and run PHP, maybe Perl. Would love to automate this as much as possible. I can build a list of the files and feed that into a script easily enough.</p>
<p>Filename pattern: ab12345.html (numeric portion varies from 3-6 digits)</p>
<p>Filename content sample--this is the entirety of the file, there are not HTML footers/headers:</p>
<pre><code><div class="abEntry"><a name="top"><img width="1" height="1" src="images/common/blank.gif"/></a><div id="abEntryTitle"><div id="abEntryTitleText">What does error note "90210 Cannot Do This Thing" mean?</div></div>
<div class="abEntryParagraph">This error means your McWhopper drive is frazzled. Read me the number off the modem--thats the little boxy thing attached to the big boxy thing--thanks.</div>
<div class="abEntryDocumentNumber">ab90210</div>
</code></pre>
<p>MySQL columns and how I'd like them to map back to the content above</p>
<pre><code>EntryID = auto increment
title = contents of #abEntryTitleText
content = contents of #abEntryParagraph
lastupdated = curdate
related = "1"
visible = "1"
sortorder = "0"
userid = "1"
views = "0"
posvotes = "1"
negvotes = "0"
score = null
emailed = null
detectrelated = "1"
metakeywords = null
metadescription = contents of #abEntryDocumentNumber
startdate = curdate
enableexpiry = "0"
expirydate = null
featured = "0"
workflowstatus = "auto_approved"
</code></pre>
<p>XSL that I've tried:</p>
<pre><code><xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform ">
<xsl:output method="html" indent="no"/>
<xsl:template match="/"><xsl:apply-templates/></xsl:template>
<xsl:template match="content">
<xsl:text>INSERT INTO questions (approved, title, description, publishDate) VALUES </xsl:text><xsl:text>(1, </xsl:text><xsl:value-of select="id(abEntryTitleText)"/><xsl:text>, </xsl:text>
<xsl:copy-of select="node()|@*"/>
<xsl:text>, </xsl:text>TODAY<xsl:text>,1, 1)</xsl:text>
</xsl:template>
</xsl:transform>
</code></pre>
| <p>I'm not familiar with xsl, so I would tackle this problem using <a href="http://php.net/dom" rel="nofollow">php's DOM</a>.
IIRC it could parse html without being proper xml.</p>
<p>Tutortial at <a href="http://www.phpro.org/examples/Parse-HTML-With-PHP-And-DOM.html" rel="nofollow">www.phpro.org</a></p>
|
Why does my DBI program complain about 'Undefined subroutine &DBD::Pg::db::_login'? <p>I am trying to use PostgreSQL database for storing Apache's session information, but I can't get it to work. It is failing with the following error:</p>
<pre><code> Undefined subroutine &DBD::Pg::db::_login
</code></pre>
<p>It seems that MySQL users have run into the same problem in DBD::MySQL::db. I have the latest CPAN version of both DBI and DBD::Pg. It doesn't seem that the <code>_login</code> function is there in the module. Any ideas how to get around this problem? I appreciate your help!</p>
<p>Thanks</p>
| <p>Browsing back through the history, there has never been a Perl method named <code>_login</code> defined in the package <code>DBD::Pg::db</code> (which is defined in Pg.pm), and the invocation is explicitly <code>DBD::Pg::db::_login()</code>.</p>
<p>This is a guess, but I think that <code>_login</code> is a C function that's bound through XS, and that's why you can't find its source in the module. That would indicate some problem with the Postgres library that it's trying to use.</p>
|
IIS7 Authentication on Server 2008 <p>I recently upgraded my Server 2000 running IIS6 to Server 2008 running IIS7. Servers are stand alone, no A/D. I have a website designed with Frontpage 2003 running Server Extensions 2003 which I also migrated to my new Server 2008. Site on old server required username and password which I set up to allow access by disabling annonomous access. How do I do the same thing with IIS7 on Server 2008? I prefer to use Windows Authentication.</p>
| <p>In the site's Authentication settings, disable anonymous and enable integrated windows authentication.</p>
|
Oracle Application Server; What role in an organization typically supports the middle tier? <p><strong>In medium to large organizations what team or group typically support middle tier components like Oracle Application Servers?</strong> </p>
<p>(Unix Team, DBA Team, Or Application Development/Support Team)</p>
<p>In a client server application design the delineation of ownership between the server and the client is very clear. In the client server case the Unix Administrators manage the servers and the development support team manage and support the clients. (and the DBA's support/manage the database)</p>
<p>Recently at our shop the lines have become blurred; the introduction of an Oracle application Server (OAS) has popped up; </p>
<p>OAS seems to require a very unique set of skills but also show some similarity to the client server skills. (part Unix Admin, Part Dba, Part Application Developer/Client Support)</p>
<p><strong>What have others done when confronted with this kind of challenge......??</strong> </p>
<p><strong>Does a completely new team form that exclusively supports the Middle Tier??</strong></p>
<p>Our It Group has 3 Unix Admins; 3 Application Support staff; 3 Dba's to give the perspective of the size of the teams....</p>
| <p>For large organizations, you generally eventually get to a point where there are dedicated teams to manage the middle tier web servers and application servers. </p>
<p>The problem for smaller organizations generally comes that when you first deploy the app servers, there may not be enough admin work to justify a separate person in that role, at which point you have to cobble together time from other teams. It's not particularly unusual for DBAs to manage the app server (particularly for Oracle DBAs managing Oracle Application Servers). It's also not particularly unusual for the Unix admins to manage the app server. Either way, though, some of the work will inevitably benefit from input from the other team.</p>
|
Dashboard Cross-domain AJAX with jquery <p>Hey everyone, I'm working on a widget for Apple's Dashboard and I've run into a problem while trying to get data from my server using jquery's ajax function. Here's my javascript code:</p>
<pre><code>$.getJSON("http://example.com/getData.php?act=data",function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
</code></pre>
<p>And the server responds with this json:</p>
<pre><code>{"message":"Hello World","version":"1.0"}
</code></pre>
<p>For some reason though, when I run this the fields on the widget don't change. From debugging, I've learned that the widget doesn't even make the request to the server, so it makes me think that Apple has some kind of external URL block in place. I know this can't be true though, because many widgets phone home to check for updates.</p>
<p>Does anyone have any ideas as to what could be wrong?</p>
<p>EDIT: Also, this code works perfectly fine in Safari.</p>
<p><hr />
As requested by Luca, here's the PHP and Javascript code that's running right now:</p>
<p>PHP:</p>
<pre><code>echo $_GET["callback"].'({"message":"Hello World","version":"1.0"});';
</code></pre>
<p>Javascript:</p>
<pre><code>function showBack(event)
{
var front = document.getElementById("front");
var back = document.getElementById("back");
if (window.widget) {
widget.prepareForTransition("ToBack");
}
front.style.display = "none";
back.style.display = "block";
stopTime();
if (window.widget) {
setTimeout('widget.performTransition();', 0);
}
$.getJSON('http://nakedsteve.com/data/the-button.php?callback=?',function(json) {
$("#devMessage").html(json.message)
if(json.version != version) {
$("#latestVersion").css("color","red")
}
$("#latestVersion").html(json.version)
})
}
</code></pre>
| <p>In Dashcode click <strong>Widget Attributes</strong> then <strong>Allow Network Access</strong> make sure that option is checked. I've built something that simply refused to work, and this was the solution.</p>
|
Throttling login attempts <p>(This is in principal a language-agnostic question, though in my case I am using ASP.NET 3.5)</p>
<p>I am using the standard ASP.NET <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.aspx">login control</a> and would like to implement the following failed login attempt throttling logic.</p>
<ul>
<li>Handle the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.loginerror.aspx"><code>OnLoginError</code></a> event and maintain, in <a href="http://msdn.microsoft.com/en-us/library/ms972429.aspx">Session</a>, a count of failed login attempts</li>
<li>When this count gets to <em>[some configurable value]</em> block further login attempts from the originating IP address or for that user / those users for 1 hour</li>
</ul>
<p>Does this sound like a sensible approach? Am I missing an obvious means by which such checks could be bypassed?</p>
<p>Note: ASP.NET Session is associated with the user's browser using a cookie</p>
<h2>Edit</h2>
<p>This is for an administration site that is only going to be used from the UK and India</p>
| <p>The last thing you want to do is storing all unsuccessful login attempts in a database, that'll work well enough but also makes it extremely trivial for DDOS attacks to bring your database server down.</p>
<p>You are probably using some type of server-side cache on your webserver, memcached or similar. Those are perfect systems to use for keeping track of failed attempts by IP address and/or username. If a certain threshold for failed login attempts is exceeded you can then decide to deactivate the account in the database, but you'll be saving a bunch of reads and writes to your persisted storage for the failed login counters that you don't need to persist.</p>
<p>If you're trying to stop people from brute-forcing authentication, a throttling system like Gumbo suggested probably works best. It will make brute-force attacks uninteresting to the attacker while minimizing impact for legitimate users under normal circumstances or even while an attack is going on. I'd suggest just counting unsuccessful attempts by IP in memcached or similar, and if you ever become the target of an extremely distributed brute-force attack, you can always elect to also start keeping track of attempts per username, assuming that the attackers are actually trying the same username often. As long as the attempt is not extremely distributed, as in still coming from a countable amount of IP addresses, the initial by-IP code should keep attackers out pretty adequately.</p>
<p>The key to preventing issues with visitors from countries with a limited number of IP addresses is to not make your thresholds too strict; if you don't receive multiple attempts in a couple of seconds, you probably don't have much to worry about re. scripted brute-forcing. If you're more concerned with people trying to unravel other user's passwords manually, you can set wider boundaries for subsequent failed login attempts by username.</p>
<p>One other suggestion, that doesn't answer your question but is somewhat related, is to enforce a certain level of password security on your end-users. I wouldn't go overboard with requiring a mixed-case, at least x characters, non-dictionary, etc. etc. password, because you don't want to bug people to much when they haven't even signed up yet, but simply stopping people from using their username as their password should go a very long way to protect your service and users against the most unsophisticated â guess why they call them brute-force ;) â of attacks.</p>
|
How can I deploy my WCF Service without IIS? <p>I'm doing some quick Java-.NET interop and have decided on POX with WCF. However, I don't want to -- nor have access to -- deploy to IIS. </p>
<p>Would just wrapping it up as a .NET Service be the way to go? (I've built my fair share of Windows services in my years.)</p>
<p>Are there any good samples around of this? </p>
<p>What handles the HTTP if I'm not using IIS?</p>
<p>I'm open to any suggestion that will allow me to create a simple http-based, xml contract.</p>
<p>Also, it's important to note that this will only be exposed to the internal server farm, so security and all that is pretty minimal with this.</p>
<p>(Searching Google isn't delivering very good results because of all the Blog spam.)</p>
| <p>You can deploy it as Windows service and expose an http endpoint. Check the following url.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms751414.aspx">http://msdn.microsoft.com/en-us/library/ms751414.aspx</a> </p>
|
Are Java Applets unable to communicate with javascript within Firefox on Mac OS? <p>I have a java applet running in a browser that is calling some javascript functions and expecting a result from theses functions. This is working with the following configurations :</p>
<ul>
<li>Internet Explorer</li>
<li>FireFox / Windows</li>
<li>Safari / Mac</li>
</ul>
<p>BUT It's not working with Firefox on MAC OS</p>
<p>The source of the problem seems to be the win.eval calls that always return null.
I tested this with Firefox 3.0.6 on a Mac OS X 10.4.11 </p>
<p>A bit of code : </p>
<pre><code>JSObject win = (JSObject) JSObject.getWindow(this);
Object exp = win.eval("testfunc()");
System.out.println("exp = " + exp.toString());
</code></pre>
<p>This triggers a java.lang.NullPointerException (exp.toString()) statement).
The testfunc javascript function just returns true.</p>
<p>I tried with win.call and got the same result.</p>
<p>My applet tag includes the mayscript and scriptable attributes.</p>
<p><hr /></p>
<p>I found the answer thanks to Tristan. Testing his solution I created a really simple test that could work and worked my way to find the culprit. I was sure I did my tests with an empty testfunc() that just returned true, but I probably didn't because in that case it DOES work.
The real problem here was that the function called a public method of the applet. Liveconnect doesn't seem to be able to handle that case in Firefox Mac.</p>
<p>Let me give you an example :</p>
<p>Java class : </p>
<pre><code>public class MyApplet extends Applet {
public int getMyValue() {
return 5;
}
public void somefunction() {
JSObject win = (JSObject) JSObject.getWindow(this);
Object exp = win.eval("jsfunc()");
System.out.println("exp = " + exp.toString());
}
}
</code></pre>
<p>And the javascript code :</p>
<pre><code>function jsfunc() {
var myApplet = document.getElementById("applet_id");
return myApplet.getMyValue() + 5;
}
</code></pre>
<p>exp will be null in somefunction BECAUSE jsfunc calls the getMyValue() method of the applet. If you remove all calls to properties of the applet you're cool.<br />
To solve my problem I decided to give all the values of the applet that I neeeded as parameters of my javascript function and I'm good now.<br />
That may not be the case always, if the javascript changes the state of the applet ...I was lucky :)</p>
| <p>I haven't used the applet api in a while but if i recall correctly in order to allow an Applet to cann JS code you should enable the attribute mayscript in your applet tag or a param mayscript in the object tag notation.</p>
<p>For communication in the other way JS to Applet you should also use the scriptable attribute or parameter, for example:</p>
<pre><code><applet code="..." mayscript="true" />
</code></pre>
<p>This allows your applet to use script functions.</p>
<pre><code><applet code="..." scriptable="true" />
</code></pre>
|
PowerShell - Most Compact way of "Delete all files from this folder except one" <p>What is the most compact way of deleting all files from a folder <em>except</em> one file in a PowerShell script. I doesn't matter at all which file is kept, just as long as one is kept.</p>
<p>I'm using the PowerShell 2 CTP.</p>
<p><strong>UPDATE:</strong><br />
An amalgamation of all the answers so far... </p>
<pre><code>$fp = "\\SomeServer\SomeShare\SomeFolder"
gci $fp |where {$_.mode -notmatch "d"} |sort creationtime -desc |select -last ((@(gci $fp)).Length - 1) |del
</code></pre>
<p>Anybody see any issues with using this? How about the -notmatch part? </p>
| <p>In PS V2 we added -SKIP to Select so you could do:</p>
<p>dir | where {$_.mode -notmatch "d"} |select -skip 1 |del</p>
|
Recording sound as WAV on iphone <p>I am making an iPhone recording app that needs to submit the sound file as a .wav to an external server.</p>
<p>Starting from the SpeakHere example, I am able to record sound as a file, but only as .caf</p>
<p>Does anyone know how to record it as a wav instead? Or how to convert from .caf to .wav on the iphone? (The conversion must happen on the phone)</p>
<p>EDIT:</p>
<p>I'm wondering if anything can be done with using kAudioFileWAVEType instead of kAudioFileCAFType in AudioFileCreateWithURL</p>
| <p>Yup, the key is kAudioFileWAVEType</p>
<pre><code>AudioFileCreateWithURL (
audioFileURL,
kAudioFileWAVEType,
&audioFormat,
kAudioFileFlags_EraseFile,
&audioFileID
);
</code></pre>
<p>Changing to WAVE from CAF in the SpeakHere example causes the recording to be as wav. I also edit the same thing in the playback class, and changed the filename to be Recording.wav</p>
|
Running commands over ssh with Java <p>Scenerio: I'd like to run commands on remote machines from a Java program over ssh (I am using OpenSSH on my development machine). I'd also like to make the ssh connection by passing the password rather than setting up keys as I would with 'expect'.<br />
Problem: When trying to do the 'expect' like password login the Process that is created with ProcessBuilder cannot seem to see the password prompt. When running regular non-ssh commands (e.g 'ls') I can get the streams and interact with them just fine. I am combining standard error and standard out into one stream with <code>redirectErrorStream(true);</code> so I am not missing it in standard error...When I run ssh with the '-v' option, I see all of the logging in the stream but I do not see the prompt. This is my first time trying to use ProcessBuilder for something like this. I know it would be easier to use Python, Perl or good ol' expect but my boss wants to utilize what we are trying to get back (remote log files and running scripts) within an existing Java program so I am kind of stuck.</p>
<p>Thanks in advance for the help!</p>
| <p>The prompt might only be shown when <code>ssh</code> is connected to a TTY, which it isn't in the case of Java.</p>
<p>There's probably a way to supply the password on the command-line in your <code>ssh</code> application. That will be the way to get past the prompt.</p>
<p>Alternately, consider connecting directly to the host server from native Java code rather than running an external application. There's <a href="http://www.google.com/search?q=java+ssh+library">a million libraries</a> that will do this.</p>
|
Most robust Equals implementation for custom classes for value equality in C# <p>Say I have a Point2 class, and I want to implement the following Equals:</p>
<pre><code>public override bool Equals ( object obj )
public bool Equals ( Point2 obj )
</code></pre>
<p>This is from the Effective C# 3 book:</p>
<pre><code>public override bool Equals ( object obj )
{
// STEP 1: Check for null
if ( obj == null )
{
return false;
}
// STEP 3: equivalent data types
if ( this.GetType ( ) != obj.GetType ( ) )
{
return false;
}
return Equals ( ( Point2 ) obj );
}
public bool Equals ( Point2 obj )
{
// STEP 1: Check for null if nullable (e.g., a reference type)
if ( obj == null )
{
return false;
}
// STEP 2: Check for ReferenceEquals if this is a reference type
if ( ReferenceEquals ( this, obj ) )
{
return true;
}
// STEP 4: Possibly check for equivalent hash codes
if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )
{
return false;
}
// STEP 5: Check base.Equals if base overrides Equals()
System.Diagnostics.Debug.Assert (
base.GetType ( ) != typeof ( object ) );
if ( !base.Equals ( obj ) )
{
return false;
}
// STEP 6: Compare identifying fields for equality.
return ( ( this.X.Equals ( obj.X ) ) && ( this.Y.Equals ( obj.Y ) ) );
}
</code></pre>
<p>Is that an overkill?</p>
| <p>Supporting equality with an inheritance hierarchy is tricky. You need to work out exactly what you mean. Do you really need inheritance here? If not - if Point2 derives directly from System.Object, and you can make it sealed, life becomes a bit easier. In that case I would use:</p>
<pre><code>public override bool Equals (object obj)
{
return Equals(obj as Point2);
}
public bool Equals (Point2 obj)
{
// STEP 1: Check for null if nullable (e.g., a reference type)
// Note use of ReferenceEquals in case you overload ==.
if (object.ReferenceEquals(obj, null))
{
return false;
}
// STEP 2: Check for ReferenceEquals if this is a reference type
// Skip this or not? With only two fields to check, it's probably
// not worth it. If the later checks are costly, it could be.
if (object.ReferenceEquals( this, obj))
{
return true;
}
// STEP 4: Possibly check for equivalent hash codes
// Skipped in this case: would be *less* efficient
// STEP 5: Check base.Equals if base overrides Equals()
// Skipped in this case
// STEP 6: Compare identifying fields for equality.
// In this case I'm using == instead of Equals for brevity
// - assuming X and Y are of a type which overloads ==.
return this.X == obj.X && this.Y == obj.Y;
}
</code></pre>
|
Manually create unbound datagrid <p>Can anyone tell me if it is possible to create and add data to an unbound WPF Toolkit datagrid.</p>
<p>If it is in fact possible to do, can someone please provide an example of the following:</p>
<p>Programmatically:
create a datagrid
create a datagridtextcolumn
add the datagridtextcolumn to the datagrid
create a datagridrow
set the text of the datagridtextcolumn for the row to "test"
add the datagridrow to the datagrid</p>
<p>I would like to create a datagrid that is unbound. My reason is that i would like to create a template column with multiple controls of different types and numbers - 2 checkboxes, 4 radiobuttons, 5 checkboxes, etc. - which are dynamically added at runtime and since the type and number are unknown cannot think of a way to databind them. I am happy to work unbound.</p>
<p>Thank you in advance!</p>
<p><strong>[Edit: I have not yet found an appropriate answer to this question and have started a bounty]</strong></p>
| <p>I've never used a grid without binding it to something. </p>
<p><strong><em>BUT</em></strong> looking at the underlying reason, that can be solved while still using databinding. </p>
<p>For example:
If you use a ViewModel class for you object that the grid is being bound to, then you can make an aspect of that class be the visibility setters for the various controls. </p>
<p>In the object, you'd have this:</p>
<pre><code>Public ReadOnly Property CheckboxAVisibility As Windows.Visibility
Get
' Do Logic
Return Visiblity
End Get
End Property
</code></pre>
<p>And in the XAML you'd do:</p>
<pre><code><CheckBox IsChecked="{Binding IsBoxAChecked}" Visibility={Binding CheckboxAVisibility}" />
</code></pre>
<p>This also makes things easier, as you'll be able to modify the visibility of various controls by modification of other controls within the row (ex: unchecking CheckboxA causes RadioButtons B, C & D to appear).</p>
<p>A second option would be to list just "Header" information in the grid, and when the user double clicks a row, you would display an editor with the editable aspects in a secondary panel or window (similar to how MVC editing works).</p>
<p><strong>edit due to comment</strong></p>
<p>Here's another suggestion, rather than a datagrid, use a StackPanel. For each row you need, you can add a grid panel or stackpanel or something similar, created at runtime according to your rules. For example:</p>
<p>XAML:</p>
<pre><code><StackPanel Name="stkItems" Orientation="Vertical" />
</code></pre>
<p>Code:</p>
<pre><code>Public Sub AddItems(dt as DataTable)
For Each row As DataRow in dt.Rows
Select Case row("Which")
Case 1:
Dim i As New Checkbox
i.Content = "Foo"
i.IsChecked = row("Content")
stkItems.Children.Add(i)
Case 2:
Dim i as New TextBox
i.Text = row("Content")
stkItems.Children.Add(i)
End Select
Next
End Sub
</code></pre>
<p>This is highly simplified, and you could do things such as have predefined user controls that you could use, or just build a bunch of controls into a programatically defined container, and then add that to the StackPanel</p>
|
Managing the merge of DBA's production changes/tweaks with dev's pending DB changescripts <p>We maintain a set of change scripts that must be run on the DB when our web application is released. We waste a lot of time and experience some difficultly keeping these updated however, our DBA likes to (rightly) tweak stored procedures and schemas on the live system to maintain system performance.</p>
<p>Every so often we have to rebase our patches to the current schema and stored procedures, however, it is extremely difficult to detect which changes might conflict and work out which of our DBAs' changes we might be clobbering.</p>
<p>How do others manage the need for changes on live DBs against pending changes? </p>
<p>What processes can we put in place to make this process more smooth? </p>
<p>What is the best way to store, manage our schema and apply our/his changesets?</p>
<p>Thanks in advance.</p>
| <p>DBAs should not ever tweak procs on prod only. They should also use source control and put the changes onthe other environments so that others making changes are aware of them. </p>
|
HttpHandler is not processed when its associate HttpModule is processed <p>In our asp.net 2.0 application we have the an HttpModule and HttpHandler. They are registered in web.config to handle requests for certain file types.
The request is initiated asynchronously from client side using MS AJAX.
I noticed something strange:
HttpHandler:ProcessRequest is not entered on every HttpModule:EndRequest which seems like incorrect behavior since my understanding of the flow of events:
HttpModule:BeginRequest > HttpHandler:ProcessRequest > HttpModule:EndRequest. For some reason, the handler part is sometimes skipped.
What could be causing this?</p>
| <p>Do you have that file type set up in IIS to be processed by .net?</p>
|
Can I use jtracert to sequence diagram a unit test running in eclipse? <p>How would I go about using jtracert to sequence diagram a junit test being run within eclipse?</p>
| <p>In the "Run" dialog, select your JUnit configuration and go the "Arguments" tab.
Add jTracert parameters to "VM arguments" section (something like -javaagent:/home/dmitrybedrin/work/jtracert/deploy/jTracert.jar)</p>
<p>Click on "Run" button.</p>
<p>You will see the following in the "Console" tab:</p>
<p>jTracert agent started
Waiting for a connection from jTracert GUI on port 7007</p>
<p>Now execute jTracert gui and connect to the jTracert agent.</p>
<p>That's it - you will see the sequence diagrams now!</p>
|
What could be wrong: ping works fine but tnsping works intermittently <p>We have oracle 10g running on windows server 2003. A machine which runs an application using that database has as of a few weeks ago suddenly started having connectivity problems. Today we ran the automatic updates for windows server and the problem has only gotten worse. I realize this isn't enough information for anyone to diagnose the problem but perhaps you can get me pointed in the right direction with the following more specific scenario:</p>
<p>From this machine we can ping the server with absolutely no problem and, being physically close and on an intranet the return is very fast.</p>
<p>However, when we run tnsping I have seen 3 different results within a few minutes of each other. </p>
<ol>
<li>tnsping returns just fine and in a reasonable amount of time</li>
<li>tnsping returns but only after a real long time (several seconds)</li>
<li>tnsping results in an ora-12560 protocol adapter error</li>
</ol>
<p>At the same time I can tnsping the server from my machine with no problem.</p>
<p>Can anyone point me in the right direction?</p>
| <p>To help eliminate DNS issues from the equation, specify the host's IP address in the TNSNAMES.ora file for your connection instead of a hostname. Are you using DHCP?</p>
<p>Have you eliminated hardware as the problem - have you tried a different NIC?</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.