instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm trying to write a parser to get the data out of a typical html table day/time schedule (like <a href="http://kut.org/about/schedule" rel="nofollow noreferrer">this</a>). </p>
<p>I'd like to give this parser a page and a table class/id, and have it return a list of events, along with days & times they occur. It should take into account rowspans and colspans, so for the linked example, it would return </p>
<pre><code>{:event => "Music With Paul Ray", :times => [T 12:00am - 3:00am, F 12:00am - 3:00am]}, etc.
</code></pre>
<p>I've sort of figured out a half-executed messy approach using ruby, and am wondering how you might tackle such a problem?</p>
|
<p>The best thing to do here is to use a HTML parser. With a HTML parser you can look at the table rows programmatically, without having to resort to fragile regular expressions and doing the parsing yourself.</p>
<p>Then you can run some logic along the lines of (this is not runnable code, just a sketch that you should be able to see the idea from):</p>
<pre><code>for row in table:
i = 0
for cell in row: # skipping row 1
event = name
starttime = row[0]
endtime = table[ i + cell.rowspan + 1 ][0]
print event, starttime, endtime
i += 1
</code></pre>
|
<p>This is what the program will need to do:</p>
<ol>
<li>Read the tags in (detect attributes and open/close tags)</li>
<li>Build an internal representation of the table (how will you handle malformed tables?)</li>
<li>Calculate the day, start time, and end time of each event</li>
<li>Merge repeated events into an event series</li>
</ol>
<p>That's a lot of components! You'll probably need to ask a more specific question.</p>
| 14,469
|
<p>I trying to implement a typical languages menu where users can select the language they want to view the site in through a menu that appears throughout all pages in the site.</p>
<p>The menu will appear on multiple master pages (currently one for pages where users are logged in and one for pages where users are not).</p>
<p>My current implementation is having a single master page base class (let's call it MasterBase). MasterBase has an event</p>
<pre><code>public event LanguageChangedEventHandler LanguageChanged;
</code></pre>
<p>where LanguagedChangedEventHandler is simply defined as</p>
<pre><code>public delegate void LanguageChangedEventHandler(string NewCulture);
</code></pre>
<p>MasterBase also has an overridable method</p>
<pre><code>protected virtual void OnLanguageChanged(string NewCulture)
</code></pre>
<p>which just basically fires the event.</p>
<p>Each master page that inherits MasterBase overrides OnLanguageChanged and does the usual stuff like set the Thread's CurrentUICulture and the language cookie then does a </p>
<pre><code>Server.Transfer(this.Page.AppRelativeVirtualPath, true);
</code></pre>
<p>to get the page to reload with localized values for the new culture. On the master page for logged in users it also updates the user's language pref in the db.</p>
<p>Each language option is currently a LinkButton on a master page that inherits from MasterBase. When the link is clicked it calls the base OnLanguagedChanged method passing in the correct culture info. E.g.</p>
<pre><code>protected void btnEnglish_Click(object sender, EventArgs e) {
this.OnLanguageChanged("en-US");
}
</code></pre>
<p>Each page that needs to handle a language change then has some code in the page load that looks like...</p>
<pre><code>((MasterBase)this.Master).LanguageChanged += this.Page_OnLanguageChanged;
// Where Page_OnLanguageChanged has the signature of LanguageChangedEventHandler
// and has stuff like reloading options in a drop down using the new language.
</code></pre>
<p>Quite a convoluted 'framework' =)</p>
<ol>
<li>Firstly it's hard for new developers to know they have to hook up a method to the MasterBase's LanguageChanged event to handle language changes. Yes, we do document it. But still it's not something straightforward and obvious.</li>
<li>Secondly, all language changes are post backs. This is problematic especially when you want to navigate back with the browser Back button.</li>
</ol>
<p>I'm looking for a more elegant solution. One that doesn't have both the problems above and also handles my current requirements.</p>
<p>Greatly appreciate any suggestions. Thanks.</p>
|
<p>How about <a href="http://www.ericmmartin.com/projects/simplemodal/" rel="nofollow noreferrer">SimpleModal</a> for jQuery?</p>
|
<p>I've found <a href="http://dev.iceburg.net/jquery/jqModal/" rel="nofollow noreferrer">jqModal</a> [for jQuery] to be very easy to work with.</p>
| 34,710
|
<p>How does one execute some VBA code periodically, completely automated?</p>
|
<p>You can use Application.OnTime to schedule a macro to be executed periodically. For example create a module with the code below. Call "Enable" to start the timer running. </p>
<p>It is important to stop the timer running when you close your workbook: to do so handle Workbook_BeforeClose and call "Disable"</p>
<pre><code>Option Explicit
Private m_dtNextTime As Date
Private m_dtInterval As Date
Public Sub Enable(Interval As Date)
Disable
m_dtInterval = Interval
StartTimer
End Sub
Private Sub StartTimer()
m_dtNextTime = Now + m_dtInterval
Application.OnTime m_dtNextTime, "MacroName"
End Sub
Public Sub MacroName()
On Error GoTo ErrHandler:
' ... do your stuff here
' Start timer again
StartTimer
Exit Sub
ErrHandler:
' Handle errors, restart timer if desired
End Sub
Public Sub Disable()
On Error Resume Next ' Ignore errors
Dim dtZero As Date
If m_dtNextTime <> dtZero Then
' Stop timer if it is running
Application.OnTime m_dtNextTime, "MacroName", , False
m_dtNextTime = dtZero
End If
m_dtInterval = dtZero
End Sub
</code></pre>
<p>Alternatively you can use the Win32 API SetTimer/KillTimer functions in a similar way.</p>
|
<p>You could consider the Windows Task Scheduler and VBScript.</p>
| 26,023
|
<p>When I open cmd on my laptop it is defaulting to the F: drive. This is troubling me does anyone know how it got that way or how to get it back to where it opens to the C: drive by default?</p>
|
<p>I believe it defaults to <code>%HOMEDRIVE%\%HOMEPATH%</code> so if you can muck about with those environment variables that might be an option. I can't edit these environment variables on my company's network, so I had to use the <a href="http://technet.microsoft.com/en-us/library/cc756720.aspx" rel="nofollow noreferrer">AutoRun</a> to change it to something sane.</p>
|
<p>If you are opening it from a shortcut change the working dir for the shortcut.</p>
| 6,598
|
<p>Let's say that I want to merge from a release branch to the master branch and there are some commits in the release branch that I don't want to include in the master branch. Is there a way to do the merge so that one or more of those commits will not be merged?</p>
<p>My strategy so far is to do the following (in master):</p>
<pre><code>git merge --no-commit release-branch
# Resolve conflicts and apply reverse patch of the commits that I don't want included
git commit # Edit commit message so that it lists the commits that have been reverse-patched
</code></pre>
<p>Is there a better way to do this?</p>
|
<p>Create a new branch, rebase the branch interactively and drop commits you don't want, and then merge that.</p>
<p>You can't take changes out of the middle of a branch without rehashing, but the right thing will happen when it sees the same changes in a later merge (e.g. from cherry-picking and what-not).</p>
|
<p>To avoid overwriting problem encountered with <a href="https://stackoverflow.com/a/3970442/5784834">@fcurella</a>'s answer, start by defining a merge driver that would always favor our current version of the file, by making use of the existing true command. We’ll call this driver ours, to keep in line with similar merge strategies:</p>
<p><code>git config --global merge.ours.driver true</code></p>
<p>After that we can implement the <a href="https://stackoverflow.com/a/3970442/5784834">@fcurella</a> solution:</p>
<blockquote>
<p>Let's say you want to exclude the file .env</p>
<p>On branch A (e.g. Master):</p>
<ol>
<li><p>Create a file named <em>.gitattributes</em> in the same dir, with this line:</p>
<pre><code>.env merge=ours
</code></pre>
<p>This tells git what strategy to use when merging the file. In this case it always keep your version, ie. the version on the branch you are merging into.</p>
</li>
<li><p>Add the .gitattributes file and commit</p>
</li>
</ol>
<p>On branch B (e.g. Develop): repeat steps 1-2</p>
<p>Try merging now. Your file should be left untouched.</p>
</blockquote>
<p>Read <a href="https://medium.com/@porteneuve/how-to-make-git-preserve-specific-files-while-merging-18c92343826b" rel="nofollow noreferrer">this</a> for further explanations</p>
| 43,078
|
<p>What would the purpose of this construct in a c file be?: </p>
<pre><code>#define _TIMERC
#include "timer.h"
#undef _TIMERC
</code></pre>
<p>I am aware of the guard for preventing multiple inclusion of a header file. This doesn't appear to be whats happening though.</p>
<p>thanks!</p>
|
<p>Often times a library header file will have multiple options, that are enabled and disabled by macro defines. This will enable such an option.</p>
<p>More typically these are set at a global scope by configuring your build system to add (for eg with gcc) <strong>-D_TIMERC</strong> to the compilers command line.</p>
|
<p>At the risk of stating the obvious, "timer.h" expects to have _TIMERC and the rest of your code does not.</p>
<p>Clearly not good practice in the general case, but I have seen similar when including third party code. Can get nasty when you have #defs that clash...</p>
| 43,354
|
<p>We are currently using the <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;118623" rel="noreferrer">NetBios method</a>, and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bound to change. Our alternative method - with <a href="http://msdn.microsoft.com/en-us/library/aa378021(VS.85).aspx" rel="noreferrer">SNMPExtensionQuery</a> - seems to be broken under Vista.</p>
<p>The question is: do you know of a reliable way to get a list of the local MAC addresses on a Vista machine? Backwards compatibility with XP is a plus (I'd rather have one single method than lots of ugly #ifdef's). Thanks!</p>
|
<p>This will give you a list of all MAC addresses on your computer. It will work with all versions of Windows as well:</p>
<pre><code>void getdMacAddresses(std::vector<std::string> &vMacAddresses;)
{
vMacAddresses.clear();
IP_ADAPTER_INFO AdapterInfo[32]; // Allocate information for up to 32 NICs
DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer
DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo
AdapterInfo, // [out] buffer to receive data
&dwBufLen); // [in] size of receive data buffer
//No network card? Other error?
if(dwStatus != ERROR_SUCCESS)
return;
PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo;
char szBuffer[512];
while(pAdapterInfo)
{
if(pAdapterInfo->Type == MIB_IF_TYPE_ETHERNET)
{
sprintf_s(szBuffer, sizeof(szBuffer), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x"
, pAdapterInfo->Address[0]
, pAdapterInfo->Address[1]
, pAdapterInfo->Address[2]
, pAdapterInfo->Address[3]
, pAdapterInfo->Address[4]
, pAdapterInfo->Address[5]
);
vMacAddresses.push_back(szBuffer);
}
pAdapterInfo = pAdapterInfo->Next;
}
}
</code></pre>
|
<p>You can use WMI on both XP and Vista, there are a number of examples online. e.g:
<a href="http://www.thescarms.com/dotnet/WMI.aspx" rel="nofollow noreferrer">Use Windows Management Instrumentation (WMI) to get a MAC Address</a></p>
| 27,358
|
<p>So I bought this printer three days ago as a way to dip my toes into the 3D printing world, and it was working great at first. But at some point, the ABL procedure started behaving oddly: Instead of moving down to touch each corner of the printing bed, it's now only doing so for one corner, then moving to the next, but instead of going down, it goes up. It then continues to the third corner, stops, and moves up again. After that, it returns back to home position. The result is that the extruder hovers way above where it's supposed to be --or alternatively bumps into the printing bed when it's near the origin corner-- thinking it's adjusting for some nonexistent slant, dripping filament all over the place.</p>
<p>The gantry itself is totally level, and I can't see any mechanical faults. As far as I can tell, there's no way to manually level the bed, the only option is to use ABL.</p>
<p>I found out that the Monoprice Cadet printer is the exact same one as the Tina2, so if anyone has experience with that printer in particular, it'll apply here too.</p>
|
<p>This is a community wiki answer from <a href="https://www.reddit.com/r/3Dprinting/comments/lz4c9l/comment/gr9v9pb/?utm_source=reddit&utm_medium=web2x&context=3" rel="nofollow noreferrer">an answer</a> on <a href="https://www.reddit.com/r/3Dprinting/comments/lz4c9l/monoprice_cadet_autoleveling_question/" rel="nofollow noreferrer">Reddit - Monoprice Cadet auto-leveling question</a>, for those who stumble upon this question:</p>
<blockquote>
<p>Then I tried their text chat support and the response was basically:</p>
<p>"It is a bad level sensor, which we've never heard of happening to a 3 month old printer and is very rare in general. You are under warranty so here's a preprinted return shipping label, and we'll send you a new printer once we receive your busted one."</p>
</blockquote>
<hr />
<p><em>From the many "me too" answers, this appears to be a genuine issue rather than a "one-off" issue...</em></p>
|
<p>According to the <a href="http://www.weedo.ltd/product-detail/tina2/" rel="nofollow noreferrer">manufacturer's page for the Weedo Tina 2</a>, the bed sensor for the ABL is magnetic -- which means that if you've removed the magnetic build surface you likely have removed the printer's ability to sense the bed height. You most likely need to replace the worn out magnetic build surface for the (mandatory) ABL to work.</p>
<p>Weedo ought to sell replacements for a part that wears out, but if not, you can buy one made for the Ender 3 (and cut it down to fit) on Amazon (very reasonably priced, too) and have it in your hands in a couple days, though I have no way to know the original didn't have specific poles in particular locations on the sheet. You'll likely need to remove the base sheet from the Tina 2, if there is one, so as to follow the instructions on the Creality and ensure the upper, removable, flexible sheet actually sticks to the adhesive-backed lower sheet.</p>
| 1,953
|
<p>I'm customizing the 404 page for my website. I'd like it to include a "Did you mean...?" I need to figure out how to do this.</p>
<p>Here's what I'm doing so far: I come up with a broad list of files that the user might be looking for, then use levenshtein() to compare each possible filename to the mistyped filename. Those with the lowest differences are selected for "Did you mean."</p>
<p>I've also considered using metaphone(), but I think it may be excessive.</p>
<p><strong>What would <em>you</em> suggest for a "Did you mean...?" script?</strong></p>
|
<p>One thing you might want to consider is Google's 404 script for doing just what you mentioned. It probably wouldn't be as good as a custom solution, but it may be worth trying out to be sure.</p>
<p><a href="http://googlewebmastercentral.blogspot.com/2008/08/make-your-404-pages-more-useful.html" rel="nofollow noreferrer">http://googlewebmastercentral.blogspot.com/2008/08/make-your-404-pages-more-useful.html</a></p>
|
<p>One thing you might want to consider is Google's 404 script for doing just what you mentioned. It probably wouldn't be as good as a custom solution, but it may be worth trying out to be sure.</p>
<p><a href="http://googlewebmastercentral.blogspot.com/2008/08/make-your-404-pages-more-useful.html" rel="nofollow noreferrer">http://googlewebmastercentral.blogspot.com/2008/08/make-your-404-pages-more-useful.html</a></p>
| 42,720
|
<p>I have intermittent crashes occurring in my ActiveMQ libraries due to the way I'm using the activemq-cpp API. It'd be much easier to debug the issue if I could observe every function being called leading up to the crash. Are there any quick ways to trace the entry and exit of functions in a Visual Studio 2005 c++ multithreaded program?</p>
<p>Thanks in advance!</p>
|
<p>Use a Tracer object. Something like this:</p>
<pre><code>
class Tracer
{
public:
Tracer(const char *functionName) : functionName_(functionName)
{
cout << "Entering function " << functionName_ << endl;
}
~Tracer()
{
cout << "Exiting function " << functionName_ << endl;
}
const char *functionName_;
};
</code></pre>
<p>Now you can simply instantiate a Tracer object at the top the function, and it will automatically print "exiting... " when the function exits and the destructor is called:</p>
<pre><code>
void foo()
{
Tracer t("foo");
...
}
</code></pre>
|
<p>While the debugger is attached to a process, you can rightclick in the source code and select "breakpoint->add TracePoint", with the text you want (even some macro's are supplied).</p>
<p>The Tracepoint is in fact a BreakPoint with the "When Hit" field on some message printer functionality, and it doesn't actually break the process. I found it mighty useful: it also has a macro $FUNCTION, which does exactly what you need: print the function it is in (provided it has the debug info available...), and a $THREADID.</p>
| 29,499
|
<p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p>
<p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p>
|
<p>Subversion has native support for moving files.</p>
<pre><code>svn move SOURCE DESTINATION
</code></pre>
<p>See the online help (svn help move) for more information.</p>
|
<p>If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop. </p>
| 6,811
|
<p>Real UID, effective UID, and some systems even have a "saved UID". What's the purpose of all these, especially the last one?</p>
|
<p>Each UNIX process has 3 UIDs associated to it. Superuser privilege is UID=0.</p>
<p><strong>Real UID</strong></p>
<p>This is the UID of the user/process that created THIS process. It can be changed only if the running process has EUID=0.</p>
<p><strong>Effective UID</strong></p>
<p>This UID is used to evaluate privileges of the process to perform a particular action. EUID can be changed either to RUID, or SUID if EUID!=0. If EUID=0, it can be changed to anything.</p>
<p><strong>Saved UID</strong></p>
<p>If you run an executable with the set-UID bit set, then the resulting running process will start off with a real UID of the real user running it, and an effective and saved UID of the owner of the executable file. If the process then calls setuid() or seteuid() to change their effective UID, they can still get back their original privileges again thanks to the saved UID. If the set-UID bit is not set, SUID will be the RUID.</p>
|
<p>The accepted answer is not correct regarding that real UD's can not be changed by anyone except root.
From the man page for setuid:
(I could not make a comment)</p>
<blockquote>
<p>The setuid() function sets the real and effective user IDs and the
saved set-user-ID of
the current process to the specified value. The setuid() function is permitted if the
effective user ID is that of the super user, or if the specified user ID is the same as
the effective user ID. If not, but the specified user ID is the same as the real user
ID, setuid() will set the effective user ID to the real user ID.</p>
</blockquote>
| 25,119
|
<p>My source code needs to support both .NET version 1.1 and 2.0 ... how do I test for the different versions & what is the best way to deal with this situation.</p>
<p>I'm wondering if I should have the two sections of code inline, in separate classes, methods etc. What do you think?</p>
|
<p>There are a lot of different options here. Where I work we use #if pragmas but it could also be done with separate assemblies for the separate versions. </p>
<p>Ideally you would at least keep the version dependant code in separate partial class files and make the correct version available at compile time. I would enforce this if I could go back in time, our code base now has a whole lot of #if pragmas and sometimes it can be hard to manage. The worst part of the whole #if pragma thing is that Visual Studio just ignores anything that won't compile with the current defines and so it's very easy to check in breaking changes.</p>
<p><a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">NUnit</a> supports both 1.1 and 2.0 and so is a good choice for a test framework. It's not too hard to use something like <a href="http://nant.sourceforge.net/" rel="nofollow noreferrer">NAnt</a> to make separate 1.1 and 2.0 builds and then automatically run the NUnit tests.</p>
|
<p>I would be asking the question of WHY you have to maintain two code bases, I would pick one and go with it if there is any chance of it.</p>
<p>Trying to keep two code bases in sync with the number of changes, and types of changes would be very complex, and a build process to build for either version would be very complex.</p>
| 11,129
|
<p>I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds. I come from a Java background, and in Java libraries are everything! </p>
<p>I understand from compiling open-source projects on my Linux box that all the source code for the library seems to need to be included, with the exception of those .so files.</p>
<p>Also I've heard of the .lib static libraries and .dll dynamic libraries, but I'm still not entirely sure how to add them to a build and make them work. How does one go about this?</p>
|
<p>In I think you might be asking the mechanics of how to add a lib to a project/solution in the IDEs...</p>
<p>In 2003, 2005 and 2008 it is something similar to:</p>
<p>from the solution explorer - right click on the project
select properties (typically last one)
I usually select all configurations at the top...
Linker
Input</p>
<p>Additional dependencies go in there </p>
<p>I wish I could do a screen capture for this.</p>
<p>In VC6 it is different bear with me as this is all from memory</p>
<p>project settings or properties and then go to the linker tab and find where the libs can be added.</p>
<p>Please excuse the haphazard nature of this post. I think that is what you want though.</p>
|
<p>What do you mean "add them to a build"?</p>
<p>In VC, within a solution, you can have a project whose output is a library (static or dynamic) and then another project that depends upon the output and uses it (ie, links to it).</p>
<p>In our code base, we typically have a separate solution for each library or set of libraries and then link them into target projects. Most of our target projects are managed assemblies - those that need unmanaged functionality are usually written in managed C++ or C++/CLI and link in unmanaged static libraries. We've found that this has been the easiest to maintain since the unmanaged libraries change the least.</p>
| 26,116
|
<p>I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL:</p>
<blockquote>
<p>unable to write 'random state'</p>
</blockquote>
<p>What does this mean?</p>
<p>This is on an Ubuntu server. I have upgraded libssl to fix <a href="http://www.ubuntu.com/usn/usn-612-1">the recent security vulnerability</a>.</p>
|
<p>In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account. The quick fix:</p>
<pre><code>sudo rm ~/.rnd
</code></pre>
<p>For more information, here's the entry from the <a href="http://www.openssl.org/support/faq.html#USER2" rel="noreferrer">OpenSSL FAQ</a>:</p>
<blockquote>
<p>Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.) </p>
</blockquote>
<p>So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.</p>
<p>If everything seems to be in order, you could try running with <a href="http://en.wikipedia.org/wiki/Strace" rel="noreferrer">strace</a> and see what exactly is going on.</p>
|
<p>The problem for me was that I had .rnd in my home directory but it was owned by root. Deleting it and reissuing the openssl command fixed this.</p>
| 12,005
|
<p>What is BPEL? I'm looking for some nice simple examples of BPEL usage. The wikipedia page isn't too enlightening. How about a "Hello world" in BPEL? A BPEL shell? A BPEL IDE?</p>
|
<p>BPEL is just a way to build centralized control of disparate but interdependent systems from a centralized place. </p>
<p>Users can create rules, workflows and other control structures to make sure everything plays nice. </p>
<p>For example, say you run a school district; in particular, a school districts information infrastructure. Over the years you have accumulated a motley assorted group of hardware and software. For each aspect of your district; grading, attendance, bus routes, nutrition, payroll, etc, etc, you have various distinct software written in different languages by different vendors. Well, you have some overlap in your data and different end users use the different pieces of software and they expect it all to agree with each other - you use your BPEL system to be sure all the data is where it is supposed to be when it is supposed to be there. </p>
<p>You also have some processes that absolutely have to run after the successful completion of another process on a different system. You use BPEL to make sure those are coordinated. BPEL is all about centralized coordination and you probably don't need it unless you are in a large organization and lots of different systems.</p>
|
<p><strong>Background</strong></p>
<p>I'll add a little bit to what has been said. BPEL is a procces orchestrator. You can use it to do any kind of serialised of parallel process automation.
For example: A customer buys something on the website of company 'AAA', this instigates a BPEL process in that companies service oriented architecture (SOA). Within this BPEL a series of BPEL components does their work on the payload generated by the consumers purchase. This payload can consist of all kinds of information regarding the buyer and the purchased item, such as <code><shippingAdress></code> and <code><itemId</code>. An invoke BPEL component can be used to send information from the payload to another BPEL process or to another chained company through a webservice call in the composite wherin the BPEL lies. That company can be responsible for the shipping of the purchased item, another company can be responsible for the processing of the money. All of these companies dealings are automated through composite applications containing series of BPEL processes. All are communicating information across the web through (a)synchronous webservice calls.
The BPEL part is where the logic lies, where the true automation/orchestration of function resides.</p>
<p><strong>Getting started</strong>
The Oracle documentation websites for soa suite 11g and 12c are quite extensive for those willing to read. If you like to do a tutorial from the basics and up you can use their suggested code to get started. It's a little bit trickier when it comes to applying their documentation to existing BPEL projects, but its still a good source for many basic questions and examples regarding SOA.</p>
<p><a href="https://docs.oracle.com/cd/E12483_01/integrate.1013/b28981/async.htm" rel="nofollow noreferrer">https://docs.oracle.com/cd/E12483_01/integrate.1013/b28981/async.htm</a>
Also, a quick google search will lead you to some expert guides written by bloggers. Some of these are a bit more beginner friendly than the oracle documentation, but mostly lack details pertaining to your own project.</p>
<p><a href="http://javaoraclesoa.blogspot.com/2016/02/asynchronous-interaction-in-oracle-bpel.html" rel="nofollow noreferrer">http://javaoraclesoa.blogspot.com/2016/02/asynchronous-interaction-in-oracle-bpel.html</a></p>
<p>You can also just youtube some videos about BPEL to get the gest of it :).</p>
<p>Good luck and have fun!</p>
| 39,165
|
<p>I need to be able to store a date (year/month/day) with no time component. It's an abstract concept of a date, such as a birthday - I need to represent a date in the year and not a particular instant in time.</p>
<p>I am using Java to parse the date from some input text, and need to store in a MySQL database. No matter what timezone the database, application, or any client is in, they should all see the same year/month/day.</p>
<p>My application will run on a machine with a different system timezone from the database server, and I don't have control over either. Does anyone have an elegant solution for ensuring I store the date correctly?</p>
<p>I can think of these solutions, neither of which seems very nice:</p>
<ul>
<li>Query my MySQL connection for its timezone and parse the input date in that timezone</li>
<li>Process the date entirely as a string yyyy-MM-dd</li>
</ul>
|
<p>I concluded that the best way in my current application (a simple utility using jdbc directly) was to insert directly as a string. For a bigger Hibernate app I might bother to write my own user type. Can't believe someone hasn't already solved this problem in some publicly available code though...</p>
|
<p>Couldn't you just use the MySQL <code>DATE</code> type in your table and then essentially use the formatted string in your insert statement? I'd think something like this would avoid any time zone adjustments.</p>
<pre><code>INSERT INTO time_table(dt) VALUES('2008-12-31')
</code></pre>
| 36,258
|
<p>We're getting ready to translate our PHP website into various languages, and the gettext support in PHP looks like the way to go.</p>
<p>All the tutorials I see recommend using the english text as the message ID, i.e.</p>
<p>gettext("Hi there!")</p>
<p>But is that really a good idea? Let's say someone in marketing wants to change the text to "Hi there, y'all!". Then don't you have to update all the language files because that string -- which is actually the message ID -- has changed?</p>
<p>Is it better to have some kind of generic ID, like "hello.message", and an english translations file?</p>
|
<p>Wow, I'm surprised that no one is advocating using the English as a key. I used this style in a couple of software projects, and IMHO it worked out pretty well. The code readability is great, and if you change an English string it becomes obvious that the message needs to be considered for re-translation (which is a good thing).</p>
<p>In the case that you're only correcting spelling or making some other change that definitely doesn't require translation, it's a simple matter to update the IDs for that string in the resource files.</p>
<p>That said, I'm currently evaluating whether or not to carry this way of doing I18N forward to a new project, so it's good to hear some thoughts on why it might not be a good idea.</p>
|
<p>In addition to the considerations above, there are many cases where you'd want the "key" (msgid) to be different from the source text (English). For example, in the HTML view, I might want to say [yyyy] where the destination and label of that anchor tag depend on the locale of the user. E.g. it might be a link to a social network, and in US it would be Facebook but in China it would be Weibo. So the MsgIds might be something like socialSiteUrl and socialSiteLabel.</p>
<p>I use a mix.</p>
<p>For basic strings that I don't think will have conflicts/changes/weird meanings, I'll make the key be the same as the English. </p>
| 26,612
|
<p>I am studying how two-phase commit works across a distributed transaction. It is my understanding that in the last part of the phase the transaction coordinator asks each node whether it is ready to commit. If everyone agreed, then it tells them to go ahead and commit.</p>
<p>What prevents the following failure?</p>
<ol>
<li>All nodes respond that they are
ready to commit</li>
<li>The transaction
coordinator tells them to "go ahead
and commit" but one of the nodes
crashes before receiving this
message</li>
<li>All other nodes commit successfully, but now the distributed transaction is corrupt</li>
<li>It is my understanding that when the crashed node comes back, its transaction will have been rolled back (since it never got the commit message)</li>
</ol>
<p>I am assuming each node is running a normal database that doesn't know anything about distributed transactions. What did I miss?</p>
|
<p>No, they are not instructed to roll back because in the original poster's scenario, some of the nodes have already committed. What happens is when the crashed node becomes available, the transaction coordinator tells it to commit again.</p>
<p>Because the node responded positively in the "prepare" phase, it is required to be able to "commit", even when it comes back from a crash.</p>
|
<p>There are many ways to attack the problems with two-phase commit. Almost all of them wind up as some variant of the Paxos three-phase commit algorithm. Mike Burrows, who designed the Chubby lock service at Google which is based on Paxos, said that there are two types of distributed commit algorithms - "Paxos, and incorrect ones" - in a lecture I saw.</p>
<p>One thing the crashed node could do, when it reawakes, is say "I never heard about this transaction, should it have been committed?" to the coordinator, which will tell it what the vote was.</p>
<p>Bear in mind that this is an example of a more general problem: the crashed node could miss many transactions before it recovers. Therefore it's terribly important that upon recovery it should talk either to the coordinator or another replica before making itself available. If the node itself can't tell whether or not it has crashed, then things get more involved but still tractable. </p>
<p>If you use a quorum system for database reads, the inconsistency will be masked (and made known to the database itself). </p>
| 20,723
|
<p>How can I exclude the bin folder from SourceSafe in a Visual Studio 2008 web application? I want to be able to check in everything recursively from the solution node without picking up anything in the bin folder.</p>
|
<ul>
<li>Right-click the folder in your
project</li>
<li>select "Exclude from project"</li>
</ul>
|
<p>You can hide the folder through Windows explorer, although it'll disappear from your Visual Studio Solution Exporer, I don't think that'll affect the website.</p>
| 9,890
|
<p>I have a database that I would like class files generated from, and also a .aspx page generated which contains a listview to interface with the classfile for create/read/update/delete. I have started to use Subsonic but am not sure how flexible the scaffold control is. Also, LINQ seems like an option, but it would be nice if that was generated.</p>
<p>Ideally, I would have a DAL which was a set of database classes so I could fine-tune anything I wanted to, and also it would output a web form for the web interface with listview/datagrid that I could incorporate into the back-end but would be generated output so I could fine-tune it myself if I wanted to.</p>
<p>Thanks in advance. The reason I am asking is because I'm working on a project independently and the data access operations are always the most time consuming part of it.</p>
|
<p><strong><a href="http://en.wikipedia.org/wiki/ASP.NET_Dynamic_Data" rel="nofollow noreferrer">ASP.NET Dynamic Data</a></strong> is supergreat! Saw a really cool demo on MSDN Live about a month ago. Create a full .net 3.5 web site from a database in 1 minute!!! Same idea as Ruby on Rails, kind of.</p>
<p>And then you can enhance, configure and modify the parts of the site you want. Basically you get a LINQ 2 SQL layer + some scaffolding witch you then modify to your liking. A quick start for any data centric web project.</p>
<p>And the scaffolding part is probably going to be introduced to other parts of the .net framework - like WPF and silverlight - so this technology is something one should know.</p>
<p>And since it's part of the .net framework it's basically free, which isn't a bad thing either.</p>
|
<p>You should check out <a href="http://www.llblgen.com" rel="nofollow noreferrer">LLBLGen</a> - it's a great product! Not sure how well it does the ASPX side of things, but I'm aware that it does contain that functionality and at the very least does a bloody good job at generating a DAL as a .net project you can include in your solution.</p>
<p>Hope that helps :)</p>
| 26,863
|
<p>Here is the situation:</p>
<p>I have been called upon to work with InstallAnywhere 8, a Java-based installer IDE, of sorts, that allows starting and stopping of windows services, but has no built-in method to query their states. Fortunately, it allows you to create custom actions in Java which can be called at any time during the installation process (by way of what I consider to be a rather convoluted API). </p>
<p>I just need something that will tell me if a specific service is started or stopped.</p>
<p>The IDE also allows calling batch scripts, so this is an option as well, although once the script is run, there is almost no way to verify that it succeeded, so I'm trying to avoid that.</p>
<p>Any suggestions or criticisms are welcome.</p>
|
<p>here's what I had to do. It's ugly, but it works beautifully.</p>
<pre><code>String STATE_PREFIX = "STATE : ";
String s = runProcess("sc query \""+serviceName+"\"");
// check that the temp string contains the status prefix
int ix = s.indexOf(STATE_PREFIX);
if (ix >= 0) {
// compare status number to one of the states
String stateStr = s.substring(ix+STATE_PREFIX.length(), ix+STATE_PREFIX.length() + 1);
int state = Integer.parseInt(stateStr);
switch(state) {
case (1): // service stopped
break;
case (4): // service started
break;
}
}
</code></pre>
<p><code>runProcess</code> is a private method that runs the given string as a command line process and returns the resulting output. As I said, ugly, but works. Hope this helps.</p>
|
<p>During startup, create a file with <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/File.html#deleteOnExit()" rel="nofollow noreferrer">File.deleteOnExit()</a>.</p>
<p>Check for the existence of the file in your scripts.</p>
| 43,369
|
<p>I have a bit of an unusual question. I'm running an old DOS game in dosbox under windows xp and i'm trying to determine when and where it access it's data file.</p>
<p>what can i use that will give me a log of all read requests made to a file? I want to know the "when", "from" and "size" of each file read.</p>
<p>I know my basic 8086/8088 assembly but nothing more. so if there's no shortcut tool available, a recommendation of a debugging tool / tutorial that can help me get on the right track can be great also.</p>
<p>the game's "below the roots", if anyone can shed some light about this game's internals, it will be a great help :)</p>
|
<p>You could try using <a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">FileMon for Windows</a> and see what dosbox is accessing via the windows file system.</p>
|
<p>You could patch the DOSBOX source code :) Just get it to write some debug messages when the reads occur. If you set the debug level high enough it might happen anyway!</p>
<p>Most DOS programs use DOS interrupts. Some however use BIOS interrupts or worse.</p>
<p>Anyway, in case it helps, here are the file-reading DOS interrupts I know of:</p>
<p>FCB-oriented functions:</p>
<ul>
<li>INT 21h, AH=14h (sequential read)</li>
<li>INT 21h, AH=21h (random read)</li>
<li>INT 21h, AH=27h (random block read, à la <code>fread()</code>)</li>
</ul>
<p>Handle-oriented functions:</p>
<ul>
<li>INT 21h, AH=3Fh (sequential read)</li>
<li>INT 21h, AH=42h (seek)</li>
</ul>
| 34,639
|
<p>I have been trying to figure out how to programmatically identify the process that has a lock on a particular file. I've searched through the Win32 API and WMI, but so far I can't find anything. I know it's possible - Sysinternals is able to list every resource accessed/locked by every process on the system.</p>
<p>Can anyone drop me a hint?</p>
|
<p>You can use <a href="http://technet.microsoft.com/en-us/sysinternals/bb896655" rel="noreferrer">handle.exe from Sysinternals</a>.</p>
<p>Something like:</p>
<pre><code>> handle /accepteula C:\path\to\directory
...
program.exe pid: 1234 type: File 2E4: C:\path\to\directory
...
</code></pre>
<p>Thanks to <a href="https://stackoverflow.com/a/599268/367916">https://stackoverflow.com/a/599268/367916</a> .</p>
|
<p>I don't know in Windows, but somebody might find useful to know that, in Linux, you can use the <em>lsof</em> command, or just search through the folders /proc/PROCESS_ID/fd and see what process has opened the file.</p>
| 49,753
|
<p>I have the following tables, the <code>groups</code> table which contains hierarchically ordered groups and <code>group_member</code> which stores which groups a user belongs to. </p>
<pre><code>groups
---------
id
parent_id
name
group_member
---------
id
group_id
user_id
ID PARENT_ID NAME
---------------------------
1 NULL Cerebra
2 1 CATS
3 2 CATS 2.0
4 1 Cerepedia
5 4 Cerepedia 2.0
6 1 CMS
ID GROUP_ID USER_ID
---------------------------
1 1 3
2 1 4
3 1 5
4 2 7
5 2 6
6 4 6
7 5 12
8 4 9
9 1 10
</code></pre>
<p>I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data: </p>
<pre><code>USER VISIBLE_GROUPS
9 4, 5
3 1,2,4,5,6
12 5
</code></pre>
<p>I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL. </p>
|
<p>Two things come to mind:</p>
<p><strong>1 -</strong> You can repeatedly outer-join the table to itself to recursively walk up your tree, as in:</p>
<pre><code>SELECT *
FROM
MY_GROUPS MG1
,MY_GROUPS MG2
,MY_GROUPS MG3
,MY_GROUPS MG4
,MY_GROUPS MG5
,MY_GROUP_MEMBERS MGM
WHERE MG1.PARENT_ID = MG2.UNIQID (+)
AND MG1.UNIQID = MGM.GROUP_ID (+)
AND MG2.PARENT_ID = MG3.UNIQID (+)
AND MG3.PARENT_ID = MG4.UNIQID (+)
AND MG4.PARENT_ID = MG5.UNIQID (+)
AND MGM.USER_ID = 9
</code></pre>
<p>That's gonna give you results like this:</p>
<pre><code>UNIQID PARENT_ID NAME UNIQID_1 PARENT_ID_1 NAME_1 UNIQID_2 PARENT_ID_2 NAME_2 UNIQID_3 PARENT_ID_3 NAME_3 UNIQID_4 PARENT_ID_4 NAME_4 UNIQID_5 GROUP_ID USER_ID
4 2 Cerepedia 2 1 CATS 1 null Cerebra null null null null null null 8 4 9
</code></pre>
<p>The limit here is that you must add a new join for each "level" you want to walk up the tree. If your tree has less than, say, 20 levels, then you could probably get away with it by creating a view that showed 20 levels from every user.</p>
<p><strong>2 -</strong> The only other approach that I know of is to create a recursive database function, and call that from code. You'll still have some lookup overhead that way (i.e., your # of queries will still be equal to the # of levels you are walking on the tree), but overall it should be faster since it's all taking place within the database.</p>
<p>I'm not sure about MySql, but in Oracle, such a function would be similar to this one (you'll have to change the table and field names; I'm just copying something I did in the past):</p>
<pre><code>CREATE OR REPLACE FUNCTION GoUpLevel(WO_ID INTEGER, UPLEVEL INTEGER) RETURN INTEGER
IS
BEGIN
DECLARE
iResult INTEGER;
iParent INTEGER;
BEGIN
IF UPLEVEL <= 0 THEN
iResult := WO_ID;
ELSE
SELECT PARENT_ID
INTO iParent
FROM WOTREE
WHERE ID = WO_ID;
iResult := GoUpLevel(iParent,UPLEVEL-1); --recursive
END;
RETURN iResult;
EXCEPTION WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;
END GoUpLevel;
/
</code></pre>
|
<p><del>There's no way to do this in the SQL standard, but you can usually find vendor-specific extensions, e.g., <code>CONNECT BY</code> in Oracle.</del></p>
<p>UPDATE: As the comments point out, this was added in SQL 99.</p>
| 8,417
|
<p>I'm having some problems with a datagridview element I'm using in VS2008.
This DataGridView is actually a tab in a TabControl element.</p>
<p>I gave it 5 colums which need to be filled up with elements from a costum Object i made.</p>
<p>It's basically a small library application which contains a main class and several classed derived from it. They all have a ToString() method which represents the data as a string of keywords containing the values needed for me to fill up the datagridview.</p>
<p>I only need the first 5 though, some objects will have up to 12 keywords.
Currently, Whenever I add an object, the datagrid doesn't fill itself, instead it adds an amount of columns equall to the amount of keywords the specific object has.</p>
<p>What i'm currently doing is this:</p>
<pre><code>public void libDataGrid_Click(object sender, EventArgs e)
{
if(this.manager.Lib.LibList[0] != null)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
}
</code></pre>
<p><code>this.manager.Lib.LibList</code> returns and ArrayList, in which all objects are stored. The ArrayList can contain elements of all derived classes, but since they are all connected, the string representation will always contain the elements I need to fill up the grid.</p>
<p>I don't see how I can filter only the first five and them have them put in the correct colums.</p>
<p>And another thing. Currently I can only refresh the DataGridView by clicking it. It should change on when I switch to it switch to its specific tab on the Tabcontrol I mean.</p>
<p>I tried adding an argument for SelectedIndexChanged, but that does nothing really...
Or at least, it doesn't appear to do anything.</p>
<p>What I mean is I commented out the code above and added this instead:</p>
<pre><code>public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
</code></pre>
<p>This refreshes it everytime the tab is changed, no matter to which one.
I had to remove the if-statement, since it gave me an Exception. Probably because the length of the ArrayList isn't set on initialisation.</p>
|
<p>I'm a little confused by the question, but here are some thoughts:</p>
<ol>
<li><code>DataGridView</code> has an <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.autogeneratecolumns.aspx" rel="nofollow noreferrer"><code>AutoGenerateColumn</code>s</a> property; if you don't want it to create its own columns, set this to false</li>
<li>To bind to existing columns, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.datapropertyname.aspx" rel="nofollow noreferrer"><code>DataPropertyName</code></a> must be set on each</li>
<li><code>DataGridView</code> (in cmomon with any list control using <code>TypeDescriptor</code>) will hugely prefer <code>List<T></code> (for some <code>T</code> != <code>object</code>) to <code>ArrayList</code>, since it can get meta-data even for an empty list. In general, in 2.0 using <code>ArrayList</code> is a mistake.</li>
</ol>
|
<p>I can only give a partial answer but I think the reason that </p>
<pre><code>public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
libDataGrid.DataSource = this.manager.Lib.LibList;
libDataGrid.Refresh();
}
</code></pre>
<p>isn't working, is because you need to add this line where tabControl1 is being initialized. I've had this problem where VS won't do this itself.</p>
<pre><code>tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);
</code></pre>
| 41,228
|
<p>I've been trying to call Page Methods from my own JavaScript code but it doesn't work. If I use jQuery AJAX I can sucessfully call the Page Methods, but I need to do this from my own JavaScript code because we can't use third-party libraries (we are building our own library).</p>
<p>Whenever I use jQuery AJAX methods I get the result of the Page Method, and when I use my custom JS methods I get whole page back from the AJAX Request.</p>
<p>There must be something different in the way jQuery handles AJAX requests. Does anyone know what could it be?</p>
<p>Below is the code I use to call the same Page Method with jQuery, which works, and the code that I'm using to call it on my own.</p>
<p><strong>jQuery</strong></p>
<pre><code>// JScript File
$(document).ready(function() {
$("#search").click(function() {
$.ajax({
type: "POST",
url: "Account.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Substitui o conteúdo da DIV vom o retorno do Page Method.
displayResult(msg);
}
});
});
});
</code></pre>
<p><strong>Custom JS</strong></p>
<pre><code>function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}
function prepareLinks() {
var btn = document.getElementById("search");
btn.onclick = function() {
var url = "Account.aspx/GetData"
return !grabFile(url);
}
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
displayLoading(document.getElementById("result"));
request.onreadystatechange = function() {
parseResponse(request);
};
//Abre o SOCKET
request.open("GET", file, true);
//Envia a requisição
request.send(null);
return true;
} else {
return false;
}
}
function parseResponse(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var details = document.getElementById("result");
details.innerHTML = request.responseText;
fadeUp(details,255,255,153);
}
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(prepareLinks);
</code></pre>
<p><strong>UPDATE:</strong> I've decided to accept Stevemegson's since his answer was the actual cause to my problem. But I'd like to share with yo a few alterantives I've found to this problem.</p>
<p><em>Stevemegson's Answer</em>:
All I had to do was to change to a POST request and set the request header to JSON,that solved my problem on requesting Page Methods, but now I'm haing a hard time on handling the Response (I'll say more about that on another question).</p>
<p>Here's the right code to get this stuff:</p>
<pre><code>print("function prepareLinks() {
var list = document.getElementById("search");
list.onclick = function() {
var url = "PMS.aspx/GetData"
return !grabFile(url);
} }");
print("function grabFile(file) {
var request = getHTTPObject();
if (request) {
//Evento levantado pelo Servidor a cada mudança de Estado na
//requisição assíncrona
request.onreadystatechange = function() {
parseResponse(request);
};
//USE POST
request.open('POST', file, true);
//SET REQUEST TO JSON
request.setRequestHeader('Content-Type', 'application/json');
// SEND REQUISITION
request.send(null)
return true;
} else {
return false;
}
}");
</code></pre>
<p><em>Brendan's Answer</em>: Through Brendan's answer I did a little research on the ICallBack Interface and the ICallBackEventHandler. To my surprise that's a way to develop aspx pages using Microsoft's implementation of AJAX Request's. This turns out to be a really interesting solution, since it dosen't require any JS Library to work out and it's inside .Net Framework and I believe that only a few people know about this stuff (at least those that are around me didn't know about it at all).
If you wanna know more abou ICallBack check this <a href="http://msdn.microsoft.com/en-us/library/ms178208(VS.80).aspx" rel="nofollow noreferrer" title="How to Implement ICallBack and what's all about">link text</a> on MS or just copy and paste Brendan's answer.</p>
<p><em>A Third Solution:</em> Another solution I found was to instead of creating ASPX pages to handle my server side code I would implement HTML pages and call ASHX files that would do the same thing but they would use less bandwith than an ASPX page. One great about this solution is that I maged to make it work with POST and GET requisitions. Below is the code.</p>
<p>ASHX Code:</p>
<pre><code>print("Imports System.Web
Imports System.Web.Services
Public Class CustomHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim strBuilder As New System.Text.StringBuilder
strBuilder.Append("<p>")
strBuilder.Append("Your name is: ")
strBuilder.Append("<em>")
strBuilder.Append(context.Request.Form(0))
strBuilder.Append("</em>")
strBuilder.Append("</p>")
context.Response.Write(strBuilder.ToString)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get End Property End Class");
</code></pre>
<p>JavaScript File:</p>
<pre><code>print("function prepareLinks() {
var list = document.getElementById("search");
list.onclick = function() {
var url = "CustomHandler.ashx"
return !grabFile(url);
}
}");
print("function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseResponse(request);
};
//VERSÃO do POST
request.open('POST', file, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('name=Helton Valentini')
return true;
} else {
return false;
} }");
</code></pre>
<p>With any of these three options we can make asynchronous calls without use JQuery, using our own Javacript or using the resources Microsoft embeeded on .Net Framework. </p>
<p>I hope this helps our some of you.</p>
|
<p>You're requesting the URL with a GET, while the jQuery code uses a POST. I expect that a Page Method can only be called through a POST, to allow you to include any parameters in the body of your request. You may also need to set the Content-Type of your request to application/json, as the jQuery code does - I don't know whether or not .NET will accept other content types.</p>
|
<p>If you are using ASP.NET AJAX you don't need to do any of this. There is a well defined way of using PageMethods that is a whole lot less complex.</p>
<p>Codebehind</p>
<pre><code> [WebMethod]
public static Whatever GetWhatever( int someParameter, string somethingElse )
{
... make a Whatever ...
return whatever;
}
</code></pre>
<p>Page</p>
<pre><code>...
<script type="text/javascript">
function invokePageMethod(button)
{
var ctx = { control: button };
var someParameter = ...get value from a control...
var somethingElse = ...get another value from a control...
PageMethods.GetWhatever( someParameter, somethingElse, success, failure, ctx );
}
function success(result,context) {
... rearrange some stuff on the page...
}
function failure(error,context) {
... show some error message ...
}
</script>
...
<asp:ScriptManager runat="server" id="myScriptManager" EnablePageMethods="true">
</asp:ScriptManager>
...
<input type="button" onclick="invokePageMethod(this);" value="Do Something" />
</code></pre>
| 24,518
|
<p>I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java. </p>
<p>I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.</p>
|
<p>If the only thing in there is whitespace and integers, just try something like this:</p>
<pre><code>int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
</code></pre>
<p>or easier:</p>
<pre><code>int i1, i2;
theFileStream >> i1 >> i2;
</code></pre>
|
<p>It's more than a little bit C-ish, but you could use sscanf() on the C string representation. Or you could use strtol() or relatives - also on the C string representation.</p>
<p>A more C++-ish way would probably use a string stream and an extractor.</p>
| 26,561
|
<p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
|
<p>Starting with Python 3.6, formatting in Python can be done using <a href="https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498" rel="noreferrer">formatted string literals</a> or <em>f-strings</em>:</p>
<pre><code>hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
</code></pre>
<p>or the <a href="https://docs.python.org/library/stdtypes.html#str.format" rel="noreferrer"><code>str.format</code></a> function starting with 2.7:</p>
<pre><code>"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
</code></pre>
<p>or the <a href="https://docs.python.org/library/stdtypes.html#printf-style-string-formatting" rel="noreferrer">string formatting <code>%</code> operator</a> for even older versions of Python, but see the note in the docs:</p>
<pre><code>"%02d:%02d:%02d" % (hours, minutes, seconds)
</code></pre>
<p>And for your specific case of formatting time, there’s <a href="https://docs.python.org/library/time.html#time.strftime" rel="noreferrer"><code>time.strftime</code></a>:</p>
<pre><code>import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
</code></pre>
|
<p><em>str()</em> in python on an integer will <strong>not</strong> print any decimal places.</p>
<p>If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).</p>
<p>Perhaps the following code will demonstrate:</p>
<pre><code>>>> str(5)
'5'
>>> int(8.7)
8
</code></pre>
| 4,266
|
<p>I'm working with a existing database and trying to write a sql query to get out all the account information including permission levels. This is for a security audit. We want to dump all of this information out in a readible fashion to make it easy to compare. My problem is that there is a bridge/link table for the permissions so there are multiple records per user. I want to get back results with all the permission for one user on one line. Here is an example:</p>
<pre><code>Table_User:
UserId UserName
1 John
2 Joe
3 James
Table_UserPermissions:
UserId PermissionId Rights
1 10 1
1 11 2
1 12 3
2 11 2
2 12 3
3 10 2
</code></pre>
<p>PermissionID links to a table with the name of the Permission and what it does. Right is like 1 = view, 2 = modify, and etc.</p>
<p>What I get back from a basic query for User 1 is:</p>
<pre><code>UserId UserName PermissionId Rights
1 John 10 1
1 John 11 2
1 John 12 3
</code></pre>
<p>What I would like something like this:</p>
<pre><code>UserId UserName Permission1 Rights1 Permission2 Right2 Permission3 Right3
1 John 10 1 11 2 12 3
</code></pre>
<p>Ideally I would like this for all users.
The closest thing I've found is the Pivot function in SQL Server 2005.
<a href="https://web.archive.org/web/20191230182030/http://geekswithblogs.net:80/lorint/archive/2006/08/04/87166.aspx" rel="nofollow noreferrer">Link</a>
The problem with this from what I can tell is that I need to name each column for each user and I'm not sure how to get the rights level. With real data I have about 130 users and 40 different permissions.</p>
<p>Is there another way with just sql that I can do this?</p>
|
<p>You could do something like this:</p>
<pre><code>select userid, username
, max(case when permissionid=10 then rights end) as permission10_rights
, max(case when permissionid=11 then rights end) as permission11_rights
, max(case when permissionid=12 then rights end) as permission12_rights
from userpermissions
group by userid, username;
</code></pre>
<p>You have to explicitly add a similar max(...) column for each permissionid.</p>
|
<p>You could create a temporary table_flatuserpermissions of:</p>
<pre>UserID
PermissionID1
Rights1
PermissionID2
Rights2
...etc to as many permission/right combinations as you need</pre>
<p>Insert records to this table from Table_user with all permission & rights fields null. </p>
<p>Update records on this table from table_userpermissions - first record insert and set PermissionID1 & Rights1, Second record for a user update PermissionsID2 & Rights2, etc.</p>
<p>Then you query this table to generate your report.</p>
<p>Personally, I'd just stick with the UserId, UserName, PermissionID, Rights columns you have now.</p>
<p>Maybe substitute in some text for PermissionID and Rights instead of the numeric values. </p>
<p>Maybe sort the table by PermissionID, User instead of User, PermissionID so the auditor could check the users on each permission type.</p>
| 38,357
|
<p>I am working on a small team of web application developers. We edit JSPs in Eclipse on our own machines and then move them over to a shared application server to test the changes. I have an Ant script that will take ALL the JSPs on my machine and move them over to the application server, but will only overwrite JSPs if the ones on my machine are "newer". This works well most of the time, but not all of the time. Our update method doesn't preserve file change day/times, so it is possible that an Update on my machine will set the file day/time to now instead of when the file was actually last changed. If someone else worked on that file 1 hour ago (but hasn't committed the changes yet), then the older file on my PC will actually have a newer date. So when I run the Ant script it will overwrite their changes with an older file.</p>
<p>What I am looking for is an easy way to just move the file I am currently working on. Is there a way to specify the "current" file in an Ant script? Or an easy way to move the current file within Eclipse? Perhaps a good plugin to do this kind of stuff? I could go out to Windows Explorer to separately move the file, but I would much prefer to be able to do it from within Eclipse.</p>
|
<p>Add a target to your <a href="http://ant.apache.org" rel="nofollow noreferrer">ant</a> build file to copy a single jsp using a command line property definition as @matt b described.</p>
<p>Create a new external tool launch profile and use the "String Substitution Preferences" to pass in the reference to the active file in the editor (<code>resource_name</code>).</p>
<p>See Eclipse Help | Java Development User Guide | Reference | Preferences | Run/Debug | Launching | String Substitution</p>
|
<p>I suggest you to use source control. I prefer Subversion. You can use <a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a> to make the build automatically whenever someone commits new code.</p>
| 38,416
|
<p>I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:</p>
<pre><code>myvalue = CType(value, "String, Integer or Boolean")
</code></pre>
<p>The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.</p>
<p>Is this possible?</p>
|
<p>Sure, but <code>myvalue</code> will have to be defined as of type <code>Object</code>, and you don't necessarily want that. Perhaps this is a case better served by generics.</p>
<p>What determines what type will be used?</p>
|
<p>Well, how do you determine which type is required? As Joel said, this is probably a case for generics. The thing is: since you don't know the type at compile time, you can't treat the value returned anyway so casting doesn't really make sense here.</p>
| 31,324
|
<p>What is the best client side http library to upload multiple files? If it can handle directories that's a huge bonus. I'm looking for something that is open source or free. I'm looking for something like FTP, but that works over http, through the browser. Uploading multiple files through a normal HTML 4.x form is a bit of a hassle when it comes to uploading more than 5-6 files.</p>
<p>Feel free to share your personal experiences.</p>
|
<p><a href="http://www.uploadify.com/" rel="nofollow noreferrer">Uploadify</a> is also another great multiple file uploader. It was built off of SWFUpload and they added new features to it. </p>
<p>Some of the features that I have found most helpful are: </p>
<blockquote>
<p>The user can upload all the files at once using ctrl + clicking on all of
the files</p>
<p>As the files are being downloaded a queue is displayed which
shows the files being downloaded including a completeion bar. </p>
<p>As files are completed they are removed from the queue</p>
<p>It also allows you to specify which file types the user is
able to download (they can only see the ones you choose)</p>
</blockquote>
|
<p>Another option that I have used before is uploading and then extracting ZIP files. I have used <a href="http://pear.php.net/package/Archive_Zip" rel="nofollow noreferrer">PEAR::Archive_Zip</a> to extract. Requires more knowledge on the user's side, but supports directories and unlimited files (depending on the memory alloted to PHP).</p>
| 19,309
|
<p>What languages and tools do you consider a youngster starting out in programming should use in the modern era?</p>
<p>Lots of us started with proprietary Basics and they didn't do all of us long term harm :) but given the experiences you have had since then and your knowledge of the domain now are there better options?</p>
<p>There are related queries to this one such as "<a href="https://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program">Best ways to teach a beginner to program?</a>" and "<a href="https://stackoverflow.com/questions/3553/one-piece-of-advice">One piece of advice</a>" about starting adults programming both of which I submitted answers to but children might require a different tool.</p>
<p>Disclosure: it's bloody hard choosing a 'correct' answer to a question like this so who ever has the best score in a few days will get the 'best answer' mark from me based on the communities choice.</p>
|
<p>I would suggest <a href="http://mindstorms.lego.com/Products/Default.aspx" rel="nofollow noreferrer">LEGO Mindstorm</a>, it provides an intuitive drag and drop interface for programming and because it comes with hardware it provides something tangible for a child to grasp. Also, because it is "LEGO" they might think of it as more of a game then a programming exercise.</p>
|
<p>Wasn't Smalltalk designed for such a purpose? I think Ruby would be a good choice, as a descendant of Smalltalk.</p>
| 4,040
|
<p>What are some good steps to follow for a smooth migration from PHP4 to PHP5. What are some types of code that are likely to break?</p>
|
<p>I also once worked on an app which used PHP4's XML support quite heavily, and would have required quite a bit of work to move to PHP5.</p>
<p>One of the other significant changes I was looking at at the time was the change of the default handling of function parameters. In PHP4 if I remember, they were pass-by-copy unless you specified otherwise, but in PHP5 is changed to pass-by-reference by default. In well written code, that probably won't make a big difference to you, but it could certainly cause problems.</p>
<p>I think one other thing I found changed is that objects are no longer allowed to overwrite their 'this' field. I would say that was a really bad idea to begin with (and I think it may have not been an intentional feature in PHP4), but I certainly found a few parts of our system that relied on it.</p>
<p>Hope some of that helps.</p>
|
<p>We had an app that relied heavily on the PHP 4 XML DOM functions and it required a lot of retooling to change over PHP 5.</p>
<p>Beyond that most changes were improvements to things like error handling (to take advantage of exceptions) and PHP Classes.</p>
| 2,830
|
<p>I am trying to set up apache instead of IIS because <a href="https://stackoverflow.com/questions/188896/why-does-iis-crash-when-i-print-to-stderr-in-perl">IIS needlessly crashes</a> all the time, and it would be nice to be able to have my own checkout of the source instead of all of us editing a common checkout.</p>
<p>In IIS we <em>must</em> do something like this at the beginning of each file:</p>
<pre><code>use CGI;
my $input = new CGI();
print "HTTP/1.0 200 OK";
print $input->header();
</code></pre>
<p>whereas with apache we <em>must</em> leave off the 200 OK line. The following works with both:</p>
<pre><code>use CGI;
my $input = new CGI();
print $input->header('text/html','200 OK');
</code></pre>
<p>Can anyone explain why? And I was under the impression that the CGI module was supposed to figure out these kind of details automatically...</p>
<p>Thanks!</p>
<p><strong>Update</strong>: brian is right, nph fixes the problem for IIS, but it is still broken for Apache. I don't think it's worth it to have conditionals all over the code so I will just stick with the last method, which works with and without nph.</p>
|
<p>HTTP and CGI are different things. The Perl CGI module calls what it does an "HTTP header", but it's really just a CGI header for the server to fix up before it goes back to the client. They look a lot alike which is why people get confused and why the CGI.pm docs don't help by calling them the wrong thing.</p>
<p>Apache fixes up the CGI headers to make them into HTTP headers, including adding the HTTP status line and anything else it might need. </p>
<p>If you webserver isn't fixing up the header for you, it's probably expecting a "no-parsed header" where you take responsibility for the entire header. To do that in CGI.pm, you have to add the <code>-nph</code> option to your call to header, and you have to make the complete header yourself, including headers such as <code>Expires</code> and <code>Last-Modified</code>. See the docs under <a href="http://search.cpan.org/~lds/CGI.pm-3.42/CGI.pm#CREATING_A_STANDARD_HTTP_HEADER:" rel="nofollow noreferrer">Creating a Standard HTTP Header</a>. You can turn on NPH in three ways:</p>
<pre><code>use CGI qw(-nph)
CGI::nph(1)
print header( -nph => 1, ...)
</code></pre>
<p>Are you using an older version of IIS? CGI.pm used to turn on the NPH feature for you automatically for IIS, but now that line is commented out in the source in CGI.pm:</p>
<pre><code># This no longer seems to be necessary
# Turn on NPH scripts by default when running under IIS server!
# $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
</code></pre>
|
<p>I'm still experiencing this problem with ActivePerl 5.14 running under IIS 7 via ISAPI. The <a href="http://docs.activestate.com/activeperl/5.10/faq/Windows/ActivePerl-Winfaq7.html#My_CGI_scripts_don_t_seem_to_run" rel="nofollow">ActivePerl 5.10 FAQ</a> claims the problem is fixed (the 5.14 FAQ doesn't even address the issue), but it doesn't appear to be and setting the registry key they suggest using has no effect in this environment.</p>
<p>Using <code>$ENV{PerlXS} eq 'PerlIS'</code> to detect ISAPI and turn on the NPH key per the aforementioned FAQ seems to work. I hacked my CGI.pm to add the final two lines below under the old IIS handler:</p>
<pre><code># This no longer seems to be necessary
# Turn on NPH scripts by default when running under IIS server!
# $NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{'SERVER_SOFTWARE'}=~/IIS/;
# Turn on NPH scripts by default when running under IIS server via ISAPI!
$NPH++ if defined($ENV{'SERVER_SOFTWARE'}) && $ENV{PERLXS} eq 'PerlIS';
</code></pre>
| 39,666
|
<p>I was curious as to what other shops are doing regarding base application frameworks? I look at an application framework as being able to provide additional or extended functionality to improve the quality of applications built from it.</p>
<p>There are a variety of out of the box frameworks, such as Spring (or Spring.NET), etc. I find that the largest problem with these being that they are not a la carte. Basically, they have too much functionality and unless every piece of that functionality is the best implementation available, chances are that you will end up using a patchwork of multiple frameworks to accomplish these tasks - causing bloat and confusion. This applies to free and commercial systems, in my opinion.</p>
<p>Of course, writing is largely re-inventing the wheel. I don't think it is without merit, though, as it provides the most customizable option. Some things are just too large to develop, though, and seem to be poorly implemented or not implemented at all in this case because of the hesitation to commit to the upfront costs of development.</p>
<p>There are a large variety of open source projects that address individual portions of a could-be application framework as well. These can be adopted or assimilated (obviously depending upon license agreements) to help frame in a comprehensive framework from diverse sources.</p>
<p>We approached the situation by looking at some of the larger concerns in our applications across the entire enterprise and came up with a list of valid cross-cutting concerns and recurring implementation issues. In the end, we came up with hybrid solution that is partially open source, partially based on existing open source options, and partially custom developed.</p>
<p>A few examples of things that are in our framework:</p>
<ul>
<li>Exception and event logging providers. A simple, uniform means by which every application can log exceptions and events in an identical fashion with a minimal coding effort. Out of the box, it can log to a SQL Server, text file, event viewer, etc. It contains extensibility points to log to other sources, as well.</li>
<li>Variable assignment enforcement. A generic class that exposes extension methods based upon the object type, using a syntax that is inspired by JUnit. For example, to determine if myObject is not null, we can do a simple Enforce.That(myObject).IsNotNull(); or determine if it is a specific type by doing a simple Enforce.That(myObject).IsOfType(typeof(Hashtable)); Enforcement failures raise the appropriate exception, both reducing the amount of code and providing consistency in implementation.</li>
<li>Unit testing helpers. A series of classes, based upon reflection that can automatically test classes and their properties. (Inspired by <a href="http://www.codeplex.com/classtester" rel="nofollow noreferrer">Automatic Class Tester</a> from CodePlex) but written from the ground up. Helps to simplify the creation of unit tests for things that are traditionally hard or time-consuming to test.</li>
</ul>
<p>We have also outright adopted some other functionality, as is. For example, we are using <a href="http://postsharp.org" rel="nofollow noreferrer">PostSharp</a> for AOP, <a href="http://code.google.com/p/moq" rel="nofollow noreferrer">moq</a> for mocking, and <a href="http://code.google.com/p/autofac/" rel="nofollow noreferrer">autofaq</a> for DI.</p>
<p>Just wondering what other people might have done and what concerns your framework addresses that you did not find tooling that you were satisfied with? As for our experience, we are definitely reaping the benefits of the new framework and are content with the approach that we have taken.</p>
|
<p>You could use a TBytesField or a TBlobField</p>
<p>ClientDataSet1MySet: TBytesField, Size=32</p>
<pre><code>var
MySet: set of Byte;
Bytes: array of Byte;
begin
MySet := [1, 2, 4, 8, 16];
// Write
Assert(ClientDataSet1MySet.DataSize >= SizeOf(MySet), 'Data field is too small');
SetLength(Bytes, ClientDataSet1MySet.DataSize);
Move(MySet, Bytes[0], SizeOf(MySet));
ClientDataSet1.Edit;
ClientDataSet1MySet.SetData(@Bytes[0]);
ClientDataSet1.Post;
// Read
SetLength(Bytes, ClientDataSet1MySet.DataSize);
if ClientDataSet1MySet.GetData(@Bytes[0]) then
Move(Bytes[0], MySet, SizeOf(MySet))
else
MySet := []; // NULL
end;
</code></pre>
|
<blockquote>
<blockquote>
<p>Based on the example of Andreas, but made somewhat simpler and clearer IMHO.</p>
</blockquote>
</blockquote>
<p>Tested on XE2</p>
<p>You could use a TBytesField or a TBlobField</p>
<p>ClientDataSet1MySet: TBytesField, Size=32</p>
<p>1) Writing </p>
<pre><code>var
MySet: set of Byte;
Bytes: TBytes;
begin
MySet := [0];
// Write
Assert(ClientDataSet1Test.DataSize >= SizeOf(MySet), 'Data field is too small');
SetLength(Bytes, ClientDataSet1Test.DataSize);
Move(MySet, Bytes[0], SizeOf(MySet));
ClientDataSet1.Edit;
ClientDataSet1Test.AsBytes := Bytes;
ClientDataSet1.Post;
end;
</code></pre>
<p>2) Reading</p>
<pre><code>var
MyResultSet: set of Byte;
begin
Move(ClientDataSet1Test.AsBytes[0], MyResultSet, ClientDataSet1Test.DataSize);
end;
</code></pre>
| 45,236
|
<p>C++ preprocessor <code>#define</code> is totally different.</p>
<p>Is the PHP <code>define()</code> any different than just creating a var?</p>
<pre><code>define("SETTING", 0);
$something = SETTING;
</code></pre>
<p>vs</p>
<pre><code>$setting = 0;
$something = $setting;
</code></pre>
|
<p>'define' operation itself is rather slow - confirmed by xdebug profiler.</p>
<p>Here is benchmarks from <a href="http://t3.dotgnu.info/blog/php/my-first-php-extension.html" rel="noreferrer">http://t3.dotgnu.info/blog/php/my-first-php-extension.html</a>: </p>
<ul>
<li><p>pure 'define'<br>
380.785 fetches/sec<br>
14.2647 mean msecs/first-response</p></li>
<li><p>constants defined with 'hidef' extension<br>
930.783 fetches/sec<br>
6.30279 mean msecs/first-response </p></li>
</ul>
<hr>
<p><strong>broken link update</strong></p>
<p>The blog post referenced above has left the internet. It can still be viewed <a href="http://web.archive.org/web/20100504144640/http://t3.dotgnu.info/blog/php/my-first-php-extension.html" rel="noreferrer">here via Wayback Machine</a>. Here is another <a href="http://shwup.blogspot.com/2010/04/about-constants.html" rel="noreferrer">similar article</a>.</p>
<p>The libraries the author references can be found <a href="http://sg.php.net/manual/en/function.apc-define-constants.php" rel="noreferrer">here (apc_define_constants)</a> and <a href="http://pecl.php.net/package/hidef" rel="noreferrer">here (hidef extension)</a>.</p>
|
<p>Main differences:</p>
<ul>
<li>define is constant, variable is variable </li>
<li>they different scope/visibility</li>
</ul>
| 17,856
|
<p>How do you specify the Fill Factor when creating an index in MySql?</p>
|
<p>You don't.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/create-index.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/create-index.html</a></p>
<p>However, it is an 'accepted' feature request for version 6.x:
<a href="http://bugs.mysql.com/bug.php?id=18178" rel="noreferrer">http://bugs.mysql.com/bug.php?id=18178</a></p>
<p>So, don't hold your breath on seeing it any time soon.</p>
|
<p>Assuming that you are using InnoDB, it seems like this is only supported at database level, not index level.</p>
<p>The setting is called <code>innodb_fill_factor</code> and defaults to <code>100</code> see
<a href="https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_fill_factor" rel="nofollow noreferrer">https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_fill_factor</a> for more details.</p>
| 42,888
|
<p>I have a solid of revolution defined by two equations, and I want to generate a STL file for printing from the <a href="https://www.desmos.com/calculator/eh18uwasw9" rel="nofollow noreferrer">difference of the two equations</a>, revolved around x=0. I can get a good visualization when I <a href="https://www.wolframalpha.com/input/?i=rotate%20the%20region%20between%20x%3Dsqrt(129%2B12y-y%5E2)-15.858%20and%20x%3Dsqrt(129%2B12y-y%5E2)-16.358%20around%20x%3D0%20from%20y%3D0%20to%20y%3D4" rel="nofollow noreferrer">query this on Wolfram Alpha</a>, but I cannot figure out how to download an STL of this. I know there is a way to do this via Wolfram's Development Program but I'm not sure how or if that is the best way to do this. Solutions do not have to involve WA.</p>
|
<p>If you properly define your own machine with a <code>delta_wasp.def.json</code> file you can fill in the acceleration and jerk settings of your printer, so that Cura will use the correct values for print time estimation.</p>
<p>For example, take a look at <a href="https://github.com/Ultimaker/Cura/blob/master/resources/definitions/ultimaker2.def.json" rel="nofollow noreferrer">how the Ultimaker 2 is defined.</a></p>
<p>Exposing these settings to the Custom FDM Printer wizard hasn't been implemented (yet).</p>
|
<p>Estimating time for any CNC based machines are measured in this formula:</p>
<p><em>The length of pulses that machine travels x The feedrate of the pulse itself</em></p>
<p>It gives you the time for whole movements. If you're familiar with NC codes, information of any movement is listed in a single line, having its own <code>feedrate</code>, that's what we call pulses.</p>
<p>As machines are not ideal, some delay occurs between pulses, approximately <em>1 or 2 ms</em> according to machine type. That's what is not measured in the formula.</p>
<p>If you were able to measure that <code>delay time</code> and multiply it in <code>number of pulses</code>, by adding it in the <code>estimated time</code> found by machine, you could find a much more definite estimated time, for your process.</p>
| 600
|
<p>I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.</p>
<p>This form uses these styles:</p>
<pre><code>this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );
</code></pre>
<p>And has these non-default property values:</p>
<pre><code>this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
</code></pre>
<p>I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.</p>
|
<p>A borderless window, if I am not mistaken, is flagged such that it offers no system menu, and that it does not appear in the taskbar. </p>
<p>The fact that any given window does not have a border and does not appear in the taskbar is the result of the style flags set on the window. These particular Style flags can be set using the <code>GetWindowLong</code> and <code>SetWindowLong</code> API calls. However you have to be careful as certain styles just don't work together. </p>
<p>I have written a number of custom controls over the years and I am constantly coaxing windows to become something they weren't originally intended to be.<br>
For example I have written my own dropdown control where I needed a window to behave as a popup and not to activate.<br>
The following code will do that. Note that the code appears in the <code>OnHandleCreated</code> event handler. This is because the flags need to be changed just after the handle is setup which indicates that Windows has already set what it thinks the flags should be.</p>
<pre><code>using System.Runtime.InteropServices;
protected override void OnHandleCreated(EventArgs e) {
uint dwWindowProperty;
User32.SetParent(this.Handle, IntPtr.Zero);
dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE );
dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE;
User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty );
dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE );
dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP;
User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty );
base.OnHandleCreated (e);
}
//this is a fragment of my User32 library wrapper needed for the previous code segment.
class User32
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]
public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong);
[DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )]
public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex );
[FlagsAttribute]
public enum WS: uint {
POPUP = 0x80000000,
CHILD = 0x40000000,
}
public enum GWL {
STYLE = -16,
EXSTYLE = -20
}
[FlagsAttribute]
public enum WSEX: uint {
TOP = 0x0,
TOPMOST = 0x8,
TOOLWINDOW = 0x80,
NOACTIVATE = 0x08000000,
}
}
</code></pre>
<p>Unfortunately the <code>SysMenu</code> style cannot be set without using the <code>Caption</code> style, so I can't say if this is a problem in your implementation.</p>
<p>You can check out the original style list and the extend style list at these two links:<br>
<a href="https://learn.microsoft.com/en-us/windows/desktop/winmsg/window-styles" rel="nofollow noreferrer">Window Styles</a><br>
<a href="https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createwindowexw" rel="nofollow noreferrer">CreateWindowEx</a></p>
|
<p>I have the same properties in my application and Right click doesn't work either, so this is not <em>your problem</em>, it appears to be the way windows forms respond when they have no border.</p>
<p>If you set your border to the normal value, you will be able to have right click in the taskbar and such. </p>
<p>For right click on other controls, you'll need to set the ContextMenuStrip and provide your "menu". But I'm not sure if this works when you have it without border. I have been unable to make it work.</p>
| 16,913
|
<p>I'm writing an asp.net application that will need to be localized to several regions other than North America. What do I need to do to prepare for this globalization? What are your top 1 to 2 resources for learning how to write a world ready application.</p>
|
<p>A couple of things that I've learned:</p>
<ul>
<li><p>Absolutely and brutally minimize the number of images you have that contain text. Doing so will make your life a billion percent easier since you won't have to get a new set of images for every friggin' language.</p></li>
<li><p>Be very wary of css positioning that relies on things always remaining the same size. If those things contain text, they will <strong>not</strong> remain the same size, and you will then need to go back and fix your designs.</p></li>
<li><p>If you use character types in your sql tables, make sure that any of those that might receive international input are unicode (nchar, nvarchar, ntext). For that matter, I would just standardize on using the unicode versions.</p></li>
<li><p>If you're building SQL queries dynamically, make sure that you include the N prefix before any quoted text if there's any chance that text might be unicode. If you end up putting garbage in a SQL table, check to see if that's there.</p></li>
<li><p>Make sure that all your web pages definitively state that they are in a unicode format. See Joel's article, mentioned above.</p></li>
<li><p>You're going to be using resource files a lot for this project. That's good - ASP.NET 2.0 has great support for such. You'll want to look into the App_LocalResources and App_GlobalResources folder as well as GetLocalResourceObject, GetGlobalResourceObject, and the concept of meta:resourceKey. Chapter 30 of <a href="https://rads.stackoverflow.com/amzn/click/com/0470041781" rel="noreferrer" rel="nofollow noreferrer">Professional ASP.NET 2.0</a> has some great content regarding that. The 3.5 version of the book may well have good content there as well, but I don't own it.</p></li>
<li><p>Think about fonts. Many of the standard fonts you might want to use aren't unicode capable. I've always had luck with Arial Unicode MS, MS Gothic, MS Mincho. I'm not sure about how cross-platform these are, though. Also, note that not all fonts support all of the Unicode character definition. Again, test, test, test.</p></li>
<li><p>Start thinking now about how you're going to get translations into this system. Go talk to whoever is your translation vendor about how they want data passed back and forth for translation. Think about the fact that, through your local resource files, you will likely be repeating some commonly used strings through the system. Do you normalize those into global resource files, or do you have some sort of database layer where only one copy of each text used is generated. In our recent project, we used resource files which were generated from a database table that contained all the translations and the original, english version of the resource files. </p></li>
<li><p>Test. Generally speaking I will test in German, Polish, and an Asian language (Japanese, Chinese, Korean). German and Polish are wordy and nearly guaranteed to stretch text areas, Asian languages use an entirely different set of characters which tests your unicode support.</p></li>
</ul>
|
<p>I would suggest:</p>
<ol>
<li>Put all strings in either the database or resource files. </li>
<li>Allow extra space for translated text, as some (e.g. German) are wordier.</li>
</ol>
| 8,362
|
<p>I have been working on a printer project that basically is a 2D printer (dot matrix type). We are using solenoids as actuators to make impressions on the paper. We are now in the process of designing custom software. But a problem that we have encountered is that we have no idea how to design software as we are a bunch of beginners in this field.</p>
<p>An idea we are working on is based on position-acknowledge technique. In this technique the computer sends G-code to the controller. The controller after reaching the position defined in code sends an acknowledgement and the computer then sends the next signal. This is the model we are currently working on. </p>
<ul>
<li>Can anyone suggest any other ideas to make this work? </li>
<li>Is Our approach right? </li>
<li>Do 3D printers work using same technique?</li>
</ul>
|
<p>3D printer firmware use gcode that is derived from CNC and no acknowledgment. They send movement commands to the stepper motors like <code>G1 X10 Y10</code> to move the printhead 10 mm along the X and Y.</p>
<p>You could use a ready 3D printer firmware like Marlin on a 3d printer board and use the X-axis or extruder output to couple to your solenoid, sending a <code>G1 Z0.1</code> or <code>G1 E0.1</code>, which will actuate it for a short time. You might even use E and Z on different solenoids.</p>
|
<p>The CNC system, and simplifying intentionally, is divided into several steps:</p>
<ol>
<li><strong>Acquisition of the g-code</strong>: This depends on the platform, whether is a file from an USB flash-memory, network or direct input from the operator. G-code operations needs to be buffered in a quantity enough to allow some "look-ahead" in the program.</li>
<li><strong>Parsing of the g-code</strong>: Parsing of any formal language is based on "formal grammars" theory <a href="https://en.wikipedia.org/wiki/Formal_grammar" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Formal_grammar</a>. Fortunately, g-code is one of the simplest grammar of the Chomsky hierarchy. Language parsing is a full topic in itself, and it follows lexical, syntactical and semantical analysis.</li>
<li><p><strong>Driving</strong>: It exists several different strategies:</p>
<ul>
<li><strong>Open-loop vs closed loop</strong>: In closed-loop CNC, sensors provide a feedback from the movement, allowing the driver to fix deviations (e.g. no step lots). Those systems are more expensive and usually not available in cheap 3D printers. In open-loop CNC, the driver send signals and "hope" the machine will follow, this is the case of most cheap 3D-printers, where if you block the head, it will lose steps.</li>
<li><strong>Synchronous vs asynchronous</strong> (not sure about this naming): In synchronous systems, the driver send a single step for each axis each loop (one step forward, no step, or one step backward for each of the x, y, z, a... axis). In each iteration, the driver establish which steps need to be activated and send it; the speed of the movement depends on how fast this loop is performed. In Asynchronous driving, the loop run at a specific speed and apply steps as needed to correct the distance between the previous/detected position and the expected position.</li>
</ul></li>
</ol>
<p>Acquisition and parsing of g-code can be performed in soft real-time, however the driving needs hard real-time, which precision determine the maximum speed that your CNC can manage.</p>
<p>The servos/steppers usually cannot manage infinite acceleration, this is why the system needs to read g-code instructions ahead to anticipate closed angles or changes in direction. It should then reduce the indicated speed down to something which allows the next instruction.</p>
<p>I hope this give a quick introduction to the topic, obviously, each aspect needs further reading.</p>
| 1,176
|
<p>As I started to learn about 3D printing, the gist I learned was "it's better to store the filaments in a drybox." As I rechecked these notes, they were to a good degree from an era when PLA was rather new to the market and ABS was the goTo.</p>
<p>Then I learned "PLA is not really hygroscopic and can be stored freely."<sup>1</sup></p>
<p>Now, I know some materials are pretty hygroscopic, but not all. So, let's try to pin it down:</p>
<p><strong>Which materials are hygroscopic enough to demand a drybox?</strong></p>
<p>I know that it is good practice to store all filament <a href="https://3dprinting.stackexchange.com/questions/84/does-filament-have-to-be-stored-in-an-airtight-environment">in a somewhat dehumidified or airtight box</a>, but there are some materials out there that become <strong>unprintable</strong> and need drying before printing if improperly stored. <em><strong>This question is to point out these "special storage mandatory" filaments only.</strong></em> If a material can't be printed without dry storage it belongs here. If it is a nice to have, it doesn't.</p>
<p>This is a <strong>Back It Up</strong> question: answers need to provide one of two:</p>
<ul>
<li>explain personal experience, marked as such.</li>
<li>provide an authoritative source (scientific paper/videos, manufacturer papers, quote from an experienced maker).</li>
</ul>
<hr />
<p><sup>1 - For some time (month?). I do store my PLA in a closed but unsealed IKEA container with all the desiccant bags I can find as it is clearly <em>benefitial</em>.</sup></p>
|
<h1><a href="https://ultimaker.com/en/products/materials/pva" rel="nofollow noreferrer">PVA</a></h1>
<p>From experience I can tell that PVA filaments need to be stored with silica beads in a plastic bag or in a specific dry-box. PVA is soluble in water and is very hygroscopic. With moisture it gets soft and swells. My Ultimaker came with an open spool of PVA which popped when heated (steam bubbles popping) resulting in very poor quality supports and clogging of the nozzle. A newly bought spool which was properly packed did not have these issues.</p>
<h1>Nylon</h1>
<p>Some Nylon filament brands require to be stored dry or need to be dried before printing. I have a spool of Nylon that has taken up some moisture although carefully packed, the only time it was out is when it was being printed. This experience applies to Ultimaker Nylon; I've learned now that not all Nylon filaments are behaving the same, it is suggested to look-up the specifics from the manufacturer or from reviews prior to buying.</p>
|
<p>Some brands of PLA+ and colors of filament seem to have issues if left in the open air for too long a period. These then need to be dried back out in a dry box. The filament seems to be softer and the hobb seems to strip it out more easily causing print failures. The colors I have had the most troubles with are transparent Blue, Dark Green, and silky Copper.</p>
| 1,046
|
<p>I have a Rails app that I need to deploy. Here are the facts:</p>
<ul>
<li>The app was developed on Windows and requires Windows binary gems</li>
<li>The app is to be deployed onto an Open Solaris shared server (Joyent)</li>
<li>I do not have permissions to install gems on the server</li>
<li>For the non-binary gems, I can simply do a <code>rake gems:unpack</code> locally and then upload; this works just fine.</li>
</ul>
<p>So my question is, how do I get the <strong>binary</strong> gems I need onto my production server?</p>
|
<blockquote>
<ul>
<li>The app was developed on Windows and requires Windows binary gems</li>
<li>The app is to be deployed onto an Open Solaris shared server (Joyent)</li>
</ul>
</blockquote>
<p>You do realise that you can't run windows binaries on open solaris. Windows is in fact entirely different from solaris...</p>
<p>If the gems are from a third party, you may be able to download pre-packaged binary versions for solaris which someone else has produced. You can then put them in the vendor directory and load them from there rather than installing a gem.</p>
<p>If you can't get pre-packaged binaries for solaris, you'll need to get your own solaris machine (using Virtual PC, VMWare, VirtualBox, etc), use it to compile the gems, then pull the binary files out.</p>
<p>If you in fact only have source code which works on windows (eg: you built it yourself, or the person providing the gem only designed it to work on windows), you are screwed. You will need to find a cross-platform replacement.</p>
<p>It would help if you could tell us <em>which</em> gems you are talking about, so people could help track down a more specific solution, and explain exactly what's going on.</p>
|
<p>The binary gems are the real problem. For all other gems you can use the <code>vendor/gems</code> directory (only possible with Rails 2.1+).</p>
| 23,130
|
<p>I want to be able to change the status message for Live Messenger, but everything I've found only works for the music message (see <a href="http://coldacid.net/images/screenshots/live-messenger-status-and-music-messages" rel="nofollow noreferrer">this screenshot</a> to see the difference between the two).</p>
<p>It is possible to do this, as there are programs that have the ability to change it, and some alternate clients for Live Messenger can also set the status message themselves. I just need to know how to do this myself.</p>
<p><strong>Clarification:</strong> The solution needs to work with the latest versions of Live Messenger (i.e. the wave 3 beta). Working with older versions is good too, but it's the 14.x versions that I'm working with.</p>
|
<p>There is no programmatic way of setting the Live Messenger status message that works with versions inclusive of Live Wave 3.</p>
|
<p>You could possibly go for the messy work-around, using windows API functions to simulate user input.</p>
| 34,605
|
<p>OpenID is all good... UNTIL the provider goes down. At that point you're potentially locked out of EVERYTHING (since you jumped on the bandwagon and applied OpenID everywhere you could).</p>
<p><em>This question came up because I can't, for the life of me, login with my <strong>myopenid.com</strong> provider. :-(</em></p>
|
<p>The fix is for your OpenID site to accept multiple OpenIDs per user account. Something that the spec recommends.</p>
|
<p>The answer is simple. Store an email for the user. Have your own login mechanism. Making OpenId optional is the straight forward answer to this. </p>
<p>Unfortunately some sites are closed minded about OpenId.</p>
| 16,996
|
<p>I'm doing some optimising for my site and am trying to figure out just how big some inline code can be before it can justify having it's own file instead of being written inline.</p>
<p>My guess on how to measure it would be that the amount of code (CSS or JS in this case) would need to be bigger than the HTTP packets sent and received to get a 304 response. </p>
<p>Please ignore the fact that it's a good practice to keep styles and javascript out of the HTML page and think only in terms of browser performance. :)</p>
|
<p>Honestly, in terms of browser performance, separating your CSS & JS files out and properly setting expires headers so they are cached will <em>increase</em> performance, not degrade it. The browser will cache it and never request it again, which reduces the amount of data transferred during multiple page views.</p>
<p>Only if a majority of your audience is coming to your website with an empty cache <strong>and</strong> only viewing 1 page would inlining CSS & JS help.</p>
<p>See:</p>
<ul>
<li><a href="http://developer.yahoo.com/performance/" rel="noreferrer">http://developer.yahoo.com/performance/</a></li>
<li><a href="http://www.ryandoherty.net/2008/10/12/optimizing-openspacebook/" rel="noreferrer">http://www.ryandoherty.net/2008/10/12/optimizing-openspacebook/</a></li>
</ul>
|
<p>I'd also like to add that you should combine your JS/CSS into one download (each) if possible, to save on HTTP connections to the web server. I believe Yahoo suggest this in their URL that Ryan posted. I ended up writing my own .NET component that can combine scripts and CSS, and also minimize them if needed and cache them (server side.)</p>
| 25,907
|
<p>I am new to MVC and I notice that the view pages can look pretty nasty with all the intermixed script tags. Does it make sense to generate the HTML in a method in the view code-behind and then just insert the string result of the method as a single bit of script?</p>
<p>For example: <code><div><%= GenerateTonsOfHTMLFromSomeIEnumerable() %></div></code></p>
<p>Is this contrary to the MVC philosophy? Dumb for some other reason, like performance? Does it have any merit?</p>
|
<p>It's a matter of practice.</p>
<p>Here's an interesting read.</p>
<ol>
<li><p><a href="http://stevesmithblog.com/blog/codebehind-files-in-asp-net-mvc-are-evil/" rel="nofollow noreferrer">Codebehind files are evil</a></p></li>
<li><p><a href="http://msmvps.com/blogs/luisabreu/archive/2008/09/19/codebehind-files-in-asp-net-mvc-are-not-evil.aspx" rel="nofollow noreferrer">Codebehind files are not evil</a></p></li>
</ol>
<p>Also there's an interesting article by "Rob Conery"</p>
<ol>
<li><a href="http://blog.wekeroad.com/blog/crazy-talk-inline-scripting-and-code-behind/" rel="nofollow noreferrer">Inline Scripting and Code behind</a></li>
</ol>
<p>So, the choice is yours. It depends on your application architecuture, how you want to structure it, blah-blah...</p>
<p>I guess the advantage with views without codebehind is that is is much easier to switch to different viewengine which doesn't support codebehind.</p>
<p>Though there will be some amount of work, but still it will be much seamless.</p>
|
<p>You can use code behind as well. It is only a matter of style preference.</p>
| 46,283
|
<p>I'm implementing an SOA at a large company, and I'm not sure which web service specifications (WS-*) actually make sense to implement. At a minimum, I'm looking at WS-Addressing, WS-Security, WS-Eventing, and WS-ReliableMessaging. However, there are <a href="http://www-128.ibm.com/developerworks/webservices/standards/" rel="nofollow noreferrer">several other standards</a> that look interesting, but I don't know which ones are widely adapted. I don't want to implement a standard (and force all the developers to follow them) if they're not mature or necessary.</p>
<p>EDIT:</p>
<p>I'm asking this question not about a specific situation, but in general. There are quite a few WS-* standards that don't seem to have a lot of practical use (at least to me), so I'm really curious about which ones are widely used.</p>
<p>Thanks for your help!</p>
<p>KA</p>
|
<p>WS-Adressing is widely used, and quite useful. For WS-Security, consider the set of mechanisms you'll need (based on your usage scenarios).</p>
|
<p>There are two types of web services : REST and SOAP. They represent different protocols of sending data over the internet.</p>
<p>SOA is an acronym standing for Service Oriented Architecture. It is a way of architecturing your system using multiplet tiers (applications) one atop the other. Web services, mostly soap based are used to implement this archtecture, but they are not the only way.</p>
| 33,372
|
<p>What is the single most effective practice to prevent <a href="http://en.wikipedia.org/wiki/Arithmetic_overflow" rel="nofollow noreferrer">arithmetic overflow</a> and <a href="http://en.wikipedia.org/wiki/Arithmetic_underflow" rel="nofollow noreferrer">underflow</a>?</p>
<p>Some examples that come to mind are:</p>
<ul>
<li>testing based on valid input ranges</li>
<li>validation using formal methods</li>
<li>use of invariants</li>
<li>detection at runtime using language features or libraries (this does not prevent it)</li>
</ul>
|
<p>One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.</p>
<p>Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow. You could even have it do the check on debug builds, and leave things optimized for release builds. In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.</p>
<pre><code>class CheckedInt
{
private:
int Value;
public:
// Constructor
CheckedInt(int src) : Value(src) {}
// Conversions back to int
operator int&() { return Value; }
operator const int &() const { return Value; }
// Operators
CheckedInt operator+(CheckedInt rhs) const
{
if (rhs.Value < 0 && rhs.Value + Value > Value)
throw OverflowException();
if (rhs.Value > 0 && rhs.Value + Value < Value)
throw OverflowException();
return CheckedInt(rhs.Value + Value);
}
// Lots more operators...
};
</code></pre>
<p>Edit:</p>
<p>Turns out someone is <a href="http://www.codeplex.com/SafeInt" rel="nofollow noreferrer">doing this already for C++</a> - the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well.</p>
|
<p>There are more important considerations when choosing which language you use than the size of the integer. Simply check your input if you don't know if the value is in bounds, or use exception handling if the case is extremely rare.</p>
| 10,436
|
<p>Being vaguely familiar with the Java world I was googling for a static analysis tool that would also was intelligent enough to fix the issues it finds. I ran at CodePro tool but, again, I'm new to the Java community and don't know the vendors. </p>
<p>What tool can you recommend based on the criteria above?</p>
|
<ul>
<li><a href="http://findbugs.sourceforge.net/" rel="noreferrer">Findbugs</a></li>
<li><a href="http://pmd.sourceforge.net" rel="noreferrer">PMD</a></li>
<li><a href="http://checkstyle.sourceforge.net" rel="noreferrer">Checkstyle</a></li>
<li><a href="http://www.jutils.com" rel="noreferrer">Lint4J</a></li>
<li><a href="http://classycle.sourceforge.net" rel="noreferrer">Classycle</a></li>
<li><a href="http://sourceforge.net/projects/jdepends" rel="noreferrer">JDepend</a></li>
<li><a href="http://sissy.sourceforge.net" rel="noreferrer">SISSy</a></li>
<li><a href="https://developers.google.com/java-dev-tools/codepro/doc/" rel="noreferrer">Google Codepro</a></li>
</ul>
|
<p>All the above are great tools. PMD is probably the most common. </p>
<p>Another tool is <a href="http://www.enerjy.com/" rel="nofollow noreferrer">Enerjy</a>. It recently became free, so you can download it and try for yourself. Enerjy is somewhat more organized and a better fit to larger teams. It makes it easier to customize and share the rules. Personally, I'm not a big fan, but maybe you'll fancy it more than I do.</p>
| 12,312
|
<p>From what I understand, the parent attribute of a db.Model (typically defined/passed in the constructor call) allows you to define hierarchies in your data models. As a result, this increases the size of the entity group. However, it's not very clear to me why we would want to do that. Is this strictly for ACID compliance? I would like to see scenarios where each is best suited or more appropriate.</p>
|
<p>There are several differences:</p>
<ul>
<li>All entities with the same ancestor are in the same entity group. Transactions can only affect entities inside a single entity group.</li>
<li>All writes to a single entity group are serialized, so throughput is limited.</li>
<li>The parent entity is set on creation and is fixed. References can be changed at any time.</li>
<li>With reference properties, you can only query for direct relationships, but with parent properties you can use the .ancestor() filter to find everything (directly or indirectly) descended from a given ancestor.</li>
<li>Each entity has only a single parent, but can have multiple reference properties.</li>
</ul>
|
<p>The only purpose of entity groups (defined by the parent attribute) is to enable transactions among different entities. If you don't need the transactions, don't use the entity group relationships.</p>
<p>I suggest you re-reading the <a href="http://code.google.com/appengine/docs/datastore/keysandentitygroups.html" rel="noreferrer">Keys and Entity Groups</a> section of the docs, it took me quite a few reads to grasp the idea.</p>
<p>Also watch these talks, among other things they discuss transactions and entity groups:</p>
<ul>
<li><a href="http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine" rel="noreferrer">Building Scalable Web Applications with Google App Engine</a></li>
<li><a href="http://sites.google.com/site/io/under-the-covers-of-the-google-app-engine-datastore" rel="noreferrer">Under the Covers of the Google App Engine Datastore</a></li>
</ul>
| 26,495
|
<p>I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point. If I use:</p>
<pre><code>printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
</code></pre>
<p>I get</p>
<pre><code>359.013
359.010
</code></pre>
<p>Instead of the desired</p>
<pre><code>359.013
359.01
</code></pre>
<p>Can anybody help me?</p>
|
<p>This can't be done with the normal <code>printf</code> format specifiers. The closest you could get would be:</p>
<pre><code>printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01); // 359.01
</code></pre>
<p>but the ".6" is the <em>total</em> numeric width so</p>
<pre><code>printf("%.6g", 3.01357); // 3.01357
</code></pre>
<p>breaks it.</p>
<p>What you <em>can</em> do is to <code>sprintf("%.20g")</code> the number to a string buffer then manipulate the string to only have N characters past the decimal point.</p>
<p>Assuming your number is in the variable num, the following function will remove all but the first <code>N</code> decimals, then strip off the trailing zeros (and decimal point if they were all zeros).</p>
<pre><code>char str[50];
sprintf (str,"%.20g",num); // Make the number.
morphNumericString (str, 3);
: :
void morphNumericString (char *s, int n) {
char *p;
int count;
p = strchr (s,'.'); // Find decimal point, if any.
if (p != NULL) {
count = n; // Adjust for more or less decimals.
while (count >= 0) { // Maximum decimals allowed.
count--;
if (*p == '\0') // If there's less than desired.
break;
p++; // Next character.
}
*p-- = '\0'; // Truncate string.
while (*p == '0') // Remove trailing zeros.
*p-- = '\0';
if (*p == '.') { // If all decimals were zeros, remove ".".
*p = '\0';
}
}
}
</code></pre>
<hr>
<p>If you're not happy with the truncation aspect (which would turn <code>0.12399</code> into <code>0.123</code> rather than rounding it to <code>0.124</code>), you can actually use the rounding facilities already provided by <code>printf</code>. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:</p>
<pre><code>#include <stdio.h>
void nDecimals (char *s, double d, int n) {
int sz; double d2;
// Allow for negative.
d2 = (d >= 0) ? d : -d;
sz = (d >= 0) ? 0 : 1;
// Add one for each whole digit (0.xx special case).
if (d2 < 1) sz++;
while (d2 >= 1) { d2 /= 10.0; sz++; }
// Adjust for decimal point and fractionals.
sz += 1 + n;
// Create format string then use it.
sprintf (s, "%*.*f", sz, n, d);
}
int main (void) {
char str[50];
double num[] = { 40, 359.01335, -359.00999,
359.01, 3.01357, 0.111111111, 1.1223344 };
for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
nDecimals (str, num[i], 3);
printf ("%30.20f -> %s\n", num[i], str);
}
return 0;
}
</code></pre>
<p>The whole point of <code>nDecimals()</code> in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness <code>main()</code> shows this in action:</p>
<pre><code> 40.00000000000000000000 -> 40.000
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
359.00999999999999090505 -> 359.010
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
</code></pre>
<p>Once you have the correctly rounded value, you can once again pass that to <code>morphNumericString()</code> to remove trailing zeros by simply changing:</p>
<pre><code>nDecimals (str, num[i], 3);
</code></pre>
<p>into:</p>
<pre><code>nDecimals (str, num[i], 3);
morphNumericString (str, 3);
</code></pre>
<p>(or calling <code>morphNumericString</code> at the end of <code>nDecimals</code> but, in that case, I'd probably just combine the two into one function), and you end up with:</p>
<pre><code> 40.00000000000000000000 -> 40
359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
359.00999999999999090505 -> 359.01
3.01357000000000008200 -> 3.014
0.11111111099999999852 -> 0.111
1.12233439999999995429 -> 1.122
</code></pre>
|
<p>Your code rounds to three decimal places due to the ".3" before the f</p>
<pre><code>printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
</code></pre>
<p>Thus if you the second line rounded to two decimal places, you should change it to this:</p>
<pre><code>printf("%1.3f", 359.01335);
printf("%1.2f", 359.00999);
</code></pre>
<p>That code will output your desired results:</p>
<pre><code>359.013
359.01
</code></pre>
<p>*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:</p>
<pre><code>printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);
</code></pre>
<p>The Following program source code was my test for this answer</p>
<pre><code>#include <cstdio>
int main()
{
printf("%1.3f\n", 359.01335);
printf("%1.2f\n", 359.00999);
while (true){}
return 0;
}
</code></pre>
| 35,056
|
<p>I'm playing around with the <a href="http://developer.mozilla.org/en/HTML/Canvas" rel="noreferrer"><code><canvas></code></a> element, drawing lines and such.</p>
<p>I've noticed that my diagonal lines are antialiased. I'd prefer the jaggy look for what I'm doing - is there any way of turning this feature off?</p>
|
<p>For images there's now <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled" rel="noreferrer"><code>context.imageSmoothingEnabled</code></a><code>= false</code>.</p>
<p>However, there's nothing that explicitly controls line drawing. You may need to draw your own lines (<a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm" rel="noreferrer">the hard way</a>) using <code>getImageData</code> and <code>putImageData</code>.</p>
|
<p><strong>Just two notes on StashOfCode's answer:</strong></p>
<ol>
<li>It only works for a grayscale, opaque canvas (fillRect with white then draw with black, or viceversa)</li>
<li>It may fail when lines are thin (~1px line width)</li>
</ol>
<p><strong>It's better to do this instead:</strong></p>
<p>Stroke and fill with <code>#FFFFFF</code>, then do this:</p>
<pre><code>imageData.data[i] = (imageData.data[i] >> 7) * 0xFF
</code></pre>
<p>That solves it for lines with 1px width.</p>
<p>Other than that, StashOfCode's solution is perfect because it doesn't require to write your own rasterization functions (think not only lines but beziers, circular arcs, filled polygons with holes, etc...)</p>
| 23,716
|
<p>I'm trying to find a way with javascript to highlight the text the user selects when they click some odd highlight button (as in <span style="background-color:yellow">highlighted text</span>). It only has to work with either WebKit or Firefox, but it seems to be well nigh impossible because it has to work in the following cases:</p>
<pre><code><p>this is text</p>
<p>I eat food</p>
</code></pre>
<p>When the user selects from "is text" through "I eat" in the browser (can't just put a span there).</p>
<p>and this case:</p>
<pre><code><span><span>this is text</span>middle text<span>this is text</span></span>
</code></pre>
<p>When the user selects from "is text" to "this is" in the browser (even though you can wrap your highlight spans around each element in the selection, I'd like to see you try to get that middle text highlighted).</p>
<p>This problem doesn't seem to be solved anywhere, frankly I doubt it's possible.</p>
<p>It would be possible if you could get the Range that you get from the selection as a string complete with html which could be parsed and then replaced, but as far as I can tell you can't get the raw html of a Range.. pity.</p>
|
<p>This answer is probably a few years too late for you, but I faced a similar problem and wanted to document it here, since it is the first hit on google.</p>
<p>To reiterate, the <strong>problem</strong> is that you would like to just capture the Range object from the User Selection and surround it with a styled div, like so:</p>
<pre><code>function highlightSelection() {
var userSelection = window.getSelection().getRangeAt(0);
highlightRange(userSelection);
}
function highlightRange(range) {
var newNode = document.createElement("div");
newNode.setAttribute(
"style",
"background-color: yellow; display: inline;"
);
range.surroundContents(newNode);
}
</code></pre>
<p>But as Original Parent states, this is unsafe. It will work if the selection does not cross element boundaries, but it will throw a DOM eror if the Range created by the User Selection is an unsafe range which crosses the boundaries of HTML tags.</p>
<hr>
<p><strong>The solution</strong> is to produce an array of smaller Range objects, none of which individually crosses an element barrier, but which collectively cover the Range selected by the user. Each of these safe Ranges can be highlighted as above.</p>
<pre><code>function getSafeRanges(dangerous) {
var a = dangerous.commonAncestorContainer;
// Starts -- Work inward from the start, selecting the largest safe range
var s = new Array(0), rs = new Array(0);
if (dangerous.startContainer != a)
for(var i = dangerous.startContainer; i != a; i = i.parentNode)
s.push(i)
;
if (0 < s.length) for(var i = 0; i < s.length; i++) {
var xs = document.createRange();
if (i) {
xs.setStartAfter(s[i-1]);
xs.setEndAfter(s[i].lastChild);
}
else {
xs.setStart(s[i], dangerous.startOffset);
xs.setEndAfter(
(s[i].nodeType == Node.TEXT_NODE)
? s[i] : s[i].lastChild
);
}
rs.push(xs);
}
// Ends -- basically the same code reversed
var e = new Array(0), re = new Array(0);
if (dangerous.endContainer != a)
for(var i = dangerous.endContainer; i != a; i = i.parentNode)
e.push(i)
;
if (0 < e.length) for(var i = 0; i < e.length; i++) {
var xe = document.createRange();
if (i) {
xe.setStartBefore(e[i].firstChild);
xe.setEndBefore(e[i-1]);
}
else {
xe.setStartBefore(
(e[i].nodeType == Node.TEXT_NODE)
? e[i] : e[i].firstChild
);
xe.setEnd(e[i], dangerous.endOffset);
}
re.unshift(xe);
}
// Middle -- the uncaptured middle
if ((0 < s.length) && (0 < e.length)) {
var xm = document.createRange();
xm.setStartAfter(s[s.length - 1]);
xm.setEndBefore(e[e.length - 1]);
}
else {
return [dangerous];
}
// Concat
rs.push(xm);
response = rs.concat(re);
// Send to Console
return response;
}
</code></pre>
<p>It is then possible to (appear to) highlight the User Selection, with this modified code:</p>
<pre><code>function highlightSelection() {
var userSelection = window.getSelection().getRangeAt(0);
var safeRanges = getSafeRanges(userSelection);
for (var i = 0; i < safeRanges.length; i++) {
highlightRange(safeRanges[i]);
}
}
</code></pre>
<hr>
<p>Note that you'' probably need some fancier CSS to make the many disparate elements a user could look nice together. I hope that eventually this helps some other weary soul on the internet!</p>
|
<p>since HTML use <code><mark></code> element as highlighted text, maybe it's easy to use this node, instead of using your own css, much more clean code:</p>
<pre><code>function highlightRange(range) {
var newNode = document.createElement('mark');
range.surroundContents(newNode);
}
// original select range function
function highlight() {
var userSelection = window.getSelection();
for(var i = 0; i < userSelection.rangeCount; i++) {
highlightRange(userSelection.getRangeAt(i));
}
}
</code></pre>
| 39,192
|
<p>I've got two tables that need to be joined via LINQ, but they live in different databases. Right now I'm returning the results of one table, then looping through and retrieving the results of the other, which as you can guess isn't terribly efficient. Is there any way to get them into a single LINQ statement? Is there any other way to construct this to avoid the looping? I'm just looking for ideas, in case I'm overlooking something.</p>
<p>Note that I can't alter the databases, i.e. I can't create a view in one that references the other. Something I haven't tried yet is creating views in a third database that references both tables. Any ideas welcome.</p>
|
<p>You <em>can</em> do this, even across servers, as long as you can access one database from the other. That is, if it's possible to write a SQL statement against <em>ServerA</em>.<em>DatabaseA</em> that accesses <em>ServerB</em>.<em>DatabaseB</em>.<em>schema</em>.<em>TableWhatever</em>, then you can do the same thing in LINQ.</p>
<p>To do it, you'll need to edit the .dbml file by hand. You can do this in VS 2008 easily like this: Right-click, choose <strong>Open With...</strong>, and select <strong>XML Editor</strong>.</p>
<p>Look at the <strong>Connection</strong> element, which should be at the top of the file. What you need to do is provide an explicit database name (and server name, if different) for tables not in the database pointed to by that connection string.</p>
<p>The opening tag for a <strong>Table</strong> element in your .dbml looks like this:</p>
<pre><code><Table Name="dbo.Customers" Member="Customers">
</code></pre>
<p>What you need to do is, for any table <em>not</em> in the connection string's database, change that <strong>Name</strong> attribute to something like one of these:</p>
<pre><code><Table Name="SomeOtherDatabase.dbo.Customers" Member="Customers">
<Table Name="SomeOtherServer.SomeOtherDatabase.dbo.Customers" Member="Customers">
</code></pre>
<p>If you run into problems, make sure the other database (or server) is really accessible from your original database (or server). In SQL Server Management Studio, try writing a small SQL statement running against your original database that does something like this:</p>
<pre><code>SELECT SomeColumn
FROM OtherServer.OtherDatabase.dbo.SomeTable
</code></pre>
<p>If <em>that</em> doesn't work, make sure you have a user or login with access to both databases with the same password. It should, of course, be the same as the one used in your .dbml's connection string.</p>
|
<p>Given your conditions, I don't think you can do this in one Linq statement. But you can join the results of your L2S queries into a Linq to Objects query.</p>
| 45,967
|
<p>I'm thinking about learning CAS, but I need to quickly grasp basic architecture, performance implications and if it at all suits my needs. What should I read?</p>
|
<p>MSDN itself provides the info <a href="http://msdn.microsoft.com/en-us/library/930b76w0(VS.71).aspx" rel="nofollow noreferrer">here</a>.</p>
<p>You also can refer to <a href="http://msdn.microsoft.com/en-us/library/aa302424.aspx" rel="nofollow noreferrer">patterns and practices</a> advocated by Microsoft.</p>
|
<p>There is one very important thing to remember with CAS: a lot of code (too much code) runs at full trust. And with full trust, most of CAS is silently ignored.</p>
| 31,531
|
<p>I have to override Add method of "Controls" property of myControl that is extended from a Panel control of windows. For that i extended ControlCollection class into MyControlCollection where i overriden its Add method. Now i declared a Controls property of MyControlCollection type to hide panel's Controls property. When i am accessing this.Controls.Add(control), it refers to overriden Add method. But if i drags and drops a control on myControl the behaviour is of base type's Add method. Can any body suggest the cause and remedy for this problem? Thanks in advance.</p>
|
<p>You may instead override the CreateControlCollection function, and return an instance of the class of your choice, which inherits System.Web.UI.ControlCollection.
Remove the Controls property from your class, you should not need to override or hide original implementation.</p>
|
<p>Actually i have to restrict adding controls in my control if some flags are true. I used that ControlAdded event but it added problems only. ControlAdded fires only after adding the that control in parent at location 0, 0. After raising that event it relocates the control according to mouse position at droping time. If i removes that new control from parent in ControlAdded's EventHandler exception occurs.</p>
| 28,890
|
<p>I have given a location defined by latitude and longitude.
Now i want to calculate a bounding box within e.g. 10 kilometers of that point.</p>
<p>The bounding box should be defined as latmin, lngmin and latmax, lngmax.</p>
<p>I need this stuff in order to use the <a href="http://www.panoramio.com/api/" rel="noreferrer">panoramio API</a>.</p>
<p>Does someone know the formula of how to get thos points?</p>
<p><strong>Edit:</strong> Guys i am looking for a formula/function which takes lat & lng as input and returns a bounding box as latmin & lngmin and latmax & latmin.
Mysql, php, c#, javascript is fine but also pseudocode should be okay.</p>
<p><strong>Edit:</strong> I am not looking for a solution which shows me the distance of 2 points</p>
|
<p>I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).</p>
<p>My implementation follows (It's written in Python; I have not tested it):</p>
<pre class="lang-py prettyprint-override"><code># degrees to radians
def deg2rad(degrees):
return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
return 180.0*radians/math.pi
# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0 # Major semiaxis [m]
WGS84_b = 6356752.3 # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
# http://en.wikipedia.org/wiki/Earth_radius
An = WGS84_a*WGS84_a * math.cos(lat)
Bn = WGS84_b*WGS84_b * math.sin(lat)
Ad = WGS84_a * math.cos(lat)
Bd = WGS84_b * math.sin(lat)
return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
lat = deg2rad(latitudeInDegrees)
lon = deg2rad(longitudeInDegrees)
halfSide = 1000*halfSideInKm
# Radius of Earth at given latitude
radius = WGS84EarthRadius(lat)
# Radius of the parallel at given latitude
pradius = radius*math.cos(lat)
latMin = lat - halfSide/radius
latMax = lat + halfSide/radius
lonMin = lon - halfSide/pradius
lonMax = lon + halfSide/pradius
return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))
</code></pre>
<p>EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):</p>
<pre class="lang-py prettyprint-override"><code>def dps2deg(degrees, primes, seconds):
return degrees + primes/60.0 + seconds/3600.0
def deg2dps(degrees):
intdeg = math.floor(degrees)
primes = (degrees - intdeg)*60.0
intpri = math.floor(primes)
seconds = (primes - intpri)*60.0
intsec = round(seconds)
return (int(intdeg), int(intpri), int(intsec))
</code></pre>
|
<p>It is very simple just go to panoramio website and then open World Map from panoramio website.Then go to specified location whichs latitude and longitude required.</p>
<p>Then you found latitude and longitude in address bar for example in this address.</p>
<p><a href="http://www.panoramio.com/map#lt=32.739485&ln=70.491211&z=9&k=1&a=1&tab=1&pl=all" rel="nofollow">http://www.panoramio.com/map#lt=32.739485&ln=70.491211&z=9&k=1&a=1&tab=1&pl=all</a></p>
<p>lt=32.739485 =>latitude
ln=70.491211 =>longitude</p>
<p>this Panoramio JavaScript API widget create a bounding box around a lat/long pair and then returning all photos with in those bounds.</p>
<p>Another type of Panoramio JavaScript API widget in which you can also change background color with <a href="http://codespk.blogspot.com/2013/10/panoramio-javascript-api-widget-example.html" rel="nofollow">example and code is here</a>.</p>
<p>It does not show in composing mood.It show after publishing.</p>
<pre><code><div dir="ltr" style="text-align: center;" trbidi="on">
<script src="https://ssl.panoramio.com/wapi/wapi.js?v=1&amp;hl=en"></script>
<div id="wapiblock" style="float: right; margin: 10px 15px"></div>
<script type="text/javascript">
var myRequest = {
'tag': 'kahna',
'rect': {'sw': {'lat': -30, 'lng': 10.5}, 'ne': {'lat': 50.5, 'lng': 30}}
};
var myOptions = {
'width': 300,
'height': 200
};
var wapiblock = document.getElementById('wapiblock');
var photo_widget = new panoramio.PhotoWidget('wapiblock', myRequest, myOptions);
photo_widget.setPosition(0);
</script>
</div>
</code></pre>
| 29,466
|
<p>In Java, is there a programmatic way to find out how many concurrent threads are supported by a CPU?</p>
<p><strong>Update</strong></p>
<p>To clarify, I'm not trying to hammer the CPU with threads and I am aware of Runtime.getRuntime().availableProcessors() function, which provides me part of the information I'm looking for.</p>
<p>I want to find out if there's a way to automatically tune the size of thread pool so that:</p>
<ul>
<li>if I'm running on a 1-year old server, I get 2 threads (1 thread per CPU x an arbitrary multiplier of 2)</li>
<li>if I switch to an Intel i7 quad core two years from now (which supports 2 threads per core), I get 16 threads (2 logical threads per CPU x 4 CPUs x the arbitrary multiplier of 2).</li>
<li>if, instead, I use a eight core Ultrasparc T2 server (which supports 8 threads per core), I get 128 threads (8 threads per CPU x 8 CPUs x the arbitrary multiplier of 2)</li>
<li>if I deploy the same software on a cluster of 30 different machines, potentially purchased at different years, I don't need to read the CPU specs and set configuration options for every single one of them.</li>
</ul>
|
<p>Runtime.availableProcessors returns the number of logical processors (i.e. hardware threads) not physical cores. See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5048379" rel="noreferrer">CR 5048379</a>.</p>
|
<p>This is a function of the VM, not the CPU. It has to do with the amount of heap consumed per thread. When you run out of space on the heap, you're done. As with other posters, I suspect your app becomes unusable before this point if you exceed the heap space because of thread count.</p>
<p>See this <a href="http://forums.sun.com/thread.jspa?threadID=645335&tstart=20" rel="nofollow noreferrer">discussion</a>.</p>
| 26,454
|
<p>Why do you think Microsoft wants us to go through IEnumerable to get to IEnumerator? Isn't the presence or absence of a valid cast to IEnumerator for a given type enough to determine if the type is enumerable or not?</p>
<p>For example whats wrong with the following?</p>
<pre><code>class MyClass : IEnumerator
{
...
}
MyClass myObj = new MyClass();
if(myObj as IEnumerator != null)
{
Console.WriteLine("myObj is enumerable");
}
else
{
Console.WriteLine("myObj doesn't support enumeration");
}
</code></pre>
|
<p>You might have two threads enumerating - each needs its own enumerator.</p>
<p>IEnumerable.GetEnumerator returns an enumerator that is initially positioned before the first element of the collection. If you only had IEnumerator, you'd have to remember to reset yourself before using it, even in a single-threaded scenario.</p>
|
<p>It is a matter of seperating responsibilities, IEnumerable is a class that can be iterated over IEnumerator is a class that does the iteration.</p>
| 42,640
|
<p>I like having my warning level set at W4 but all new projects start at W3. Is there some way to change the default value for warning levels for new projects?</p>
|
<p>I don't know how to do it at the IDE but you cand always edit the new project templates at:</p>
<pre><code>%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\
</code></pre>
<p>If you're using the express version there could be a minor variation in the path:</p>
<pre><code>%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\{Version}\ProjectTemplates\
</code></pre>
<p>Where {Version} is the express flavor you are using, VCSExpress, VBExpress, etc.</p>
<p>The templates are zip files, just edit the project changing:</p>
<pre><code><WarningLevel>3</WarningLevel>
</code></pre>
<p>to</p>
<pre><code><WarningLevel>4</WarningLevel>
</code></pre>
|
<p>I couldn't find any project templates or anything on my machine so I just searched in all the files for WarningLevel. I found common.js at</p>
<pre><code>%\Microsoft Visual Studio 9.0\VC\VCWizards\1033
</code></pre>
<p>Searching in the file showed WarningLevel appeared in three places, lines 672, 699 and 3354. I simply changed the three lines reading</p>
<pre><code>CLTool.WarningLevel = WarningLevel_3;
</code></pre>
<p>to</p>
<pre><code>CLTool.WarningLevel = WarningLevel_4;
</code></pre>
<p>When I made a new project it was set at /w4. So this worked for me, won't guarantee it won't hose your machine.</p>
| 20,451
|
<p>What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?</p>
|
<p>Profile. Profile. Profile. I'm not sure if there is anything out there for PHP, but it should be simple to write a little tool to insert profiling information in your code. You will want to profile function times and SQL query times.</p>
<p>So where you have a function:</p>
<pre><code>function foo($stuff) {
...
return ...;
}
</code></pre>
<p>I would change it to:</p>
<pre><code>function foo($stuff) {
trace_push_fn('foo');
...
trace_pop_fn('foo');
return ...;
}
</code></pre>
<p>(This is one of those cases where multiple returns in a function become a hinderance.)</p>
<p>And SQL:</p>
<pre><code>function bar($stuff) {
trace_push_fn('bar');
$query = ...;
trace_push_sql($query);
mysql_query($query);
trace_pop_sql($query);
trace_pop_fn('bar');
return ...;
}
</code></pre>
<p>In the end, you can generate a full trace of the program execution and use all sorts of techniques to identify your bottlenecks.</p>
|
<p>Whenever I look at performance problems, I think the best thing to do is time how long your pages take to run, and then look at the slowest ones. When you get these real metrics, you can often improve performance on the slowest ones by orders of magnitude, either by fixing a slow SQL query or perhaps tightening up the code a bit.</p>
<p>This of course requires no new hardware or special software, just a critical eye on the existing code.</p>
<p>That said, this will only work for so long... if you really are getting enough traffic to hit the limits of your hardware, and/or there is some code that is just inherently slow and really required, you will have to look at other possibilities.</p>
| 3,360
|
<p>In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files.</p>
<p>layout</p>
<p>+src<br>
+++META-INF<br>
----my.tld<br>
+++++++++++tags<br>
---------------include.jsp<br></p>
<p>I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp</p>
<p>How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup</p>
|
<p>Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a "Java Project", but instead a "Dynamic Web Project" in Eclipse. Nonetheless, I'll try to answer your question.</p>
<p>Based on the diagram of your file system, your files are laid out incorrectly. If you're trying to create a web app (a .war file), then you need a WEB-INF directory. Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory.</p>
<p>Compiled class files must go in the WEB-INF/classes directory.
Jar files that you depend on must go in the WEB-INF/lib directory.
Tablibs must go in the WEB-INF/tags directory.
Finally, your .jsp files must go in src directory (the parent dir of WEB-INF).</p>
<p>So, your layout should look like this:</p>
<pre>
myproject/
`-- src
|-- WEB-INF
| |-- classes
| | `-- MyClass.class
| |-- lib
| | `-- my.jar
| |-- tags
| | `-- my.tld
| `-- web.xml
`-- include.jsp
</pre>
<p>Hope this helps.</p>
<p>-Bryan</p>
|
<p>Maybe the path of the jsp page is incorrect!You can check it using ctrl+left click,if can't open the jsp file,I suggest you check the path.</p>
| 33,021
|
<p>I am trying to use the following code to write data into an excel file</p>
<pre><code> Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Documents.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
Set wbexcel = objexcel.Workbook.Add
End If
</code></pre>
<p>but I'm getting an </p>
<blockquote>
<p>runtime error object doesn't support property or method</p>
</blockquote>
<p>in the line</p>
<pre><code>Set wbexcel = objexcel.Workbook.Add
</code></pre>
<p>I have referenced the Excel object library.</p>
|
<p>You will need to change this line:</p>
<pre><code> Set wbexcel = objexcel.WorkBooks.Open( _
"C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
</code></pre>
<p>Note WorkBooks, not Documents </p>
<p>As For this line Set wbexcel = objexcel.Workbook.Add, wbexcel is defined as a workbook, but the line is an action, so:</p>
<pre><code>objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
</code></pre>
<p>EDIT:
As an aside, DoCmd.Transferspreadsheet is probably the easiest way of transferring a set of data (query, table) from Access to Excel.</p>
|
<p>I have got this code which works fine</p>
<pre><code>Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Dim objSht As Excel.Worksheet
Dim objRange As Excel.Range
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Workbooks.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\reports\ERROR REPORT2.xls")
Set objSht = wbexcel.Worksheets("Sheet1")
objSht.Activate
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
Set objSht = wbexcel.Worksheets("Sheet1")
End If
</code></pre>
<p>but I want to add one more check that if the file exists then I want to see if its is populated with values and if so then I want the next set of values to be populated from the end. As of now it is overwriting the existing values</p>
| 35,505
|
<p>Anybody have a good example how to deep clone a WPF object, preserving databindings?</p>
<hr>
<p>The marked answer is the first part.</p>
<p>The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:<br>
<a href="http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571" rel="noreferrer">http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571</a></p>
|
<p>The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader.</p>
<p>ex:
Write the object to xaml (let's say the object was a Grid control):</p>
<pre><code>string gridXaml = XamlWriter.Save(myGrid);
</code></pre>
<p>Load it into a new object:</p>
<pre><code>StringReader stringReader = new StringReader(gridXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
Grid newGrid = (Grid)XamlReader.Load(xmlReader);
</code></pre>
|
<p>How about:</p>
<pre><code> public static T DeepClone<T>(T from)
{
using (MemoryStream s = new MemoryStream())
{
BinaryFormatter f = new BinaryFormatter();
f.Serialize(s, from);
s.Position = 0;
object clone = f.Deserialize(s);
return (T)clone;
}
}
</code></pre>
<p>Of course this deep clones any object, and it might not be the fastest solution in town, but it has the least maintenance... :)</p>
| 5,250
|
<p>Why is it called a single in VB.net? I'm sure there is a good reason but it doesn't seem intuitive to a non formally trained programmer like me.</p>
|
<p>BPAndrew's question seems to be really "why float in C# and Single in VB.NET", which noone actually answered, so here's my 2p...</p>
<p>The use of "float" in C# seems to be a throwback to its C/C++ heritage. "float" still maps to the System.Single type in C#, so the keyword just exists for convenience. You could just as well declare the variable as "Single" in C# the same as you do in VB.NET.</p>
<p>(And as stated above, naming them Single/Double actually makes more sense as they are single/double precision floating-point numbers.)</p>
|
<p>The technical name is a 'single precision floating point', 'single' because it takes a single word in memory (32 bits). A double, meanwhile, takes 64 bits on most architectures.</p>
| 34,234
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/311054/how-do-i-select-last-5-rows-in-a-table-without-sorting">How do I select last 5 rows in a table without sorting?</a> </p>
</blockquote>
<p>I want to select the top 10 records from a table in SQL Server without arranging the table in ascending or descending order.</p>
|
<p>if random order is needed, you can try</p>
<pre><code>select top 10 * from [tablename] order by newid()
</code></pre>
|
<p>SELECT TOP 10 <requiredfieldListHere> FROM <TheTableNameHere></p>
<p>If you have clustered index this will return the first 10 records in the table. Note however that this would be bad form. A relational table should not be considered as having any particular order. If you don't have a clustered index, it may to return the first 10 records but could just easily return a random set.</p>
<p>Unless you are happy for this to return any 10 records from the table, you should apply a an ORDER BY to your query. This is true even if you have a clustered index since it may be removed or changed in the future.</p>
| 40,077
|
<p>I've seen it used a couple places:</p>
<ul>
<li><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/" rel="nofollow noreferrer">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/</a></li>
<li><a href="http://developer.yahoo.com/flash/astra-flash/classreference/" rel="nofollow noreferrer">http://developer.yahoo.com/flash/astra-flash/classreference/</a></li>
</ul>
<p>Is this just a coincidence or is it somewhere I can grab? I'd love to use it for a new project I'm working on.</p>
<p>Thanks!</p>
|
<p>Take a look at <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=asdoc_1.html" rel="nofollow noreferrer">asdoc</a>. It's what the documentation is automatically generated with.</p>
|
<p>Take a look at <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=asdoc_1.html" rel="nofollow noreferrer">asdoc</a>. It's what the documentation is automatically generated with.</p>
| 47,579
|
<p>What is a proxy object in the Inversion of Control / Aspect-Oriented sense?</p>
<p>Any good articles on what a proxy object is ?<br>
Why you would want to use one ?<br>
And how to write one in C# ? </p>
|
<p>In general, a Proxy object is an object (instance of a class) that exposes the exact same public interface as a "real class" but simply forwards all calls made to it's members to the other real class. Proxy objects are used for a variety of reasons... </p>
<p>One purpose is to "pretend" to be the real class so a client component (or object) can "believe" it's talking to the "real" object, but inside the proxy, other stuff, (like logging, transactional support, etc.) is being done at the same time... Secondly, a proxy can be very cheap in comparson to the real object,. and often is used so that the real objects can be conserved (turned off or released to a pool to be used by other clients) when the client is not using them... The proxy stays "alive" and the client thinks it still has a connection to the real object, but whenever it "calls" the object, it is actually calling the proxy, which goes and gets another real object just to handle the call, and then releases the real object when the call is done. </p>
<p>As to <strong>Inversion of Control</strong> (IOC).. That refers to a common pattern (also referred to as Dependency Injection), where dependant objects inside of a class are "injected" into an instance of the class, from client code, to control which version of a dependant object the instance will use... IOC can be used to inject a "Proxy" object into a class where it thinks it is using the real object... The phrase <em>Inversion of Control</em> refers to the fact that when using this pattern, the decision as to which actual implementation is called is no longer under the control of the class making the call, but to the client of that class, when it <em>injects</em> an instance of a dependant object into the class to be used for this call.</p>
<p>Generally the term IOC is used with what is called an <em>IOC Container</em>, which is a class specifically designed to be responsible for creating instances of dependant classes based on loosely coupled information about those classes (Types) which it gets from some source other than hard-wired dependencies (most often, from some kind of configuration file). Generally, when you use an IOC container, you create an instance of it when the application starts, and then (by reading config data or whatever), you "register" each of the classes (types) that the IOC container will be responsible for, with a key value. The key is often the abstract type or interface that all instances of this registration must implement). Then, in the normal operations of your application, where you might otherwise have new'd up an instance of one of these types, you call the IOC Container, and ask it for an instance instead, using the abstract type/Interface as the key. The IOC container then uses reflection or dynamic loading, (or whatever), to create an instance of whatever type has been "registered" with that key. In this way, simply by changing configuration data, you can control the actual types used by the application, changing them in one environment or deployment location from those used in another. </p>
|
<p>A very good resource about this is the old "Gang of Four" design patterns book. This book is very usefull for anyone developing object-oriented software.
I'm personally using proxy objects for lazy loading with NHibernate. I don't use proxies with inversion of control because I resolve interfaced types only with my IoC. </p>
<p>Charles Bretana's explanation is very good. </p>
<p>I can't imagine the relation between proxy and AoP. Could someone explain that here?</p>
| 36,575
|
<p>I am very close to buying a 3D printer and have started to do some preliminary design work from the things I'd like to make, but I have a question: Which corner of the print bed corresponds to the origin (0,0,0) in slicer software? Is this the same across slicers and printers?</p>
<p>The reason I ask this is because of the difficulty some have in removing items from the bed. It seems to me like I'd want to print small items closer to the front of the printer to make access easier, but it looks like most slicer hosts only show a box representing the build volume with no real indication of what's "front".</p>
|
<p>Depending on what kind of printer you have, the build table origin and slicer origin (0,0) are usually either the front left corner, or the center of the build plate. This can be changed by the end-user in most open-source printers. There is no standard or requirement for a particular origin location. The important thing is merely that the slicer and printer coordinate systems match, so parts actually come out where your slicer thinks they should. </p>
<p>In practice, it's usually quite easy to tell what's "front" in your slicer's build volume. When you open the program, the bed usually appears as it does when you stand in front of your printer. It is rarely an issue. </p>
<p>In terms of difficulty removing prints from the bed, a removable build plate is an excellent solution. Plastic has a higher coefficient of thermal expansion than most build plate materials (like glass), so throwing the print+plate in your freezer will generate large separation forces and help remove the part for you. Non-removable build surfaces are a deal-breaker for most serious 3D printer users I know. Either don't buy such a printer, or add a removable plate yourself. </p>
|
<p>Normally the home position of the printer is the front left corner of the bed. The slicing software will ask you where this is so you can than position your object anywhere on the bed. The slicing software will make all the necessary adjustments for you. You normally would print the object in the middle of the bed, especially when heated, so it would be the most consistent in temperature. </p>
<p>Personally, I have more of an issue keeping the object stuck to the bed than getting it off. Once the bed cools, the objects are easy to pop off. My experience using PLA and a glue stick. </p>
| 279
|
<p>I'm aware there is an AssociationChanged event, however, this event fires after the association is made. There is no AssociationChanging event. So, if I want to throw an exception for some validation reason, how do I do this and get back to my original value? </p>
<p>Also, I would like to default values for my entity based on information from other entities <strong>but do this only when I know the entitiy is instanced for insertion into the database</strong>. How do I tell the difference between that and the object getting instanced because it is about to be populated based on existing data? Am I supposed to know? Is that considiered business logic that should be outside of my entity business logic? </p>
<p>If that's the case, then should I be designing controller classes to wrap all these entities? My concern is that if I deliver back an entity, I want the client to get access to the properties, but I want to retain tight control over validations on how they are set, defaulted, etc. Every example I've seen references context, which is outside of my enity partial class validation, right? </p>
<p>BTW, I looked at the EFPocoAdapter and for the life of me cannot determine how to populate lists of from within my POCO class... anyone know how I get to the context from a EFPoco Class? </p>
|
<p>This is in reply to a comment I left. Hopefully this answers your question, Shimmy. Just comment, and I will shorten it or remove it if it doesn't answer your question.</p>
<p>You will need both INotifyPropertyChanging and INotifyPropertyChanged interfaces to be implemented on your class (unless it is something like an entity framework object, which I believe implements these internally).</p>
<p>And before you set a value to this property, you will need to raise NotifyPropertyChanging.PropertyChanging event, using the name of the property in PropertyChangingEventArgs constructor.</p>
<p>And after you set this value you need to raise NofityPropertyChanged.PropertyChanged event, again using the name of the property this is being raised in PropertyChangedEventArgs constructor.</p>
<p>Then you have to handle the PropertyChanging and PropertyChanged events. In the PropertyChanging event, you need to cache the value. In the PropertyChanged event, you can compare and throw an exception.</p>
<p>To get the property from PropertyChanging/PropertyChanged event args, you need to use relfection.</p>
<pre><code>// PropertyName is the key, and the PropertyValue is the value.
Dictionary <string, object> propertyDict = new Dictionary<object, object>();
// Convert this function prototype to C# from VBNet. I like how Handles is descriptive.
Public Sub PropertyChanging(sender As object, e As PropertyChangingEventArgs) Handles Foo.PropertyChanging
{
if (sender == null || preventRecursion)
{
return;
} // End if
Type senderType = sender.GetType();
PropertyInfo info = senderType.GetProperty(e.PropertyName);
object propertyValue = info.GetValue(sender, null);
// Change this so it checks if e.PropertyName already exists.
propertyDict.Add(e.PropertyName, propertyValue);
} // End PropertyChanging() Event
// Convert this function prototype to C# from VBNet. I like how Handles is descriptive.
Public Sub PropertyChanged(sender As object, e As PropertyChangedEventArgs) Handles Foo.PropertyChanged
{
if (sender == null || preventRecursion)
{
return;
} // End if
Type senderType = sender.GetType();
PropertyInfo info = senderType.GetProperty(e.PropertyName);
object propertyValue = info.GetValue(sender, null);
// Change this so it makes sure e.PropertyName exists.
object oldValue = propertyDict(e.PropertyName);
object newValue = propertyValue;
// No longer needed.
propertyDict.Remove(e.PropertyName);
if (/* some condition */)
{
try {
preventRecursion = true;
info.SetValue(oldValue, null);
Throw New Exception();
} finally {
preventRecursion = false;
} // End try
} // End if
} // End PropertyChanging() Event
</code></pre>
<p>Notice how I am using PreventRecursion, which is a boolean I forgot to add above these methods? When you reset the property back to its previous value, these events will be recalled.</p>
<p>tl;dr</p>
<p>Now you could derive a single event which inherits from INotifyPropertyChanged, but uses an argument which holds an Object representing the previous value as well as the Property Name. And that would reduce the number of events being fired down to one, have similar functionality, and have backwards compatibility with INotifyPropertyChanged.</p>
<p>But if you want to handle anything before the property gets set (say the property does an irreversible change or you need to setup other properties before setting that variable, otherwise an exception will be thrown) you won't be able to do that.</p>
<p>Overall, this method is a very old way of doing things. I would take Poker Villian's answer and have invalid data able to be entered. But disallow saving to a database.</p>
<p>Entity Framework has some excellent code towards validation. You add validation to your properties via attributes. And then it takes care of the work of processing those attributes. Then you can make a property called IsValid, which calls Entity Framework specific validation. It also distinguishes both field errors (like typing in the wrong characters or having a string too long), and class errors (like having missing data or conflicting keys).</p>
<p>Then you can bind IsValid to controls validation, and they will display a red bubble while invalid data is entered. Or you could just implement IsValid validation yourself. But If IsValid is false, SaveChanges event would need to cancel saving.</p>
<p>btw. The code provided will not compile and is pseudocode only (mixing vb and c#). But I believe it is much more descriptive than c# alone--showing exactly what is being handled.</p>
|
<p>Concerning your first question, I would simply implement the changes to the associations as business logic. For example, if you add a Teacher class with multiple Student, do not add students like</p>
<pre><code>aTeacher.Students.Add(new Student)
</code></pre>
<p>instead, create a AddStudent method</p>
<pre><code>public Student AddNewStudent(string name, string studentID)
{
Student s = new Student( name, studentID);
s.Teacher = this; // changes the association
return s;
}
</code></pre>
<p>That way you have full control on when associations are changed. Of course that what prevents another programmer from adding a student directly? On the Student side, you can set the Teacher setter to private (and change the constructor to accept a teacher or similar). On the teacher side, how to make the Students collection non-insertable? I'm not certain... maybe transforming it in a custom collection that doesn't accept inserts.</p>
<p>Concerning the second part of your question, you could probably use the OnVarNameChanging events. If the EntityState is 'New' then you can apply your logic that fetches the real values.</p>
<p>There is also an event that fires when you save changes (OnSavingChanges?) that you could use to determine which objects are new and set some values.</p>
<p>But maybe the simplest solution is to always set the defaults in the constructor and they will get overwritten if the data is loaded from the DB.</p>
<p>Good luck</p>
| 38,909
|
<p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
|
<p>A <a href="http://msdn.microsoft.com/en-us/library/wa80x488.aspx" rel="noreferrer">partial type</a> (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.</p>
<p>The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.</p>
<p>I've no idea whether Python/Perl have the same capabilities, I'm afraid.</p>
|
<p>A Partial type is a type whose declaration is separated across multiple files. It makes sense to use them if you have a big class, which is hard to handle and read for a typical developer, to separate that class definition in separate files and to put in each file a logically separated section of code (for instance all public methods and proprieties in one file, private in other, db handling code in third and so on..)</p>
<p>No you don't have the same syntactical element in Python. </p>
| 37,796
|
<p>What are your experiences with running SQL server in a virtual pc?
Currently we have an sql2008 instance running in a virtual machine.
Both CPU's hit the roof the moment a query is executed.</p>
<p>what are your experiences and what do you suggest in this matter?</p>
|
<p>I've had some serious performance issues using virtualised SQL servers for database heavy applications (ETL development). See <a href="https://stackoverflow.com/questions/149318/virtualized-sql-server-why-not#149381">this Stackoverflow post</a> for a run-down on my experiences and the outcomes of digging into the underlying issues.</p>
<p>Essentially a DB heavy process like ETL will thrash the I/O (more sequential operations, so it isn't waiting for disk seeks as much as an OLTP app) and Translation Lookaside Buffer (large data sets), both of which are very slow on a naively virtualised image. The posting links out to <a href="http://developer.amd.com/assets/NPT-WP-1%201-final-TM.pdf" rel="nofollow noreferrer">this whitepaper on AMD's site</a> (written by a vendor so take with a grain of salt) which (in between extolling the virtues of AMD's new Opteron chips) talks a bit about the underlying issues.</p>
|
<p>Are you using VMWare? If so apply service packs from back in September and since.</p>
<p>Otherwise you can limit the resources that 2008 uses if you have no limited of a machine.</p>
| 48,034
|
<p>I have an Interbase DB. How can I convert it to SQL Server?</p>
|
<p>You could use SQL Server built in <strong>Data Transformation Services (DTS)</strong> in SQL Server 2000 or <strong>SQL Server Integration Services (SSIS)</strong> in SQL Server 2005.</p>
<p>Try setting up an <strong>ODBC DSN</strong> for Interbase. Then in DTS / SSIS use the Other (ODBC Data Source) and the DSN.</p>
<p>If that does not work then see if Interbase has a utility to export to text files and then use DTS / SSIS to import the text files.</p>
|
<p>The Interbase DB Wikipedia page says that it supports OBDC and ADO.NET, so I would think that SQL Server can probably import this database on its own. I don't have access to an Interbase DB installation to try, but you might find these pages helpful.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms141209.aspx" rel="nofollow noreferrer">MSDN on import data wizard</a><br>
<a href="http://msdn.microsoft.com/en-us/library/aa196743(SQL.80).aspx" rel="nofollow noreferrer">MSDN on bulk import command (if Interbase DB can dump a text file)</a><br>
<a href="http://www.developer.com/db/article.php/3702826" rel="nofollow noreferrer">Article on bulk importing from an ADO.NET supporting source</a> </p>
<p>Hopefully somebody will have direct experience with this database and can help. Good luck!</p>
| 13,647
|
<p>There's lots of information about how cached execution plans in SQL Server eliminate much if not most of the performance advantage of stored procedures over dynamic sql. However, I have not found much about whether the same is true for Oracle databases. Does anyone have information or pointers to information about dynamic sql handling in Oracle? Preferably real performance numbers, not general "sp's are good"/ "sp's are bad" discussions.</p>
|
<p>Oracle also has a cached execution facility. The Query is hashed and matched to a plan if it hits on the hash table. You can also use this mechanism to force a plan for a particular query. As with SQL Server, you need to use a parameterised query to do this, rather than substituting the values into the string - as the latter will generate a different hash value.</p>
|
<p>There is something called client side statement caching: <a href="http://www.oracle.com/technology/oramag/oracle/06-jul/o46odp.html" rel="nofollow noreferrer">http://www.oracle.com/technology/oramag/oracle/06-jul/o46odp.html</a></p>
<p>Be aware, client side result caching and client side statement caching are different beasts. </p>
| 48,684
|
<p>I wanna stop the reading of my text input file when the word "synonyms" appears. I'm using ifstream and I don't know how to break the loop. I tried using a stringstream "synonyms" but it ended up junking my bst. I included the complete project files below in case you wanna avoid typing. </p>
<p>Important part:</p>
<pre><code> for(;;) /*here, I wanna break the cycle when it reads "synonyms"*/
{
inStream >> word;
if (inStream.eof()) break;
wordTree.insert(word);
}
wordTree.graph(cout);
</code></pre>
<p>dictionary.txt</p>
<pre><code> 1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
antonyms
1 3
3 1 7
4 5
5 4
7 3
</code></pre>
<p>Project.cpp</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include "MiBST.h"
using namespace std;
class WordInfo{
public:
//--id accesor
int id ()const {return myId; }
/* myId is the number that identifies each word*/
//--input function
void read (istream &in)
{
in>>myId>>word;
}
//--output function
void print(ostream &out)
{
out<<myId<<" "<<word;
}
//--- equals operator
bool operator==(const WordInfo & otherword) const
{ return myId == otherword.myId; }
//--- less-than operator
bool operator<(const WordInfo & otherword) const
{ return myId < otherword.myId; }
private:
int myId;
string word;
};
//--- Definition of input operator
istream & operator>>(istream & in, WordInfo & word)
{
word.read(in);
}
//---Definition of output operator
ostream & operator <<(ostream &out, WordInfo &word)
{
word.print(out);
}
int main(){
// Open stream to file of ids and words
string wordFile;
cout << "Enter name of dictionary file: ";
getline(cin, wordFile);
ifstream inStream(wordFile.data());
if (!inStream.is_open())
{
cerr << "Cannot open " << wordFile << "\n";
exit(1);
}
// Build the BST of word records
BST<WordInfo> wordTree; // BST of word records
WordInfo word; // a word record
for(;;) /*here, I wanna break the cycle when it reads "synonyms"*/
{
inStream >> word;
if (inStream.eof()) break;
wordTree.insert(word);
}
wordTree.graph(cout);
//wordTree.inorder(cout);
system ("PAUSE");
return 0;
}
</code></pre>
<p>MiBST.h (in case you wanna run it)</p>
<pre><code>#include <iostream>
#include <iomanip>
#ifndef BINARY_SEARCH_TREE
#define BINARY_SEARCH_TREE
template <typename DataType>
class BST
{
public:
/***** Function Members *****/
BST();
bool empty() const;
bool search(const DataType & item) const;
void insert(const DataType & item);
void remove(const DataType & item);
void inorder(std::ostream & out) const;
void graph(std::ostream & out) const;
private:
/***** Node class *****/
class BinNode
{
public:
DataType data;
BinNode * left;
BinNode * right;
// BinNode constructors
// Default -- data part is default DataType value; both links are null.
BinNode()
: left(0), right(0)
{}
// Explicit Value -- data part contains item; both links are null.
BinNode(DataType item)
: data(item), left(0), right(0)
{}
}; //end inner class
typedef BinNode * BinNodePointer;
/***** Private Function Members *****/
void search2(const DataType & item, bool & found,
BinNodePointer & locptr, BinNodePointer & parent) const;
/*------------------------------------------------------------------------
Locate a node containing item and its parent.
Precondition: None.
Postcondition: locptr points to node containing item or is null if
not found, and parent points to its parent.#include <iostream>
------------------------------------------------------------------------*/
void inorderAux(std::ostream & out,
BST<DataType>::BinNodePointer subtreePtr) const;
/*------------------------------------------------------------------------
Inorder traversal auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Subtree with root pointed to by subtreePtr has been
output to out.
------------------------------------------------------------------------*/
void graphAux(std::ostream & out, int indent,
BST<DataType>::BinNodePointer subtreeRoot) const;
/*------------------------------------------------------------------------
Graph auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Graphical representation of subtree with root pointed
to by subtreePtr has been output to out, indented indent spaces.
------------------------------------------------------------------------*/
/***** Data Members *****/
BinNodePointer myRoot;
}; // end of class template declaration
//--- Definition of constructor
template <typename DataType>
inline BST<DataType>::BST()
: myRoot(0)
{}
//--- Definition of empty()
template <typename DataType>
inline bool BST<DataType>::empty() const
{ return myRoot == 0; }
//--- Definition of search()
template <typename DataType>
bool BST<DataType>::search(const DataType & item) const
{
typename BST<DataType>::BinNodePointer locptr = myRoot;
typename BST<DataType>::BinNodePointer parent =0;
/* BST<DataType>::BinNodePointer locptr = myRoot;
parent = 0; */ //falta el typename en la declaracion original
bool found = false;
while (!found && locptr != 0)
{
if (item < locptr->data) // descend left
locptr = locptr->left;
else if (locptr->data < item) // descend right
locptr = locptr->right;
else // item found
found = true;
}
return found;
}
//--- Definition of insert()
template <typename DataType>
inline void BST<DataType>::insert(const DataType & item)
{
typename BST<DataType>::BinNodePointer
locptr = myRoot, // search pointer
parent = 0; // pointer to parent of current node
bool found = false; // indicates if item already in BST
while (!found && locptr != 0)
{
parent = locptr;
if (item < locptr->data) // descend left
locptr = locptr->left;
else if (locptr->data < item) // descend right
locptr = locptr->right;
else // item found
found = true;
}
if (!found)
{ // construct node containing item
locptr = new typename BST<DataType>::BinNode(item);
if (parent == 0) // empty tree
myRoot = locptr;
else if (item < parent->data ) // insert to left of parent
parent->left = locptr;
else // insert to right of parent
parent->right = locptr;
}
else
std::cout << "Item already in the tree\n";
}
//--- Definition of remove()
template <typename DataType>
void BST<DataType>::remove(const DataType & item)
{
bool found; // signals if item is found
typename BST<DataType>::BinNodePointer
x, // points to node to be deleted
parent; // " " parent of x and xSucc
search2(item, found, x, parent);
if (!found)
{
std::cout << "Item not in the BST\n";
return;
}
//else
if (x->left != 0 && x->right != 0)
{ // node has 2 children
// Find x's inorder successor and its parent
typename BST<DataType>::BinNodePointer xSucc = x->right;
parent = x;
while (xSucc->left != 0) // descend left
{
parent = xSucc;
xSucc = xSucc->left;
}
// Move contents of xSucc to x and change x
// to point to successor, which will be removed.
x->data = xSucc->data;
x = xSucc;
} // end if node has 2 children
// Now proceed with case where node has 0 or 2 child
typename BST<DataType>::BinNodePointer
subtree = x->left; // pointer to a subtree of x
if (subtree == 0)
subtree = x->right;
if (parent == 0) // root being removed
myRoot = subtree;
else if (parent->left == x) // left child of parent
parent->left = subtree;
else // right child of parent
parent->right = subtree;
delete x;
}
//--- Definition of inorder()
template <typename DataType>
inline void BST<DataType>::inorder(std::ostream & out) const
{
inorderAux(out, myRoot);
}
//--- Definition of graph()
template <typename DataType>
inline void BST<DataType>::graph(std::ostream & out) const
{ graphAux(out, 0, myRoot); }
//--- Definition of search2()
template <typename DataType>
void BST<DataType>::search2(const DataType & item, bool & found,
BST<DataType>::BinNodePointer & locptr,
BST<DataType>::BinNodePointer & parent) const
{
locptr = myRoot;
parent = 0;
found = false;
while (!found && locptr != 0)
{
if (item < locptr->data) // descend left
{
parent = locptr;
locptr = locptr->left;
}
else if (locptr->data < item) // descend right
{
parent = locptr;
locptr = locptr->right;
}
else // item found
found = true;
}
}
//--- Definition of inorderAux()
template <typename DataType>
void BST<DataType>::inorderAux(std::ostream & out,
BST<DataType>::BinNodePointer subtreeRoot) const
{
if (subtreeRoot != 0)
{
inorderAux(out, subtreeRoot->left); // L operation
out << subtreeRoot->data << " "; // V operation
inorderAux(out, subtreeRoot->right); // R operation
}
}
//--- Definition of graphAux()
template <typename DataType>
void BST<DataType>::graphAux(std::ostream & out, int indent,
BST<DataType>::BinNodePointer subtreeRoot) const
{
if (subtreeRoot != 0)
{
graphAux(out, indent + 8, subtreeRoot->right);
out << std::setw(indent) << " " << subtreeRoot->data << std::endl;
graphAux(out, indent + 8, subtreeRoot->left);
}
}
#endif
</code></pre>
|
<p>You can do it like</p>
<pre><code>/* here, it stops when reading "synonyms" or when failing to extract a word. */
while(inStream >> word && word != "synonym") {
wordTree.insert(word);
}
wordTree.graph(cout);
</code></pre>
<p>Note that when it fails to read a sequence of non-whitespace characters, it sets the fail-bit of the stream. inStream evaluates to false then. That is what makes the loop work. Be careful when using <code>.eof();</code> It only returns true after you tried to read beyond the end of file. So for example, you will exit the loop, and miss the word <em>3 tree</em> here:</p>
<pre><code>1 house 2 garden 3 tree
</code></pre>
<p>Assuming there is no white-space after <em>tree</em>. The same will of course happen if you have newlines between the word information and have no trailing newline after the last word. Using <code>if(inStream)</code> (which the while loop does implicitly) is safe. It would still evaluate to true in this case, and only to false if it didn't read anything except white-space.</p>
|
<p>@SoapBox:</p>
<p>I created this == operator:</p>
<pre><code> //--- equals operator for String
bool operator==(const string & aString) const
{ return word == aString; } // word is the WordInfo string field for 'real' word
</code></pre>
<p>And changed the for(;;) to:</p>
<pre><code>for(;;)
{
inStream >> word;
if (word=="synonyms") break;
wordTree.insert(word);
}
</code></pre>
<p>And ended up with an infinite loop printing:</p>
<pre><code>"Item already in the tree"
</code></pre>
<p>Btw, I previoulsy tested the tree with a sample dictionary like this and it worked.</p>
<pre><code>dict2.txt
</code></pre>
<p>1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful</p>
| 48,358
|
<p>Can someone tell me what the statuses mean in SQL Server's sp_who command? Why might a spid be suspended? What does it mean to be "runnable"?</p>
<p>Thanks!</p>
|
<p>Pretty easy to find answer online. <a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-who-transact-sql" rel="nofollow noreferrer">Link</a></p>
<p><strong>dormant.</strong> SQL Server is resetting the session.</p>
<p><strong>running.</strong> The session is running one or more batches. When Multiple Active Result Sets (MARS) is enabled, a session can run multiple batches. For more information, see Using Multiple Active Result Sets (MARS).</p>
<p><strong>background.</strong> The session is running a background task, such as deadlock detection.</p>
<p><strong>rollback.</strong> The session has a transaction rollback in process.</p>
<p><strong>pending.</strong> The session is waiting for a worker thread to become available.</p>
<p><strong>runnable.</strong> The session's task is in the runnable queue of a scheduler while waiting to get a time quantum.</p>
<p><strong>spinloop.</strong> The session's task is waiting for a spinlock to become free.</p>
<p><strong>suspended.</strong> The session is waiting for an event, such as I/O, to complete.</p>
|
<p>I believe that part of the confusion on this is that there are statuses outside of the list shown above that are seen. Three that come to mind are</p>
<ul>
<li>Sleeping </li>
<li>Awaiting Command</li>
<li>Other</li>
</ul>
| 25,289
|
<p>I was thinking about <a href="https://lifehacks.stackexchange.com/questions/24627/how-to-paint-a-circle-pattern-on-a-big-piece-of-paper">this question</a> and thought of maybe printing a pattern-drawing roller painter.</p>
<p>The question is: is it possible to print with an ink absorbing material that could make a paint roller possible?</p>
<p>P.S: I don't own a 3D printer, nor have I any deep knowledge in this matter. I simply want to know if this is feasible, so I can start looking for someone to 3D print this for me. If it's not, knowing beforehand could spare me a lot of time.</p>
|
<p>While printing a <em>roller stamp</em> or rubber-roll from a flexible material such as <a href="https://all3dp.com/2/tpe-vs-tpu-flexible-filament-the-differences/" rel="nofollow noreferrer">[hard]TPU, [softer] TPE</a>, or even a [super soft] foaming flexible filament is certainly possible. In any case, this would create soft, somewhat squishy prints. These prints will work quite easily as a stamp or woodblock printing stock, transferring ink from a pad to paper. The print pattern will depend a lot on how soft the stamp is: the harder, the sharper it will print. A massive roll of this material can behave akin to a rubber roll as one uses it in linoleum printing.</p>
<p>A foaming filament might be able to take <em>a little</em> paint in its airgaps, but it will never be as soft and contain as much paint as a foam lacquer roll - making it at best an improvised tool, or one that is chosen for a specific artistic purpose. It behaves more akin to closed-cell foam, while foam brushes and rolls from artist supply are typically open-cell ones. So if you go for a roller-stamp, you'll need to have an ink reservoir in the shape of a soaky-roller that isn't printed.</p>
<p>To top it off, it is nearly impossible to print a hairy wall painting roller: the hairs used in them can't be achieved with common print materials and slicers at the time. Even if stringing creates hair of <em>similar</em> dimensions, they are not affixed well enough to not get lost in the paint and can't be reliably created on demand.</p>
<p>Notes on pricing: One of the few options for foaming print materials is colorFabb, who was the first to offer such. Most of their foaming filaments cost around <a href="https://colorfabb.com/filaments/lightweight-foaming-filaments" rel="nofollow noreferrer">50 €/kg</a>, their flexible NinjaFlex costs about <a href="https://colorfabb.com/filaments/ninjatek-filaments" rel="nofollow noreferrer">80 €/kg</a>.</p>
|
<p>I'm relatively new to 3D printing, but I know some stuff. If you really wanted to print a paint roller with a pattern, I would actually go with nylon or TPR. TPE is okay, but I find that it is less cushy. I would highly suggest buying your own printer for this project. It would be much more cost effective in not only the long run, but for testing different materials. 3D printing services get pricey, so choose your printer wisely. If you do decide to buy your own printer, I would go with an Ender 3 pro. Mine is very smooth, and has an easy-to-use interface.</p>
| 1,907
|
<p>I can print with <code>printf</code> as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?</p>
<p>I am running gcc.</p>
<pre><code>printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
print("%b\n", 10); // prints "%b\n"
</code></pre>
|
<p>Hacky but works for me:</p>
<pre><code>#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
</code></pre>
<pre><code>printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));
</code></pre>
<p>For multi-byte types </p>
<pre><code>printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));
</code></pre>
<p>You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to <code>BYTE_TO_BINARY</code>) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.</p>
|
<p>Even for the runtime libraries that DO support %b it seems it's only for integer values.</p>
<p>If you want to print floating-point values in binary, I wrote some code you can find at <a href="http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/" rel="nofollow noreferrer">http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/</a> .</p>
| 13,710
|
<p>Are there any good tools out there for automatically converting non-Java source code into Java source?</p>
<p>I'm not expecting something perfect, just to get the worst of the grunt work out of the way.</p>
<p>I guess there is a sliding scale of difficulty. C# should be relatively easy (so long as you ignore all the libraries). (well written) C++ not so bad. C requires making a little OO. (Statically type) functional languages may be easy to grok. Dynamic OO languages may require non-local analysis.</p>
|
<p>One thing you can try is find a Java bytecode compiler for the language you're talking about (there are JVM compilers for all kinds of languages) and then decompile the bytecode back into Java using a decompiler like Jad. </p>
<p>This is fraught with peril. The regenerated code will suck and will probably be unreadable.</p>
|
<p>ADA to Java can be done with a find-and-replace!</p>
| 6,893
|
<p>What is the fastest way of transferring few thousand rows of data from one DataTable to another? Would be great to see some sample code snippets.</p>
<p>Edit: I need to explain a bit more. There is a filtering condition for copying the rows. So, a plain Copy() will not work.</p>
|
<p>You can't copy the whole table, you need to copy one rows. From <a href="http://support.microsoft.com/kb/308909" rel="noreferrer">http://support.microsoft.com/kb/308909</a> (sample code if you follow the link)</p>
<p>"How to Copy DataRows Between DataTables
Before you use the ImportRow method, you must ensure that the target table has the identical structure as the source table. This sample uses the Clone method of DataTable class to copy the structure of the DataTable, including all DataTable schemas, relations, and constraints.</p>
<p>This sample uses the Products table that is included with the Microsoft SQL Server Northwind database. The first five rows are copied from the Products table to another table that is created in memory."</p>
|
<p>What is wrong with <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.copy.aspx" rel="nofollow noreferrer">DataTable.Copy</a>?</p>
| 9,347
|
<p>I'm building a Lifestreaming app that will involve pulling down lots of feeds for lots of users, and performing data-mining, and machine learning algorithms on the results. GAE's load balanced and scalable hosting sounds like a good fit for a system that could eventually be moving around a LOT of data, but it's lack of cron jobs is a nuisance. Would I be better off using Django on a co-loc and dealing with my own DB scaling? </p>
|
<p>While I can not answer your question directly, my experience of building <a href="https://github.com/juvenn/microupdater" rel="nofollow noreferrer">Microupdater</a> (a news aggregator collecting a few hundred feeds on AppEngine) may give you a little insight.</p>
<ul>
<li><p>Fetching feeds. Fetching lots of feeds by cron jobs (it was the only solution until SDK 1.2.5) is not efficient and scalable, which has lower limit on job frequency (say 1 min, so you could only fetch at most 60 feeds hourly). And with latest SDK 1.2.5, there is <a href="http://drupal.org/project/xmpp" rel="nofollow noreferrer">XMPP API</a>, which I have not implemented yet. The best promising approach would be <a href="http://code.google.com/p/pubsubhubbub/" rel="nofollow noreferrer">PubSubHubbub</a>, of which you offer an callback url and HubBub will notify you new entries in <strong>real-time</strong>. And there is an <a href="http://pubsubhubbub.appspot.com/" rel="nofollow noreferrer">demo implementation</a> on AppEngine, which you can play around.</p></li>
<li><p>Parsing feeds. You may already know that parsing feeds is cpu-intensive. I use <a href="http://www.feedparser.org/" rel="nofollow noreferrer">Universal Feed Parser</a> by Mark Pilgrim, when parsing a large feed (say a public google reader topic), AppEngine may fail to process all entries. My dashboard have a lot of these CPU-limit warnings. But it may result in my incapability to optimize the code yet.</p></li>
</ul>
<p>Totally said, AppEngine is not yet an ideal platform for lifestream app, but that may change in future.</p>
|
<p>No. If you need to pull lots of things down, App Engine isn't going to work so well. You can use it as a front end by putting your data in their store after doing your offline preprocessing, but you can't do much in the ~1 second time you have per request without doing some <i>really</i> crazy things.</p>
<p>Your app would likely be better off on your own hosting.</p>
| 16,372
|
<p>Are <strong>CDATA</strong> tags ever necessary in script tags and if so when?</p>
<p>In other words, when and where is this:</p>
<pre><code><script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
</code></pre>
<p>preferable to this:</p>
<pre><code><script type="text/javascript">
...code...
</script>
</code></pre>
|
<p>A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) <em>and you want to be able to write literal <code>i<10</code> and <code>a && b</code> instead of <code>i&lt;10</code> and <code>a &amp;&amp; b</code></em>, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will <em>probably</em> want to use a CDATA section.</p>
<p>Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.</p>
<p>For a good writeup on the subject, see <a href="https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm" rel="noreferrer">https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm</a></p>
|
<p><a href="http://javascript.about.com/library/blxhtml.htm" rel="nofollow noreferrer">When you want it to validate</a> (in XML/XHTML - thanks, <a href="https://stackoverflow.com/users/6436/loren-segal">Loren Segal</a>).</p>
| 9,238
|
<p>I am trying to convince those who set standards at my current organization that we should use jQuery rather than Prototype and/or YUI. What are some convincing advantages I can use to convince them?</p>
|
<p>The 3 main advantages of jQuery are:</p>
<ul>
<li>its light weight when compared to other javascript frameworks</li>
<li>it has a wide range of <a href="http://plugins.jquery.com/" rel="nofollow noreferrer">plugins</a> available for various specific needs</li>
<li>it is easier for a designer to learn jQuery as it uses familiar CSS syntax. jQuery is <a href="http://www.sitepoint.com/article/jquery-javascipt-designers/" rel="nofollow noreferrer">Javascript for Designers</a></li>
</ul>
|
<p>Why don't you create a quick comparison? </p>
<p>Take a task like "find all divs or tables which contain images of class foo and attach a click event to each of them which makes them expand 50%." Or something more relevant to what you're doing.</p>
<p>Then code that with jQuery, Prototype, etc, and compare. Which is shorter? Easier to read? Faster to run? (You can find a speed comparison <a href="http://mootools.net/slickspeed" rel="nofollow noreferrer">here</a>.)</p>
| 9,262
|
<p>I'm using the mockrunner package from <a href="http://mockrunner.sourceforge.net/" rel="noreferrer">http://mockrunner.sourceforge.net/</a> to set up a mock queue for JUnit testing an XML filter which operates like this:</p>
<ol>
<li>sets recognized properties for an ftp server to put and get xml input and a jms queue server that keeps track of jobs. Remotely there waits a server that actually parses the xml once a queue message is received.</li>
<li>creates a remote directory using ftp and starts a queue connection using mqconnectionfactory to the given address of the queue server.</li>
<li>once the new queue entry is made in 2), the filter waits for a new queue message to appear signifying the job has been completed by the remote server. The filter then grabs the modified xml file from the ftp and passes it along to the next filter. </li>
</ol>
<p>The JUnit test I am working on simply needs to emulate this environment by starting a local ftp and mock queue server for the filter to connect to, then waiting for the filter to connect to the queue and put the new xml input file on a local directory via a local ftp server, wait for the queue message and then modify the xml input slightly, put the modified xml in a new directory and post another message to the queue signifying the job has completed. </p>
<p>All of the tutorials I have found on the net have used EJB and JNDI to lookup the queue server once it has been made. If possible, I'd like to sidestep that route by just creating a mock queue on my local machine and connecting to it in the simplest manner possible, not using EJB and JNDI.</p>
<p>Thanks in advance!</p>
|
<p>I'd recommend having a look at using <a href="http://activemq.apache.org/camel/" rel="nofollow noreferrer">Apache Camel</a> to create your test case. Then its really easy to switch your test case from any of the <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">available components</a> and most importantly Camel comes with some really handy <a href="http://activemq.apache.org/camel/mock.html" rel="nofollow noreferrer">Mock Endpoints</a> which makes it super easy to test complex routing logic particularly with asynchronous operations.</p>
<p>If you also use Spring, then maybe start by trying out these <a href="http://activemq.apache.org/camel/spring-testing.html" rel="nofollow noreferrer">Spring unit tests with mock endpoints in Camel</a> which let you inject the mock endpoints to perform assertions on together with the ProducerTemplate object to make it really easy to fire your messages for your test case. e.g. see the last example on that page.</p>
<p>Start off using simple endpoints like the <a href="http://activemq.apache.org/camel/seda.html" rel="nofollow noreferrer">SEDA endpoint</a> - then when you've got your head around the core spring/mock framework, try using the <a href="http://activemq.apache.org/camel/jms.html" rel="nofollow noreferrer">JMS endpoint</a> or <a href="http://activemq.apache.org/camel/ftp.html" rel="nofollow noreferrer">FTP endpoint</a> endpoints etc.</p>
|
<p>I'd recommend having a look at using <a href="http://activemq.apache.org/camel/" rel="nofollow noreferrer">Apache Camel</a> to create your test case. Then its really easy to switch your test case from any of the <a href="http://activemq.apache.org/camel/components.html" rel="nofollow noreferrer">available components</a> and most importantly Camel comes with some really handy <a href="http://activemq.apache.org/camel/mock.html" rel="nofollow noreferrer">Mock Endpoints</a> which makes it super easy to test complex routing logic particularly with asynchronous operations.</p>
<p>If you also use Spring, then maybe start by trying out these <a href="http://activemq.apache.org/camel/spring-testing.html" rel="nofollow noreferrer">Spring unit tests with mock endpoints in Camel</a> which let you inject the mock endpoints to perform assertions on together with the ProducerTemplate object to make it really easy to fire your messages for your test case. e.g. see the last example on that page.</p>
<p>Start off using simple endpoints like the <a href="http://activemq.apache.org/camel/seda.html" rel="nofollow noreferrer">SEDA endpoint</a> - then when you've got your head around the core spring/mock framework, try using the <a href="http://activemq.apache.org/camel/jms.html" rel="nofollow noreferrer">JMS endpoint</a> or <a href="http://activemq.apache.org/camel/ftp.html" rel="nofollow noreferrer">FTP endpoint</a> endpoints etc.</p>
| 19,126
|
<p>Is there a way to sniff SQL queries sent to a SQL Server db on any level (above transport level)? Perhaps there's some kind of a tracer in ASP.NET or built-in log in SQL Server ? </p>
|
<p>SQL Server Profiler perhaps? This will pick up what queries are executed. You can also get statistics, query plans and many other items of interest from this.</p>
|
<p>The tool your looking for is <a href="http://msdn.microsoft.com/en-us/library/ms181091.aspx" rel="nofollow noreferrer">SQL Server Profiler</a>, learn to use it and to love it.</p>
<p>Try starting with a filter on ApplicationName and/or HostName for your IIS server running your ASP.NET application. Profiler can get quite chatty.</p>
| 45,477
|
<p>Suppose we have:</p>
<pre><code>interface Foo
{
bool Func(int x);
}
class Bar: Foo
{
bool Func(int x)
{
return (x>0);
}
}
class Baz: Foo
{
bool Func(int x)
{
return (x<0);
}
}
</code></pre>
<p>Now we can toss around Bar and Baz as a Foos and call their Func methods.</p>
<p>Delegates simplify this a little bit:</p>
<pre><code>delegate bool Foo(int x);
bool Bar(int x)
{
return (x<0);
}
bool Baz(int x)
{
return (x>0);
}
</code></pre>
<p>Now we can toss around Bar and Baz as Foo delegates.</p>
<p>What is the real benefit of delegates, except for getting shorter code?</p>
|
<p>There is a slight difference, delegates can access the member variables of classes in which, they are defined. In C# (unlike Java) all inner class are consider to be static. Therefore if you are using an interface to manage a callback, e.g. an ActionListener for a button. The implementing inner class needs to be passed (via the constructor) references to the parts of the containing class that it may need to interact with during the callback. Delegates do not have this restriction therefore reduces the amount of code required to implement the callback.</p>
<p>Shorter, more concise code is also a worthy benefit.</p>
|
<p>A delegate is a typed method pointer. This gives you more flexibility than interfaces because you can take advantage of covariance and contravariance, and you can modify object state (you'd have to pass the this pointer around with interface based functors).</p>
<p>Also, delegates have lots of nice syntactic sugar which allows you to do things like combine them together easily.</p>
| 12,151
|
<p>I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I want to avoid is to simply have the stored procedure take a list of parameters and generate a SQL statement to execute, since that would open doors to SQL injection at an internal level.</p>
<p>Can this be done?</p>
|
<p>While the <code>COALESCE</code> trick is neat, my preferred method is:</p>
<pre><code>CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry
@Cus_Name varchar(30) = NULL
,@Cus_City varchar(30) = NULL
,@Cus_Country varchar(30) = NULL
,@Dept_ID int = NULL
,@Dept_ID_partial varchar(10) = NULL
AS
SELECT Cus_Name
,Cus_City
,Cus_Country
,Dept_ID
FROM Customers
WHERE (@Cus_Name IS NULL OR Cus_Name LIKE '%' + @Cus_Name + '%')
AND (@Cus_City IS NULL OR Cus_City LIKE '%' + @Cus_City + '%')
AND (@Cus_Country IS NULL OR Cus_Country LIKE '%' + @Cus_Country + '%')
AND (@Dept_ID IS NULL OR Dept_ID = @DeptID)
AND (@Dept_ID_partial IS NULL OR CONVERT(varchar, Dept_ID) LIKE '%' + @Dept_ID_partial + '%')
</code></pre>
<p>These kind of SPs can easily be code generated (and re-generated for table-changes).</p>
<p>You have a few options for handling numbers - depending if you want exact semantics or search semantics.</p>
|
<p>My first thought was to write a query something like this...</p>
<pre><code>SELECT EmpId, NameLast, NameMiddle, NameFirst, DepartmentName
FROM dbo.Employee
INNER JOIN dbo.Department ON dbo.Employee.DeptId = dbo.Department.Id
WHERE IdCrq IS NOT NULL
AND
(
@bitSearchFirstName = 0
OR
Employee.NameFirst = @vchFirstName
)
AND
(
@bitSearchMiddleName = 0
OR
Employee.NameMiddle = @vchMiddleName
)
AND
(
@bitSearchFirstName = 0
OR
Employee.NameLast = @vchLastName
)
AND
(
@bitSearchDepartment = 0
OR
Department.Id = @intDeptID
)
</code></pre>
<p>...which would then have the caller provide a bit flag if they want to search a particular field and then supply the value if they are to search for it, but I don't know if this is creating a sloppy WHERE clause or if I can get away with a CASE statement in the WHERE clause.</p>
<p>As you can see this particular code is in T-SQL, but I'll gladly look at some PL-SQL / MySQL code as well and adapt accordingly.</p>
| 25,178
|
<p>short:</p>
<p>Is there a way in Ruby to DRY-ify this:</p>
<pre><code>def entry_point_one
begin
do_something
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
def entry_point_two
begin
do_something_else
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
</code></pre>
<p>longer:</p>
<p>I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do_something, especially since the interpreter makes use of recursion.</p>
<p>As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:</p>
<pre><code>def entry_point_one
re_raise_known_exceptions {do_something}
end
def entry_point_two
re_raise_known_exceptions {do_something_else}
end
def re_raise_known_exceptions
yield
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
</code></pre>
<p>But that makes the method re-raise-known-exceptions show up in the back trace.</p>
<p>edit: I guess what I want would be something like a C pre-processing macro</p>
|
<p>while thinking about it a bit more, I came up with this:</p>
<pre><code>interpreter_block {do_something}
def interpreter_block
yield
rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc
raise exc.exception(exc.message)
end
</code></pre>
<p>Although it's still not quiet what I would like to have, at least now the extra entry in the back trace has become somewhat better looking.</p>
|
<p>If you have all of the information you need in the exceptions, and you do not need the backtrace at all, you can just define your own error and raise that, instead of reraising the existing exception. This will give it a fresh backtrace. (Of course, presumably your sample code is incomplete and there is other processing happening in the rescue block -- otherwise your best bet is to just let the error bubble up naturally.)</p>
<pre><code>class MyError < StandardError; end
def interpreter_block
yield
rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc
raise MyError
end
</code></pre>
| 16,515
|
<p><a href="http://php.net/Interfaces" rel="noreferrer">Interfaces</a> allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods. </p>
<p><a href="http://php.net/Abstract" rel="noreferrer">Abstract classes</a> allow you to do the same thing, along with adding code to the method. </p>
<p>Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? </p>
<p>I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?</p>
|
<p>The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the <a href="http://en.wikipedia.org/wiki/Multiple_inheritance" rel="noreferrer">wikipedia</a> page on it sums them up pretty well.</p>
<p>Interfaces are a compromise. Most of the problems with multiple inheritance don't apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.</p>
|
<p>Below are the points for PHP Interface </p>
<ol>
<li>It is used to define required no of methods in class [if you want to load html then id and name is required so in this case interface include setID and setName].</li>
<li>Interface strictly force class to include all the methods define in it. </li>
<li>You can only define method in interface with public accessibility.</li>
<li>You can also extend interface like class. You can extend interface in php using extends keyword.</li>
<li>Extend multiple interface.</li>
<li>You can not implement 2 interfaces if both share function with same name. It will throw error.</li>
</ol>
<p><strong>Example code :</strong></p>
<pre><code>interface test{
public function A($i);
public function B($j = 20);
}
class xyz implements test{
public function A($a){
echo "CLASS A Value is ".$a;
}
public function B($b){
echo "CLASS B Value is ".$b;
}
}
$x = new xyz();
echo $x->A(11);
echo "<br/>";
echo $x->B(10);
</code></pre>
| 4,082
|
<p>I'm auditing a project that uses what is called a <a href="http://en.wikipedia.org/wiki/Business_rules_engine" rel="noreferrer">Rules Engine</a>. In short, it's a way to externalize business logic from application code. </p>
<p>This concept is entirely new to me and I'm pretty skeptical about it. After hearing people talk about <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html" rel="noreferrer">Anemic Domain Models</a> for the past few years, I'm questioning the Rules Engine Approach. To me they seem like a great way to WEAKEN a domain model. For example say I'm doing a java webapp interacting with a Rules Engine. Then I decide I want to have an Android app based on the same domain. Unless I want the Android app to interact with the Rules Engine as well, I'm going to have to miss out on whatever business logic was already written. </p>
<p>As I don't have any experience with them yet, just curiosity, I was interested to hear about the pros and cons are in using a Rules Engine? The only pro that I can think of is that you don't need to rebuild your entire Application just to change some business rule (but really, how many apps really have that many changes?). But using a Rules Engine to solve that problem kind of sounds to me like putting a band-aid over a shotgun wound. </p>
<p>UPDATE - since writing this, the god himself, Martin Fowler, has <a href="http://martinfowler.com/bliki/RulesEngine.html" rel="noreferrer">blogged about using a Rules engine</a>.</p>
|
<p>Most rule engines that I have seen are viewed as a black box by system code. If I were to build a domain model, I would probably want certain business rules to be intrinsic to the domain model, e.g. business rules that tell me when an object has invalid values. This allows multiple systems to share the domain model without duplicating business logic. I could have each system use the same rule service to validate my domain model, but this appears to weaken my domain model (as was pointed out in the question). Why? Because instead of consistently enforcing my business rules across all systems at all times, I am relying on system programmers to determine when the business rules should be enforced (by calling the rule service). This may not be a problem if the domain model comes to you completely populated, but can be problematic if you're dealing with a user interface or system that changes values in the domain model over its lifetime.</p>
<p>There is another class of business rules: decision making. For example, an insurance company may need to classify the risk of underwriting an applicant and arrive at a premium. You could place these types of business rules in your domain model, but a centralized decision for scenarios like this are usually desirable and, actually, fit quite well into a service-oriented architecture. This does beg the question of why a rule engine and not system code. The place where a rule engine may be a better choice is where business rules responsible for the decision change over time (as some other answers have pointed out).</p>
<p>Rule engines usually allow you to change rules without restarting your system or deploying new executable code (regardless of what promises you receive from a vendor, do make sure you test your changes in a non-production environment because, even if the rule engine is flawless, humans are still changing the rules). If you're thinking, "I can do that by using a database to store values that change", you're right. A rule engine is not a magical box that does something new . It is intended to be a tool that provides a higher level of abstraction so you can focus less on reinventing the wheel. Many vendors take this a step further by letting you create templates so that business users can fill in the blanks instead of learning a rule language. </p>
<p>One parting caution about templates: templates can never take less time than writing a rule without a template because the template must, at the bare minimum, describe the rule. Plan for a higher initial cost (the same as if you were to build a system that used a database to store values that change vs. writing the rules in directly in system code) - the ROI is because you save on future maintenance of system code.</p>
|
<p>The biggest complexity from my experience in Rule Engines is that:</p>
<ol>
<li>from OOP POV it's a real pain to refactor and test rules written in a declarative language while you are refactoring code that affects them.</li>
<li>Often we should always think about the execution order of rules which turns into a mess when there are lots of them.</li>
<li>Some minor changes may trigger incorrect behaviour of rules leading to production bugs. In practice it's not always possible to cover all cases with tests up front.</li>
<li>Rules mutating objects used in other ones also increase complexity causing developers to break them into stages.</li>
</ol>
| 31,153
|
<p>I have a ~23000 line SQL dump containing several databases worth of data. I need to extract a certain section of this file (i.e. the data for a single database) and place it in a new file. I know both the start and end line numbers of the data that I want.</p>
<p>Does anyone know a Unix command (or series of commands) to extract all lines from a file between say line 16224 and 16482 and then redirect them into a new file?</p>
|
<pre><code>sed -n '16224,16482p;16483q' filename > newfile
</code></pre>
<p>From the <a href="https://www.gnu.org/software/sed/manual/sed.html#Common-Commands" rel="noreferrer">sed manual</a>:</p>
<blockquote>
<p><strong>p</strong> -
Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.</p>
<p><strong>n</strong> -
If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If
there is no more input then sed exits without processing any more
commands.</p>
<p><strong>q</strong> -
Exit <code>sed</code> without processing any more commands or input.
Note that the current pattern space is printed if auto-print is not disabled with the -n option.</p>
</blockquote>
<p><a href="https://www.gnu.org/software/sed/manual/sed.html#Addresses" rel="noreferrer">and</a></p>
<blockquote>
<p>Addresses in a sed script can be in any of the following forms:</p>
<p><strong>number</strong>
Specifying a line number will match only that line in the input.</p>
<p>An address range can be specified by specifying two addresses
separated by a comma (,). An address range matches lines starting from
where the first address matches, and continues until the second
address matches (inclusively).</p>
</blockquote>
|
<p>The -n in the accept answers work. Here's another way in case you're inclined.</p>
<pre><code>cat $filename | sed "${linenum}p;d";
</code></pre>
<p>This does the following:</p>
<ol>
<li>pipe in the contents of a file (or feed in the text however you want).</li>
<li>sed selects the given line, prints it</li>
<li>d is required to delete lines, otherwise sed will assume all lines will eventually be printed. i.e., without the d, you will get all lines printed by the selected line printed twice because you have the ${linenum}p part asking for it to be printed. I'm pretty sure the -n is basically doing the same thing as the d here.</li>
</ol>
| 10,903
|
<p>How can I Handler 404 errors without the framework throwing an Exception 500 error code?</p>
|
<p><a href="http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx" rel="noreferrer">http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx</a> gives the following explanation:</p>
<p>Add a wildcard routing rule as your final rule:</p>
<pre><code>routes.MapRoute("Error",
"{*url}",
new { controller = "Error", action = "Http404" });
</code></pre>
<p>Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:</p>
<pre><code>public ActionResult Http404(string url) {
Response.StatusCode = 404;
ViewData["url"] = url;
return View();
}
</code></pre>
|
<p>With MVC 3 you can return HttpNotFound() to properly return a 404.</p>
<p>Like this:</p>
<pre><code>public ActionResult Download(string fontName)
{
FontCache.InitalizeFonts();
fontName = HttpUtility.UrlDecode(fontName);
var font = FontCache.GetFontByName(fontName);
if (font == null)
return HttpNotFound();
return View(font);
}
</code></pre>
| 13,412
|
<p>This is more an observation than a real question: MS-Access (and VBA in general) is desperately missing a tool where error handling code can be generated automatically, and where the line number can be displayed when an error occurs. Did you find a solution? What is it? I just realized how many hundreds of hours I spared since I found the right answer to this basic problem a few years ago, and I'd like to see what are your ideas and solutions on this very important issue. </p>
|
<p>My solution is the following:</p>
<ol>
<li>install <a href="http://www.mztools.com" rel="nofollow noreferrer">MZ-Tools</a>, a very interesting add-on for VBA. No they did not pay me to write this. Version 3 was free, but since version 8.0, the add-in is commercially sold.</li>
<li>program a standard error handler code such as this one (see MZ-Tools menu/Options/Error handler):</li>
</ol>
<hr>
<pre><code>On Error GoTo {PROCEDURE_NAME}_Error
{PROCEDURE_BODY}
On Error GoTo 0
Exit {PROCEDURE_TYPE}
{PROCEDURE_NAME}_Error:
debug.print "#" & Err.Number, Err.description, "l#" & erl, "{PROCEDURE_NAME}", "{MODULE_NAME}"
</code></pre>
<hr>
<p>This standard error code can be then automatically added to all of your procs and function by clicking on the corresponding button in the MZ-Tools menu. You'll notice that we refer here to a hidden and undocumented function in the VBA standard library, 'Erl', which stands for 'error line'. You got it! If you ask MZ-Tools to automatically number your lines of code, 'Erl' will then give you the number of the line where the error occured. You will have a complete description of the error in your immediate window, such as:</p>
<pre><code>#91, Object variable or With block variable not set, l# 30, addNewField, Utilities
</code></pre>
<p>Of course, once you realize the interest of the system, you can think of a more sophisticated error handler, that will not only display the data in the debug window but will also:</p>
<ol>
<li>display it as a message on the screen</li>
<li>Automatically insert a line in an error log file with the description of the error <strong>or</strong></li>
<li>if you are working with Access or if you are connected to a database, automatically add a record to a Tbl_Error table! </li>
</ol>
<p>meaning that each error generated at the user level can be stored either in a file or a table, somewhere on the machine or the network. Are we talking about <strong>building an automated error reporting system</strong> working with VBA?</p>
|
<p>Love it Vlado!</p>
<p>I realize this is an old post, but I grabbed it and gave it a try, but I ran into a number of issues with it, which I managed to fix. Here's the code with fixes:</p>
<p>First of course, be sure to add the "Microsoft Visual Basic for Applications Extensibility 5.3" library to your project, and add these subroutines / modules to your project as well.</p>
<p>First, the module with the main code was named "modVBAChecks", and contained the following two subroutines:</p>
<p>To go through all modules (behind forms, sheets, the workbook, and classes as well, though not ActiveX Designers):</p>
<pre><code>Sub AddErrorHandlingToAllProcs()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim lCtr As Long
StartNewWorksheetLog
Set VBProj = Workbooks("LabViewAnalysisTools.xla").VBProject
For Each VBComp In VBProj.VBComponents
If VBComp.Type <> vbext_ct_ActiveXDesigner Then
If VBComp.Name <> "modVBAChecks" And VBComp.Name <> "modLogToWorksheet" Then
AddToWksLog "============ Looking at Module """ & VBComp.Name & """"
'InsertErrHandling VBComp.Name
AddToWksLog
AddToWksLog
End If
End If
Next
MsgBox "Done!", vbSystemModal
End Sub
</code></pre>
<p>Then the modified version of your code (including a suggested change by<br />
Rafał B.):</p>
<pre><code>Public Sub InsertErrHandling(modsProcName As String)
' Modified from code submitted to StackOverflow by user Vlado, originally found
' here: https://stackoverflow.com/questions/357822/automatically-generating-handling-of-issues
Dim vbcmA As VBIDE.CodeModule
Dim ProcKind As VBIDE.vbext_ProcKind
Dim LineProcKind As VBIDE.vbext_ProcKind
Dim sProcName As String
Dim sLineProcName As String
Dim lFirstLine As Long
Dim lProcLinesCount As Long
Dim lLastLine As Long
Dim sDeclaration As String
Dim sProcType As String
Dim lLine As Long, lLine2 As Long
Dim sLine As String
Dim lcStartLines As Collection, lcLastlines As Collection, scProcsProcNames As Collection, scProcTypes As Collection
Dim bAddHandler As Boolean
Dim lLinesAbove As Long
Set lcStartLines = New Collection
Set lcLastlines = New Collection
Set scProcsProcNames = New Collection
Set scProcTypes = New Collection
Set vbcmA = Application.VBE.ActiveVBProject.VBComponents(modsProcName).CodeModule
' Remove empty lines on the end of the module. Cleanup, not error handling.
lLine = vbcmA.CountOfLines
If lLine = 0 Then Exit Sub ' Nothing to do!
Do
If Trim(vbcmA.Lines(lLine, 1)) <> "" Then Exit Do
vbcmA.DeleteLines lLine, 1
lLine = lLine - 1
Loop
lLine = vbcmA.CountOfDeclarationLines + 1
Do While lLine < vbcmA.CountOfLines
bAddHandler = False
' NOTE: ProcKind is RETRUNED from ProcOfLine!
sProcName = vbcmA.ProcOfLine(lLine, ProcKind)
' Fortunately ProcBodyLine ALWAYS returns the first line of the procedure declaration!
lFirstLine = vbcmA.ProcBodyLine(sProcName, ProcKind)
sDeclaration = Trim(vbcmA.Lines(lFirstLine, 1))
Select Case ProcKind
Case VBIDE.vbext_ProcKind.vbext_pk_Proc
If sDeclaration Like "*Function *" Then
sProcType = "Function"
ElseIf sDeclaration Like "*Sub *" Then
sProcType = "Sub"
End If
Case VBIDE.vbext_ProcKind.vbext_pk_Get, VBIDE.vbext_ProcKind.vbext_pk_Let, VBIDE.vbext_ProcKind.vbext_pk_Set
sProcType = "Property"
End Select
' The "lProcLinesCount" function will sometimes return ROWS ABOVE
' the procedure, possibly up until the prior procedure,
' and often rows BELOW the procedure as well!!!
lProcLinesCount = vbcmA.ProcCountLines(sProcName, ProcKind)
lLinesAbove = 0
lLine2 = lFirstLine - 1
If lLine2 > 0 Then
Do
sLineProcName = vbcmA.ProcOfLine(lLine2, LineProcKind)
If Not (sLineProcName = sProcName And LineProcKind = ProcKind) Then Exit Do
lLinesAbove = lLinesAbove + 1
lLine2 = lLine2 - 1
If lLine2 = 0 Then Exit Do
Loop
End If
lLastLine = lFirstLine + lProcLinesCount - lLinesAbove - 1
' Now need to trim off any follower lines!
Do
sLine = Trim(vbcmA.Lines(lLastLine, 1))
If sLine = "End " & sProcType Or sLine Like "End " & sProcType & " '*" Then Exit Do
lLastLine = lLastLine - 1
Loop
AddToWksLog modsProcName & "." & sProcName, "First: " & lFirstLine, "Lines:" & lProcLinesCount, "Last: " & lLastLine
AddToWksLog "sDeclaration: " & vbcmA.Lines(lFirstLine, 1), lFirstLine
AddToWksLog "Closing Proc: " & vbcmA.Lines(lLastLine, 1), lLastLine
If lLastLine - lFirstLine < 8 Then
AddToWksLog " --------------- Too Short to bother!"
Else
bAddHandler = True
' do not insert error handling if there is one already:
For lLine2 = lFirstLine To lLastLine Step 1
If vbcmA.Lines(lLine2, 1) Like "*On Error GoTo *" And Not vbcmA.Lines(lLine2, 1) Like "*On Error GoTo 0" Then
bAddHandler = False
Exit For
End If
Next lLine2
If bAddHandler Then
lcStartLines.Add lFirstLine
lcLastlines.Add lLastLine
scProcsProcNames.Add sProcName
scProcTypes.Add sProcType
End If
End If
AddToWksLog
lLine = lFirstLine + lProcLinesCount + 1
Loop
For lLine = lcLastlines.Count To 1 Step -1
vbcmA.InsertLines lcLastlines.Item(lLine), "ExitProc:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 1, " Exit " & scProcTypes.Item(lLine)
vbcmA.InsertLines lcLastlines.Item(lLine) + 2, "ErrHandler:"
vbcmA.InsertLines lcLastlines.Item(lLine) + 3, " ShowErrorMsg Err, """ & scProcsProcNames.Item(lLine) & """, """ & modsProcName & """"
vbcmA.InsertLines lcLastlines.Item(lLine) + 4, " Resume ExitProc"
' Now replace any "On Error Goto 0" lines with "IF ErrorTrapping Then On Error Goto ErrHandler"
For lLine2 = lcStartLines(lLine) To lcLastlines(lLine)
sLine = vbcmA.Lines(lLine2, 1)
If sLine Like "On Error GoTo 0" Then
vbcmA.ReplaceLine lLine2, Replace(sLine, "On Error Goto 0", "IF ErrorTrapping Then On Error Goto ErrHandler")
End If
Next
lLine2 = lcStartLines.Item(lLine)
Do
sLine = vbcmA.Lines(lLine2, 1)
If Not sLine Like "* _" Then Exit Do
lLine2 = lLine2 + 1
Loop
vbcmA.InsertLines lLine2 + 1, " If ErrorTrapping Then On Error GoTo ErrHandler"
Next lLine
End Sub
</code></pre>
<p>And rather than pushing things to the Immediate window I used subroutines in a module I named "modLogToWorksheet", the full module being here:</p>
<pre><code>Option Explicit
Private wksLog As Worksheet
Private lRow As Long
Public Sub StartNewWorksheetLog()
Dim bNewSheet As Boolean
bNewSheet = True
If ActiveSheet.Type = xlWorksheet Then
Set wksLog = ActiveSheet
bNewSheet = Not (wksLog.UsedRange.Cells.Count = 1 And wksLog.Range("A1").Formula = "")
End If
If bNewSheet Then Set wksLog = ActiveWorkbook.Worksheets.Add
lRow = 1
End Sub
Public Sub AddToWksLog(ParamArray sMsg() As Variant)
Dim lCol As Long
If wksLog Is Nothing Or lRow = 0 Then StartNewWorksheetLog
If Not (IsNull(sMsg)) Then
For lCol = 0 To UBound(sMsg)
If sMsg(lCol) <> "" Then wksLog.Cells(lRow, lCol + 1).Value = "'" & sMsg(lCol)
Next
End If
lRow = lRow + 1
End Sub
</code></pre>
<p>And finally, here's my Error Dialog generator:</p>
<pre><code>Public Sub ShowErrorMsg(errThis As ErrObject, strSubName As String, strModName As String _
, Optional vbMBStyle As VbMsgBoxStyle = vbCritical, Optional sTitle As String = APP_TITLE)
If errThis.Number <> 0 Then
MsgBox "An Error Has Occurred in the Add-in. Please inform " & ADMINS & " of this problem." _
& vbCrLf & vbCrLf _
& "Error #: " & errThis.Number & vbCrLf _
& "Description: " & " " & errThis.Description & vbCrLf _
& "Subroutine: " & " " & strSubName & vbCrLf _
& "Module: " & " " & strModName & vbCrLf _
& "Source: " & " " & errThis.Source & vbCrLf & vbCrLf _
& "Click OK to continue.", vbMBStyle Or vbSystemModal, sTitle
End If
End Sub
</code></pre>
<p>Hope future users find it useful!</p>
| 46,661
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx" rel="nofollow noreferrer"><code>FILETIME</code> structure</a> counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?</p>
|
<p>The question shouldn't be if <code>FILETIME</code> includes leap seconds. </p>
<p>It should be:</p>
<blockquote>
<p>Do the people, functions, and libraries, who interpret a <code>FILETIME</code> (i.e. <code>FileTimeToSystemTime</code>) include leap seconds when counting the duration?</p>
</blockquote>
<p>The simple answer is <em>"no"</em>. <code>FileTimeToSystemTime</code> returns seconds as <code>0..59</code>. </p>
<hr>
<p>The simpler answer is: "<em>of course not, how could it?</em>". </p>
<p>My Windows 2000 machine doesn't know that there were 2 leap seconds added in the decade since it was released. Any interpretation it makes of a <code>FILETIME</code> is wrong.</p>
<hr>
<p>Finally, rather than relying on logic, we can determine by direct experimental observation, the answer to the posters question:</p>
<pre class="lang-pascal prettyprint-override"><code>var
systemTime: TSystemTime;
fileTime: TFileTime;
begin
//Construct a system-time for the 12/31/2008 11:59:59 pm
ZeroMemory(@systemTime, SizeOf(systemTime));
systemtime.wYear := 2008;
systemTime.wMonth := 12;
systemTime.wDay := 31;
systemTime.wHour := 23;
systemtime.wMinute := 59;
systemtime.wSecond := 59;
//Convert it to a file time
SystemTimeToFileTime(systemTime, {var}fileTime);
//There was a leap second 12/31/2008 11:59:60 pm
//Add one second to our filetime to reach the leap second
filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s
//Convert the filetime, sitting on a leap second, to a displayable system time
FileTimeToSystemTime(fileTime, {var}systemTime);
//And now print the system time
ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime)));
</code></pre>
<p>Adding one second to </p>
<pre><code>12/31/2008 11:59:59pm
</code></pre>
<p>gives</p>
<pre><code>1/1/2009 12:00:00am
</code></pre>
<p>rather than</p>
<pre><code>1/1/2009 11:59:60pm
</code></pre>
<p>Q.E.D.</p>
<p>Original poster might not like it, but god intentionally rigged it so that a year is not evenly divisible by a day. He did it just to screw up programmers.</p>
|
<p>A very crude summary:</p>
<p>UTC = (Atomic Time) + (Leap Seconds) ~~ (Mean Solar Time)</p>
<p>The MS documentation says, specifically, "UTC", and so should include the leap seconds. As always with MS, your mileage may vary.</p>
| 15,855
|
<p>I'm in the process of starting a User Group in my area related to .NET development. The format of the community will be the average free food, presentation, and then maybe free swag giveaway.</p>
<p>What would you, as a member of a user community, look for in order to keep you coming back month to month?</p>
|
<p>It's true that some of the talks out there are very rudimentary, unfortunately some times the bulk of your crowd may need that. I consider myself a novice in a lot of fields, but I've attend talks that I thought were beneath me and still people were asking very basic questions. Perhaps it would be worth having a bi-monthly user group, one week for entry level and one week for advanced. It doesn't necessarily have to mean twice the work if you can get someone to help you coordinate a lot of the work will overlap. On the other hand you might just need to feel out the members of the group and see what their average skill level is and play to that.</p>
|
<p>If there isn't beer, its not a good enough user group to attend. The open source guys get this. Their user group meetings are funner, and more dynamic because of this. Just make it BYOB and it'll naturally get better in my experience.</p>
| 3,128
|
<p>I'm after (short) opinions on FCKeditor vs TinyMCE and whether either or both are XHTML compliant.</p>
<p>In the interest of keeping with the spirit of stackoverflow, if someone has already made your point, just upvote them.</p>
|
<p>From my experience FCKEditor does indeed produce XHTML compliant code, but that code is slightly different depending on what browser you're in. Mostly, this was related to the enter key producing either a break or a paragraph, and I think it may have been configurable.</p>
|
<p>Afaik, they both allow the browser to mess with the code they produce, which doesn't result in XHTML compliance.</p>
<p><a href="http://xstandard.com/" rel="nofollow noreferrer">XStandard</a> is the only rich web editor I'm aware of that produces XHTML compliant code, but unfortunately it requires a client-side install, which rules it out for real web stuff.</p>
| 20,517
|
<p>When using Mercurial I sometimes find that it is hard to understand the relationship between changesets when there are thousands of changesets, and sometimes ten or more active branches at any one time. Currently, I use <a href="http://www.logilab.org/project/hgview/screenshots?selected=4873" rel="noreferrer">hgview</a> which is okay, and while it makes a reasonable attempt to represent the parent relationships it is still basically one dimensional. I imagine something making use of graph visualisation programs such as <a href="http://www.graphviz.org/" rel="noreferrer">GraphViz</a> might work nicely, or perhaps something more wacky.</p>
<p>Currently I'm working on projects with around 30,000 revisions, and I expect that number to grow significantly; if 100 full time developers really grok distributed version control and start committing regularly and sharing their full development history then we could end up dealing with millions of revisions. A browser which doesn't have to load the entire history in to RAM every time you want to look at it therefore becomes necessary</p>
<p>I'm interested in good history browsers for any version control systems as well, especially if there is a chance I can port them to Mercurial.</p>
|
<p>the <code>gitk(1)</code> tool for git is what I use at work. Note that it takes a <code>git rev-list</code> constraint so you can limit what you see. You definitely want to begin doing such selective picking in the long run when the amount of commits go up.</p>
|
<p>I use ClearCase VCS at work and its Version Tree browser could presumably suit you. But, alas, I don't know any separate ready-made tool for this. </p>
| 20,765
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.