instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I've read the description of "functionoids" <a href="https://isocpp.org/wiki/faq/pointers-to-members#functionoids" rel="nofollow noreferrer">here</a>. They look like a poor-man's version of Boost::function and Boost::bind. Am I missing something? Is there a good reason to use them if you're already using Boost?</p>
|
<p>No. </p>
<p>Alternatively see the FQA answer <a href="http://yosefk.com/c++fqa/function.html#fqa-33.10" rel="nofollow noreferrer">here.</a></p>
|
<p>My vote goes to tr1::function. </p>
<p><em>Functors</em> or <em>functionoids</em> represent the base from which <code>tr1/boost::function</code> has evolved. The limit with common-interface functors is that they break the OO-paradigm since they represent different types and can only passed to template functions (unless you provide a base class from which they derive from).</p>
<p>Indeed by means of the <em><a href="http://www.artima.com/cppsource/type_erasure2.html" rel="nofollow noreferrer">type erasure technique</a></em> <code>tr1::function</code> overcomes this limit: They are best used to implement dynamic <em>strategy classes</em>.</p>
| 32,200
|
<p>I have an array (<code>arr</code>) of elements, and a function (<code>f</code>) that takes 2 elements and returns a number.</p>
<p>I need a permutation of the array, such that <code>f(arr[i], arr[i+1])</code> is as little as possible for each <code>i</code> in <code>arr</code>. (and it should loop, ie. it should also minimize <code>f(arr[arr.length - 1], arr[0])</code>)</p>
<p>Also, <code>f</code> works sort of like a distance, so <code>f(a,b) == f(b,a)</code></p>
<p>I don't need the optimum solution if it's too inefficient, but one that works reasonable well and is fast since I need to calculate them pretty much in realtime (I don't know what to length of <code>arr</code> is, but I think it could be something around 30)</p>
|
<p>What does "such that f(arr[i], arr[i+1]) is as little as possible for each i in arr" mean? Do you want minimize the <em>sum</em>? Do you want to minimize the largest of those? Do you want to minimize f(arr[0],arr[1]) first, then among all solutions that minimize this, pick the one that minimizes f(arr[1],arr[2]), etc., and so on?</p>
<p>If you want to minimize the <em>sum</em>, this is <em>exactly</em> the Traveling Salesman Problem in its full generality (well, "metric TSP", maybe, if your f's indeed form a metric). There are clever optimizations to the naive solution that will give you the exact optimum and run in reasonable time for about n=30; you could use one of those, or one of the heuristics that give you approximations.</p>
<p>If you want to minimize the <em>maximum</em>, it is a simpler problem although still NP-hard: you can do binary search on the answer; for a particular value d, draw edges for pairs which have f(x,y)
<p>If you want to minimize it <em>lexiocographically</em>, it's trivial: pick the pair with the shortest distance and put it as arr[0],arr[1], then pick arr[2] that is closest to arr[1], and so on.</p>
<p>Depending on where your f(,)s are coming from, this might be a much easier problem than TSP; it would be useful for you to mention that as well.</p>
|
<p>I don't think the problem is well-defined in this form:</p>
<p>Let's instead define n fcns g_i : Perms -> Reals</p>
<pre><code>g_i(p) = f(a^p[i], a^p[i+1]), and wrap around when i+1 > n
</code></pre>
<p>To say you want to minimize <em>f</em> over all permutations really implies you can pick a value of <em>i</em> and minimize <em>g_i</em> over all permutations, but for any <em>p</em> which minimizes <em>g_i</em>, a related but <em>different</em> permatation minimizes <em>g_j</em> (just conjugate the permutation). So therefore it makes no sense to speak minimizing f over permutations for each <em>i</em>.</p>
| 40,052
|
<p>What's the secret to getting ClaimsResponse working with <a href="http://code.google.com/p/dotnetopenid/" rel="noreferrer">DotNetOpenId</a>?</p>
<p>For example, in this bit of code (from <a href="http://www.hanselman.com/blog/CategoryView.aspx?category=DasBlog" rel="noreferrer">Scott Hanselman's blog</a>) the ClaimsResponse object should have lots of nice little things like 'nickname' and 'email address', but the ClaimsResponse object itself is 'null':</p>
<pre><code> OpenIdRelyingParty openid = new OpenIdRelyingParty();
if (openid.Response != null)
{
// Stage 3: OpenID Provider sending assertion response
switch (openid.Response.Status)
{
case AuthenticationStatus.Authenticated:
ClaimsResponse fetch = openid.Response.GetExtension(typeof(ClaimsResponse)) as ClaimsResponse;
string nick = fetch.Nickname;
string homepage = openid.Response.ClaimedIdentifier;
string email = fetch.Email;
string comment = Session["pendingComment"] as string;
string entryId = Session["pendingEntryId"] as string;
if (String.IsNullOrEmpty(comment) == false && String.IsNullOrEmpty(entryId) == false)
{
AddNewComment(nick, email, homepage, comment, entryId, true);
}
break;
}
}
</code></pre>
<p>At first, I thought it was because I wasn't redirecting to the provider with a 'ClaimsRequest' ... but using this code to redirect to the OpenId provider still doesn't help:</p>
<pre><code>OpenIdRelyingParty openid = new OpenIdRelyingParty();
IAuthenticationRequest req = openid.CreateRequest(openid_identifier.Text);
ClaimsRequest fetch = new ClaimsRequest();
fetch.Email = DemandLevel.Require;
fetch.Nickname = DemandLevel.Require;
req.AddExtension(fetch);
req.RedirectToProvider();
</code></pre>
<p>What am I doing wrong? Or have other devs experienced the same pain?</p>
|
<p>Your code looks fine. But be aware that the sreg extension, which you are using, isn't supported by all OPs. If the OP you're authenticating with doesn't support it, then the response extension will be null as you're seeing. So a null check is always a good idea. </p>
<p>myopenid.com supports sreg, if you're looking for an OP to test against.</p>
|
<p>I could receive parameters correctly after the following updated in web.config that I copied from a sample.</p>
<pre><code><section name="dotNetOpenAuth"
type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection"
requirePermission="false"
allowLocation="true"/>
</code></pre>
<p>under <code><configsections></code></p>
<p>and add these alone</p>
<pre><code><dotNetOpenAuth>
<openid>
<relyingParty>
<behaviors>
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth"/>
</behaviors>
</relyingParty>
</openid>
</dotNetOpenAuth>
</code></pre>
| 37,388
|
<p>If I have...</p>
<pre><code>class Bunny < ActiveRecord::Base
has_many :carrots
end
</code></pre>
<p>...how can I check in the View if <code>@bunny</code> has any carrots? I want to do something like this:</p>
<pre><code><% if @bunny.carrots? %>
<strong>Yay! Carrots!</strong>
<% for carrot in @bunny.carrots %>
You got a <%=h carrot.color %> carrot!<br />
<% end %>
<% end %>
</code></pre>
<p>I know <code>@bunny.carrots?</code> doesn't work -- what would?</p>
|
<pre><code><% if @bunny.carrots.any? %>
<strong>Yay! Carrots!</strong>
<% for carrot in @bunny.carrots %>
You got a <%=h carrot.color %> carrot!<br />
<% end %>
<% end %>
</code></pre>
|
<p><code>@bunny.carrots</code> is an array, so you can treat it as such by calling <a href="http://www.ruby-doc.org/core/classes/Array.html" rel="nofollow noreferrer">array methods</a> on it, e.g. <code>unless @bunny.carrots.empty?</code></p>
| 38,058
|
<p>I'm building an Android app and I want to copy the text value of an EditText widget. It's possible for the user to press <code>Menu+A</code> then <code>Menu+C</code> to copy the value, but how would I do this programmatically?</p>
|
<p>Use <a href="https://developer.android.com/reference/android/content/ClipboardManager#setPrimaryClip(android.content.ClipData)" rel="noreferrer"><code>ClipboardManager#setPrimaryClip</code></a> method:</p>
<pre><code>import android.content.ClipboardManager;
// ...
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
</code></pre>
<p><a href="http://developer.android.com/reference/android/content/ClipboardManager.html" rel="noreferrer"><code>ClipboardManager</code> API reference</a></p>
|
<p>Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher.
<a href="https://developer.android.com/about/versions/10/privacy/changes#clipboard-data" rel="nofollow noreferrer">https://developer.android.com/about/versions/10/privacy/changes#clipboard-data</a></p>
| 29,468
|
<p>In SharePoint MOSS 2007, I have created a custom content type that I will be applying to a document library. One of the required fields is "Incoming Date" and another is the "Due Date". </p>
<p>The Due Date is always 10 working days from the Incoming Date. The Incoming Date is when the mail room received the letter, not necessarily when the document is posted to the library.</p>
<p>From here: <a href="http://msdn.microsoft.com/en-us/library/bb862071.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb862071.aspx</a></p>
<pre><code>=DATE(YEAR([Incoming Date]),MONTH([Incoming Date]),DAY([Incoming Date])+10)
</code></pre>
<p>adds 10 days, but how can I add 10 working days? I don't have the luxury of VS.NET either per the governance plan of our sharepoint rollout.</p>
<p>Assume a human is responsible for the data entry, but I would like to make it easier for them.</p>
|
<p>Firstly I should point out that you are making hard work of that formula, this will do the same.</p>
<p>=[Incoming Date] + 10</p>
<p>From the comments you have figured out that 10 working days (M-F) will always have 2 weekends so you can use this</p>
<p>=[Incoming Date] + 14</p>
<p>But this still doesn't take account of holidays</p>
<p>You are not going to be able to do this without some custom code in a workflow or possibly some <a href="http://www.endusersharepoint.com/?p=964" rel="nofollow noreferrer">javascript 'hack'</a> and a database of holiday days for your region.</p>
<p>One possibility would be to default your Due Date to 10 working days from now when the record is created</p>
<p>=Today+14</p>
<p>and then rely on your users to manual alter this date if there are holidays in that period.</p>
<p>More details on this in a blog entry I've just written - <a href="http://blog.pentalogic.net/2008/11/working-days-weekdays-holidays-sharepoint-calculated-columns/" rel="nofollow noreferrer">Working Days, Weekends and Holidays in SharePoint Calculated Columns</a></p>
|
<p>Perhaps you can work around this limitation by using a workflow (possibly a custom one) to manage the due date? A due date implies that it is an actionable item that should be assigned to somebody anyways.</p>
<p>Note that VS.NET doesn't have to be a luxury - you can use it for <a href="http://www.microsoft.com/Express/" rel="nofollow noreferrer">free</a>.</p>
| 39,422
|
<p>I'm trying to determine if the user is using 24 hour or 12 hour time, and there doesn't seem to be a good way to figure this out other than creating an NSDateFormatter and searching the format string for the period field ('a' character)</p>
<p>Here's what I'm doing now:</p>
<pre><code>NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterShortStyle];
NSRange range = [[formatter dateFormat] rangeOfString:@"a"];
BOOL is24HourFormat = range.location == NSNotFound && range.length == 0;
[formatter release];
</code></pre>
<p>Which works, but feels kinda fragile. There has to be a better way, right?</p>
|
<p>This information is provided in NSUserDefaults. Maybe under the NSShortTimeDateFormatString key? (Still requires parsing of course).</p>
<p>(Use</p>
<pre><code>NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
</code></pre>
<p>to dump all the pre-defined user defaults).</p>
<p>Not quite sure why you want to do this - I bet you have a good reason - but maybe it's best just to use the defaults in NSDateFormatter instead?</p>
|
<p>NSShortTimeDateFormatString is deprecated, and I believe it also effectively doesn't work in 10.5 and later. See the 10.4 and 10.5 Foundation release notes. Dumping all defaults is a good way to depend on stuff that is not guaranteed by the interface, though it can be interesting to sort of see what's going on under the hood.</p>
<p>Why do you need this? As schwa says, everything works much better if you can get away from needing to know anything about the localized presentation.</p>
| 20,806
|
<p>When a customer logs in to my site, I need to know their account id and their menu id. This lets me know what data they can see on a page and what menu they get. I don't want to have to read this data over and over. Should I store this in a session variable or customize the membership user and membership provider to contain this information?</p>
|
<p>As already suggested, the profile system is super easy.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx</a></p>
|
<p>The profile system would probably suit your needs.</p>
| 12,076
|
<p>I'm doing some design (initially for Java) (but may extend to .NET in the future?) and I'm getting confused between the terms "cache" and "pool".</p>
<p>As far as I can see, the main point of difference is what is contained in them?</p>
<p>Any guidelines as to which should be used when?</p>
<p>And what then is a "cache pool" which is referred to in a number of articles?</p>
|
<p>Although they both refer to keeping objects around, they are quite different, and I wouldn't say they're interchangeable.</p>
<p><strong>Cache</strong> - store frequently used values, typically because the lookup and/or creation is non-trivial. e.g. if a lookup table from a database is frequently used, or values are read from a file on disk, it's more efficient to keep it in memory and refresh it periodically. </p>
<p>A cache only manages object lifetime in the cache, but does not impose semantics on what is held in the cache. A cache also doesn't create the items, but just stores objects.</p>
<p><strong>Pool</strong> - term to describe a group of resources that are managed by the pool itself. e.g. (Database) Connection Pool - When a connection is needed it is obtained from the pool, and when finished with is returned to the pool. </p>
<p>The pool itself handles creation and destruction of the pooled objects, and manages how many objects can be created at any one time.</p>
<p><strong>Cache Pool</strong> - mostly seems to describe the number of (independent?) cache's that exist. E.g. an asp.net application has 1 cache per Application Domain (cache isn't shared between asp.net applications). Literally a pool of caches, although this term seems to be used rarely.</p>
|
<p>I agree with Ken, and to add a little--a Cache would not effect your system if some or all of the resources were removed from it at any time--the data is all easily reproducable/refetchable, and the reproducing is generally automatic (you ask the cache for something, if it doesn't exist in the cache, the cache makes one, saves it and returns it to you). </p>
<p>A "Pool" can be anything, but you don't just delete pool objects because they are old--usually a pool contains unique, maybe unreproducible instances of some resource.</p>
| 36,710
|
<p>I'm trying to use <code>SetWindowsHookEx</code> to set up a <code>WH_SHELL</code> hook to get notified of system-wide <code>HSHELL_WINDOWCREATED</code> and <code>HSHELL_WINDOWDESTROYED</code> events. I pass 0 for the final <code>dwThreadId</code> argument which, according to <a href="http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx" rel="noreferrer">the docs</a>, should "associate the hook procedure with all existing threads running in the same desktop as the calling thread". I also pass in the handle to my DLL (<code>HInstance</code> in Delphi) for the <code>hMod</code> parameter as did all the examples I looked at.</p>
<p>Yet, I only ever get notified of windows created by my own app and - more often than not - my tests result in the desktop process going down in flames once I close down my app. Before you ask, I do call <code>UnhookWindowsHookEx</code>. I also always call <code>CallNextHookEx</code> from within my handler.</p>
<p>I am running my test app from a limited user account but so far I haven't found any hints indicating that this would play a role... (though that actually surprises me)</p>
<p>AFAICT, I did everything by the book (obviously I didn't but so far I fail to see where).</p>
<p>I'm using Delphi (2007) but that shouldn't really matter I think.</p>
<p><strong>EDIT:</strong> Maybe I should have mentioned this before: I did download and try a couple of examples (though there are unfortunately not that many available for Delphi - especially none for <code>WH_SHELL</code> or <code>WH_CBT</code>). While they do not crash the system like my test app does, they still do not capture events from other processes (even though I can verify with ProcessExplorer that they get loaded into them alright). So it seems there is either something wrong with my system configuration or the examples are wrong or it is simply not possible to capture events from other processes. Can anyone enlighten me?</p>
<p><strong>EDIT2:</strong> OK, here's the source of my test project.</p>
<p>The DLL containing the hook procedure:</p>
<pre><code>library HookHelper;
uses
Windows;
{$R *.res}
type
THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall;
var
WndHookCallback: THookCallback;
Hook: HHook;
function HookProc(ACode, AWParam, ALParam: Integer): Integer; stdcall;
begin
Result := CallNextHookEx(Hook, ACode, AWParam, ALParam);
if ACode < 0 then Exit;
try
if Assigned(WndHookCallback)
// and (ACode in [HSHELL_WINDOWCREATED, HSHELL_WINDOWDESTROYED]) then
and (ACode in [HCBT_CREATEWND, HCBT_DESTROYWND]) then
WndHookCallback(ACode, AWParam, ALParam);
except
// plop!
end;
end;
procedure InitHook(ACallback: THookCallback); register;
begin
// Hook := SetWindowsHookEx(WH_SHELL, @HookProc, HInstance, 0);
Hook := SetWindowsHookEx(WH_CBT, @HookProc, HInstance, 0);
if Hook = 0 then
begin
// ShowMessage(SysErrorMessage(GetLastError));
end
else
begin
WndHookCallback := ACallback;
end;
end;
procedure UninitHook; register;
begin
if Hook <> 0 then
UnhookWindowsHookEx(Hook);
WndHookCallback := nil;
end;
exports
InitHook,
UninitHook;
begin
end.
</code></pre>
<p>And the main form of the app using the hook:</p>
<pre><code>unit MainFo;
interface
uses
Windows, SysUtils, Forms, Dialogs, Classes, Controls, Buttons, StdCtrls;
type
THookTest_Fo = class(TForm)
Hook_Btn: TSpeedButton;
Output_Lbx: TListBox;
Test_Btn: TButton;
procedure Hook_BtnClick(Sender: TObject);
procedure Test_BtnClick(Sender: TObject);
public
destructor Destroy; override;
end;
var
HookTest_Fo: THookTest_Fo;
implementation
{$R *.dfm}
type
THookCallback = procedure(ACode, AWParam, ALParam: Integer); stdcall;
procedure InitHook(const ACallback: THookCallback); register; external 'HookHelper.dll';
procedure UninitHook; register; external 'HookHelper.dll';
procedure HookCallback(ACode, AWParam, ALParam: Integer); stdcall;
begin
if Assigned(HookTest_Fo) then
case ACode of
// HSHELL_WINDOWCREATED:
HCBT_CREATEWND:
HookTest_Fo.Output_Lbx.Items.Add('created handle #' + IntToStr(AWParam));
// HSHELL_WINDOWDESTROYED:
HCBT_DESTROYWND:
HookTest_Fo.Output_Lbx.Items.Add('destroyed handle #' + IntToStr(AWParam));
else
HookTest_Fo.Output_Lbx.Items.Add(Format('code: %d, WParam: $%x, LParam: $%x', [ACode, AWParam, ALParam]));
end;
end;
procedure THookTest_Fo.Test_BtnClick(Sender: TObject);
begin
ShowMessage('Boo!');
end;
destructor THookTest_Fo.Destroy;
begin
UninitHook; // just to make sure
inherited;
end;
procedure THookTest_Fo.Hook_BtnClick(Sender: TObject);
begin
if Hook_Btn.Down then
InitHook(HookCallback)
else
UninitHook;
end;
end.
</code></pre>
|
<p>The problem is that your hook DLL is actually being loaded into several different address spaces. Any time Windows detects an event in some foreign process that must be processed by your hook, it loads the hook DLL into that process (if it's not already loaded, of course).</p>
<p>However, each process has its own address space. This means that the callback function pointer that you passed in InitHook() only makes sense in the context of your EXE (that's why it works for events in your app). In any other process that pointer is <strong>garbage</strong>; it may point to an invalid memory location or (worse) into some random code section. The result can either be an access violation or silent memory corruption.</p>
<p>Generally, the solution is to use some sort of <a href="http://msdn.microsoft.com/en-us/library/aa365574(VS.85).aspx" rel="noreferrer">interprocess communication</a> (IPC) to properly notify your EXE. The most painless way for your case would be to post a message and cram the needed info (event and HWND) into its WPARAM/LPARAM. You could either use a WM_APP+n or create one with RegisterWindowMessage(). Make sure the message is posted and not sent, to avoid any deadlocks.</p>
|
<p>Lol, it looks like the error is in the test code.</p>
<p>If you create two separate buttons, one for Init and one for UnInit (I prefer Exit).</p>
<pre><code>procedure THooktest_FO.UnInitClick(Sender: TObject);
begin
UninitHook;
end;
procedure THooktest_FO.InitClick(Sender: TObject);
begin
InitHook(HookCallback)
end;
</code></pre>
<p>Start the app. Click Init and then The test button, the following output is shown:</p>
<pre><code>created handle #1902442
destroyed handle #1902442
created handle #1967978
created handle #7276488
</code></pre>
<p>Then the messagebox is shown.</p>
<p>If you click ok you get:</p>
<pre><code>destroyed handle #1967978
</code></pre>
<p>HTH</p>
| 38,349
|
<p>I've been asked to screen some candidates for a MySQL DBA / Developer position for a role that requires an enterprise level skill set.</p>
<p>I myself am a SQL Server person so I know what I would be looking for from that point of view with regards to scalability / design etc but is there anything specific I should be asking with regards to MySQL?</p>
<p>I would ideally like to ask them about enterprise level features of MySQL that they would typically only use when working on a big database. Need to separate out the enterprise developers from the home / small website kind of guys.</p>
<p>Thanks.</p>
|
<p>Although SQL Server and MySQL are both RDBMs, MySQL has many unique features that can illustrate the difference between novice and expert.</p>
<p>Your first step should be to ensure that the candidate is comfortable using the command line, not just GUI tools such as phpMyAdmin. During the interview, try asking the candidate to write MySQL code to create a database table or add a new index. These are very basic queries, but exactly the type that GUI tools prevent novices from mastering. You can double-check the answers with someone who is more familiar with MySQL.</p>
<p>Can the candidate demonstrate knowledge of how JOINs work? For example, try asking the candidate to construct a query that returns all rows from Table One where no matching entries exist in Table Two. The answer should involve a LEFT JOIN.</p>
<p>Ask the candidate to discuss backup strategies, and the various strengths and weaknesses of each. The candidate should know that backing up the database files directly is not an effective strategy unless all the tables are MyISAM. The candidate should definitely mention mysqldump as a cornerstone for backups. More sophisticated backup solutions include ibbackup/innobackup and LVM snapshots. Ideally, the candidate should also discuss how backups can affect performance (a common solution is to use a slave server for taking backups).</p>
<p>Does the candidate have experience with replication? What are some of the common replication configurations and the various advantages of each? The most common setup is master-slave, allowing the application to offload SELECT queries to slave servers, along with taking backups using a slave to prevent performance issues on the master. Another common setup is master-master, the main benefit being the ability to make schema changes without impacting performance. Make sure the candidate discusses common issues such as cloning a slave server (<a href="http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html#option_mysqldump_master-data" rel="noreferrer">mysqldump + notation of the binlog position</a>), load distribution using a load balancer or MySQL proxy, <a href="http://www.mysqlperformanceblog.com/2007/10/12/managing-slave-lag-with-mysql-replication/" rel="noreferrer">resolving slave lag</a> by breaking larger queries into chunks, and how to promote a slave to become a new master.</p>
<p>How would the candidate troubleshoot performance issues? Do they have sufficient knowledge of the underlying operating system and hardware to diagnose whether a bottleneck is CPU bound, IO bound, or network bound? Can they demonstrate how to use <a href="http://www.devshed.com/c/a/MySQL/Analyzing-Queries-for-Speed-with-EXPLAIN/" rel="noreferrer">EXPLAIN</a> to discover indexing problems? Do they mention the slow query log or configuration options such as the key buffer, tmp table size, innodb buffer pool size, etc?</p>
<p>Does the candidate appreciate the subtleties of each storage engine? (MyISAM, InnoDB, and MEMORY are the main ones). Do they understand how each storage engine optimizes queries, and how locking is handled? At the least, the candidate should mention that MyISAM issues a table-level lock whereas InnODB uses row-level locking.</p>
<p>What is the safest way to make schema changes to a live database? The candidate should mention master-master replication, as well as avoiding the locking and performance issues of ALTER TABLE by creating a new table with the desired configuration and using mysqldump or INSERT INTO ... SELECT followed by RENAME TABLE.</p>
<p>Lastly, the only true measurement of a pro is experience. If the candidate cannot point to specific experience managing large data sets in a high availability environment, they might not be able to back up any knowledge they possess on a purely intellectual level.</p>
|
<p>I think it would depend on the database type: transactional or data warehouse?</p>
<p>Anyhow, for all types I'd ask about specific to MySQL replication and clustering, performance tuning and monitorization concepts.</p>
| 8,741
|
<p>I am a .Net programmer(both C# and VB.net) , and I want to go into F# area also, but can't find some good online article/pdf to start with. Please guide me through this.</p>
|
<p><a href="http://cs.hubfs.net/" rel="noreferrer">hubFS: THE place for F#</a></p>
<p><a href="http://cs.hubfs.net/forums/88/ShowForum.aspx" rel="noreferrer">hubFS: THE place for F# » Establish skills in F# » Books, Tutorials, links and other resources</a></p>
|
<p>Check the MSDN F# Development center, they have some articles on there:</p>
<p><a href="http://msdn.microsoft.com/en-us/fsharp/default.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/fsharp/default.aspx</a></p>
| 19,519
|
<p>Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them.</p>
<ul>
<li>What categories of vunerabilities?
<ul>
<li>crashing site</li>
<li>breaking into server</li>
<li>breaking into other people's logins</li>
<li>spam</li>
<li><a href="http://en.wikipedia.org/wiki/Internet_sock_puppet" rel="nofollow noreferrer">sockpuppeting</a>, <a href="http://en.wikipedia.org/wiki/Internet_sock_puppet#Meatpuppet" rel="nofollow noreferrer">meatpuppeting</a></li>
<li>etc...</li>
</ul></li>
<li>What kind of defensive programming techniques?</li>
<li>etc...</li>
</ul>
|
<p>From the <a href="http://www.owasp.org/" rel="nofollow noreferrer">Open Web Application Security Project</a>:</p>
<ol>
<li>The <a href="http://www.owasp.org/images/e/e8/OWASP_Top_10_2007.pdf" rel="nofollow noreferrer">OWASP Top Ten</a> vulnerabilities (pdf)</li>
<li>For a more painfully exhaustive list: <a href="http://www.owasp.org/index.php/Category:Vulnerability" rel="nofollow noreferrer">Category:Vulnerability</a></li>
</ol>
<p>The top ten are:</p>
<ol>
<li>Cross-site scripting (XSS)</li>
<li>Injection flaws (SQL injection, script injection)</li>
<li>Malicious file execution</li>
<li>Insecure direct object reference</li>
<li>Cross-site request forgery (XSRF)</li>
<li>Information leakage and improper error handling</li>
<li>Broken authentication and session management</li>
<li>Insecure cryptographic storage</li>
<li>Insecure communications</li>
<li>Failure to restrict URL access</li>
</ol>
|
<p>SQL injection</p>
| 4,864
|
<p>I have a project with a post build event:</p>
<pre><code>copy $(ProjectDir)DbVerse\Lunaverse.DbVerse.*.exe $(TargetDir)
</code></pre>
<p>It works fine every time on my machine. I have a new developer who always gets the "exited with code 1" error. I had her run the same command in a DOS prompt, and it worked fine. What could be causing this? Is there any way to get to the real error?</p>
<p>We are both using Visual Studio 2008.</p>
|
<p>She had a space in one of the folder names in her path, and no quotes around it.</p>
|
<p>So many solutions...</p>
<p>In my case, I had to save the bat file with non-unicode (Western, Windows) encoding. By default when I added the file to visual studio (and probably I should have done it outside of the VS), it added with UTF-8 encoding.</p>
| 39,961
|
<p>I'm working on a REST service that has a few requirements:</p>
<ol>
<li>It has to be secure.</li>
<li>Users should not be able to forge requests.</li>
</ol>
<p>My current proposed solution is to have a custom Authorization header that look like this (this is the same way that the amazon web services work):</p>
<pre><code>Authorization: MYAPI username:signature
</code></pre>
<p>My question is how to form the signature. When the user logs into the service they are given a secret key which they should be able to use to sign requests. This will stop other users submitting requests on their behalf, but will not stop them forging requests.</p>
<p>The application that will be using this service is an iPhone application, so I was thinking we could have a public key embedded in the application which we can do an additional signature with, but does this mean we'll have to have two signatures, one for the user key and one for the app key?</p>
<p>Any advice would be greatly appreciated, I'd quite like to get this right the first time.</p>
|
<p>The answer is simple: It cannot be done. As soon as you ship any solution to the end user, he or she can allways attack the server it is communicating with. The most common version of this problem is cheating with hi-score lists in Flash games. You can make it <em>harder</em> by embedding some sort of encryption in the client and obfuscating the code... But all compiled and obfuscated code can allways be decompiled and unobfuscated. It is just a matter of how much time and money you are willing to spend and likewise for the potential attacker.</p>
<p>So your concern is <em>not</em> how to try to prevent the user from sending faulty data to your system. It is how to prevent the user from <em>damaging</em> your system. You have to design your interfaces so that all damage done by faulty data only affects the user sending it.</p>
|
<p>There is a better discussion of this here:</p>
<p><a href="https://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service">Best Practices for securing a REST API / web service</a></p>
| 29,743
|
<p>Is it possible to create an STL-like container, or even just an STL-style iterator, for an existing array of POD-type elements?</p>
<p>For example, suppose I have an array of ints. It would be convenient to be able to call some of the STL functions, such as find_if, count_if, or sort directly on this array.</p>
<p>Non-solution: copying the entire array, or even just references to the elements. The goal is to be very memory- and time-saving while hopefully allowing use of other STL algorithms.</p>
|
<p>You can call many of the STL algorithms directly on a regular C style array - they were designed for this to work. e.g.,:</p>
<pre><code>int ary[100];
// init ...
std::sort(ary, ary+100); // sorts the array
std::find(ary, ary+100, pred); find some element
</code></pre>
<p>I think you'll find that most stuff works just as you would expect.</p>
|
<p>You can use <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/array.html" rel="nofollow noreferrer">Boost.Array</a> to create a C++ array type with STL semantics.</p>
<p>using arrays:</p>
<pre><code>int a[100];
for (int i = 0; i < 100; ++i)
a[i] = 0;
</code></pre>
<p>using boost.arrays:</p>
<pre><code>boost::array<int,100> a;
for (boost::array<int,100>::iterator i = a.begin(); i != a.end(); ++i)
*i = 0;
</code></pre>
<p><strong>Update:</strong> With C++11, you can now use <code>std::array</code>.</p>
| 21,222
|
<p>Is there a way to set "work offline" in TFS without having to try opening a solution, waiting for it to time out, and then having Visual Studio work out that it has failed?</p>
<p>It seems a touch ridiculous that I can't just tick a box to tell it myself, seeing as I'm probably the one most qualified to know when I'm not in the office!</p>
|
<p>This extension should solve your problem (for VS 2010):</p>
<p><a href="http://visualstudiogallery.msdn.microsoft.com/425f09d8-d070-4ab1-84c1-68fa326190f4?SRC=Home">http://visualstudiogallery.msdn.microsoft.com/425f09d8-d070-4ab1-84c1-68fa326190f4?SRC=Home</a></p>
|
<p>If TFS is down, you might have trouble going into offline mode. If you close and reopen your solution, a nice little dialog will appear asking you if you want to Go Offline.</p>
<p>Alternatively if you don't want to close/reopen the solution, you can install <a href="https://visualstudiogallery.msdn.microsoft.com/6e54271c-2c4e-4911-a1b4-a65a588ae138" rel="nofollow">the TFS Go-Offline plugin</a>, then click:</p>
<pre><code>TEAM -> Go Offline
</code></pre>
| 40,440
|
<p>OK, so see questions like <a href="https://stackoverflow.com/questions/60620/getting-started-with-silverlight-development">this one</a> and <a href="https://stackoverflow.com/questions/28826/what-exactly-is-microsoft-expression-studio-and-how-does-it-integrate-with-visu">this one</a> and the question I have is - does one <em>have</em> to use Expression Blend to do Silverlight development or can any of it be done with just Visual Studio? (2008, in this case)</p>
<p>I haven't gotten started using Silverlight yet and through my workplace's MSDN I can get Expression Blend without any issues, but for my side work, do I have to drop the $499 for Expression Blend 2? (I know there's a trial but I'm thinking beyond that)</p>
<p>Obviously I'm concerned that in order to get into Silverlight development there's a huge financial investment involved and I already own Visual Studio 2008 - is it possible to do development without Expression Blend or would that just be impossible?</p>
|
<p>You can do everything in Visual Studio. But then again you can do everything in Notepad as well... it all depends on how much the given tool will help you along in the process. Having Blend will be a great asset from a design point of view but wont really do much for you in terms of programming the application. Download the trial and see how it works... if it adds value and saves time then it's well worth the purchase.</p>
|
<p>It quite is possible. If you don't care too much about the eye candy.
Blend is more of a designer's tool than a development tool.</p>
<p>You could try the Microsoft Action Pack Special edition for <a href="http://partner.microsoft.com/40047166" rel="nofollow noreferrer">Web Solutions</a> if you are at least a <a href="http://partner.microsoft.com/" rel="nofollow noreferrer">Microsoft Registered Partner</a>.</p>
| 26,076
|
<p>Suppose I have a set of values, stored in a std::set:</p>
<p>{1, 2, 6, 8}</p>
<p>and I have a search key, say, 3. I want to put 3 into a function and get the first value greater than or equal to 3, in this case I would want to get 6.</p>
<p>The find() function provided in map/set/multimap/and set will, of course, return the end iterator for this case. Is there a similar function to find that would return 6 in this case?</p>
|
<p>Yes: <code>upper_bound(X)</code> returns an iterator pointing to the first element greater than <code>X</code>. There is also a <code>lower_bound(X)</code> function which returns an iterator pointing to the first element not less than <code>X</code>. Thus, all of the elements in the half-open interval <code>[lower_bound(X), upper_bound(X))</code> will be equal to X.</p>
|
<p>You want the <a href="http://www.sgi.com/tech/stl/upper_bound.html" rel="nofollow noreferrer">upper_bound</a> function.</p>
<pre><code>map<int, int> mymap = { 1,2,6,8 };
map<int,int>::iterator i = mymap.upper_bound(3); // returns an iterator to the '6' element.
</code></pre>
| 21,248
|
<p>I am trying to use Lambda Expressions in a project to map to a third party query API. So, I'm parsing the Expression tree by hand.</p>
<p>If I pass in a lambda expression like:</p>
<pre><code>p => p.Title == "title"
</code></pre>
<p>everything works.</p>
<p>However, if my lambda expression looks like:</p>
<pre><code>p => p.Title == myaspdropdown.SelectedValue
</code></pre>
<p>Using the .NET debugger, I don't see the actual value of that funciton. Instead I see something like:</p>
<pre><code>p => p.Title = (value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)
</code></pre>
<p>What gives? And when I try to grab the right side of the expression as a string, I get <code>(value(ASP.usercontrols_myaspusercontrol_ascx).myaspdropdown.SelectedValue)</code> instead of the actual value. <strong>How do I get the actual value?</strong></p>
|
<p>Remember that when you're dealing with the lambda expression as an expression tree, you don't have executable code. Rather you have a tree of expression elements, that make up the expression you wrote.</p>
<p>Charlie Calvert has <a href="https://learn.microsoft.com/en-us/archive/blogs/charlie/expression-tree-basics" rel="nofollow noreferrer">a good post</a> that discusses this in detail. Included is an example of using an expression visualiser for debugging expressions.</p>
<p>In your case, to get the value of the righthand side of the equality expression, you'll need to create a new lambda expression, compile it and then invoke it.</p>
<p>I've hacked together a quick example of this - hope it delivers what you need.</p>
<pre><code>public class Class1
{
public string Selection { get; set; }
public void Sample()
{
Selection = "Example";
Example<Book, bool>(p => p.Title == Selection);
}
public void Example<T,TResult>(Expression<Func<T,TResult>> exp)
{
BinaryExpression equality = (BinaryExpression)exp.Body;
Debug.Assert(equality.NodeType == ExpressionType.Equal);
// Note that you need to know the type of the rhs of the equality
var accessorExpression = Expression.Lambda<Func<string>>(equality.Right);
Func<string> accessor = accessorExpression.Compile();
var value = accessor();
Debug.Assert(value == Selection);
}
}
public class Book
{
public string Title { get; set; }
}
</code></pre>
|
<p>I'm not sure I understand. Where are you "seeing" that? Is that at design-time or run-time? Lambda expressions can be thought of essentially as anonymous delegates, and will operate with deferred execution. So you shouldn't expect to see the value assigned until after execution has passed that line, obviously. <br />
I don't think that's really what you mean though... if you clarify the question a bit maybe I can help :)</p>
| 29,483
|
<p>One of the web pages on our site is extremely long. Although the page itself does not call any javascript or jquery functions, its base page registers the JQuery source script (jquery-1.2.6.js) and this seems to cause IE7 to display the "A script on this page is causing Internet Explorer to run slowly." message when you click on a link that will navigate you away from this long page.</p>
<p>Removing the registration of the jquery source script makes the problem go away, however there are other controls on the page that require jquery so this is not really an option.</p>
<p>Any ideas why this happens and is there any way around it?
Thanks.</p>
|
<p>As a crude workaround, could you unregister the script on the child page?</p>
<p>Did you try moving the script reference to the bottom of the page?</p>
|
<p>If it is worth it to you. you could try to optimize the jquery calls. there are some simple techniques that could really improve performance on large pages.</p>
<pre><code>//cache any jQuery objects that are used frequently
$myObj = $(".someClass");
...
</code></pre>
<p>Also think that this is still relevant: <a href="http://www.learningjquery.com/2006/12/quick-tip-optimizing-dom-traversal" rel="nofollow noreferrer">Optimizing DOM Traversal</a></p>
| 49,962
|
<p>In a WPF UserControl, I have to make to call to a WebService. I am making this call on a separate thread but I want to inform the user that the call may take some time. </p>
<p>The WebMethod returns me a collection of objects and I bind it to a ListBox in my UC. So far, so good... This part works really well. However, <strong>I want to display a progress bar (or an animation of any kind...) during the call. This animation would be on top and centered in the ListBox control.</strong></p>
<p>I tried Adorner and it partially works. However, I have to draw all controls in protected override void OnRender(DrawingContext drawingContext)... I simply want to add a control for a couple of seconds...</p>
<p>Anybody has an idea of how I could achieve this?</p>
<p>Thanks!</p>
|
<p>Don't go with the adorner - what I do is have two separate container controls (usually grids) that occupy the same area of the screen. One is my "progress" control, and the other is my "content" control. I set the visibility of the progress control to Collapsed and the visibility of the content control to Visible by default.</p>
<p>If you have it set up that way, when you start the asynchronous call to the webservice you can make the progress control visible and the content control collapsed. When the webservice finishes, have it use Dispatcher.BeginInvoke to update the UI, and at that point, switch the progress control back to collapsed and the content control back to visible.</p>
<p>I generally make the progress control indeterminate. Here is an example; in this, I have a separate UserControl called ProgressGrid that has my progress bar.</p>
<pre><code> <Grid x:Name="layoutRoot">
<Grid x:Name="contentGrid" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Visible">
<!-- snip -->
</Grid>
<controls:ProgressGrid x:Name="progressGrid" Text="Signing in, please wait..." Visibility="Collapsed"/>
</Grid>
</code></pre>
<p>And in the code behind, just something simple like this:</p>
<pre><code> private void SignInCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
contentGrid.Visibility = Visibility.Collapsed;
progressGrid.Visibility = Visibility.Visible;
}
</code></pre>
|
<p>There is a trick you can use with a zero height Canvas that might work. Chris Anderson's WPF book goes into detail on this and why it works, but it goes something like this.</p>
<ul>
<li>create a StackPanel</li>
<li>add a Canvas with Height="0" and a high z-index to the stack panel</li>
<li>add your user control to the stack panel.</li>
</ul>
<p>When you want to show the progress bar add it to the zero height canvas. It will allow you to position it over the user control. Canvas allows you to go beyond its borders. Centering the progress bar should just require looking at the dimensions of the user control and setting the position of the progress bar on the Canvas accordingly. Remove the progress bar from the canvas when you are done.</p>
<p>Here is a simple example that uses a TextBox. It's not perfect but it shows the idea. Clicking the button shows the TextBox on top of the InkCanvas</p>
<pre><code><DockPanel LastChildFill="True">
<Button DockPanel.Dock="Top" Name="showButton" Click="showProgress">show</Button>
<StackPanel DockPanel.Dock="Bottom">
<Canvas Name="zeroHeight" Height="0"/>
<InkCanvas Name="inky">
</InkCanvas>
</StackPanel>
</DockPanel>
private void showProgress(object sender, RoutedEventArgs e)
{
TextBox box = new TextBox();
box.Text = "on top";
StackPanel.SetZIndex(zeroHeight, 8);
zeroHeight.Children.Add(box);
box.Width = 30;
box.Height = 30;
Canvas.SetLeft(box, 10);
Canvas.SetTop(box, 10);
Canvas.SetZIndex(box, 10);
}
</code></pre>
| 42,712
|
<p>Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.</p>
<p>I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from <a href="http://forums.asp.net/t/1208353.aspx" rel="noreferrer">this source</a>, but I need to save the bitmap back into the SQL database, which I think I need to convert back into a byte[] format.</p>
<p>So how do I convert the bitmap to a byte[] format?</p>
<p>If I am going about this the wrong way I would be grateful it you could correct me.</p>
<p>Here is my code:</p>
<pre><code> // Find the fileUpload control
string filename = uplImage.FileName;
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(uplImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = sngRatio * newWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
PHJamesDataContext db = new PHJamesDataContext();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = data,
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
db.SubmitChanges();
</code></pre>
|
<p>You should be able to change this block to</p>
<pre><code> System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
</code></pre>
|
<p>Assuming, that your bitmap is bmp</p>
<pre><code>byte[] data;
using(System.IO.MemoryStream stream = new System.IO.MemoryStream()) {
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
data = new byte[stream.Length];
stream.Read(data, 0, stream.Length);
stream.Close();
}
</code></pre>
| 33,624
|
<p>this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy.</p>
<p>I have the following class <em>SubSim</em> which extends <em>Sim</em>, which is extending <em>MainSim</em>. In a completely separate class (and library as well) I need to check if an object being passed through is a type of <em>MainSim</em>. So the following is done to check;</p>
<pre>
Type t = GetType(sim);
//in this case, sim = SubSim
if (t != null)
{
return t.BaseType == typeof(MainSim);
}
</pre>
<p>Obviously <em>t.BaseType</em> is going to return <em>Sim</em> since <em>Type.BaseType</em> gets the type from which the current Type directly inherits. </p>
<p>Short of having to do <em>t.BaseType.BaseType</em> to get <em>MainSub</em>, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class? </p>
<p>Thank you in advance</p>
|
<p>There are 4 related standard ways: </p>
<pre><code>sim is MainSim;
(sim as MainSim) != null;
sim.GetType().IsSubclassOf(typeof(MainSim));
typeof(MainSim).IsAssignableFrom(sim.GetType());
</code></pre>
<p>You can also create a recursive method:</p>
<pre><code>bool IsMainSimType(Type t)
{ if (t == typeof(MainSim)) return true;
if (t == typeof(object) ) return false;
return IsMainSimType(t.BaseType);
}
</code></pre>
|
<p>How about "is"?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx</a></p>
| 27,388
|
<p>I'm importing a MySQL dump and getting the following error.</p>
<pre><code>$ mysql foo < foo.sql
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes
</code></pre>
<p>Apparently there are attachments in the database, which makes for very large inserts.</p>
<hr>
<p>This is on my local machine, a Mac with MySQL 5 installed from the MySQL package.</p>
<p>Where do I change <code>max_allowed_packet</code> to be able to import the dump? </p>
<p>Is there anything else I should set? </p>
<p>Just running <code>mysql --max_allowed_packet=32M …</code> resulted in the same error.</p>
|
<p>You probably have to change it for both the client (you are running to do the import) AND the daemon mysqld that is running and accepting the import.</p>
<p>For the client, you can specify it on the command line:</p>
<pre><code>mysql --max_allowed_packet=100M -u root -p database < dump.sql
</code></pre>
<p>Also, <strong>change the my.cnf or my.ini file</strong> (usually found in /etc/mysql/) under the mysqld section and set:<br/></p>
<pre><code>max_allowed_packet=100M
</code></pre>
<p>or you could run these <strong>commands</strong> in a MySQL console connected to that same server:</p>
<pre><code>set global net_buffer_length=1000000;
set global max_allowed_packet=1000000000;
</code></pre>
<p>(Use a very large value for the packet size.)</p>
|
<p>Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.</p>
<p>That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.</p>
| 11,862
|
<p>For example: </p>
<p>First, say I have a Silverlight app with Windowless=true so that I can place ASP.NET controls on top of it. Then I place an ASP.NET button on the page. How can I have say the text of a control in the Silverlight app change when the user presses the ASP.NET button? How would I send the Silverlight app an update message from the C# code that catches the Click of the ASP.NET button?</p>
<p>Thanks,
Jeff</p>
|
<p>For me, the difference depends on whether or not the web project is open in Visual Studio.</p>
<p>I find if I commit the project file to version control with the project open in Visual Studio the SubType elements are present. Closing the solution/project then removes the SubType elements from the project file. Now I always ensure my commits are performed with the project closed in VS to avoid unnecessary changes to the project file.</p>
|
<p>These lines are also appearing in the project file in VS2012 when committing project changes in Tortoise SVN. This project used to be a website that I converted into a web application.</p>
<p>I was able to bypass this issue using the following steps which <strong>do not</strong> require closing the project:</p>
<ol>
<li>Just prior to committing to SVN, clean the solution using "BUILD > Clean Solution".</li>
<li>Click the "Save All" button to save the project file.</li>
<li>Commit changes using Tortoise SVN.</li>
<li>Continue working on project...</li>
</ol>
| 33,073
|
<p>I would like to generate a list of files within a directory. Some of the filenames contain Chinese characters.</p>
<p>eg: [试验].Test.txt</p>
<p>I am using the following code:</p>
<pre><code>require 'find'
dirs = ["TestDir"]
for dir in dirs
Find.find(dir) do |path|
if FileTest.directory?(path)
else
p path
end
end
end
</code></pre>
<p>Running the script produces a list of files but the Chinese characters are escaped (replaced with backslashes followed by numbers). Using the example filename above would produce:</p>
<p>"TestDir/[\312\324\321\351]Test.txt" instead of "TestDir/[试验].Test.txt".</p>
<p>How can the script be altered to output the Chinese characters?</p>
|
<p>Ruby needs to know that you are dealing with unicode in your code. Set appropriate character encoding using KCODE, as below:</p>
<pre><code>$KCODE = 'utf-8'
</code></pre>
<p>I think utf-8 is good enough for chinese characters.</p>
|
<p>The following code is more elegant and doesn't require 'find.' It produces a list of files (but not directories) in whatever the working directory is (or whatever directory you put in). </p>
<pre><code>Dir.entries(Dir.pwd).each do |x|
p x.encode('UTF-8') unless FileTest.directory?(x)
end
</code></pre>
<p>And to get a recursive digging down one level use:</p>
<pre><code>Dir.glob('*/*').each do |x|
p x.encode('UTF-8') unless FileTest.directory?(x)
end
</code></pre>
<p>I'm sure there is a way to get it to go all the way down but <code>Dir.glob('**/*')</code> will go through the whole file system if I remember right.</p>
| 39,878
|
<p>I want to extend a WPF application with database functionality. Which database engine would you suggest and why? SQLite, SQL CE, other?</p>
|
<p>Depending on the applications use, <strong>I would recommend using SQL Lite</strong> because it doesn't require you to install any other software (SQL CE or Express, etc. usually would require a separate install).</p>
<p>A list of the most important benefits for SQL Lite from the provider link at the bottom of this post:</p>
<blockquote>
<p>SQLite is a small C library that
implements a self-contained,
embeddable, zero-configuration SQL
database engine. Features include:</p>
<ul>
<li>Zero-configuration - no setup or
administration needed.</li>
<li>Implements most of SQL92. (Features
not supported)</li>
<li>A complete database is stored in a
single disk file.</li>
<li>Database files can be freely shared
between machines with different byte
orders.</li>
<li>Supports databases up to 2 terabytes
(2^41 bytes) in size.</li>
<li>Small code footprint: less than 30K
lines of C code, less than 250KB
code space (gcc on i486)</li>
<li>Faster than popular client/server
database engines for most common
operations.</li>
<li>Simple, easy to use API.</li>
<li>Self-contained: no external
dependencies.</li>
<li>Sources are in the public domain.
Use for any purpose.</li>
</ul>
</blockquote>
<p>Since you're using WPF I can assume you're using at least .NET 3.0. I would then recommend going to .NET 3.5 SP1 (sames size as .NET 3.5 but includes a bunch of performance improvements) which includes LINQ.</p>
<p>When using SQLite, however, you would want to use the following SQLite Provider which should provide LINQ support: <a href="http://sqlite.phxsoftware.com/" rel="noreferrer">An open source ADO.NET provider for the SQLite database engine</a></p>
|
<p>I would agree that SQLite is the way to go.
Subsonic 2.1 now includes SQLite support as well.</p>
| 9,271
|
<p>I need to test if a file is a shortcut. I'm still trying to figure out how stuff will be set up, but I might only have it's path, I might only have the actual contents of the file (as a byte[]) or I might have both.</p>
<p>A few complications include that I it could be in a zip file (in this cases the path will be an internal path)</p>
|
<p>Shortcuts can be manipulated using the COM objects in SHELL32.DLL. </p>
<p>In your Visual Studio project, add a reference to the COM library "Microsoft Shell Controls And Automation" and then use the following:</p>
<pre><code>/// <summary>
/// Returns whether the given path/file is a link
/// </summary>
/// <param name="shortcutFilename"></param>
/// <returns></returns>
public static bool IsLink(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
return folderItem.IsLink;
}
return false; // not found
}
</code></pre>
<p>You can get the actual target of the link as follows:</p>
<pre><code> /// <summary>
/// If path/file is a link returns the full pathname of the target,
/// Else return the original pathnameo "" if the file/path can't be found
/// </summary>
/// <param name="shortcutFilename"></param>
/// <returns></returns>
public static string GetShortcutTarget(string shortcutFilename)
{
string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
if (folderItem.IsLink)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return shortcutFilename;
}
return ""; // not found
}
</code></pre>
|
<p>Check the extension? (.lnk)</p>
| 40,021
|
<p>We have an issue related to a Java application running under a (rather old) FC3 on an Advantech POS board with a Via C3 processor. The java application has several compiled shared libs that are accessed via JNI.</p>
<p>Via C3 processor is supposed to be i686 compatible. Some time ago after installing Ubuntu 6.10 on a MiniItx board with the same processor, I found out that the previous statement is not 100% true. The Ubuntu kernel hanged on startup due to the lack of some specific and optional instructions of the i686 set in the C3 processor. These instructions missing in C3 implementation of i686 set are used by default by GCC compiler when using i686 optimizations. The solution, in this case, was to go with an i386 compiled version of Ubuntu distribution.</p>
<p>The base problem with the Java application is that the FC3 distribution was installed on the HD by cloning from an image of the HD of another PC, this time an Intel P4. Afterwards, the distribution needed some hacking to have it running such as replacing some packages (such as the kernel one) with the i386 compiled version.</p>
<p>The problem is that after working for a while the system completely hangs without a trace. I am afraid that some i686 code is left somewhere in the system and could be executed randomly at any time (for example after recovering from suspend mode or something like that).</p>
<p>My question is: </p>
<ul>
<li>Is there any tool or way to find out at what specific architecture extensions a binary file (executable or library) requires? <code>file</code> does not give enough information.</li>
</ul>
|
<p>The unix.linux <code>file</code> command is great for this. It can generally detect the target architecture and operating system for a given binary (and has been maintained on and off since 1973. wow!)</p>
<p>Of course, if you're not running under unix/linux - you're a bit stuck. I'm currently trying to find a java based port that I can call at runtime.. but no such luck.</p>
<p>The unix <code>file</code> command gives information like this:</p>
<pre><code>hex: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.17, not stripped
</code></pre>
<p>More detailed information about the details of the architecture are hinted at with the (unix) <code>objdump -f <fileName></code> command which returns:</p>
<pre><code>architecture: arm, flags 0x00000112:
EXEC_P, HAS_SYMS, D_PAGED
start address 0x0000876c
</code></pre>
<p>This executable was compiled by a gcc cross compiler (compiled on an i86 machine for the ARM processor as a target) </p>
|
<p>Expanding upon @Hi-Angel's answer I found an easy way to check the bit width of a static library:</p>
<pre><code>readelf -a -W libsomefile.a | grep Class: | sort | uniq
</code></pre>
<p>Where <code>libsomefile.a</code> is my static library. Should work for other ELF files as well.</p>
| 33,613
|
<p>I was wondering how other developers begin refactoring. What is your first step? How this process (refactoring) differ if you refactor code which is not yours? Do you write tests while refactoring?</p>
|
<ol>
<li>do not refactor anything non-trivial that does not already have unit tests</li>
<li>write unit tests, then refactor</li>
<li>refactor small pieces and re-run the tests frequently</li>
<li>stop refactoring when the code is DRY<sup>*</sup> clean</li>
</ol>
<p><sup>*</sup> DRY = Don't Repeat Yourself</p>
|
<p>First step: Identify a <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">code smell.</a></p>
<p>Second step: Consider alternative implementations and what the trade offs are and which do I accept in terms of which is "better."</p>
<p>Third step: Implement better solution.</p>
<p>This doesn't differ if the code is mine or not as sometimes I may go back over code I wrote months or years ago and it'll look like code from someone else. I may write tests if I'm making new methods or there aren't adequate tests to the code, IMO.</p>
| 25,167
|
<p>by default is a class:</p>
<ol>
<li>private ?</li>
<li>internal ? </li>
<li>sealed ?</li>
</ol>
|
<p>internal</p>
<p>see:
<a href="http://msdn.microsoft.com/en-us/library/ms173121.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms173121.aspx</a></p>
|
<blockquote>
<p>Top-level types, which are not nested into other types, can only have internal or public accessibility. The default accessibility for these types is <strong>internal</strong>.</p>
</blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/ba0a1yw2(VS.71).aspx" rel="nofollow noreferrer">Accessibility Levels (C#) on MSDN</a></p>
| 45,180
|
<p>I've got a local .mdf SQL database file that I am using for an integration testing project. Everything works fine on the initial machine I created the project, database, etc. on, but when I try to run the project on another machine I get the following:</p>
<p><em>System.Data.SqlClient.SqlException : A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)</em></p>
<p>I figure while I am investigating this problem I would also ask the community here to see if someone has already overcome this.</p>
<p>The exception occurs when I instantiate the new data context. I am using LINQ-to-SQL.</p>
<pre><code>m_TransLogDataContext = new TransLogDataContext ();
</code></pre>
<p>Let me know if any additional info is needed. Thanks.</p>
|
<p>I'm going to answer my own question as I have the solution.</p>
<p>I was relying on the automatic connection string which had an incorrect "AttachDbFilename" property set to a location that was fine on the original machine but which did not exist on the new machine.</p>
<p>I'm going to have to dynamically build the connection string since I want this to run straight out of source control with no manual tweaking necessary.</p>
<p>Easy enough.</p>
|
<p>That because your application have more than one setting to database, try to "Find All" on your solution by search your connection name
likes</p>
<p></p>
<p>I'm using "<strong>EnergyRetailSystemConnectionString</strong>" or you can search by your database name</p>
| 15,431
|
<p>Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device.</p>
<p>And it goes without saying that it needs to be smaller than XML, and faster to parse.</p>
<hr>
<p>The data would be something akin to SVG.</p>
|
<p>You might want to take a look at <a href="http://en.wikipedia.org/wiki/WBXML" rel="noreferrer">wbxml</a> (Wireless Binary XML) it is optimized for size, and often used on mobile phones, but it is not optimized for parsing speed.</p>
|
<p>It very much depends on the target device. If you have JSR172 available, then you are done with the parsing, the runtime does it for you. And XML is mainly about making your own format. As was alredy stated if your goal is performance, than XML is probably not the best way to go and you will end up doing some binary stuff.</p>
| 3,003
|
<p>I am working on a project that requires the parsing of log files. I am looking for a fast algorithm that would take groups messages like this:</p>
<blockquote>
<p>The temperature at P1 is 35F.</p>
<p>The temperature at P1 is 40F.</p>
<p>The temperature at P3 is 35F.</p>
<p>Logger stopped.</p>
<p>Logger started.</p>
<p>The temperature at P1 is 40F.</p>
</blockquote>
<p>and puts out something in the form of a printf():</p>
<pre><code>"The temperature at P%d is %dF.", Int1, Int2"
{(1,35), (1, 40), (3, 35), (1,40)}
</code></pre>
<p>The algorithm needs to be generic enough to recognize almost any data load in message groups.</p>
<p>I tried searching for this kind of technology, but I don't even know the correct terms to search for.</p>
|
<p>I think you might be overlooking and missed fscanf() and sscanf(). Which are the opposite of fprintf() and sprintf().</p>
|
<p>@John: I think that the question relates to an algorithm that actually recognises patterns in log files and automatically "guesses" appropriate format strings and data for it. The <code>*scanf</code> family can't do that on its own, it can only be of help once the patterns have been recognised in the first place.</p>
| 3,121
|
<p>What type of exception is caught by the beanshell catch(ex): Exception or Throwable?.</p>
<p>Example:</p>
<pre><code>try {
.... } catch (ex) { }
</code></pre>
|
<p>That loosely typed catch will catch everything "<a href="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html" rel="nofollow noreferrer">Throwable</a>." That will include <a href="http://java.sun.com/javase/6/docs/api/java/lang/Error.html" rel="nofollow noreferrer">Errors</a>, <a href="http://java.sun.com/javase/6/docs/api/java/lang/Exception.html" rel="nofollow noreferrer">Exceptions</a> and their myriad children. You can easily confirm this with:</p>
<pre><code>try {
new Throwable("Something Exceptional");
} catch (ex) {
System.err.println(ex.getMessage());
}
</code></pre>
|
<p>Throwable is a superclass (essentially) of Exception--anything that Exception catches will also be caught by Throwable. In general usage they are the same, you rarely (if ever) see other throwable types.</p>
| 28,180
|
<p>In the image, <a href="https://i.stack.imgur.com/fcPgL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fcPgL.png" alt="enter image description here"></a>there is an object circled in blue on the anet a8 printer that I need to buy a replacement of, however, I can not find it online, please help.</p>
|
<p>This is the throat block for direct drive extrusion, Anet8 is a cheap clone of Prusa printers, so it's easy to find parts for Anet printers. </p>
<p>This is one extruder kit that may help your needs, <a href="https://es.aliexpress.com/store/product/1Set-3D-Printer-makerbot-MK8-Extruder-Aluminum-extrusion-Frame-Block-DIY-Kit-for-Reprap-i3/1962255_32715673423.html?spm=a219c.search0104.3.269.W5yIqd&ws_ab_test=searchweb0_0,searchweb201602_2_10152_10065_10151_10344_10068_10345_10342_10343_10173_10340_10341_10541_10562_10084_10083_10307_10060_10155_5680016_10154_10056_10055_10539_10537_10312_10059_10313_10314_10534_10533_100031_10103_10073_10102_10557_10142_10107,searchweb201603_25,ppcSwitch_5&btsid=79693e48-00b7-4029-908d-314b37935569&algo_expid=64c2aa2b-e9de-4722-8ecb-0ba5542f5a86-34&algo_pvid=64c2aa2b-e9de-4722-8ecb-0ba5542f5a86" rel="nofollow noreferrer">1 Unidades Impresora 3D makerbot MK8 Extrusora De extrusión de Aluminio Bloque de DIY Kit para Reprap i3</a>. This is a link for Aliexpress - of course there are other dealers.</p>
|
<p>Like @ZuOverture said the name of this component is the filament drive. Most of the manufactures sell the whole extrusion device already assembled, to avoid mismatches between the components of the extrusion device. If your device is somehow damaged, and without possibilities to be used in the printer the easiest solution would be to buy a new extrusion device. If financially is unfeasible for you, you may have the option to generate the 3D model of this piece and share the file to someone who could print this component for you. </p>
| 740
|
<p>Anybody have any good FizzBuzz type questions that are not <em>the</em> FizzBuzz problem?</p>
<p>I am interviewing someone and FB is relatively well known and not that hard to memorize, so my first stop in a search for ideas is my new addiction SO.</p>
|
<p>I've seen a small list of relatively simple programming problems used to weed out candidates, just like FizzBuzz. Here are some of the problems I've seen, in order of increasing difficulty:</p>
<ol>
<li>Reverse a string</li>
<li>Reverse a sentence ("bob likes dogs" -> "dogs likes bob")</li>
<li>Find the minimum value in a list</li>
<li>Find the maximum value in a list</li>
<li>Calculate a remainder (given a numerator and denominator)</li>
<li>Return distinct values from a list including duplicates (i.e. "1 3 5 3 7 3 1 1 5" -> "1 3 5 7")</li>
<li>Return distinct values and their counts (i.e. the list above becomes "1(3) 3(3) 5(2) 7(1)")</li>
<li>Given a string of expressions (only variables, +, and -) and a set of variable/value pairs (i.e. a=1, b=7, c=3, d=14) return the result of the expression ("a + b+c -d" would be -3).</li>
</ol>
<p>These were for Java, and you could use the standard libraries so some of them can be extremely easy (like 6). But they work like FizzBuzz. If you have a clue about programming you should be able to do most pretty quickly. Even if you don't know the language well you should at least be able to give the idea behind how to do something.</p>
<p>Using this test one of my previous bosses saw everything from people who aced it all pretty quick, to people who could do most pretty quick, to one guy who couldn't answer a single one after a half hour.</p>
<p>I should also note: he let people use his computer while they were given these tasks. They were specifically instructed that they <em>could</em> use Google and the like.</p>
|
<p>How about:
I want to use a single integer to store multiple values. Describe how that would work.</p>
<p>If they don't have a clue about bit masks and operations, they probably can't solve other problems.</p>
| 14,343
|
<p>I'm not a great fan of duplicating effort. I do find, however, that there are benefits to tracking agile iteration progress on both a physical card wall and an online "calculator" (Excel, some scrum tools) or an online card wall (e.g. Mingle).</p>
<p>I find that a physical card wall in the team space provides a visceral kind of connection to the status of the cards... and that moving a card physically when you finish something provides a level of satisfaction that can't be duplicated online. I can feel the card... and people can see me walk up to the wall to move something.</p>
<p>Online tools provide great capabilities to share remotely and to calculate progress (e.g. in Mingle, you can use the built-in tools to automatically calculate burn-ups or burn-downs from the real data, saving lots of administrative time in doing those things manually).</p>
<p>I'm curious if agile practitioners maintain two tracking media like I do, and how do you present the benefits of the physical wall to those who say "I can do it online... why would I want to do it on a card wall instead?".</p>
|
<p>I feel the same. There is something very psychologically satisfying in moving a physical card around on a wall. Thinking managerially, we like stats and we like them to be automated as much as possible.</p>
<p>Perhaps you can keep both? Use the physical wall as the main daily source of information your team work from. Then, assign one person (e.g. the scrum master) to take down the live status and put it into Mingle/Excel at the end of each day.</p>
<p>As long as there is good benefit for the users to have both, then you should find both keep happening alongside each other nicely. Find out what the motivators are for each tool. For example:</p>
<p><strong>Physical wall:</strong></p>
<ul>
<li>Instant reaction</li>
<li>Quick visual</li>
<li>Physical satisfaction</li>
</ul>
<p><strong>Online records:</strong></p>
<ul>
<li>Really really useful statistics</li>
<li>People can be rewarded against the stats in there (e.g. points completed)</li>
</ul>
<p>Hope this helps.</p>
|
<p>Cross link your online and card wall.</p>
<p>Set up two way replication. Method is left as an exercise for the student.</p>
<p>Also handy to catch whiteboard content from discussions.</p>
| 25,410
|
<p>I'm trying to get started with <strong>USSD</strong>. I'm familiar with other <em>forms of SMS</em>.
Ultimately i want to use <strong>USSD</strong> as part of a real-time payment platform.</p>
<p>Thanks.</p>
|
<p>Here are some of the questions you'd like to find answers for as you proceed with your USSD plan.</p>
<p>•. How do we want the channel to work?</p>
<p>For starters, USSD is just like connection-oriented SMS communication i.e, USSD is to SMS what IM is to email. The initiation of the communication can either be USSD-PUSH ( Mobile-terminated & provider originated) or a USSD-PULL (Mobile originated & provider terminated). In your case, I believe it would probably be a mobile originated USSD pull where the mobile subscriber dials a USSD short code on his mobile to access the app.</p>
<p>•. If it is USSD-PULL... what is our short code?</p>
<p>Every app requires a separate short code. USSD shortcodes are site addresses scheme similar to the website addresses in the internet world. I am not sure what country you are from, but here in India, USSD shortcodes are owned by the mobile service providers and one needs to get the service provider to configure the right short codes for you.</p>
<p>•. Now, what is the communication interface?</p>
<p>USSD works using a connection oriented SMPP. However, USSD gateways ( service-provider owned middle-ware that relays USSD messages to and from the subscribers' mobiles, these days are capable of acting as bridges where their app interface can be over HTTP or HTTPS. In this case, I'd think you'd need HTTP or HTTPS connectivity opened between the mobile operator's gateway and your app. From then on, it is just matter of building a web-app with a text response!</p>
|
<p>I just Googled around and gathered info.</p>
<p>According to <a href="http://www.telecomspace.com/messaging-ussd.html" rel="nofollow noreferrer">Unstructured Supplementary Services Data (USSD)</a>:</p>
<blockquote>
<p>Unstructured Supplementary Services
Data (USSD) allows for the
transmission of information via a GSM
network. Contrasting with SMS, it
offers real time connection during a
session. A USSD message can be upto
182 alphanumeric characters in length.
Unstructured Supplementary Service
Data allows interactive services
between a MS and applications hosted
by the Mobile Operator. These messages
are composed of digits and the #, *
keys, and allow users to easily and
quickly get information/access
services from the Operator.</p>
<p>USSD messages are simple to form and
easy to send. User can directly enter
the ussd string and press call to send
the message. A typical USSD message
starts with a * followed by digits
which indicate an action to be
performed or are parameters. Each
group of numbers is separated by a *,
and the message is terminated with a #.
The USSD gateway in turn can interact with external applications
based on the USSD command. This allows
access to number of value added
services via USSD.</p>
</blockquote>
<ul>
<li>USSD works on all GSM handsets of Phase II or later.</li>
</ul>
<p>However, if you are writing <a href="http://discussion.forum.nokia.com/forum/showthread.php?t=145899" rel="nofollow noreferrer">Java MIDlet on a Nokia device, it does not work</a>.</p>
| 45,208
|
<p>How can the OpenFileDialog View Menu be set to Detail View?</p>
|
<p>someone did it <a href="http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx" rel="nofollow noreferrer">here</a>, with the win32 api</p>
<pre><code>DefaultViewMode:
This property lets you choose which view the OpenFileDialog should
start in; by default, it opens using the “Details view”. Here you
can specify a different default view like Icons, List, Thumbnail, Detail, etc
</code></pre>
|
<p>Quick google search reveals this:</p>
<p><a href="http://forums.microsoft.com/Forums/ShowPost.aspx?PostID=3843682&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/Forums/ShowPost.aspx?PostID=3843682&SiteID=1</a></p>
<p>In particular it suggests:</p>
<pre><code>Dim OpenFileDialog1 As New OpenFileDialog
SendKeys.Send("{tab}{tab}{tab}{tab}{tab}{right}{right}{down}{up}{enter}")
OpenFileDialog1.ShowDialog()
</code></pre>
<p>Which is bad. It futher recommends finding the handle of that dialog and sending the key presses directly to that. You would also need to be aware that the solution could quite possibly break in different versions of windows.</p>
<p>It may be useful depending on your situation (though I do feel evil for posting this!)</p>
| 44,541
|
<p>Is there a prebuilt tool that would integrate with BEA/Oracle Weblogic 10.0 and trace on a database table each call to a web service exposed by the server?</p>
<p>UPDATE: the goal is <strong>not</strong> to debug the web services (they are working well). The objective is to <strong>trace each call</strong> on a table, using an existing add-on.</p>
|
<p>This is Object-Relational Mapping, a classically hard problem. You really need a ORM tool to do this properly, or it'll drive you nuts.</p>
<p>The connection problem you refer to is one of the pitfalls, and it needs very careful optimisation and query tuning, else it'll kill performance (e.g. the N+1 SELECT problem).</p>
<p>I can't be any more specific without knowing what your application platform is - the actual DBMS used isn't really relevent to the problem.</p>
|
<p>The other option would be to use an <a href="http://en.wikipedia.org/wiki/Comparison_of_object_database_management_systems" rel="nofollow noreferrer">Object Oriented Database</a> such as db40 or Cache. It may be looking into this if performance isn't a huge concern and you are determined to store your entire object graph.</p>
| 17,599
|
<p>I have an experiment streaming up 1Mb/s of numeric data which needs to be stored for later processing.
It seems as easy to write directly into a database as to a CSV file and I would then have the ability to easily retrieve subsets or ranges.</p>
<p>I have experience of sqlite2 (when it only had text fields) and it seemed pretty much as fast as raw disk access.
Any opinions on the best current in-process DBMS for this application?</p>
<p>Sorry - should have added this is C++ intially on windows but cross platform is nice. Ideally the DB binary file format shoudl be cross platform.</p>
|
<p>If you only need to read/write the data, without any checking or manipulation done in database, then both should do it fine. Firebird's database file can be copied, as long as the system has the same endianess (i.e. you cannot copy the file between systems with Intel and PPC processors, but Intel-Intel is fine).</p>
<p>However, if you need to ever do anything with data, which is beyond simple read/write, then go with Firebird, as it is a full SQL server with all the 'enterprise' features like triggers, views, stored procedures, temporary tables, etc.</p>
<p>BTW, if you decide to give Firebird a try, I highly recommend you use IBPP library to access it. It is a very thin C++ wrapper around Firebird's C API. I has about 10 classes that encapsulate everything and it's dead-easy to use.</p>
|
<p>Depends what language you are using. If it's C/C++, TCL, or PHP, SQLite is still among the best in the single-writer scenario. If you don't need SQL access, a berkeley DB-style library might be slightly faster, like Sleepycat or gdbm. With multiple writers you could consider a separate client/server solution but it doesn't sound like you need it. If you're using Java, hdqldb or derby (shipped with Sun's JVM under the "JavaDB" branding) seem to be the solutions of choice.</p>
| 12,070
|
<p>Despite my lack of coding knowledge I managed to write a small little app in VB net that a lot of people are now using. Since I made it for free I have no way of knowing how popular it really is and was thinking I could make it ping some sort of online stat counter so I could figure out if I should port it to other languages. Any idea of how I could ping a url via vb without actually opening a window or asking to receive any data? When I google a lot of terms for this I end up with examples with 50+ lines of code for what I would think should only take one line or so, similar to opening an IE window.</p>
<p>Side Note: Would of course fully inform all users this was happening.</p>
|
<p>Just a sidenote: You should inform your users that you are doing this (or not do it at all) for privacy concerns. Even if you aren't collecting any personal data it can be considered a privacy problem. For example, when programs collect usage information, they almost always have a box in the installation process asking if the user wants to participate in an "anonymous usage survey" or something similar. What if you just tracked downloads?</p>
|
<p>.NET? Create an ASMX Web Service and set it up on your web site. Then add the service reference to your app.</p>
<p>EDIT/CLARIFICATION: Your Web Service can then store passed data into a database, instead of relying on Web Logs: Installation Id, Install Date, Number of times run, etc.</p>
| 11,569
|
<p>From kernel mode in Windows I'm able to intercept and monitor virtually all actions performed on a particular disk. When a file is opened for any purpose I get an event.</p>
<p>Now I want to trace which application that opened it. I think this should be possible but don't know how.</p>
<p>I'm using the standard file management functions in Windows Win32 API.</p>
<p>Thanks in advance.</p>
<p>/Robert</p>
|
<p><a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">Sysinternals Filemon</a> (free) does this, and better yet they describe how they did it:</p>
<blockquote>
<p>For the Windows 9x driver, the heart
of FileMon is in the virtual device
driver, Filevxd.vxd. It is dynamically
loaded, and in its initialization it
installs a file system filter via the
VxD service,
IFSMGR_InstallFileSystemApiHook, to
insert itself onto the call chain of
all file system requests. On Windows
NT the heart of FileMon is a file
system driver that creates and
attaches filter device objects to
target file system device objects so
that FileMon will see all IRPs and
FastIO requests directed at drives.
When FileMon sees an open, create or
close call, it updates an internal
hash table that serves as the mapping
between internal file handles and file
path names. Whenever it sees calls
that are handle based, it looks up the
handle in the hash table to obtain the
full name for display. If a
handle-based access references a file
opened before FileMon started, FileMon
will fail to find the mapping in its
hash table and will simply present the
handle's value instead.</p>
</blockquote>
<p>-Adam</p>
|
<p>Just use Win32 N.API to get the pid from the File handle.
It's a FAQ for 15 years...</p>
| 28,664
|
<p>What techniques can be applied effectively to improve the performance of SQL queries? Are there any general rules that apply?</p>
|
<ul>
<li>Use primary keys</li>
<li>Avoid select *</li>
<li>Be as specific as you can when building your conditional statements </li>
<li>De-normalisation can often be more efficient </li>
<li>Table variables and temporary tables (where available) will often be better than using a large source table </li>
<li>Partitioned views </li>
<li>Employ indices and constraints </li>
</ul>
|
<p>I think using SQL query analyzer would be a good start.</p>
| 6,036
|
<p>I have two drop down menus that I want populated with identical data depending on what is selected on the parent drop down menu. Right now, I am using a javascript library that populates one child drop down menu based on a parent, but I need to have two drop down menus populated simultaneously.</p>
<p>This javascript library contains a function called PrintOptions that is supposed to populate the dropdown menu when something is selected from the parent menu. I have tried calling the same function twice one for each drop down menu, but it doesn't seem to be working.</p>
<p>This is where I got the library: <a href="http://www.javascripttoolbox.com/lib/dynamicoptionlist/documentation.php" rel="nofollow noreferrer">http://www.javascripttoolbox.com/lib/dynamicoptionlist/documentation.php</a></p>
|
<p>Reading the document you list, it seems there's a section that allows you to specify multiple child components from the parent:</p>
<pre>
To create the DynamicOptionList object, pass the names of the fields that are dependent on each other, with the parent field first.
Create the object by passing field names
var dol = new DynamicOptionList("Field1","Child1","Child2");
Or create an empty object and then pass the field names
var dol = new DynamicOptionList();
dol.addDependentFields("Field1","Child1","Child2");
</pre>
<p>Instead of trying to call the function more than once, just add the 2nd child component's name to the DynamicOptionList constructor, as in the first example above. As I read the docs that means whatever happens to Child1 will also happen to Child2 when Field1 is selected.</p>
|
<p>In the event handler you have for your parent drop down, you are probably having some other code populate that child drop down. Simply add the code again, but instead reference the second drop down. That's the rough approach. There are some details and style guidance I'm leaving out, but that'll get the job done.</p>
| 18,742
|
<p>Here's an interesting problem. On a recently installed Server 2008 64bit I opened IE and through the Tools -> Options I changed the homepage to iGoogle.com. Clicked okay and then clicked the homepage button. IE crashes.</p>
<p>Now you'd think that I could just remove iGoogle as the homepage but when I open IE it immediately goes to that page and crashes on open.</p>
<p>Obviously I'd prefer to find a solution to why IE is crashing on the iGoogle page but just to get IE running again I need to remove iGoogle as the homepage. Is there anyway to do this without opening IE?</p>
|
<p>Control Panel -> Internet Options</p>
|
<p>Not sure about IE7 on Windows Server 2008, but for IE6 the start page is stored in a registry key "Start Page" in HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main.</p>
| 8,882
|
<p>I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?</p>
<pre><code>profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
profile.to_hash
end
</code></pre>
<p>If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.</p>
|
<p>Careful with the flatten approach, if search() returned nested arrays then unexpected behaviour might result.</p>
<pre><code>profiles = ProfileResource.search(params)
profiles = [profiles] if !profiles.respond_to?(:collect)
output = profiles.collect do |profile|
profile.to_hash
end
</code></pre>
|
<p>In the <code>search</code> method of the <code>ProfileResource</code> class, always return a collection of objects (usually an Array), even if it contains only one object.</p>
| 10,469
|
<p>I am trying to use C# to parse CSV. I used regular expressions to find <code>","</code> and read string if my header counts were equal to my match count.</p>
<p>Now this will not work if I have a value like:</p>
<pre><code>"a",""b","x","y"","c"
</code></pre>
<p>then my output is:</p>
<pre><code>'a'
'"b'
'x'
'y"'
'c'
</code></pre>
<p>but what I want is:</p>
<pre><code>'a'
'"b","x","y"'
'c'
</code></pre>
<p>Is there any regex or any other logic I can use for this ?</p>
|
<p>CSV, when dealing with things like multi-line, quoted, different delimiters* etc - can get trickier than you might think... perhaps consider a pre-rolled answer? I use <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="noreferrer">this</a>, and it works very well.</p>
<p>*=remember that some locales use [tab] as the C in CSV...</p>
|
<p>Well, I'm no regex wiz, but I'm certain they have an answer for this.</p>
<p>Procedurally it's going through letter by letter. Set a variable, say dontMatch, to FALSE.</p>
<p>Each time you run into a quote toggle dontMatch.</p>
<p>each time you run into a comma, check dontMatch. If it's TRUE, ignore the comma. If it's FALSE, split at the comma.</p>
<p>This works for the example you give, but the logic you use for quotation marks is fundamentally faulty - you must escape them or use another delimiter (single quotes, for instance) to set major quotations apart from minor quotations.</p>
<p>For instance,</p>
<p><code>"a", ""b", ""c", "d"", "e""</code></p>
<p>will yield bad results.</p>
<p>This can be fixed with another patch. Rather than simply keeping a true false you have to match quotes.</p>
<p>To match quotes you have to know what was last seen, which gets into pretty deep parsing territory. You'll probably, at that point, want to make sure your language is designed well, and if it is you can use a compiler tool to create a parser for you.</p>
<p>-Adam</p>
| 40,889
|
<p>I would like to start tagging my deployed binaries with the latest SVN revision number.</p>
<p>However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number.</p>
<p>Using <code>svn info</code> on the root doesn't work (it just reports the version of that directory, not files in subdirectories):</p>
<p>I was wondering if there is a shortcut using the <code>svn</code> command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)?</p>
<p>I also understand that one alternative approach is to keep a <em>version file</em> with the <code>svn:keywords</code>. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts.</p>
<p><strong>Answer</strong> I see my problem lied with not doing a proper <code>svn up</code> before calling <code>svn info</code> in the root directory:</p>
<pre><code>$ svn info
Path: .
...
Last Changed Author: fak
Last Changed Rev: 713
Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up
At revision 721.
$ svn info
Path: .
...
Revision: 721
Last Changed Author: reuben
Last Changed Rev: 721
Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
</code></pre>
|
<p>One way. When you check out the code, look at the last line of svn output:</p>
<pre><code>$ svn up
...stuff...
Updated to revision 66593.
</code></pre>
<p>A more direct way:</p>
<pre><code>$ svn info
Path: .
URL: https://svn.example.com/svn/myproject/trunk
Repository Root: https://svn.example.com/svn/
Repository UUID: d2a7a951-c712-0410-832a-9abccabd3052
Revision: 66593
Node Kind: directory
Schedule: normal
Last Changed Author: bnguyen
Last Changed Rev: 66591
Last Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)
</code></pre>
|
<p>This is ridiculous but <code>svn info</code> or <code>svnversion</code> wont take into consideration subdirectories; it's a feature called working 'Mixed Revisions' - I call it torture. I just needed to find the latest 'revision' of the live codebase and the hacked way below worked for me - it might take a while to run:</p>
<pre><code>repo_root# find ./ | xargs -l svn info | grep 'Revision: ' | sort
...
Revision: 86
Revision: 86
Revision: 89
Revision: 90
root@fairware:/home/stage_vancity#
</code></pre>
| 8,011
|
<p>atoi() is giving me this error:</p>
<pre><code>
error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
</code></pre>
<p>from this line:
int pid = atoi( token.at(0) );
where token is a vector</p>
<p>how can i go around this?</p>
|
<p>token.at(0) is returning a single char, but atoi() is expecting a string (a pointer to a char.) Either convert the single character to a string, or to convert a single digit char into the number it represents you can usually<sup>*</sup> just do this:</p>
<pre><code>int pid = token.at(0) - '0';
</code></pre>
<p><sup>* The exception is when the charset doesn't encode digits 0-9 in order which is extremely rare.</sup></p>
|
<pre><code>stringstream ss;
ss << token.at(0);
int pid = -1;
ss >> pid;
</code></pre>
<p>Example:</p>
<pre><code>#include <iostream>
#include <sstream>
#include <vector>
int main()
{
using namespace std;
vector<char> token(1, '8');
stringstream ss;
ss << token.at(0);
int pid = -1;
ss >> pid;
if(!ss) {
cerr << "error: can't convert to int '" << token.at(0) << "'" << endl;
}
cout << pid << endl;
return 0;
}
</code></pre>
| 23,543
|
<p>I'm pivoting data in MS SQL stored procedure. Columns which are pivoted are dynamically created using stored procedure parameter (for exampe: "location1,location2,location3,") so number of columns which will be generated is not known. Output should look like (where locations are taken from stored procedure parameter):</p>
<blockquote>
<p>OrderTime | Location1 | Location2 |
Location3</p>
</blockquote>
<p>Any chance that this can be used in LINQ to SQL? When I dragged this procedure to dbml file it shows that this procedure returns int type.</p>
<p>Columns I use from <code>log_sales</code> table are:</p>
<ul>
<li>Location (various location which I'm pivoting),</li>
<li>Charge (amount of money)</li>
<li>OrderTime</li>
</ul>
<p>Stored procedure:</p>
<pre><code>CREATE PROCEDURE [dbo].[proc_StatsDay] @columns NVARCHAR(64) AS
DECLARE @SQL_PVT1 NVARCHAR(512), @SQL_PVT2 NVARCHAR(512), @SQL_FULL NVARCHAR(4000);
SET @SQL_PVT1 = 'SELECT OrderTime, ' + LEFT(@columns,LEN(@columns)-1) +'
FROM (SELECT ES.Location, CONVERT(varchar(10), ES.OrderTime, 120),ES.Charge
FROM dbo.log_sales ES
) AS D (Location,OrderTime,Charge)
PIVOT (SUM (D.Charge) FOR D.Location IN
(';
SET @SQL_PVT2 = ') )AS PVT
ORDER BY OrderTime DESC';
SET @SQL_FULL = @SQL_PVT1 + LEFT(@columns,LEN(@columns)-1) +
@SQL_PVT2;
EXEC sp_executesql @SQL_FULL, N'@columns NVARCHAR(64)',@columns = @columns
</code></pre>
<p>In dbml <code>designer.cs</code> file my stored procedure part of code:</p>
<pre><code>[Function(Name="dbo.proc_StatsDay")]
public int proc_EasyDay([Parameter(DbType="NVarChar(64)")] string columns)
{
IExecuteResult result = this.ExecuteMethodCall(this,((MethodInfo)MethodInfo.GetCurrentMethod())), columns);
return ((int)(result.ReturnValue));
}
</code></pre>
|
<p>Assuming truly dire dynamic need, you could use <a href="http://msdn.microsoft.com/en-us/library/bb361109.aspx" rel="nofollow noreferrer">DataContext.ExecuteQuery</a></p>
<p>Just whip up a type that will cover the result space (the property names must match the column names in the query):</p>
<pre><code>public class DynamicResult
{
public DateTime OrderDate {get;set;}
public decimal? Location1 {get;set;}
public decimal? Location2 {get;set;}
//..
public decimal? Location100 {get;set;}
}
</code></pre>
<p>Then call</p>
<pre><code>IEnumerable<DynamicResult> result =
myDataContext.ExecuteQuery<DynamicResult>(commandString, param1);
</code></pre>
|
<p>You can create your linq object for access after your returned dataset.</p>
<p>But would that really be of any use. Linq are usefull for typesafe calls and not dynamic results. You would not know what to look for compile time.</p>
| 33,441
|
<p>I'd like to create a sparse file such that all-zero blocks don't take up actual disk space until I write data to them. Is it possible?</p>
|
<p>As in other Unixes, it's a feature of the filesystem. Either the filesystem supports it for ALL files or it doesn't. Unlike Win32, you don't have to do anything special to make it happen. Also unlike Win32, there is no performance penalty for using a sparse file.</p>
<p>On MacOS, the default filesystem is HFS+ which does <em>not</em> support sparse files.</p>
<p><strong>Update:</strong> MacOS used to support UFS volumes with sparse file support, but that has been removed. None of the currently supported filesystems feature sparse file support.</p>
|
<p>If you want portability, the last resort is to write your own access function so that you manage an index and a set of blocks. </p>
<p>In essence you manage a single file as the OS manages the disk keeping the chain of the blocks that are part of the file, the bitmap of allocated/free blocks etc.</p>
<p>Of course this will lead to a non optimized and slower access, I would reccomend this apprach only if the requirement to save space is absolutely critical and you have enough time to write a robust set of access functions.</p>
<p>And even in that case, I would first investigate if your problem is in need of a different solution. Probably you should store your data differently?</p>
| 22,512
|
<p>On my blog, I want to display the all the posts from the last month. But if that is less than 10 posts, I want to show the ten most recent posts (in other words, there should never be less than 10 posts on the front page). I am wondering if there is a way to do this in a single query?</p>
<p>Currently, I first run this query:</p>
<pre><code>select count(*) from posts where timestamp > ($thirty_days_ago)
order by timestamp desc
</code></pre>
<p>If that count is greater than or equal to 10:</p>
<pre><code>select * from posts where timestamp > ($thirty_days_ago)
order by timestamp desc
</code></pre>
<p>Otherwise:</p>
<pre><code>select * from posts order by timestamp desc limit 10
</code></pre>
<p>But this requires me to run two queries. Is there a more efficient way to do this with a single query? (I'm using MySQL.)</p>
|
<pre><code>(SELECT * FROM posts
WHERE `timestamp` >= NOW() - INTERVAL 30 DAY)
UNION
(SELECT * FROM posts
ORDER BY `timestamp` DESC
LIMIT 10);
</code></pre>
<p><strong>edit:</strong> Re @doofledorfer's comment: I ran this on my test database, and it worked fine. I tried comparing <code>timestamp</code> to a date literal as well as the constant expression as shown in the above query, but it made no difference to the optimization plan. Of course I was using a trivial amount of data, and the optimization plan may be different if there are thousands of rows.</p>
<p>In any case, the OP was asking how to get the correct result in a single query, <em>not</em> how to make the execution plan optimal. This is a UNION query after all, and is bound to incur a filesort.</p>
<pre><code>+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
| 1 | PRIMARY | posts | ALL | timestamp | NULL | NULL | NULL | 20 | Using where |
| 2 | UNION | posts | ALL | NULL | NULL | NULL | NULL | 20 | Using filesort |
| NULL | UNION RESULT | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | |
+------+--------------+------------+------+---------------+------+---------+------+------+----------------+
</code></pre>
|
<p><strong>Idea1</strong>: do a query to fetch always the posts for this month. Then do a cycle, counting the number of posts fetched. If, and only if, this number is less than 10, do the second query.</p>
<p><strong>Idea 2</strong>: Why don't you <em>cache</em> your first query (<a href="http://code.google.com/appengine/" rel="nofollow noreferrer">Google App Engine</a>, for example, has Caching APIs)? The number of posts for this month is unlikely to change often, so you'd remove the need for the first query in most of the cases.</p>
| 45,093
|
<p>So, I'll be getting my T-Mobile G1 within a month or so, and I'm excited to start developing for it.</p>
<p>Has anyone started using it yet? Is there a dev wiki or anything set up for it yet?</p>
|
<ul>
<li>Google's android groups </li>
</ul>
<p>This is probably the best place to go. However, a good search on google will most likely take you to one of these discussion anyways. Here, you can discuss about your difficulties possibly with the core developers too.</p>
<ul>
<li>Anddev.org </li>
</ul>
<p>They're probably the most active groups so far (as of Sun, April 20, 2008) online regarding the development and the interactive community around android. Apart from the official google groups and the irc channel at #android on irc.freenode.net, they're probably the best place to go or ask questions.</p>
<ul>
<li><a href="http://davanum.wordpress.com/" rel="noreferrer">http://davanum.wordpress.com/</a> </li>
</ul>
<p>Development halted here but still some rather interesting things that have been done.</p>
<ul>
<li>phandroid.com</li>
</ul>
<p>Didn't see much development things</p>
<ul>
<li>Androforge.net</li>
</ul>
<p>A nice little repository, not a lot of files though.</p>
<p>I pulled it from my development wiki which hasn't been updated for a while but best of luck working with Android ... and T-Mobile G1</p>
|
<p>Google has set up a google code for it and has let a limited number of devs start playing arround with it.</p>
| 17,400
|
<p>I need to build full-text search functionality into our knowledge base system using C#. How do I start? </p>
|
<p>For example from Lucene:</p>
<p><a href="http://lucene.apache.org/java/docs/" rel="nofollow noreferrer">http://lucene.apache.org/java/docs/</a></p>
<p>C# port is here <a href="http://incubator.apache.org/lucene.net/" rel="nofollow noreferrer">http://incubator.apache.org/lucene.net/</a></p>
<p>You should also read something about the the information retrieval, and you can start with this one : <a href="https://rads.stackoverflow.com/amzn/click/com/020139829X" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/Modern-Information-Retrieval-Ricardo-Baeza-Yates/dp/020139829X</a></p>
|
<p>You will probably need an indexing facility if your text base is non trivial.</p>
| 37,414
|
<p>Okay, my dilemma is this. I have an admin page that I use to get a summary of the day's submissions to one of my sites. This sumamry page pulls data from several tables, some of which store the actual media data, others store the website urls, ids and owners, and another table stores the day-to-day stats to calculate in/out ratios for each domain. </p>
<p>This admin page has a main query, which pulls the actual media data, which looks like this (simplified):</p>
<pre><code>SELECT
content.con_catid,
content.con_posttime,
content.con_url,
content.con_id,
content.con_title,
categories.name,
users.username,
users.user_id,
FROM content
LEFT JOIN categories
ON (content.con_catid = categories.id)
LEFT JOIN users
ON (content.con_poster = users.user_id)
WHERE con_status = 0 ORDER BY con_posttime
</code></pre>
<p>Fairly straight forward. Then, this is where it gets messy. For each time it loops the mysql_fetch_array statement (to output each content item), I also run these 2 queries:</p>
<pre><code>SELECT count(con_id) as pending FROM content WHERE con_poster = '$this_userid' AND con_status = 0
SELECT count(con_id) as approved FROM content WHERE con_poster = '$this_userid' AND con_status = 2
</code></pre>
<p>These get the number of pending, and approved items for each user who owns the submission (which is listed next to each submission. </p>
<p>And then there is the killer, which adds a lot of time to page execution time, since it also has to be repeated for each row of the initial query.</p>
<pre><code>SELECT website_url,
website_id,
website_shady,
COALESCE(sum(dstats_hits),0)+website_in_ballast as total_in,
COALESCE(sum(dstats_hits_out),0)+website_out_ballast as total_out,
sum(dstats_hits_out_paid) as total_paid,
website_in_ballast,
website_out_ballast
FROM websites
LEFT JOIN domain_stats ON (websites.website_id = domain_stats.dstats_domid)
WHERE website_id IN (SELECT website_id FROM websites WHERE website_userid = $this_userid)
GROUP BY website_url
</code></pre>
<p>Is there any way I can merge the latter 3 queries int he first one? Because now.... if I have 100 items in the queue, thats 301 queries (401 if you include the sub-query), which take a while to generate the page. </p>
|
<p>SWFUpload</p>
<p><a href="http://demo.swfupload.org/v220beta3/simpledemo/index.php" rel="noreferrer">http://demo.swfupload.org/v220beta3/simpledemo/index.php</a></p>
<p><a href="http://swfupload.org/" rel="noreferrer">http://swfupload.org/</a></p>
<p>Javascript and Flash, there's no post-back :) and there's .NET implementations available on the site.</p>
|
<p>There is no such thing as a ajax file upload. The components that you see either use flash swfupload or a hidden iframe that they post a form to that give the impression it is happening in an ajax manner. There are many plugins avaiable to help you do this. My favourite is <a href="http://jquery.webunity.nl/" rel="nofollow noreferrer">this</a> that uses jquery and swfupload</p>
| 43,643
|
<p>What is the standard way of incorporating helper/utility functions in Obj-C classes?</p>
<p>I.e. General purpose functions which are used throughout the application and called by more than 1 class.</p>
<p>Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?</p>
|
<p>I would group similar functions as static methods in a helper class. These can then be called using the classname rather the instance name. Static methods are defined with a + instead of the usual -.</p>
<p>like so:</p>
<pre><code>@interface HelperClass: superclassname {
// instance variables - none if all methods are static.
}
+ (void) helperMethod: (int) parameter_varName;
@end
</code></pre>
<p>This would be called like so.</p>
<pre><code>[HelperClass helperMethod: 10 ];
</code></pre>
<p>As this is static you do not init/alloc the class. This has the advantage of clearly grouping like Helper functions. You could use standalone C functions but as your Application gets larger it can become a right mess! Hope this helps.</p>
<p>Tony</p>
|
<p>There are a number of options for this in Objective-C. First, since Obj-C is a strict superset of C, you can define all your library functions in a separate module (source file) and happily call them from any Obj-C object/code you already have. If you create an obj-c source file (.m file) you can then call back into/use objects.</p>
<p>If your generic functions are logically manipulating other, established objects (for instances, operates on an NSString), you can use categories to graph your functions on already existing classes (where that makes sense).</p>
<p>Finally, as Tony points out, you can create classes with static methods (although I like this option the least, personally). I tend to use a mix of one an two... adding categories where appropriate and using standard functions for others. I generally only make a new class where it makes sense to design a class.</p>
| 47,994
|
<p>We are working on a Java EE Web Application, and the people from marketing need some really detailed stats for our site. Something similar to Google Analytics, gathering the user's information, and their navigation through the site (where they come from, what they click, where they go, etc.).</p>
<p>Depending on a third party service like Analytics is not an option.</p>
<p>They would also like to get this information presented in graphs and stuff, which is not that hard since once the data is gathered, it's just about the right queries and the way we display it.</p>
<p>Not wanting to re invent the wheel, do you know if there's any API, framework or other kind of libraries to add to the project for this goal?</p>
|
<p>1) You could use a log analyser to analyse the web server logs - with Tomcat you need to install a module that does this, I've forgotten the name.</p>
<p>2) Create a table in your database called user_journey or similar. Inside you can log all the relevant details of each hit. Then in your root servlet, or the equivalent for the framework you use, add an entry to this table with the details you require - tracking by session_id, user_id, page_hit, and so on.</p>
<p>[3) Create aggregate tables to generate your monthly and yearly statistics once-only]</p>
<p>3) Use BIRT to present the analysis of these database tables.</p>
|
<p>1) You could use a log analyser to analyse the web server logs - with Tomcat you need to install a module that does this, I've forgotten the name.</p>
<p>2) Create a table in your database called user_journey or similar. Inside you can log all the relevant details of each hit. Then in your root servlet, or the equivalent for the framework you use, add an entry to this table with the details you require - tracking by session_id, user_id, page_hit, and so on.</p>
<p>[3) Create aggregate tables to generate your monthly and yearly statistics once-only]</p>
<p>3) Use BIRT to present the analysis of these database tables.</p>
| 44,394
|
<p>Is it possible in <code>PHP (as it is in C++)</code> to declare a <code>class method</code> OUTSIDE the <code>class definition?</code></p>
|
<p>No, as of PHP 5.2. However, you may use <code>__call</code> magic method to forward call to arbitrary function or method.</p>
<pre><code>class A {
public function __call($method, $args) {
if ($method == 'foo') {
return call_user_func_array('bar', $args);
}
}
}
function bar($x) {
echo $x;
}
$a = new A();
$a->foo('12345'); // will result in calling bar('12345')
</code></pre>
<p>In PHP 5.4 there is support for <em>traits</em>. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits <a href="http://www.stefan-marr.de/artikel/rfc-traits-for-php.html" rel="nofollow noreferrer">here</a>.</p>
|
<p>No it is not posible. if you define function/method outside class construct it becomes global function.</p>
| 9,699
|
<p>I am wrestling with a php 5.2.6 problem. An api we use returns dates in this format DDMMYYYYHHMM. Exactly that format, fixed length, no delimiters. However, in my experimentation, this format seems to break strptime, which returns a false (fail) when I feed it a date in this format. It can reproduced, at least on my system, with this example:</p>
<pre><code>$format = "%d%m%Y%H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true);
</code></pre>
<p>If I add any character between the date and the time, it works, even a space. So, this DOES work:</p>
<pre><code>$format = "%d%m%Y %H%M"; echo print_r(strptime(strftime($format,1225405967),$format),true);
</code></pre>
<p>Am I missing something obvious?</p>
<p>edit: further to this and owing to the results indicated by the comments, this seems to be platform specific. I can reproduce it on the Macs running OSX Leopard in the office but the Linux boxes parse it fine. I assume it is a bug or idiosyncrasy of the strptime in the underlying C library in the *nix of OSX.</p>
|
<p>This function is locale-dependent. Have you tried setting different locale? (see <code>setlocale()</code>)</p>
|
<p>Nothing obvious since both versions work fine in PHP 5.2.0. I can't readily check 5.2.6 at the moment, though. That will have to wait until I get home.</p>
| 31,708
|
<p>I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?</p>
<p>Very specifically, what would the method "SomeMethod" have to be that would produce the output below?</p>
<pre><code>string unformattedXml;
string formattedXml;
unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);
Console.WriteLine(formattedXml);
</code></pre>
<p>Output:</p>
<pre><code><?xml version="1.0"?>
<book id="123">
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
|
<pre><code>string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
</code></pre>
<p>Output:</p>
<pre><code><book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
<p>The Xml Declaration isn't output by ToString(), but it is by Save() ...</p>
<pre><code> XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));
</code></pre>
<p>Output:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
|
<p>Is the string valid XML? Do you mean how can you convert an XML string into an XML document? If so, do this:</p>
<pre><code>XmlDocument xml = new XmlDocument();
xml.LoadXml( YourString );
</code></pre>
| 23,686
|
<p>We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like:</p>
<p>// The function to alter the server side state object and set the selected node for the case tree.</p>
<pre><code>function JSMethod(caseId, url)
{
Sample.XYZ.Method(param1, param2, OnMethodReturn);
}
function OnMethodReturn(result)
{
var sessionExpiry = CheckForSessionExpiry(result);
var error = CheckForErrors(result);
... process result
}
</code></pre>
<p>And on the server side in the ".asmx.cs" file:
namespace Sample</p>
<pre><code>[ScriptService]
class XYZ : WebService
{
[WebMethod(EnableSession = true)]
public string Method(string param1, string param2)
{
if (SessionExpired())
{
return sessionExpiredMessage;
}
.
.
.
}
}
</code></pre>
<p>The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked,
then the following error is obtained:
Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed.</p>
<p>This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd":</p>
<pre><code>function Sys$Net$WebServiceProxy$invoke
{
.
.
.
{
// In debug mode, if no error was registered, display some trace information
var error;
if (result && errorObj) {
// If we got a result, we're likely dealing with an error in the method itself
error = result.get_exceptionType() + "-- " + result.get_message();
}
else {
// Otherwise, it's probably a 'top-level' error, in which case we dump the
// whole response in the trace
error = response.get_responseData();
}
// DevDiv 89485: throw, not alert()
throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error));
}
</code></pre>
<p>So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem</p>
|
<p>You have a callback method (OnMethodReturn) specified in the WebMethod call, but not an error handler method. You need to create one and pass it into as you do the callback method. Then you can handle your failed WebMethod calls in there.</p>
|
<p>try this one...use "static"</p>
<pre><code>[WebMethod(EnableSession = true)]
public static string Method(string param1, string param2)
</code></pre>
| 47,980
|
<p>I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:</p>
<pre><code> | BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
</code></pre>
<p>What are A, B, and C?</p>
|
<p>There is no clear answer to your question. It depends entirely how your data is organized.</p>
<p>Something to keep in mind:</p>
<p>Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small.</p>
<p>Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see <a href="https://web.archive.org/web/20180111010801/http://www.thomasdiewald.com/blog/?p=1488" rel="noreferrer">Octree vs BVH</a>) (archived from <del><a href="http://thomasdiewald.com/blog/?p=1488" rel="noreferrer">original</a></del>)</p>
<p>The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs <strong>much</strong> better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent).</p>
<p>BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing.</p>
<p>A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation.</p>
<p>That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer.</p>
<p>All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well.</p>
|
<p>Usually these things don't have a clear-cut answer. I would suggest that A,B, and C are the result of a function of the size of your space and the amount of stuff you are differentiating.</p>
| 12,501
|
<p>I am working on a site laid out with <code>div</code>s. I am having trouble with one in particular: the training photo <code>div</code>.</p>
<p>If you go to <a href="http://php.wmsgroup.com/eofd6.org/education.html" rel="nofollow noreferrer">http://php.wmsgroup.com/eofd6.org/education.html</a> you'll see a photo underneath the left nav that has dropped down. I want it to snap right under that nav box. I have tried several different things with its positioning as well as the main content <code>div</code>s positioning and I can't get it right.</p>
<p>Any help would be appreciated. The link to the style sheet is <a href="http://php.wmsgroup.com/eofd6.org/in.css" rel="nofollow noreferrer">http://php.wmsgroup.com/eofd6.org/in.css</a></p>
<p>Thanks!</p>
|
<p>Float #content right, not left.</p>
|
<p>Can't you change the markup to include the #training_photo div in the #nav div?</p>
| 27,490
|
<p>I wish to create an online system to track some things (e.g., a database with children, where each child has 1 or more visits from doctors). I want the users to be able to enter data as well as search for it, especially from mobile devices. So, this is a custom mobile online DB app of modest but non-zero size.</p>
<p>I've looked into DabbleDB and Zoho Creator, looking for an easy solution that will have low-cost maintenance.</p>
<p>Although I feel my app is not too complicated, I find that if I want to do something slightly out of their mainstream, I hit walls. For example, dealing with many-to-many relationships, or with 100K records, or doing an involved mathematical calculation for a field.</p>
<p>What are people's experiences with these online DB apps? Should I keep pushing ahead, or just write a custom app myself?</p>
|
<p>I also tried building a simple web application with Zoho Creator and got so frustrated that I am now looking for a different solution. I consider Zoho Creator to be at a point right now suitable for educational purposes but I would not consider using it for a functional application.</p>
|
<p>I think this systems not bad,but they are paid. Their price impresses!
Use free application, example <a href="http://mytaskhelper.com" rel="nofollow noreferrer">mytaskhelper</a>
Thanks</p>
| 42,286
|
<p>I want something that can check if a string is <code>"SELECT"</code>, <code>"INSERT"</code>, etc. I'm just curious if this exists.</p>
|
<p>Easy enough to add : </p>
<pre><code> HashSet<String> sqlKeywords =
new HashSet<String>(Arrays.asList(
new String[] { ... cut and paste a list of sql keywords here .. }));
</code></pre>
|
<p>why not start with <a href="http://www.novicksoftware.com/UDFofWeek/Vol2/T-SQL-UDF-Vol-2-Num-29-udf_SQL2K_IsKeywordBIT.htm" rel="nofollow noreferrer">this stored procedure</a> and modify it to suit your needs, possibly even convert it to Java using the hashmap as Steve suggested.</p>
<p>Personally I like the idea of a stored procedure because different databases may have different keywords so it seems elegant to have the database pass judgement</p>
| 24,669
|
<p>I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the tag and for a page header. When I tried to do this with two tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?</p>
|
<p>Title is actually an attribute on content pages, so you do something like:</p>
<pre><code><%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %>
</code></pre>
<p>on the content page. To get that into a header, on the master page just render the page title:</p>
<pre><code><h1><%= this.Page.Title %></h3>
</code></pre>
|
<p>I see that someone has just provided a (far) better answer to this specific problem. You could use the solution below if you have a master page that has the same content in multiple places (excluding the title).</p>
<p>The best solution I can come up with is the following:</p>
<p>Add an <code>asp:Label</code> for the page title and another one for the second position you want the text to appear (use two different id's, for example: <code>pageTitle</code> and <code>sameTitle</code>)</p>
<p>Add a method to your master page:</p>
<pre><code>public void SetPageTitle(string title)
{
pageTitle.Text = title;
sameTitle.Text = title;
}
</code></pre>
<p>On your content page, call the master page method. If your content page has a master page, it has a property called <code>Master</code>. You can now call the <code>SetPageTitle</code> method from your content page <code>PageLoad</code> method:</p>
<pre><code>((MyMasterPage) Master).SetPageTitle("My content page");
</code></pre>
<p>You can also use the <code>MasterType</code> directive in your master page, check <a href="http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx" rel="nofollow noreferrer">here</a> for more info. This way you get a strongly-typed <code>Master</code> property that you do not have to cast:</p>
<pre><code>Master.SetPageTitle("My content page");
</code></pre>
<p>Regards,<br>
Ronald</p>
| 18,081
|
<p>Given this class</p>
<pre><code>class Foo
{
// Want to find _bar with reflection
[SomeAttribute]
private string _bar;
public string BigBar
{
get { return this._bar; }
}
}
</code></pre>
<p>I want to find the private item _bar that I will mark with a attribute. Is that possible? </p>
<p>I have done this with properties where I have looked for an attribute, but never a private member field.</p>
<p>What are the binding flags that I need to set to get the private fields?</p>
|
<p>Use <code>BindingFlags.NonPublic</code> and <code>BindingFlags.Instance</code> flags</p>
<pre><code>FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
</code></pre>
|
<p>If your .Net framework is greater than 4.5. You can use GetRuntimeFields method.</p>
<p>This method returns all fields that are defined on the specified type, including inherited, non-public, instance, and static fields.</p>
<p><a href="https://learn.microsoft.com/en-us/dotnet/api/system.reflection.runtimereflectionextensions.getruntimefields?view=net-6.0" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/api/system.reflection.runtimereflectionextensions.getruntimefields?view=net-6.0</a></p>
<pre><code>var foo = new Foo();
var fooFields = foo.GetType().GetRuntimeFields()
</code></pre>
| 12,148
|
<p>I'm writing a sample console service host and I want to plug into WCF stack to be able to print a message to console when new message arrives, even if it won't get processed by the service at the moment (because service is working on previous calls).
This is based on my assumption that messages arriving get queued by the WCF, is that correct?</p>
<p>Additionally, I'm using netTcpBinding if this is important. </p>
|
<p>PyString_Decode does this:</p>
<pre><code>PyObject *PyString_Decode(const char *s,
Py_ssize_t size,
const char *encoding,
const char *errors)
{
PyObject *v, *str;
str = PyString_FromStringAndSize(s, size);
if (str == NULL)
return NULL;
v = PyString_AsDecodedString(str, encoding, errors);
Py_DECREF(str);
return v;
}
</code></pre>
<p>IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString_AsDecodedString, rather than PyString_AsDecodedObject. PyString_AsDecodedString does PyString_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.</p>
<p>I believe you'll need to do two calls - but you can use PyString_AsDecodedObject rather than calling the python "decode" method. Something like:</p>
<pre><code>#include <Python.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char c_string[] = { (char)0x93, 0 };
PyObject *py_string, *py_unicode;
Py_Initialize();
py_string = PyString_FromStringAndSize(c_string, 1);
if (!py_string) {
PyErr_Print();
return 1;
}
py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace");
Py_DECREF(py_string);
return 0;
}
</code></pre>
<p>I'm not entirely sure what the reasoning behind PyString_Decode working this way is. A <a href="http://mail.python.org/pipermail/python-dev/2001-May/014547.html" rel="nofollow noreferrer">very old thread on python-dev</a> seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.</p>
|
<p>You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?</p>
<p>Just use <code>PyString_FromString</code>:</p>
<pre><code>char *cstring;
PyObject *pystring = PyString_FromString(cstring);
</code></pre>
<p>That's all. Now you have a Python <code>str()</code> object. See docs here: <a href="https://docs.python.org/2/c-api/string.html" rel="nofollow noreferrer">https://docs.python.org/2/c-api/string.html</a></p>
<p>I'm a little bit confused about how to specify "str" or "unicode." They are quite different if you have non-ASCII characters. If you want to decode a C string <strong>and</strong> you know exactly what character set it's in, then yes, <code>PyString_DecodeString</code> is a good place to start.</p>
| 26,260
|
<p>When scripting in bash or any other shell in *NIX, while running a command that will take more than a few seconds, a progress bar is needed.</p>
<p>For example, copying a big file, opening a big tar file.</p>
<p>What ways do you recommend to add progress bars to shell scripts?</p>
|
<p>You can implement this by overwriting a line. Use <code>\r</code> to go back to the beginning of the line without writing <code>\n</code> to the terminal.</p>
<p>Write <code>\n</code> when you're done to advance the line.</p>
<p>Use <code>echo -ne</code> to:</p>
<ol>
<li>not print <code>\n</code> and</li>
<li>to recognize escape sequences like <code>\r</code>.</li>
</ol>
<p>Here's a demo:</p>
<pre><code>echo -ne '##### (33%)\r'
sleep 1
echo -ne '############# (66%)\r'
sleep 1
echo -ne '####################### (100%)\r'
echo -ne '\n'
</code></pre>
<p>In a comment below, puk mentions this "fails" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).</p>
|
<p>To make a tar progress bar</p>
<pre><code>tar xzvf pippo.tgz |xargs -L 19 |xargs -I@ echo -n "."
</code></pre>
<p>Where "19" is the number of files in the tar divided the length of the intended progress bar.
Example: the .tgz contains 140 files and you'll want a progress bar of 76 ".", you can put -L 2.</p>
<p>You'll need nothing else.</p>
| 29,451
|
<p>I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.</p>
<p>If I pass in a char-array of characters from <strong>0</strong> to <strong>J</strong>, and set length to 5, I want results like <em>00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ</em>.</p>
<p>Here is the base, please help me expand:</p>
<pre><code>protected void Main()
{
char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
BruteForce(chars, 5);
}
private void BruteForce(char[] chars, int length)
{
// for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
// (when passed in length is 5)
// TODO: Implement code...
}
</code></pre>
|
<p>This isn't <em>quite</em> a duplicate of <a href="https://stackoverflow.com/questions/207889/recursion-instead-of-multi-loops">"recursion instead of multi-loops"</a> but it's pretty close. I'll write up a solution if this doesn't help you.</p>
<p>EDIT: Here's a non-recursive solution. The recursive one is slightly harder to return an <code>IEnumerable<string></code> from, but returning an iterator gives a nice interface IMO :)</p>
<pre><code>private static IEnumerable<string> GetAllMatches(char[] chars, int length)
{
int[] indexes = new int[length];
char[] current = new char[length];
for (int i=0; i < length; i++)
{
current[i] = chars[0];
}
do
{
yield return new string(current);
}
while (Increment(indexes, current, chars));
}
private static bool Increment(int[] indexes, char[] current, char[] chars)
{
int position = indexes.Length-1;
while (position >= 0)
{
indexes[position]++;
if (indexes[position] < chars.Length)
{
current[position] = chars[indexes[position]];
return true;
}
indexes[position] = 0;
current[position] = chars[0];
position--;
}
return false;
}
</code></pre>
|
<p>Google for permutations.</p>
<p>If however you are just dealing with that 'hex' range, just do the following:</p>
<pre><code>for (int i = 0; i < (1 << 24); i++)
string s = i.ToString("X6");
</code></pre>
| 28,317
|
<p>I am working on an implementation for RSS feeds for a collaboration platform.
Say there are several thousands of different collaboration rooms where users can share information, and each needs to publish an RSS feed with news, changes, etc...</p>
<p>Using a plain servlet (i.e. <a href="http://www.site.com/RSSServlet/?id=roomID" rel="nofollow noreferrer">http://www.site.com/RSSServlet/?id=roomID</a>) is costly, every time an RSS client is calling the servlet (and this will happen say every 10 minutes for each user registered to an RSS feed on one of the thousand of rooms) this will trigger the entire servlet lifecycle, which is costly.</p>
<p>On the other hand, keeping a static XML file on the disk for each of the thousands of rooms is costly as well, in terms of hard disk space as well as IO operations...</p>
<p>One more limitation - using already existing frameworks might not be an option...</p>
<p>So, how would you implement RSS feeds in a Java envoronment?</p>
|
<p>You say that a new http request to your servlet "will trigger the entire servlet lifecycle", which as Alexander has already pointed out, isn't exactly true. It will simply trigger another method call to your <code>doGet()</code> or <code>doPost()</code> methods. </p>
<p>I think what you mean to say is that if you have a <code>doGet</code>/<code>doPost</code> method which contains code to build the data needed for the RSS feed from scratch, then each request triggers this fetching of data over and over again.</p>
<p>If this is your concern, and you are ruling static content out, simply modify your Servlet <code>doGet</code>/<code>doPost</code> method to cache the RSS content that you would otherwise return, so that handling each request does not mean re-fetching all of the data all over again.</p>
<p>For example</p>
<pre><code>public void doGet(HttpServletRequest request, HttpServletResponse response) {
//build the objects you need for the RSS response
Room room = getRoom(request.getParameter("roomid"));
//loadData();
//moreMethodCalls();
out.println( createRssContent(...) );
}
</code></pre>
<p>becomes</p>
<pre><code>Map rssCache;
public void doGet(HttpServletRequest request, HttpServletResponse response) {
//Map is initialized in the init() method or somewhere else
String roomId = request.getParameter("roomid");
String rssDocument = rssCache.get(roomId);
if (rssDocument == null) {
//build the objects you need for the RSS response
Room room = getRoom(roomId);
//loadData();
//moreMethodCalls();
rssDocument = createRssContent(...);
rssCache.put(roomId, rssDocument);
}
out.println( rssDocument );
}
</code></pre>
<p>If you only want to store items in a "cache" for a certain amount of time you can use one of a dozen different caching frameworks, but the idea here is that you don't reconstruct the entire object graph necessary for your RSS response with each http request. If I am reading your original question right then I think that this is what you hoping to accomplish.</p>
|
<p>You should try the <a href="https://rome.dev.java.net/" rel="nofollow noreferrer">ROME</a> framework. It is excellent for RSS.</p>
| 23,756
|
<p>We are using log4net (replacing nLog) in our Asp.Net web application. nLog had a useful feature that would allow us to create a log file per user - which is helpful for organizing and locating the log statements.</p>
<p>Does anyone have any ideas on how to do this with log4net?</p>
|
<p>Instead of logging to a file, think about logging to a database table and have the user id part of the logged data. This way you can do selects against the table based on the user (or users) and see only their data. Probably also want to log the session id, too, to make session based queries easy.</p>
|
<p>I just log to a single file and then use a nice log viewing program like <a href="http://www.log-expert.de/" rel="nofollow noreferrer">LogExpert</a> to filter by username etc when I want to see a particular user's session.</p>
<p><img src="https://i.stack.imgur.com/9T6xS.jpg" alt="enter image description here"></p>
| 39,538
|
<p>How can I present a control to the user that allows him/her to select a directory?</p>
<p>There doesn't seem to be any native .net controls which do this?</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx" rel="noreferrer">FolderBrowserDialog class</a> is the best option.</p>
|
<p>or even more better, you can put this code in a class file</p>
<pre><code>using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
internal class OpenFolderDialog : IDisposable {
/// <summary>
/// Gets/sets folder in which dialog will be open.
/// </summary>
public string InitialFolder { get; set; }
/// <summary>
/// Gets/sets directory in which dialog will be open if there is no recent directory available.
/// </summary>
public string DefaultFolder { get; set; }
/// <summary>
/// Gets selected folder.
/// </summary>
public string Folder { get; private set; }
internal DialogResult ShowDialog(IWin32Window owner) {
if (Environment.OSVersion.Version.Major >= 6) {
return ShowVistaDialog(owner);
} else {
return ShowLegacyDialog(owner);
}
}
private DialogResult ShowVistaDialog(IWin32Window owner) {
var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
uint options;
frm.GetOptions(out options);
options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
frm.SetOptions(options);
if (this.InitialFolder != null) {
NativeMethods.IShellItem directoryShellItem;
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
frm.SetFolder(directoryShellItem);
}
}
if (this.DefaultFolder != null) {
NativeMethods.IShellItem directoryShellItem;
var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
frm.SetDefaultFolder(directoryShellItem);
}
}
if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
NativeMethods.IShellItem shellItem;
if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
IntPtr pszString;
if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
if (pszString != IntPtr.Zero) {
try {
this.Folder = Marshal.PtrToStringAuto(pszString);
return DialogResult.OK;
} finally {
Marshal.FreeCoTaskMem(pszString);
}
}
}
}
}
return DialogResult.Cancel;
}
private DialogResult ShowLegacyDialog(IWin32Window owner) {
using (var frm = new SaveFileDialog()) {
frm.CheckFileExists = false;
frm.CheckPathExists = true;
frm.CreatePrompt = false;
frm.Filter = "|" + Guid.Empty.ToString();
frm.FileName = "any";
if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
frm.OverwritePrompt = false;
frm.Title = "Select Folder";
frm.ValidateNames = false;
if (frm.ShowDialog(owner) == DialogResult.OK) {
this.Folder = Path.GetDirectoryName(frm.FileName);
return DialogResult.OK;
} else {
return DialogResult.Cancel;
}
}
}
public void Dispose() { } //just to have possibility of Using statement.
}
internal static class NativeMethods {
#region Constants
public const uint FOS_PICKFOLDERS = 0x00000020;
public const uint FOS_FORCEFILESYSTEM = 0x00000040;
public const uint FOS_NOVALIDATE = 0x00000100;
public const uint FOS_NOTESTFILECREATE = 0x00010000;
public const uint FOS_DONTADDTORECENT = 0x02000000;
public const uint S_OK = 0x0000;
public const uint SIGDN_FILESYSPATH = 0x80058000;
#endregion
#region COM
[ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
internal class FileOpenDialogRCW { }
[ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig()]
uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOptions([In] uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetOptions(out uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Close([MarshalAs(UnmanagedType.Error)] uint hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint ClearClientData();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem {
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
#endregion
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
}
</code></pre>
<p>And use it like this</p>
<pre><code>using (var frm = new OpenFolderDialog()) {
if (frm.ShowDialog(this)== DialogResult.OK) {
MessageBox.Show(this, frm.Folder);
}
}
</code></pre>
| 3,287
|
<p>We have a painfully slow report.I added a Response.flush and it seems a great deal better. What are some of the caveats of using this method.</p>
|
<p>If Response.Buffer is not set to true, then you'll get a run-time error. Also, If the Flush method is called on an ASP page, the server does not honor Keep-Alive requests for that page.</p>
<p>You'll also want to look out if you're using a table-based design as it won't render in some browsers until the entire table is sent.. meaning if you have 10,000 rows, the user would still need to wait for all 10,000 rows to transfer before they'd actually see them.</p>
|
<p>Response.flush could be useful to send to the browser the report's header.. then display a "loading message", then your report process and you flush the report, then execute a little piece of javascript to hide the "loading" message.</p>
<p>This way you will let your users know that something is hapenning so they won't press STOP BACK or just close the window as they may otherwise be tempted.</p>
<p>Also, I've played a lot with what browser render what table and IE seems to be the only one that doesn't render a table unless the tag is received. Which means that all rows could gradually appears in other browser but not in IE.</p>
| 16,396
|
<p>Is there a way to combine Enums in VB.net?</p>
|
<p>I believe what you want is a flag type enum.</p>
<p>You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword.</p>
<p>Like this:</p>
<pre><code><Flags()> _
Enum CombinationEnums As Integer
HasButton = 1
TitleBar = 2
[ReadOnly] = 4
ETC = 8
End Enum
</code></pre>
<p><strong>Note:</strong> The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set.</p>
<p>Combine the desired flags using the Or keyword:</p>
<pre><code>Dim settings As CombinationEnums
settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly
</code></pre>
<p>This sets TitleBar and Readonly into the enum</p>
<p>To check what's been set:</p>
<pre><code>If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then
Window.TitleBar = True
End If
</code></pre>
|
<p>If you taking about using enum flags() there is a good article <a href="http://www.codeguru.com/vb/sample_chapter/article.php/c12963" rel="nofollow noreferrer" title="VB flags">here</a>.</p>
| 8,287
|
<p>Working on big, high loaded project I got the problem that already described in billion of topics on forums and blog, but there is no solution that will help in my case. Here is the story.</p>
<p>I have the HTML code of banner, I don't know what is the code. Sometimes it's plain HTML, but sometimes it's <code><script></code> tag with document.write inside it with <code><script></code> tag that has src to doubleclick network in it.</p>
<p>So we have: script > document.write > script(doubleclick).</p>
<p>doubleclick network, as you may know, use document.write too and most of the time they give flash banners that need to load one more js file.</p>
<p>So after all we have: script > document.write > script(doubleclick) > document.write > script > ...</p>
<p>This works good when you place it in HTML directly. Page rendering 1 part, load banner1, keep rendering page, load banner2, finalizing page rendering.</p>
<p>But right now I need to render page first and only after that load banners.
As banner use document.write I need to load it before window.onload event (note: after window.onload document.write will rewrite whole document.)</p>
<p>What I've done:</p>
<p>In the head section I have an banners object(real namespace kind of huge :)), with property scope.</p>
<p>When page rendering and banner code is meet I place the code of the banner into the scope and put <code><div id="bannerPlaceHolder"+id></div></code> -- so here I will need to put banner content later on</p>
<p>Page rendered and before <code></body></code> tag I put <code><script>banners.load()</script></code> banners.load method do this for each item in scope array:</p>
<pre><code>document.write('<div id="codeHolder'+id+'">');
document.write(bannerCode);
document.write('</div>');
</code></pre>
<p>And only after this I have <code>window.onload()</code> event that do this:</p>
<p>take all banners codeHolders and node-by-node append it nodes from codeHolder to placeHolder, so in result I have loaded banners after rendering the page and banners are on the right places.</p>
<p>All is perfect except IE, it load any js script that was putted in DOM dynamically in asynchron way, so document.write inside doubleclick scripts append nodes to the end of the document and not in my codeHolder nodes. As usual it's only in IE.</p>
<p>I will be really appreciated to anyone who may know the solution.</p>
|
<p>You need <a href="http://github.com/iamnoah/writeCapture" rel="nofollow noreferrer">writeCapture.js</a> (full disclosure: I'm the author.) All bets are off with 3rd party scripts. Today they use <code>document.write</code> to generate some specific HTML, but tomorrow they could change it and any simple hacks based on replacing <code>document.write</code> will need to be updated. writeCapture takes care of that. Your usage would be something like:</p>
<pre><code>$('#bannerPlaceHolder').writeCapture().html('<script type="text/javascript" src="http://doubleclick.net/bannerCode.js"></script>');
</code></pre>
<p>The library can handle any arbitrary depth of script tags and does just fine with interspersed HTML. It also has a standalone build if you don't use jQuery.</p>
|
<p>perhaps you could use the property innerHTML:
document.getElementById("x").innerHTML=".................";</p>
<p>Or you could you the DOM: CreateElement and AppendChild</p>
| 40,738
|
<p>Is there a nice place for learning the JVM bytecode instruction set. The specification perhaps and maybe some tutorials?</p>
<p>I ask because I would like to design a toy language and a compiler for it that generates JVM bytecode.</p>
<p>Thanks for your knowledge and perhaps googling. </p>
|
<p>A good reference for Java bytecode specification is the <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/" rel="nofollow noreferrer">The Java Virtual Machine Specification</a>.</p>
<p>See <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html" rel="nofollow noreferrer">Chapter 4. The class File Format</a> and <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html" rel="nofollow noreferrer">Chapter 6. The Java Virtual Machine Instruction Set</a>.</p>
|
<p>This is a bit more specialized, but <a href="http://www.infoq.com/presentations/click-fast-bytecodes-funny-languages" rel="nofollow noreferrer">here</a> is an on-line presentation on how to optimize generated bytecode for running on the JVM. It was presented at the recent <a href="http://openjdk.java.net/projects/mlvm/jvmlangsummit/" rel="nofollow noreferrer">JVM Languages Summit</a> conferences. InfoQ has <a href="http://www.infoq.com/JVMLanguageSummit" rel="nofollow noreferrer">a collection of presentations</a> from that conference which might be of help to someone wanting to bring up a language on the JVM (or to see what's already been done).</p>
| 46,698
|
<p>First off, there's a bit of background to this issue available on my blog:</p>
<ul>
<li><a href="http://www.codebork.com/coding/2008/06/25/message-passing-a-plug-framework.html" rel="nofollow noreferrer">http://www.codebork.com/coding/2008/06/25/message-passing-a-plug-framework.html</a></li>
<li><a href="http://www.codebork.com/coding/2008/07/31/message-passing-2.html" rel="nofollow noreferrer">http://www.codebork.com/coding/2008/07/31/message-passing-2.html</a> </li>
</ul>
<p>I'm aware that the descriptions aren't hugely clear, so I'll try to summarise what I'm attempting as best I can here. The application is a personal finance program. Further background on the framework itself is available at the end of this post.</p>
<p>There are a number of different types of plug-in that the framework can handle (e.g., accounts, export, reporting, etc.). However, I'm focussing on one particular class of plug-in, so-called data plug-ins, as it is this class that is causing me problems. I have one class of data plug-in for accounts, one for transactions, etc.</p>
<p>I'm midway through a vast re-factoring that has left me with the following architecture for data plug-ins:</p>
<ul>
<li>The data plug-in object (implementing intialisation, installation and plug-in metadata) [implements <code>IDataPlugin<FactoryType></code>] </li>
<li>The data object (such as an account) [implements, e.g., <code>IAccount</code>] </li>
<li>A factory to create instances of the data object [implements, e.g., <code>IAccountFactory</code>]</li>
</ul>
<p>Previously the data object and the plug-in object were combined into one, but this meant that a new transaction plug-in had to be instantiated for each transaction recorded in the account which caused a number of problems. Unfortunately, that re-factoring has broken my message passing. The data object implements <code>INotifyPropertyChanged</code>, and so I've hit a new problem, and one that I'm not sure how to work around: the plug-in object is registering events with the message broker, but it's the data objects that actually fire the events. This means that <strong>the subscribing plug-in currently has to subscribe to each created account, transaction, etc.!</strong> This is clearly not scalable. </p>
<p>As far as I can tell at the moment I have two possible solutions:</p>
<ol>
<li>Make the data plug-in object a go-between for the data-objects and message broker, possibly batching change notifications. I don't like this because it adds another layer of complexity to the messaging system that I feel I should be able to do without. </li>
<li>Junk the current event-based implementation and use something else that's more easily manageable (in-memory WCF?!).</li>
</ol>
<p>So I guess I'm really asking: </p>
<ol>
<li>How would you solve this problem?</li>
<li>What potential solutions do you think I've overlooked?</li>
<li>Is my approach even vaguely on-track/sensible?! :-)</li>
</ol>
<p>As you will be able to tell from the dates of the blog posts, some variant of this problem has been taxing me for quite a long time now! As such, any and all responses will be greatly appreciated. </p>
<p>The background to the framework itself is as follows: </p>
<blockquote>
<p>My plug-in framework consists of three main components: a plug-in broker, a preferences manager and a message broker. The plug-in broker does the bread-and-butter plug-in stuff: discovering and creating plug-ins. The preferences manager manages user preferences for the framework and individual plug-ins, such as which plug-ins are enabled, where data should be saved, etc. Communication is via publish/subscribe, with the message broker sitting in the middle, gathering all published message types and managing subscriptions. The publish/subscribe is currently implemented via the .NET <code>INotifyPropertyChanged</code> interface, which provides one event called <code>PropertyChanged</code>; the message broker builds a list of all plug-ins implementing <code>INotifyPropertyChanged</code> and subscribes other plug-ins this event. The purpose of the message passing is to allow the account and transaction plug-ins to notify the storage plug-ins that data has changed so that it may be saved. </p>
</blockquote>
|
<p>This is my understanding of your question: You have a plugin object that may have to listen for events on x data objects - you don't want to subscribe to the event on each data object though. I'm assuming that several plugins may want to listen to events on the same data object.</p>
<p>You could create a session type object. Each plugin listens for events on the session object. The data object no longer raises the event - it calls the session object to raise the event (one of the parameters would have to be the data object raising the event).</p>
<p>That means that your plugins only have to subscribe to one event, but they get the event from all data objects.</p>
<p>On the other hand, if only one plugin will ever listen to a data object at a time, why not just have the data object call the plugin directly?</p>
|
<p>It's early yet, but have you considered trying to use <a href="http://www.codeplex.com/MEF" rel="nofollow noreferrer">MEF</a> instead of rolling your own?</p>
| 7,363
|
<p>I've been thinking about this problem for a while and have yet to come up with any stable/elegant ideas.</p>
<p>I know with MyISAM tables, you can get the table def update time but thats not so true with InnoDB and I've found its not even reliable to look at the .frm file for an idea of when the definition might have been modified.... nevermind if the dataset has been changed.</p>
<p>I had an idea of every 30 minutes mysqldumping the contents of a schema, breaking that apart with an AWK script, then diffing that to the last version... but that seems a little excessive and could be a problem if the dataset involved is large.</p>
|
<p>If you run <code>mysqldump -d</code> it only dumps the schema:</p>
<pre><code>[gary.richardson@server ~]$ mysqldump -d -u root mysql user
-- MySQL dump 10.11
--
-- Host: localhost Database: mysql
-- ------------------------------------------------------
-- Server version 5.0.45
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`Host` char(60) collate utf8_bin NOT NULL default '',
`User` char(16) collate utf8_bin NOT NULL default '',
`Password` char(41) character set latin1 collate latin1_bin NOT NULL default '',
`Select_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Insert_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Update_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Delete_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Create_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Drop_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Reload_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Shutdown_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Process_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`File_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Grant_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`References_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Index_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Alter_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Show_db_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Super_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Create_tmp_table_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Lock_tables_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Execute_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Repl_slave_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Repl_client_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Create_view_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Show_view_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Create_routine_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Alter_routine_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`Create_user_priv` enum('N','Y') character set utf8 NOT NULL default 'N',
`ssl_type` enum('','ANY','X509','SPECIFIED') character set utf8 NOT NULL default '',
`ssl_cipher` blob NOT NULL,
`x509_issuer` blob NOT NULL,
`x509_subject` blob NOT NULL,
`max_questions` int(11) unsigned NOT NULL default '0',
`max_updates` int(11) unsigned NOT NULL default '0',
`max_connections` int(11) unsigned NOT NULL default '0',
`max_user_connections` int(11) unsigned NOT NULL default '0',
PRIMARY KEY (`Host`,`User`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Users and global privileges';
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2008-10-02 20:06:38
</code></pre>
<p>Then you could do your parsing.</p>
<p>There's another solution to your problem, but takes discipline. You can add a COMMENT field to columns and tables:</p>
<pre><code>CREATE TABLE example (
name varchar(32) COMMENT='Name of a person'
) COMMENT='example table';
</code></pre>
<p>I like to put a version number in there. You can tie that into your RCS:</p>
<pre><code>CREATE TABLE example (
name varchar(32) COMMENT='Name of a person'
) COMMENT='VERSION=1.2.3 example table';
</code></pre>
|
<p>Yeah, it's tough. That's why I use innodb. It's easier to do dump/import, we even put the schemas under VC.</p>
| 19,831
|
<p><em><flavor> I want to create a spelling test program for my grade schoolers that would let them enter and record their spelling words then test them on them through out the week.</flavor></em></p>
<p>What's a good Delphi API with which I could select a recording device, capture and save sound files, then play them back?</p>
<p>I'm also toying with doing the same project in C#, so C# Sound capture/playback API recommendations would also be appreciated.</p>
|
<p>An alternative to recording would be to use the MS Speech API with C#, enter the words via keyboard, and have it state what was keyed in.</p>
<p>Just a thought... Good luck on your app -- it sounds like a really cool program!</p>
|
<p>Why not use the TMediaPlayer that comes with Delphi (in the System Tab of the Palette)?<br>
It can record and play wave files very easily</p>
| 17,033
|
<p>I need to do some simple timezone calculation in mod_perl. DateTime isn't an option. What I need to do is easily accomplished by setting $ENV{TZ} and using localtime and POSIX::mktime, but under a threaded MPM, I'd need to make sure only one thread at a time was mucking with the environment. (I'm not concerned about other uses of localtime, etc.)</p>
<p>How can I use a mutex or other locking strategy to serialize (in the non-marshalling sense) access to the environment? The <a href="http://perl.apache.org/docs/2.0/api/APR/ThreadMutex.html" rel="nofollow noreferrer">docs</a> I've looked at don't explain well enough how I would create a mutex for just this use. Maybe there's something I'm just not getting about how you create mutexes in general.</p>
<p>Update: yes, I am aware of the need for using Env::C to set TZ.</p>
|
<p>(repeating what I said over at PerlMonks...)</p>
<pre><code>BEGIN {
my $mutex;
sub that {
$mutex ||= APR::ThreadMutex->new( $r->pool() );
$mutex->lock();
$ENV{TZ}= ...;
...
$mutex->unlock();
}
}
</code></pre>
<p>But, of course, lock() should happen in a c'tor and unlock() should happen in a d'tor except for one-off hacks.</p>
<p>Update: Note that there is a race condition in how $mutex is initialized in the subroutine (two threads could call that() for the first time nearly simultaneously). You'd most likely want to initialize $mutex before (additional) threads are created but I'm unclear on the details on the 'worker' Apache MPM and how you would accomplish that easily. If there is some code that gets run "early", simply calling that() from there would eliminate the race.</p>
<p>Which all suggests a much safer interface to APR::ThreadMutex:</p>
<pre><code>BEGIN {
my $mutex;
sub that {
my $autoLock= APR::ThreadMutex->autoLock( \$mutex );
...
# Mutex automatically released when $autoLock destroyed
}
}
</code></pre>
<p>Note that autoLock() getting a reference to undef would cause it to use a mutex to prevent a race when it initializes $mutex.</p>
|
<p>If you're using apache 1.3, then you shouldn't need to resort to mutexes. Apache 1.3 spawns of a number of worker processes, and each worker executes a single thread. In this case, you can write:</p>
<pre><code>{
local $ENV{TZ} = whatever_I_need_it_to_be();
# Do calculations here.
}
</code></pre>
<p>Changing the variable with <code>local</code> means that it reverts back to the previous value at the end of the block, but is still passed into any subroutine calls made from within that block. It's almost certainly what you want. Since each process has its own independent environment, you won't be changing the environment of other processes using this technique.</p>
<p>For apache 2, I don't know what model it uses with regards to forks and threads. If it keeps the same approach of forking off processes and having a single thread each, you're fine.</p>
<p>If apache 2 uses honest to goodness real threads, then that's outside my area of detailed knowledge, but I hope another lovely stackoverflow person can provide assistance.</p>
<p>All the very best,</p>
<pre><code>Paul
</code></pre>
| 15,119
|
<p>I've been led to believe that for single variable assignment in T-SQL, <code>set</code> is the best way to go about things, for two reasons:</p>
<ul>
<li>it's the ANSI standard for variable assignment</li>
<li>it's actually faster than doing a SELECT (for a single variable)</li>
</ul>
<p>So...</p>
<pre><code>SELECT @thingy = 'turnip shaped'
</code></pre>
<p>becomes</p>
<pre><code>SET @thingy = 'turnip shaped'
</code></pre>
<p>But how fast, is <em>fast</em>? Am I ever really going to notice the difference?</p>
|
<p>SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc.</p>
<p>Here is a sample script, with the number of runs set to 1:</p>
<pre><code>SET NOCOUNT ON
DECLARE @runs int
DECLARE @i int, @j int
SET @runs = 1
SET @i = 0
SET @j = 0
DECLARE @dtStartDate datetime, @dtEndDate datetime
WHILE @runs > 0
BEGIN
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SET @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SELECT @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS
SET @runs = @runs - 1
END
</code></pre>
<p>RESULTS:</p>
<p>Run #1:</p>
<p>SET_MILLISECONDS </p>
<p>5093</p>
<p>SELECT_MILLISECONDS </p>
<p>5186</p>
<p>Run #2:</p>
<p>SET_MILLISECONDS </p>
<p>4876</p>
<p>SELECT_MILLISECONDS </p>
<p>5466</p>
<p>Run #3:</p>
<p>SET_MILLISECONDS </p>
<p>4936</p>
<p>SELECT_MILLISECONDS </p>
<p>5453</p>
<p>Run #4:</p>
<p>SET_MILLISECONDS </p>
<p>4920</p>
<p>SELECT_MILLISECONDS </p>
<p>5250</p>
<p>Run #5:</p>
<p>SET_MILLISECONDS </p>
<p>4860</p>
<p>SELECT_MILLISECONDS </p>
<p>5093</p>
<p><strong>Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.</strong></p>
<p>Here is a 10-run result:</p>
<p>SET_MILLISECONDS </p>
<p>5140</p>
<p>SELECT_MILLISECONDS </p>
<p>5266</p>
<p>SET_MILLISECONDS </p>
<p>5250</p>
<p>SELECT_MILLISECONDS </p>
<p>5466</p>
<p>SET_MILLISECONDS </p>
<p>5220</p>
<p>SELECT_MILLISECONDS </p>
<p>5280</p>
<p>SET_MILLISECONDS </p>
<p>5376</p>
<p>SELECT_MILLISECONDS </p>
<p>5280</p>
<p>SET_MILLISECONDS </p>
<p>5233</p>
<p>SELECT_MILLISECONDS </p>
<p>5453</p>
<p>SET_MILLISECONDS </p>
<p>5343</p>
<p>SELECT_MILLISECONDS </p>
<p>5423</p>
<p>SET_MILLISECONDS </p>
<p>5360</p>
<p>SELECT_MILLISECONDS </p>
<p>5156</p>
<p>SET_MILLISECONDS </p>
<p>5686</p>
<p>SELECT_MILLISECONDS </p>
<p>5233</p>
<p>SET_MILLISECONDS </p>
<p>5436</p>
<p>SELECT_MILLISECONDS </p>
<p>5500</p>
<p>SET_MILLISECONDS </p>
<p>5610</p>
<p>SELECT_MILLISECONDS </p>
<p>5266</p>
|
<p>Take a look at the "execution plan", it should tell you the cost of each line of your statement</p>
| 22,999
|
<p>I've tried this, but it doesn't work:</p>
<pre><code>col * format a20000
</code></pre>
<p>Do I really have to list every column specifically? That is a huge pain in the arse.</p>
|
<p>Never mind, figured it out:</p>
<pre><code>set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
</code></pre>
<p>Which I found by:</p>
<pre><code>show all
</code></pre>
<p>And looking for some option that seemed relevant.</p>
|
<pre class="lang-sql prettyprint-override"><code>set WRAP OFF
set PAGESIZE 0
</code></pre>
<p>Try using those settings.</p>
| 22,797
|
<p>I need assistance finding a delivery method that best fulfills the following requirements:</p>
<ul>
<li>We wish to deliver a single file to my clients.</li>
<li>Clients should be able to launch this file from the operating system shell - much like running an '.exe' on Windows.</li>
<li>After being launched, the program/script should be able to display a window with HTML content. this may be done using a stand alone program, a runtime or by running within a browser.</li>
<li>We need the ability to embed a resource within the delivered file, such as an mp3 file, which i can later extract programmatically.</li>
<li>Optimally, the solution should run on Windows, Mac and Linux machines. Less than perfect cross-platform interoperability is acceptable, but we want as broad a penetration as possible.</li>
<li>Clients should not need to pre-install anything (unless it is done transparently), pre-configure anything, or approve any thing for this to happen.</li>
</ul>
<p>For example:</p>
<ul>
<li>We could use a regular executable file, written in C++ to do this, but it will not be cross-platform.</li>
<li>We could use a sliverlight XAP file, an adobe Flex file or a Java JAR, but internet explorer warns users when local content is launched. In addition these approaches mean that we have less than perfect penetration, even though it is acceptable in these cases.</li>
<li>We could use a python (or equivalent) script, but the installed-base (penetration) of the python interpreter is not good enough.</li>
<li>Using a standard HTML is not enough because of the difficulty of embedding resources in it. Embedding Silverlight XAML or uuencoded content in HTML causes IE to display a warning.</li>
<li>Using something along the lines of a jpeg as a delivery method is not rich enough since we need to display HTML.</li>
</ul>
|
<blockquote>
<p><em>..but internet explorer warns users when local content is launched..</em></p>
</blockquote>
<p>I don't get it, what's the problem with IE saying "Hey this app is trying to run <em>your</em> files!"</p>
<p>I don't mean you don't have a good reason for this, it is just, I don't get it.</p>
<p>IE will only warn the user if the app has not been downloaded and try to access local resources, for instance if running from an applet or a JNLP like this <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html" rel="nofollow noreferrer">one:</a>(click on the first orange button you see ) </p>
<p>But if the users download the jar and run it from the computer ( double click on it ) the app is local and can run without problems.</p>
<p>The jar file is a zip file after all, so you can attach your mp3 file with it. Double click is supported in the desired platform, and the HTML content could be either a local file ( un-packed along with the mp3 file ) or an internet web page. </p>
<p>Java is preinstalled on those OS already.</p>
|
<p>"internet explorer warns users when local content is launched" </p>
<p>There's a reason for this. How can they distinguish your excellent, well-behaved, polite application from a virus?</p>
<p>Since the line between your app and a virus is very, very blurry, go with any of Silverlight XAP file, an adobe Flex file or a Java JAR.</p>
<p>The IE business is a good thing, not a bad thing.</p>
| 45,555
|
<p>The project I´m working on needs to auth its users against AD, and as a fallback check against its own user base. Now I need to test it outside the production environment.</p>
<p>What is the best method to setup a Active Directory test environment? Currently I´m downloading a Windows 2003 Virtual PC <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=77f24c9d-b4b8-4f73-99e3-c66f80e415b6&DisplayLang=en" rel="noreferrer">image</a>, and planning a VMWare virtual LAN. </p>
<p>Is there any problem in that approach? </p>
|
<p>Is this environment suppose to simulate as many ActiveDirectory installations as possible, or is it to just test that authentication works against a DC?</p>
<p>At a minimum, you will want to setup two Domain Controllers, a Primary and a Secondary. You will want to also setup accounts with a variety of account states (password expired, account expired, account lockout, etc).</p>
<p>Some other issues to think about:</p>
<p>Is your domain running as a Win2000 functional Domain? or a Windows 2003 functional Domain?
If you have multiple domains, will you support Universal Group membership?
If you have multiple forrests, will you support Cross-Forest Trust relationships?</p>
|
<p>You should think about multi-domain and multi-forest environments, as well as just having multiple domain controllers in the domain you're authenticating against. You're going to need more than a single VM to do that.</p>
| 41,169
|
<p>It seems there are some missing lines on the outer wall on the Z-axis with my prints. I'm not able to pinpoint the problem. Does anyone have ideas about what might be wrong with my setup/settings?</p>
<p>Example:</p>
<p><a href="https://i.stack.imgur.com/3q1k3.jpg" rel="nofollow noreferrer" title="Printed model with printing errors highlighted"><img src="https://i.stack.imgur.com/3q1k3.jpg" alt="Printed model with printing errors highlighted" title="Printed model with printing errors highlighted" /></a></p>
<p>Here are some settings that I think are relevant:<br />
Printer: Ender 3 v1<br />
Filament: Das Filament<br />
Slicer: Cura</p>
<ul>
<li>Hotend temp: 215 °C</li>
<li>Layer height: 0.2 mm</li>
<li>Wall speed: 30 mm/s</li>
<li>Travel speed: 200 mm/s</li>
<li>Retraction distance: 6.5 mm</li>
<li>Combing mode: not in skin (Max comb: 30)</li>
</ul>
<p>Cheers</p>
|
<p>According to <a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995206382" rel="nofollow noreferrer">'The-EG' comment</a> in this GitHub issue, <a href="https://github.com/MarlinFirmware/Configurations/pull/633" rel="nofollow noreferrer">Add Creality Ender 2 Pro config #633</a>, you can often determine the stepper drivers by one of a few ways:</p>
<ol>
<li><p>Listen to the sound. The 'TMC22**' will sound much quieter</p>
</li>
<li><p>Look for a marking in Sharpie on the SD Card reader</p>
<pre><code>C = HR4998
E = A4988
A = TMC2208
B = TMC2209
H = TMC2225
</code></pre>
</li>
<li><p>Remove the heat sync</p>
<p><a href="https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295" rel="nofollow noreferrer">https://github.com/MarlinFirmware/Configurations/pull/633#issuecomment-995480295</a></p>
<p>After removing the heat sync, it appears that the Chip is actually a <code>MS35775</code></p>
<p><a href="https://i.stack.imgur.com/0o5mK.jpg" rel="nofollow noreferrer" title="Closeup of MS35775 on board"><img src="https://i.stack.imgur.com/0o5mK.jpg" alt="Closeup of MS35775 on board" title="Closeup of MS35775 on board" /></a></p>
</li>
</ol>
|
<p>MS35775 appears to be TMC208 compatible. You can find the data sheet on relmon.com here is the overview:</p>
<ul>
<li>2-Phase stepping motor peak current of 2A</li>
<li>Step / dir interface 2, 4, 8, 16, or 32 microstep</li>
<li>Internal 256 micro steps</li>
<li>Quiet mode</li>
<li>Fast mode</li>
<li>HS Rdson 0.29 Ω ,LS Rdson 0.28 Ω</li>
<li>Voltage range 4.75 ~ 36V</li>
<li>When the motor is still, it will enter into the power saving mode automatically</li>
<li>Internal resistor mode is optional (no need for external sense resistor)</li>
<li>Single wire UART bus and OTP control</li>
<li>QFN28 package</li>
</ul>
| 2,073
|
<p>In PHP, which is quicker; using <code>include('somefile.php')</code> or querying a MySQL database with a simple <code>SELECT</code> query to get the same information?</p>
<p>For example, say you had a JavaScript autocomplete search field which needed 3,000 terms to match against. Is it quicker to read those terms in from another file using <code>include</code> or to read them from a MySQL database using a simple <code>SELECT</code> query?</p>
<p><strong>Edit:</strong> This is assuming that the database and the file I want to include are on the same local machine as my code.</p>
|
<p>It depends. If your file is stored locally in your server and the database is installed in another machine, then the faster is to include the file.</p>
<p>Buuuuut, because it depends on your system it could be not true. I suggest to you to make a PHP test script and run it 100 times from the command line, and repeat the test through HTTP (using cURL)</p>
<p>Example:</p>
<p><strong>use_include.php</strong></p>
<pre><code><?php
start = microtime(true);
include( 'somefile.php' );
echo microtime(true)-start;
?>
</code></pre>
<p><strong>use_myphp.php</strong></p>
<pre><code><?php
start = microtime(true);
__put_here_your_mysql_statements_to_retrieve_the_file__
echo microtime(true)-start;
?>
</code></pre>
|
<p>I exactly don't know, but in my opinio using MySQL, even if can be slower, sould be used if the content is dynamic. But I'm pretty sure it is faster, for big contents, using include.</p>
| 20,063
|
<p>I agree, that programming against interfaces is a good practice. In most cases in Java "interface" in this sense means the language construct interface, so that you write an interface and an implementation class and that you use the interface instead of the implementation class most of the time.</p>
<p>I wonder if this is a good practice for writing domain models as well. So, for example if you've got a domain class Customer and each customer may have a list of Orders, would you <em>generally</em> also write interfaces ICustomer and IOrder. And also would Customer have a list of IOrders instead of Orders? Or would you use interfaces in the domain model, only if it is really driven by the domain, e.g. you've got at least two different types of Orders? In other words, would you use interfaces because of only technical needs in the domain model, or only when it is really appropriate with respect to the actual domain?</p>
|
<p>Writing interfaces "just because" strikes me as a waste of time and energy, not to mention a violation of the KISS-principle.</p>
<p>I write them when they are actually useful in representing common behavior of related classes, not just as a fancy header file.</p>
|
<p>That's another thing to keep in mind that I've run in to, especially with generated domain and DAO objects. A lot of the interfaces are just too specific. Say a lot of domain objects have an ID and a status field, Why don't they share a common interface? This has caused me frustration, an unnecessarily flat (inheritance-wise) domain model.</p>
| 18,340
|
<p>I need help converting WAV files to MP3 format in VB6. I did already find <a href="http://www.codeproject.com/KB/audio-video/MP3Compressor/MP3Compressor.zip" rel="nofollow noreferrer">source code in C#</a>, but I can't use that</p>
|
<p>Here is a code example from the greatest programmer on Earth (Google):</p>
<p><a href="http://www.vbaccelerator.com/home/vb/code/vbmedia/audio/MP3_Encoding_with_LAME/VB6_Lame_MP3_Encoder.asp" rel="nofollow noreferrer">VB6 Lame MP3 Encoder</a></p>
<p>Don't let the word "lame" fool you - it stands for "<strong>LA</strong>me <strong>M</strong>p3 <strong>E</strong>ncoder", I think.</p>
|
<p>AFAIK, MP3 compression is under a patent, you can do that legally only by buying a license.</p>
<p>Or, like many other softwares, use the Lame DLL without distributing it but asking to download it in a site not under the same laws...</p>
<p>Somehow, that's how Opera does with GPL software: they don't provide spelling correction out of the box but they instruct to download and install aspell...</p>
<p>Note you can use free alternatives, like Ogg Vobis, it depends on your purpose.</p>
| 34,587
|
<p>I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.</p>
<p>What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?</p>
|
<p>We found a solution! Apparently the picture boxes stretched out on the Chinese XP PC, but the images they contained did not. The fix was to add code like the following:</p>
<pre><code>Me.PictureBoxIcon.Width = Me.PictureBoxIcon.Image.Width
Me.PictureBoxIcon.Height = Me.PictureBoxIcon.Image.Height
Dim loc As New Point
loc.X = Me.PictureBoxIcon.Location.X
loc.Y = Me.PictureBoxIcon.Location.Y + Me.PictureBoxIcon.Height
Me.PictureBoxAbout.Location = loc
Me.PictureBoxAbout.Width = Me.PictureBoxAbout.Image.Width
Me.PictureBoxAbout.Height = Me.PictureBoxAbout.Image.Height
</code></pre>
<p>Hope this helps someone else!</p>
|
<p>In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:</p>
<pre><code>images[0].Location = new Point(0,0);
for (int i = 1; i < images.Length; i++)
{
images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);
}
</code></pre>
<p>That will set the first image to the top left corner and all subsequent images to just after the last image.</p>
| 9,185
|
<p>This is a scenario I've seen in multiple places over the years; I'm wondering if anyone else has run across a better solution than I have...</p>
<p>My company sells a relatively small number of products, however the products we sell are highly specialized (i.e. in order to select a given product, a significant number of details must be provided about it). The problem is that while the <em>amount</em> of detail required to choose a given product is relatively constant, the <em>kinds</em> of details required vary greatly between products. For instance: </p>
<p>Product X might have identifying characteristics like (hypothetically) </p>
<ul>
<li>'Color',</li>
<li>'Material'</li>
<li>'Mean Time to Failure'</li>
</ul>
<p>but Product Y might have characteristics </p>
<ul>
<li>'Thickness', </li>
<li>'Diameter'</li>
<li>'Power Source'</li>
</ul>
<p>The problem (one of them, anyway) in creating an order system that utilizes both Product X and Product Y is that an Order Line has to refer, at some point, to what it is "selling". Since Product X and Product Y are defined in two different tables - and denormalization of products using a wide table scheme is not an option (the product definitions are quite deep) - it's difficult to see a clear way to define the Order Line in such a way that order entry, editing and reporting are practical.</p>
<hr>
<p><strong>Things I've Tried In the Past</strong></p>
<ul>
<li>Create a parent table called 'Product' with columns common to Product X and Product Y, then using 'Product' as the reference for the OrderLine table, and creating a FK relationship with 'Product' as the primary side between the tables for Product X and Product Y. This basically places the 'Product' table as the parent of both OrderLine and all the disparate product tables (e.g. Products X and Y). It works fine for order entry, but causes problems with order reporting or editing since the 'Product' record has to track what kind of product it is in order to determine how to join 'Product' to its more detailed child, Product X or Product Y. <strong>Advantages</strong>: key relationships are preserved. <strong>Disadvantages</strong>: reporting, editing at the order line/product level.</li>
<li>Create 'Product Type' and 'Product Key' columns at the Order Line level, then use some CASE logic or views to determine the customized product to which the line refers. This is similar to item (1), without the common 'Product' table. I consider it a more "quick and dirty" solution, since it completely does away with foreign keys between order lines and their product definitions. <strong>Advantages</strong>: quick solution. <strong>Disadvantages</strong>: same as item (1), plus lost RI.</li>
<li>Homogenize the product definitions by creating a common header table and using key/value pairs for the customized attributes (OrderLine [n] <- [1] Product [1] <- [n] ProductAttribute). <strong>Advantages</strong>: key relationships are preserved; no ambiguity about product definition. <strong>Disadvantages</strong>: reporting (retrieving a list of products with their attributes, for instance), data typing of attribute values, performance (fetching product attributes, inserting or updating product attributes etc.)</li>
</ul>
<p>If anyone else has tried a different strategy with more success, I'd sure like to hear about it.</p>
<p>Thank you.</p>
|
<p>The first solution you describe is the best if you want to maintain data integrity, and if you have relatively few product types and seldom add new product types. This is the design I'd choose in your situation. Reporting is complex only if your reports need the product-specific attributes. If your reports need only the attributes in the common Products table, it's fine.</p>
<p>The second solution you describe is called "Polymorphic Associations" and it's no good. Your "foreign key" isn't a real foreign key, so you can't use a DRI constraint to ensure data integrity. OO polymorphism doesn't have an analog in the relational model.</p>
<p>The third solution you describe, involving storing an attribute name as a string, is a design called "Entity-Attribute-Value" and you can tell this is a painful and expensive solution. There's no way to ensure data integrity, no way to make one attribute NOT NULL, no way to make sure a given product has a certain set of attributes. No way to restrict one attribute against a lookup table. Many types of aggregate queries become impossible to do in SQL, so you have to write lots of application code to do reports. Use the EAV design only if you must, for instance if you have an unlimited number of product types, the list of attributes may be different on every row, and your schema must accommodate new product types frequently, without code or schema changes.</p>
<p>Another solution is "Single-Table Inheritance." This uses an extremely wide table with a column for every attribute of every product. Leave NULLs in columns that are irrelevant to the product on a given row. This effectively means you can't declare an attribute as NOT NULL (unless it's in the group common to all products). Also, most RDBMS products have a limit on the number of columns in a single table, or the overall width in bytes of a row. So you're limited in the number of product types you can represent this way.</p>
<p>Hybrid solutions exist, for instance you can store common attributes normally, in columns, but product-specific attributes in an Entity-Attribute-Value table. Or you could store product-specific attributes in some other structured way, like XML or YAML, in a BLOB column of the Products table. But these hybrid solutions suffer because now some attributes must be fetched in a different way</p>
<p>The ultimate solution for situations like this is to use a semantic data model, using RDF instead of a relational database. This shares some characteristics with EAV but it's much more ambitious. All metadata is stored in the same way as data, so every object is self-describing and you can query the list of attributes for a given product just as you would query data. Special products exist, such as <a href="http://jena.sourceforge.net/" rel="noreferrer">Jena</a> or <a href="http://www.openrdf.org/" rel="noreferrer">Sesame</a>, implementing this data model and a special query language that is different than SQL.</p>
|
<p>Chris and AJ: Thanks for your responses. The product line may change, but I would not term it "volatile". </p>
<p>The reason I dislike the third option is that it comes at the cost of metadata for the product attribute values. It essentially turns columns into rows, losing most of the advantages of the database column in the process (data type, default value, constraints, foreign key relationships etc.)</p>
<p>I've actually been involved in a past project where the product definition was done in this way. We essentially created a full product/product attribute definition system (data types, min/max occurrences, default values, 'required' flags, usage scenarios etc.) The system worked, ultimately, but came with a significant cost in overhead and performance (e.g. materialized views to visualize products, custom "smart" components to represent and validate data entry UI for product definition, another "smart" component to represent the product instance's customizable attributes on the order line, blahblahblah).</p>
<p>Again, thanks for your replies!</p>
| 14,703
|
<p>Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?</p>
<p>For example, if I want to throw an exception on the server side via <a href="http://en.wikipedia.org/wiki/Apache_Struts" rel="noreferrer">Struts</a> by <code>throw new ApplicationException("User name already exists");</code>, I want to catch this message ('user name already exists') in the jQuery AJAX error message.</p>
<pre><code>jQuery("#save").click(function () {
if (jQuery('#form').jVal()) {
jQuery.ajax({
type: "POST",
url: "saveuser.do",
dataType: "html",
data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)),
success: function (response) {
jQuery("#usergrid").trigger("reloadGrid");
clear();
alert("Details saved successfully!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
</code></pre>
<p>On the second alert in the error callback, where I alert <code>thrownError</code>, I am getting <code>undefined</code> and the <code>xhr.status</code> code is <code>500</code>.</p>
<p>I am not sure where I am going wrong. What can I do to fix this problem?</p>
|
<p>Make sure you're setting <code>Response.StatusCode</code> to something other than 200. Write your exception's message using <code>Response.Write</code>, then use...</p>
<pre><code>xhr.responseText
</code></pre>
<p>..in your javascript.</p>
|
<p>First we need to set <serviceDebug includeExceptionDetailInFaults="True" /> in web.config:</p>
<pre><code><serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
**<serviceDebug includeExceptionDetailInFaults="true" />**
</behavior>
</serviceBehaviors>
</code></pre>
<p>In addition to that at jquery level in error part you need to parse error response that contains exception like:</p>
<pre><code>.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
</code></pre>
<p>Then using r.Message you can actully show exception text.</p>
<p>Check complete code: <a href="http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html" rel="nofollow">http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html</a> </p>
| 49,456
|
<p>Im adding textboxes (not a fixed number of textboxes) dynamically to a form on ASP.NET page, how do i read back data from these textboxes?</p>
|
<p>Assuming you're wanting to access the controls on the postback you'd probably re-create the dynamic controls exactly as they were created on the initial load, then use the page's FindControls method to find the controls. It would probably help to create the textboxes with IDs like Textbox1, Textbox2, etc.</p>
|
<p>To create dynamic controls, I would usually use a ASP.NET PlaceHolder Control and add the dynamic controls to this container. </p>
<p>I would give each dynamic control an ID.</p>
<p>You can then subsequently use FindControl on the PlaceHolder to access the dynamic controls.</p>
<p>I say "dynamic controls" to mean controls you add at run-time</p>
| 28,685
|
<p>The following code is in the <code>/Courses/Detail</code> action:</p>
<pre><code> [AcceptVerbs("GET")]
public ActionResult Detail(int id)
{
ViewData["Title"] = "A View Title";
return View(tmdc.GetCourseById(id));
}
</code></pre>
<p>The <code>tmdc.GetCourseById(id)</code> method returns an instance of type <code>Course</code> for the View. In the View I am using </p>
<pre><code><%= HTML.TextBox("Title")%>
</code></pre>
<p>to display the value of the <code>Title</code> property for the <code>Course</code> object. Instead the text box is displaying the string <code>A View Title</code>. Is this normal/expected behavior? What would be the best way to handle this?</p>
<p><b>Update</b><br />
As a workaround, I've changed <code>ViewData["Title"]</code> to <code>ViewData["VIEW_TITLE"]</code> but would like a cleaner way to handle this collision or to know if this is an expected result.</p>
|
<p>I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file.</p>
<p>After adding <code>debugger;</code> when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there.</p>
<p>In this scenario I was already debugging the JavaScript in <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="nofollow noreferrer">Firebug</a>, but I wanted to debug against Internet Explorer as well.</p>
|
<p>I sometimes have this problem with external JavaScript files - it is caused by the browser cache holding onto an old copy of the file. Forcing a refresh of the page linking to the JavaScript code solves the issue in this case.</p>
<p>Of course, make sure your debugger is attached to the correct browser process. ;)</p>
| 14,079
|
<p>When I get AuthenticationStatus.Authenticated (DotNetOpenId library)
response from myopenid provider, i'd like to redirect user from login page
to another one using MVC Redirect(myurl). But unfortunately, instead of
getting to myurl, user is redirected to empty page:</p>
<p>myurl?token=AWSe9PSLwx0RnymcW0q.... (+ several kilobytes of
myopenid-specific query string)</p>
<p>I also tried FormsAuthentication.RedirectFromLoginPage(), but it redirects
to original login page again instead of the myurl.</p>
<p>Could anybody suggest proper redirection to myurl?</p>
<p>Thanks</p>
|
<p>First of all you should set authorization cookie:</p>
<pre><code>FormsAuth.SetAuthCookie(UserName, RememberMe);
</code></pre>
<p>After this you should return RedirectToAction result:</p>
<pre><code>return RedirectToAction(actionName, controllerName);
</code></pre>
<p>Or Redirect result:</p>
<pre><code>return Redirect(url);
</code></pre>
<p>When you use "return Redirect(url);" it uses Response.Redirect(url, false) method for redirecting so it must work. May be you not returning this action result, please check this.
"FormsAuthentication.RedirectFromLoginPage()" will redirect to login page when you didn't set authorization cookie or when your login page is a home (default) page of the application - </p>
<blockquote>
<p>The RedirectFromLoginPage method redirects to the URL specified in the query string using the ReturnURL variable name. For example, in the URL <a href="http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx" rel="nofollow noreferrer">http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx</a>, the RedirectFromLoginPage method redirects tothe return URL caller.aspx. If the ReturnURL variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.</p>
</blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx" rel="nofollow noreferrer" title="via MSDN">Via MSDN</a></p>
|
<p>I use the classic ReturnUrl querystring parameter to get the user back to the right page. Unfortunately, the RedirectFromLoginPage does not work well after OpenId Authentication so you must do it manually. Note, this is done as an authentication module rather than deeper in on the controller. It feels cleaner this way.</p>
<pre><code> FormsAuthentication.SetAuthCookie(openid.Response.ClaimedIdentifier, false);
//FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false); <-- doesn't work
//send back to the right page
string returnUrl = ctx.Request.QueryString["ReturnUrl"];
if (!string.IsNullOrEmpty(returnUrl))
{
returnUrl = HttpUtility.UrlDecode(returnUrl);
ctx.Response.Redirect(returnUrl);
}
</code></pre>
<p>If you'd like to see the entire implementation of the OpenIdAuthenticationModule, check out the <a href="http://www.codeplex.com/blogsvc/SourceControl/changeset/view/31628#392049" rel="nofollow noreferrer">source code on codeplex</a>.</p>
| 43,094
|
<p>In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?</p>
<p>Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here. </p>
|
<p>For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions:</p>
<ol>
<li>mlint</li>
<li>dependency report and </li>
<li>coverage report</li>
</ol>
<p>Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies. To use profile, you could do </p>
<pre><code>>> profile on % turn profiling on
>> foo; % entry point to your matlab function or script
>> profile off % turn profiling off
>> profview % view the report
</code></pre>
<p>If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a):</p>
<ol>
<li>depfun</li>
<li>depdir</li>
</ol>
<p>For example, </p>
<pre><code>>> deps = depfun('foo');
</code></pre>
<p>gives a structure, deps, that contains all the dependencies of foo.m.</p>
<p>From answers <a href="https://stackoverflow.com/a/29049918/4612">2</a>, and <a href="https://stackoverflow.com/a/34621308/4612">3</a>, newer versions of MATLAB (post 2015a) use <code>matlab.codetools.requiredFilesAndProducts</code> instead.</p>
<p>See answers </p>
<p>EDIT:</p>
<p>Caveats thanks to @Mike Katz comments</p>
<blockquote>
<ul>
<li><p>Remember that the Profiler will only
show you files that were actually used
in those runs, so if you don't go
through every branch, you may have
additional dependencies. The
dependency report is a good tool, but
only resolves static dependencies on
the path and just for the files in a
single directory. </p></li>
<li><p>Depfun is more reliable but gives you
every possible thing it can think of,
and still misses LOAD's and EVAL's.</p></li>
</ul>
</blockquote>
|
<p>For <code>MATLAB 2015a</code> and later you should preferably look at <a href="http://www.mathworks.com/help/matlab/ref/matlab.codetools.requiredfilesandproducts.html" rel="noreferrer">matlab.codetools.requiredFilesAndProducts</a></p>
<p>or <code>doc matlab.codetools.requiredFilesAndProducts</code></p>
<p>because <code>depfun</code> is marked to be removed in a future release.</p>
| 12,129
|
<p><strong>Final Edit:</strong> I found a solution to the problem (at the bottom of the question).</p>
<p>I've got an Nunit problem that's causing me grief. <strong>Edit:</strong> actually it looks more like a SQLite problem, but I'm not 100% certain yet.</p>
<p>My TestFixture has a setup that generates a random filename that's used as a SQLite database in each of my tests.</p>
<pre><code>[Setup]
public void Setup()
{
// "filename" is a private field in my TestFixture class
filename = ...; // generate random filename
}
</code></pre>
<p>Each of my tests use this construct in each method that accesses the database:</p>
<pre><code>[Test]
public void TestMethod()
{
using (var connection = Connect())
{
// do database activity using connection
// I've tried including this line but it doesn't help
// and is strictly unnecessary:
connection.Close();
}
}
private DbConnection Connect()
{
var connection = DbProviderFactories.GetFactory("System.Data.SQLite").CreateConnection();
connection.ConnectionString = "Data Source=" + filename;
connection.Open();
return connection;
}
</code></pre>
<p>So that one helper method <code>Connect()</code> is used by all the methods. I'm assuming that the <code>using() { }</code> construct is calling <code>Dispose()</code> on the connection at the end of <code>TestMethod()</code> and freeing up the connection to the SQLite database file.</p>
<p>The problem I have is in my [TearDown] method:</p>
<pre><code> [TearDown]
public void Cleanup()
{
File.Delete(filename); // throws an IOException!
}
</code></pre>
<p>With every test I get an exception:</p>
<pre><code>System.IO.IOException: The process cannot access the file 'testdatabase2008-12-17_1030-04.614065.sqlite' because it is being used by another process.
</code></pre>
<p>All of the tests fail when they get to the [TearDown], so I end up with a directory full of temporary databse files (one per test, each with a different name) and a whole bunch of failed tests.</p>
<p>What process is accessing the file? I don't get how a second process could be accessing the file. The <code>connection</code> has completely gone out of scope and been Dispose()d by the time I'm trying to delete the file, so it can't be something SQLite related. Can it?</p>
<p>Note that I get the same result if I run all the tests or just a single test.</p>
<p><strong>Update:</strong> So I tried Dispose()ing of my DbCommand objects as well, since I wasn't doing that (I assumed that every other ADO.NET provider that Dispose()ing the DbConnection also Dispose()s any commands on that connection.) So now they look like:</p>
<pre><code>[Test]
public void TestMethod()
{
using (var connection = Connect())
{
using (var command = connection.CreateCommand())
{
// do database activity using connection
}
}
}
</code></pre>
<p>It didn't make any difference -- the File.Delete() line still throws an IOException. :-(</p>
<p>If I remove that one line in [TearDown] then all my tests pass, but I'm left with a whole bunch of temporary database files.</p>
<p><strong>Another Update:</strong>
This works just fine:</p>
<pre><code>var filename = "testfile.sqlite";
using (var connection = BbProviderFactories.GetFactory("System.Data.SQLite").CreateConnection())
{
connection.ConnectionString = "Data Source=" + filename;
connection.Open();
var createCommand = connection.CreateCommand();
createCommand.CommandText =
"CREATE TABLE foo (id integer not null primary key autoincrement, bar text not null);";
createCommand.ExecuteNonQuery();
var insertCommand = connection.CreateCommand();
insertCommand.CommandText = "INSERT INTO foo (bar) VALUES (@bar)";
insertCommand.Parameters.Add(insertCommand.CreateParameter());
insertCommand.Parameters[0].ParameterName = "@bar";
insertCommand.Parameters[0].Value = "quux";
insertCommand.ExecuteNonQuery();
}
File.Delete(filename);
</code></pre>
<p>I don't understand!</p>
<p><strong>Update:</strong> Solution found:</p>
<pre><code> [TearDown]
public void Cleanup()
{
GC.Collect();
File.Delete(filename);
}
</code></pre>
<p>I ran the unit tests through the debugger, and when the <code>[TearDown]</code> method starts there are definitely no references to the SQLite DbConnection around any more. Forcing a GC must clean them up though. There must be a bug in SQLite.</p>
|
<p>Thanks for the posted answer at the bottom. I was digging for hours for exactly the same case and </p>
<pre><code>GC.Collect ();
GC.WaitForPendingFinalizers ();
</code></pre>
<p>did the trick.</p>
|
<p>Tear down is executed after each test.</p>
<blockquote>
<p>This attribute is used inside a TestFixture to provide a common set of functions that are performed after each test method is run.</p>
</blockquote>
<p>You should try to delete them all with <strong>TestFixtureTearDown</strong>:</p>
<pre><code> [TestFixtureTearDown]
public void finish()
{
//Delete all file
}
</code></pre>
<p>Maybe one test is using the file that you try to delete in an other test. <em><-- [Stewart] As I stated in the question, it happens when I run only one test, so this isn't possible.</em></p>
<p><em>Update</em>
You do not give enough information about what you are doing. Have you try to clean up all the Test file with only 1 test in your test file and try it? <em>[Stewart] Yes.</em> If it works <em>[Stewart] (it doesn't)</em> then it's that you have multiple test problem (they access each other). You need to <strong>cut down the problem to find the source</strong>. Then, come back here we will help you. for the moment it's only guessing that we can give you. <em>[Stewart] I have already done these cut-downs of the problem that you suggest, you'll find that they're in my original question!</em></p>
| 48,990
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.