instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I am trying to upgrade an named instance of MSDE to SQL Server 2008 Express. When I get to the "Select Features" page of the 2008 installer there are no instances listed. The upgrade to SQL Server 2005 Express (on the same VM image) however works fine.</p>
<p>It seems to be a supported scenario (<a href="http://msdn.microsoft.com/en-us/library/ms143393.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms143393.aspx</a>), yet I am finding that it does not work. Has anyone successfully done this?</p>
|
<p>It looks to be supported: <a href="http://msdn.microsoft.com/en-us/library/ms143393.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms143393.aspx</a></p>
<p>There are also comments you might find useful.</p>
|
<p>I just had the same problem, so I'll post my solution for anyone that happens upon this thread;</p>
<p>You are probably seeing your named instance on that screen but it is greyed out.
Check that you have SP4 for MSDE, which is version 8.0.2039.</p>
| 13,976
|
<p>Does any one know of some kind of Comparator factory in Java, with a </p>
<pre><code>public Comparator getComparatorForClass(Class clazz) {}
</code></pre>
<p>It would return Comparators for stuff like String, Double, Integer but would have a</p>
<pre><code>public void addComparatorForClass(Class clazz, Comparator comparator) {}
</code></pre>
<p>For arbitrary types.</p>
|
<p>Instead of:</p>
<pre><code>factory.getComparatorForClass(x.getClass()).compare(x, y)
</code></pre>
<p>you could simply implement <code>Comparable</code> and write:</p>
<pre><code>x.compareTo(y)
</code></pre>
<p>String, the primitive wrappers, and standard collections already implement <code>Comparable</code>.</p>
|
<p>Default comparator is not exist in Java. However, if you are coding with, for example, a customized searcher, which intends to use comparator rather than the compareTo() method of derived type of Comparable class, you may write a static inner comparator class as the default comparator, simply implementing the compare() method by calling the compareTo().</p>
<p>Example:</p>
<p>class Searcher> {
private Comparator comparator;</p>
<pre><code>Searcher(Comparator<T> comparator) {
this.comparator = comparator;
}
Searcher() {
this(new DefaultComparator<T>());
}
int search(...) {
...
}
private static class DefaultComparator<E extends Comparable<E>>
implements Comparator<E> {
public int compare(E o1, E o2) {
return o1.compareTo(o2);
}
}
</code></pre>
| 29,413
|
<p>Can anyone give me pointers to good books or web sites that teach how to do Flex programming?</p>
|
<p>Check out <a href="http://joshblog.net/2007/04/05/ten-ways-beginners-can-learn-adobe-flex/" rel="noreferrer">Ten Great Ways to Learn Flex</a>, but I think number one should be to use the <a href="http://www.adobe.com/devnet/flex/?tab:quickstart=1" rel="noreferrer">Quickstarts on the Adobe Site</a>.</p>
|
<p>lynda.com has <a href="http://movielibrary.lynda.com/html/modListing.asp?pid=205" rel="nofollow noreferrer">a set of Flex videos</a>, including <a href="http://movielibrary.lynda.com/html/modPage.asp?ID=438" rel="nofollow noreferrer">basic Flex 3</a>, <a href="http://movielibrary.lynda.com/html/modPage.asp?ID=437" rel="nofollow noreferrer">advanced topics</a>, and <a href="http://movielibrary.lynda.com/html/modPage.asp?ID=542" rel="nofollow noreferrer">AIR Essentials</a>.</p>
<p>It's a subscription site, but for $250 a year, if you use other Adobe products like <a href="http://movielibrary.lynda.com/html/modListing.asp?pid=274" rel="nofollow noreferrer">ColdFusion 8</a> or the new <a href="http://movielibrary.lynda.com/html/modListing.asp?pid=362" rel="nofollow noreferrer">CS 4</a> (they have plenty of CS 3 videos too), it's easily worth it.</p>
| 31,553
|
<p>How do I set a disabled TextBox's current text color to be the same as its current background color in C#?</p>
<p>Simply doing txtLala.ForeColor = txtLala.BackColor does not seems to work.</p>
|
<p>This works:</p>
<pre><code>txtLala.Text = "Red";
txtLala.BackColor = System.Drawing.Color.Red;
txtLala.ForeColor = txtLala.BackColor;
txtLala.ReadOnly = true;
</code></pre>
<p>Try setting the <code>color</code>, before the <code>readonly</code>. And also check how you are setting the color!</p>
<p><strong>EDIT</strong></p>
<p>Try this</p>
<pre><code>txtLala.Attributes.Add("style","background-color:Red;color:Red");
</code></pre>
<p>If you are trying to make it invisible, you know you can set it as </p>
<pre><code>txtLala.Visible = False;
</code></pre>
<p><strong>EDIT II</strong></p>
<p>I finally tried </p>
<pre><code>txtLala.Enabled = false;
</code></pre>
<p>... you see that grey shadow color! I don't think you can mess with that, it looks to be a browser property setting. </p>
<p>Why not set as <code>ReadOnly</code> or <code>Visible = False</code>?</p>
<p>Maybe you have a good reason for <code>Enabled = false</code></p>
<p>But you should note:</p>
<blockquote>
Use the Enabled property to specify or determine whether a control is functional. <b>When set to false, the control appears dimmed</b>, preventing any input from being entered in the control.
<br /><br />
Note The ability to enable or disable functionality is always available. <b>However, dimming and locking the control only works in Microsoft Internet Explorer version 4 and later.</b>
<br /><br />
This property propagates down the control hierarchy. Therefore, disabling a container control will disable all child controls within that container.
<br /><br />
Note Not all controls support this property. See the indivual controls for details.
<br /><br />
</blockquote>
|
<p>If this is a readonly textbox, you need to explicitly set your BackColor first, then your statement will work.</p>
<pre><code>txtLala.BackColor = System.Drawing.SystemColors.Info;
txtLala.ForeColor = txtLala.BackColor;
</code></pre>
<p>Ref: <a href="http://bytes.com/groups/net-c/233961-read-only-textbox" rel="nofollow noreferrer">http://bytes.com/groups/net-c/233961-read-only-textbox</a></p>
<p>Then again, if it's readonly, a label might be better. If you're trying to hide it, perhaps setting <code>.Visible = false</code> would be better still.</p>
<hr>
<p><strong>Edit</strong>: This seems to be a <a href="http://www.google.com/search?hl=en&q=Enabled+false+textbox+font+color+change&btnG=Search" rel="nofollow noreferrer">common question</a> on the web. With respect to <strong>winforms</strong>: <a href="http://www.xtremevbtalk.com/showthread.php?t=296536" rel="nofollow noreferrer">This site</a> suggests dropping the box into a frame and setting <code>Enabled = false</code> <em>on the frame, not the textbox</em>. Once you do that, you may be able to maintain control of the forecolor.</p>
| 47,329
|
<p>If something is making a single-thread program take, say, 10 times as long as it should, you could run a profiler on it. You could also just halt it with a "pause" button, and you'll see exactly what it's doing. </p>
<p>Even if it's only 10% slower than it should be, if you halt it more times, before long you'll see it repeatedly doing the unnecessary thing. Usually the problem is a function call somewhere in the middle of the stack that isn't really needed. This doesn't measure the problem, but it sure does find it.</p>
<p>Edit: The objections mostly assume that you only take 1 sample. If you're serious, take 10. Any line of code causing some percentage of wastage, like 40%, will appear on the stack on that fraction of samples, on average. Bottlenecks (in single-thread code) can't hide from it.</p>
<p>EDIT: To show what I mean, many objections are of the form "there aren't enough samples, so what you see could be entirely spurious" - vague ideas about chance. But if something of <em>any recognizable description</em>, not just being in a routine or the routine being active, is in effect for 30% of the time, then the probability of seeing it on any given sample is 30%. </p>
<p>Then suppose only 10 samples are taken. The number of times the problem will be seen in 10 samples follows a <a href="http://en.wikipedia.org/wiki/Binomial_distribution" rel="noreferrer">binomial distribution</a>, and the probability of seeing it 0 times is .028. The probability of seeing it 1 time is .121. For 2 times, the probability is .233, and for 3 times it is .267, after which it falls off. Since the probability of seeing it less than two times is .028 + .121 = .139, that means the probability of seeing it two or more times is 1 - .139 = .861. The general rule is if you see something you could fix on two or more samples, it is worth fixing. </p>
<p>In this case, the chance of seeing it in 10 samples is 86%. If you're in the 14% who don't see it, just take more samples until you do. (If the number of samples is increased to 20, the chance of seeing it two or more times increases to more than 99%.) So it hasn't been precisely measured, but it has been precisely found, and it's important to understand that it could easily be something that a profiler could not actually find, such as something involving the state of the data, not the program counter.</p>
|
<p>On Java servers it's always been a neat trick to do 2-3 quick <kbd>Ctrl</kbd>-<kbd>Breaks</kbd>s in a row and get 2-3 threaddumps of all running threads. Simply looking at where all the threads "are" may extremely quickly pinpoint where your performance problems are.</p>
<p>This technique can reveal more performance problems in 2 minutes than any other technique I know of.</p>
|
<p>EDIT 2008/11/25: OK, Vineet's response has finally made me see what the issue is here. Better late than never.</p>
<p>Somehow the idea got loose in the land that performance problems are found by measuring performance. That is confusing means with ends. Somehow I avoided this by single-stepping entire programs long ago. I did not berate myself for slowing it down to human speed. I was trying to see if it was doing wrong or unnecessary things. That's how to make software fast - find and remove unnecessary operations.</p>
<p>Nobody has the patience for single-stepping these days, but the next best thing is to pick a number of cycles at random and ask what their reasons are. (That's what the call stack can often tell you.) If a good percentage of them don't have good reasons, you can do something about it.</p>
<p>It's harder these days, what with threading and asynchrony, but that's how <strong>I</strong> tune software - by finding unnecessary cycles. Not by seeing how fast it is - I do that at the end.</p>
<hr>
<p>Here's why sampling the call stack cannot give a wrong answer, and why not many samples are needed.</p>
<p>During the interval of interest, when the program is taking more time than you would like, the call stack exists continuously, even when you're not sampling it.</p>
<ul>
<li>If an instruction I is on the call stack for fraction P(I) of that time, removing it from the program, if you could, would save exactly that much. If this isn't obvious, give it a bit of thought.</li>
</ul>
<p>If the instruction shows up on M = 2 or more samples, out of N, its P(I) is approximately M/N, and is definitely significant.</p>
<p>The only way you can fail to see the instruction is to magically time all your samples for when the instruction is not on the call stack. The simple fact that it is present for a fraction of the time is what exposes it to your probes.</p>
<p>So the process of performance tuning is a simple matter of picking off instructions (mostly function call instructions) that raise their heads by turning up on multiple samples of the call stack. <em>Those are the tall trees in the forest.</em></p>
<p>Notice that we don't have to care about the call graph, or how long functions take, or how many times they are called, or recursion.</p>
<p>I'm against obfuscation, not against profilers. They give you lots of statistics, but most don't give P(I), and most users don't realize that that's what matters.</p>
<p>You can talk about forests and trees, but for any performance problem that you can fix by modifying code, you need to modify instructions, specifically instructions with high P(I). So you need to know where those are, preferably without playing Sherlock Holmes. Stack sampling tells you exactly where they are.</p>
<p>This technique is harder to employ in multi-thread, event-driven, or systems in production. That's where profilers, if they would report P(I), could really help.</p>
| 33,400
|
<p>I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far:</p>
<pre><code>public foo(Character[][] original){
clone = new Character[original.length][];
for(int i = 0; i < original.length; i++)
clone[i] = (Character[]) original[i].clone();
}
</code></pre>
<p>A test for equality <code>original.equals(clone);</code> spits out a false. Why? :|</p>
|
<pre><code>/**Creates an independent copy(clone) of the boolean array.
* @param array The array to be cloned.
* @return An independent 'deep' structure clone of the array.
*/
public static boolean[][] clone2DArray(boolean[][] array) {
int rows=array.length ;
//int rowIs=array[0].length ;
//clone the 'shallow' structure of array
boolean[][] newArray =(boolean[][]) array.clone();
//clone the 'deep' structure of array
for(int row=0;row<rows;row++){
newArray[row]=(boolean[]) array[row].clone();
}
return newArray;
}
</code></pre>
|
<p>I found this answer for cloning multidimensional arrays on <a href="http://www.jguru.com/faq/view.jsp?EID=20435" rel="nofollow noreferrer">jGuru</a>:</p>
<pre><code>ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();
</code></pre>
| 24,443
|
<p>I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.</p>
|
<p>I would recomend <a href="https://sourceforge.net/projects/simplehtmldom/" rel="noreferrer">PHP Simple HTML DOM Parser</a> after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements. </p>
|
<p>I've had very good with results with the <a href="https://sourceforge.net/projects/simplehtmldom/" rel="nofollow noreferrer">Simple Html DOM Parser</a> mentioned above as well. And then there's the <a href="http://www.php.net/tidy" rel="nofollow noreferrer">tidy Extension for PHP</a> as well which works really well too.</p>
| 5,428
|
<p>I've been curious about the various UV/Laser printers in (or coming into) market that use liquid resin. I've seen the samples of the <a href="https://fslaser.com/Products/View/1" rel="noreferrer">Pegasus Touch</a>, <a href="http://formlabs.com/products/materials/" rel="noreferrer">Form1</a>, and the <a href="http://carbon3d.com/" rel="noreferrer">Carbon3D</a> as examples. I like the specifications of the quality that machines can put out. However, in my experience with FDM printing, there almost always seems to be something not quite right about the print.</p>
<p>So, what are some major maintenance considerations for these types of 3D printing? Also, specifically, are supports and overhangs as much an issue in these types of printers as with FDM/FFF?</p>
<p>Here are some things I consider major maintenance considerations in FDM:</p>
<ul>
<li>Extruder Clogging</li>
<li>Build platform conditions (i.e. levelness, clean, type of tape, bubbles in tape)</li>
<li>Variances in material quality (i.e. diameter, purity, physical conditions)</li>
<li>Mechanics of the machine (i.e. belts, rods, gear teeth, etc.)</li>
<li>Build environment (i.e. ensuring steady temperature in the build environment, minimize draft)</li>
</ul>
<p><sub>I'm not necessarily looking for printer recommendations, more so technical insight on the technology.</sub></p>
|
<p>Taken in order your questions:</p>
<p>Maintenance for a resin printer means keeping the vat or tray clean, using appropriate methods to remove the unused resin (or leaving it in the vat per manufacturer's directions). Cleaning the tray should be done also per manufacturer's spec, although each printer's user forum may provide better or more effective options.</p>
<p>The Pegasus Touch has a caution regarding dripping resin on the mirrors, so there's operational care considerations for these types of printers.</p>
<p>There is a build platform for these printers. The flatness and level are as critical or more so for resin printers, as the resolution can be astonishingly high. If any portion of a print does not bond to the platform, that entire print will have a failed section, creating an entirely failed print. Gravity is not particularly helpful in that respect, at least with the Pegasus Touch.</p>
<p>The release medium varies from device to device. The Pegasus Touch originally used PDMS (silicon release compound) and now uses what's called a SuperVat. The plastic material in the SuperVat is purported to provide better release and fewer failures, along with increased lifespan. PDMS becomes cloudy from repeated printing in the same location and can be torn away from the vat if the print does not properly release.</p>
<p>I've become aware of a product from Australia that has had good reports from use in a B9 Creator resin printer. The report indicates that it releases the model quite easily and barely turns cloudy. I have an order pending for this material, as I am hopeful it will perform as described.</p>
<p>The mechanics are also varied. One expects a system to raise and lower the build platform and to direct the laser or illumination system (DLP), but generally, this type of printer is somewhat simpler mechanically.</p>
<p>Because I live in a hot humid climate, my Pegasus Touch remains in the box, and my brain is about to explode with what I've learned of using it. Environmental conditions are likely to vary with different machines. I've seen references that 70 degrees F is too cold, others that say 70-75 degrees F is just fine, anything higher is too hot. Another user says that 65 degrees is good. The type of resin also becomes an important factor for environmental conditions.</p>
<p>The laser will create heat in the resin, so I'm inclined to believe that cooler is better. Different colors require different durations of laser light, somewhat akin to various plastics having different temperatures.</p>
<p>supports and overhangs are important considerations in an SLA or DLP printer, just as they are in FDM.</p>
<p>Expect also that many of the resin printers require that the user purchase only the product provided by the manufacturer. This isn't necessarily a negative as most of the resin sources are priced similarly.</p>
<p>If I've missed any part of your question, let me know.</p>
|
<p>Despite how many vendors make it appear, resin-curing SLA/DLP printers are industrial or commercial tools that are really not suitable for home desktop use. Here are the major downsides:</p>
<ul>
<li>Significantly more expensive to operate than FDM printers, in most cases. </li>
<li>The resin is seriously toxic until fully cured. Fumes can be an issue for users handling raw resin, and you should NEVER put a photopolymer print into a chemically-sensitive environment like an aquarium or children's toy. </li>
<li>Prints require messy post-processing to rinse off excess resin (usually with rubbing alcohol) and additional UV light exposure to finish hardening the photopolymer. The used alcohol/resin rinse mix is basically hazmat waste. </li>
<li>In bottom-up printers, the window in the print vat is typically a consumable. Some printers require replacing the vat ($$) after every liter or two of cured resin. (Technology is advancing rapidly here though.)</li>
<li>The peel mechanism in bottom-up printers is often a major source of print flaws, due to the need to rock/tilt/slide the print to free it from the vat window.</li>
<li>In top-down printers, you have to pay a large up-front consumables cost to initially fill the resin tank. (There are workarounds here like floating a layer of resin on brine, but these have their own technical issues.)</li>
<li>If you leave the resin in the printer for an extended period, you'll probably find a hardened layer on the surface from stray light exposure and have to clean out or replace the vat.</li>
<li>Resin vats/tanks need to be kept clean and free of cured resin debris from failed prints or stray light. </li>
<li>Every combination of resin chemistry, printer light source, and printer optics requires specific tuning to dial in the photopolymer curing behavior. This means it's somewhat difficult to change resin brands, and you may effectively be locked into the printer manufacturer's resin. Many light sources will change in intensity or develop dim regions over time as they age, which will either harm print quality, require period recalibration, or require frequent light source replacement. </li>
<li>There is a limited number of options for print materials. Technology here is advancing rapidly, but for the most part, SLA/DLP prints are non-load-bearing models with a limited range of color options. </li>
</ul>
<p>These are some pretty significant "user experience" downsides compared to a consumer desktop FDM printer. It's more hazard, more work, and more cost than FDM. SLA/DLP is primarily advantageous where high resolution or high print speeds are required. </p>
| 229
|
<p>We all know that having a good note taking tool is important as a developer.</p>
<p>However, OneNote and Evernote forces us to be locked in to a particular vendor.</p>
<p>Anyone know of good open-source tools, or even other method of taking notes w/o being "locked-in"?</p>
<p>EDIT: I should kick myself in the head for not specifying. Taking text notes is easy. I'd love to be able to write ink notes ( I use a tablet ), add images,and sketch GUI ideas. </p>
|
<p>Pen and paper.</p>
|
<p>Notepad and/or VI</p>
| 29,655
|
<p>I understand the first argument must be the result of GetFileVersionInfo().</p>
<p>The third and forth are target buffer and size</p>
<p>What is the second argument, lpSubBlock?</p>
<p>Thanks In Advance</p>
|
<p>When you view the version info through the resource editor you might notice that there is an initial section with FILEVERSION, PRODUCTVERISON etc. and then one or more blocks which contain language specific settings.</p>
<pre><code>VS_VERSION_INFO VERSIONINFO
FILEVERSION 5,0,0,0
PRODUCTVERSION 5,0,0,0
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "CompanyName", ""
VALUE "FileVersion", "5, 0, 0, 0"
VALUE "ProductName", ""
VALUE "ProductVersion", "5, 0, 0, 0"
END
BLOCK "000004b0"
BEGIN
VALUE "CompanyName", ""
VALUE "FileVersion", "5, 0, 0, 0"
VALUE "ProductName", ""
VALUE "ProductVersion", "5, 0, 0, 0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0, 1200, 0x409, 1200
END
END
</code></pre>
<p>To get a VS_FIXEDFILEINFO with the non language specific detail use</p>
<pre><code>VS_FIXEDFILEINFO *versionInfo;
PUINT versionInfoSize;
VerQueryValue(buffer.get(), TEXT("\\"), (void**) &versionInfo, &versionInfoSize))
</code></pre>
<p>To find out what languages are supported use </p>
<pre><code>Var *translationsInfo;
PUINT transaltionInfoSize;
VerQueryValue(buffer.get(), TEXT("\\VarFileInfo\\Translation"), (void**) &translationsInfo, &transaltionInfoSize))
</code></pre>
<p>To get the language specific version detail then use</p>
<pre><code>StringTable *stringTable;
PUINT stringTableSize;
std::wstring path( L"\\StringFileInfo\\" );
path += L"040904b0"; // get this value from the language support list
path += L"\\FileVersion";
VerQueryValue(buffer.get(), path.c_str(), (void**) &stringTable, &stringTableSize))
</code></pre>
|
<p>It must be a string whose format you can find here:<br>
<a href="http://www.hep.wisc.edu/~pinghc/books/apirefeng/v/verqueryvalue.html" rel="nofollow noreferrer">http://www.hep.wisc.edu/~pinghc/books/apirefeng/v/verqueryvalue.html</a></p>
<p>There is another example of usage (in VB, easy to read):<br>
<a href="http://support.microsoft.com/kb/160042" rel="nofollow noreferrer">http://support.microsoft.com/kb/160042</a></p>
<p>You can also check out this whole CodeProject article for a working example in C++:<br>
<a href="http://www.codeproject.com/KB/cpp/GetLocalVersionInfos.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cpp/GetLocalVersionInfos.aspx</a></p>
<p>Another article on the subject of retrieving version information:<br>
<a href="http://www.microsoft.com/msj/0498/c0498.aspx" rel="nofollow noreferrer">http://www.microsoft.com/msj/0498/c0498.aspx</a></p>
| 41,261
|
<p>Let's assume you have one massive table with three columns as shown below:</p>
<pre><code>[id] INT NOT NULL,
[date] SMALLDATETIME NOT NULL,
[sales] FLOAT NULL
</code></pre>
<p>Also assume you are limited to one physical disk and one filegroup (PRIMARY). You expect this table to hold sales for 10,000,000+ ids, across 100's of dates (easily 1B+ records).</p>
<p>As with many data warehousing scenarios, the data will typically grow sequentially by date (i.e., each time you perform a data load, you will be inserting new dates, and maybe updating some of the more recent dates of data). For analytic purposes, the data will often be queried and aggregated for a random set of ~10,000 ids which will be specified via a join with another table. Often, these queries don't specify date ranges, or specify very wide date ranges, which leads me to my question: What is the best way to index / partition this table?</p>
<p>I have thought about this for a while, but am stuck with conflicting solutions:</p>
<p><strong>Option #1:</strong> As data will be loaded sequentially by date, define the clustered index (and primary key) as [date], [id]. Also create a "sliding window" partitioning function / scheme on date allowing rapid movement of new data in / out of the table. Potentially create a non-clustered index on id to help with querying.</p>
<p><strong>Expected Outcome #1:</strong> This setup will be very fast for data loading purposes, but sub-optimal when it comes to analytic reads as, in a worst case scenario (no limiting by dates, unlucky with set of id's queried), 100% of the data pages may be read.</p>
<p><strong>Option #2:</strong> As the data will be queried for only a small subset of ids at a time, define the clustered index (and primary key) as [id], [date]. Do not bother to create a partitioned table.</p>
<p><strong>Expected Outcome #2:</strong> Expected huge performance hit when it comes to loading data as we can no longer quickly limit by date. Expected huge performance benefit when it comes to my analytic queries as it will minimize the number of data pages read.</p>
<p><strong>Option #3:</strong> Clustered (and primary key) as follows: [id], [date]; "sliding window" partition function / scheme on date.</p>
<p><strong>Expected Outcome #3:</strong> Not sure what to expect. Given that the first column in the clustered index is [id] and thus (it is my understanding) the data is arranged by ID, I would expect good performance from my analytic queries. However, the data is partitioned by date, which is contrary to the definition of the clustered index (but still aligned as date is part of the index). I haven't found much documentation that speaks to this scenario and what, if any, performance benefits I may get from this, which brings me to my final, bonus question:</p>
<p>If I am creating a table on one filegroup on one disk, with a clustered index on one column, is there any benefit (besides partition switching when loading the data) that comes from defining a partition on the same column?</p>
|
<p>This table is awesomely narrow. If the real table will be this narrow, you should be happy to have table scans instead of index->lookups.</p>
<p>I would do this:</p>
<pre><code>CREATE TABLE Narrow
(
[id] INT NOT NULL,
[date] SMALLDATETIME NOT NULL,
[sales] FLOAT NULL,
PRIMARY KEY(id, date) --EDIT, just noticed your id is not unique.
)
CREATE INDEX CoveringNarrow ON Narrow(date, id, sales)
</code></pre>
<p>This handles point queries with seeks and wide-range queries with limited scans against date criteria and id criteria. There is no per-record lookup from index. Yes, I've doubled the write time (and space used) but that's fine, imo.</p>
<hr>
<p>If there's some need for a specific piece of data (and that need is <strong>demonstrated by profiling</strong>!!), I'd create a clustered view targetting that section of the table.</p>
<pre><code>CREATE VIEW Narrow200801
AS
SELECT * FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01'
--There is some command that I don't have at my finger tips to make this a clustered view.
</code></pre>
<p>Clustered views can be used in queries by name, or the optimizer will choose to use the clustered views when the FROM and WHERE clause are appropriate. For example, this query will use the clustered view. Note that the base table is referred to in the query.</p>
<pre><code>SELECT SUM(sales) FROM Narrow WHERE '2008-01-01' <= [date] AND [date] < '2008-02-01'
</code></pre>
<p>As <em>index</em> lets you make specific columns conveniently accessible... <em>Clustered view</em> lets you make specific rows conveniently accessible.</p>
|
<p>If you are using the partitions in the select statements, then you cn gain some speed.</p>
<p>If you are not using it, only using "standard" selects, then you have no benefit.</p>
<p>On your original problem: I would recommend you option #1 with the non-clustered index on id included.</p>
| 14,681
|
<p>I'm (surprisingly) having a problem getting my PEI substrate to stick to the heated bed surface. The ABS item being printed stuck great to the PEI surface. I've not seen anyone else post on this problem, but perhaps someone has seen it.</p>
<p>Note, this is the PRINT SURFACE warping, not the item being printed. That part went great with no delamination even on a large flat bottom.</p>
<p>I'm using 3M 468 adhesive to attach a PEI plastic sheet directly to the heated surface of my Flashforge Creator Pro printer. The heated bed is anodized black and the adhesive is a sheet cut to the requisite 6" X 9". It seemed fine and looked pretty good with few air bubbles when first attached, but the first print caused the edges of the PEI plastic to warp up from the corners of the bed. </p>
<p>It appears that the weak link is that the PEI detached from the adhesive. While this was not uniform, removal of the PEI sheet showed that 95% of the adhesive was still attached to the print bed.</p>
<p>The PEI has one glossy side and one matte side, and I chose to apply the adhesive to the matte side to get the glossy surface. Does this make a difference?</p>
<p>I applied the adhesive to the PEI surface just as it was after removing the protective plastic coating. I figured this was a clean as it was ever going to get.</p>
<p>I'd definitely appreciate some ideas on this.</p>
|
<p>Perhaps this is due to the aluminum build plate warping/crowning as it heats? I use a PEI print surface on my Monoprice Maker Select (Wanhao Di3), which has an 8.5"x8.5" build plate, and I've had no issues with the PEI coming unstuck. However, instead of attaching mine directly to the aluminum heated build plate, I attached it (using 3M 468) to a piece of Borosilicate glass, which is then attached to my aluminum build plate using silicone thermal heatsink pads. The rational for using a Borosilicate glass print surface is that a heated metal build surface is going to warp or move some, as the heat is coming from one side; the glass will not warp and so you have a completely flat surface on which to print (and the heatsink pads help make up the difference in surface geometry). I used <a href="http://3dprinterwiki.info/wiki/wanhao-duplicator-i3/duplicator-i3-basic-mods/adding-a-glass-bed/" rel="nofollow noreferrer">this 3dprinterwiki article</a> as the basis for my glass bed mod, and applied the PEI/adhesive using another source (which I've forgotten, possibly <a href="http://reprap.org/wiki/PEI_build_surface" rel="nofollow noreferrer">the RepRap wiki</a>). While the first link is Wanhao Di3 specific, it covers the idea. Make sure you tweak your z-endstops if needed on your particular machine, as adding the glass plat raises the bed height by several mm.</p>
<p>Please note that I'm theorizing - I did not ever try applying my PEI directly to my aluminum build plate, so I have no direct comparison. But the use of glass to eliminate build plate warping/crowning is fairly well documented. See also <a href="https://3dprinting.stackexchange.com/a/506/2541">this 3DPSE Answer</a>.</p>
|
<p>I never used one, but the thing that makes two parts stick together is the atmospheric pressure. The glue is just a thing that, even if it does not make any chemical bond, is keeping the air out. A pure example of that is if you put water in a glass and then put another one on it. Although the water is not glue you can't easily pull it up and if the surface is big you can't at all. It is the atmospheric pressure that keeps them together and the water keeps the air out ;). I suggest try the other side and see I'm just guessing . Good luck!!!</p>
| 493
|
<p>Is it possible to store web content (such as JSPs, HTML, images, CSS etc) in a JAR file?</p>
<p>I've been looking at various options at modularising our web applications and this is one possibility.</p>
<p>We are currently using JSF and Facelets for our view technology - I'm thinking it may be possible to write some form of custom view resolver which would examine the classpath rather than a filesystem directory, but I'm not sure this would work.</p>
<p>Any ideas would be appreciated! :)</p>
<p>Update: I should probably clarify. How do you get the web container (such as Tomcat) to load resources from a JAR file? For example, I deploy a .war file with my web application. If I access /index.jsp, the container will try to look in the web content directory for a file named index.jsp.</p>
<p>Is there an easy way to configure your own resource loader using Tomcat or the like so that it searches the classpath as well as the filesystem?</p>
|
<p>Yes, it is possible to store files e.g. properties, xml, xslt, image etc; in a JAR (or WAR) file and pull them at runtime.</p>
<p>To load a resource from your deployment jar, use the following code.</p>
<pre><code>this.getClass().getClassLoader().getResourceAsStream( filename ) ;
</code></pre>
<p>In a maven project, folders & files placed in resources are included in the jar. The filename is relative to the root of jar file, so "./filename.xml" would match the file filename.xml placed in "/src/java/resources".</p>
|
<p>Absolutely. Heck, you can store content directly in a WAR file, which is basically a JAR file with a few extra bits. Yes, you may need to write a custom resolver to use ClassLoader.getResourceAsStream, but basically as you're given the ability to generate the content however you like, fetching it from a jar file seems perfectly reasonable. You'll probably want to make sure it only fetches a very specific set of extensions though :)</p>
| 24,432
|
<p>ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain.</p>
<p>An <code>HttpWebRequest</code> works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post.</p>
<p>So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?</p>
|
<p>Here's how I solved this problem today. I started from <a href="http://www.c-sharpcorner.com/UploadFile/desaijm/ASP.NetPostURL11282005005516AM/ASP.NetPostURL.aspx" rel="nofollow noreferrer">this article</a> on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted.</p>
<p>It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site.</p>
<p>This solution involves using <code>HttpContext.Current.Response.Write()</code> to write the data for the form, then using a bit of Javascript on the <code><body onload=""></code> method to submit the form to the proper URL.</p>
<p>When the user clicks on the Support Center link, the following method is called to write the response and redirect the user:</p>
<pre><code>public static void PassthroughAuthentication()
{
System.Web.HttpContext.Current.Response.Write("<body
onload=document.forms[0].submit();window.location=\"Home.aspx\";>");
System.Web.HttpContext.Current.Response.Write("<form name=\"Form\"
target=_blank method=post
action=\"https://external-url.com/security.asp\">");
System.Web.HttpContext.Current.Response.Write(string.Format("<input
type=hidden name=\"cFName\" value=\"{0}\">", "Username"));
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body>");
}
</code></pre>
<p>The key to this method is in that onload bit of Javascript, which , when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves.</p>
<p>I'd be very interested in any cleaner ideas anyone has on this one.</p>
<p>Eric Sipple</p>
|
<p>If you're using ASP.NET 2.0, you can do this with <a href="http://msdn.microsoft.com/en-us/library/ms178139.aspx" rel="nofollow noreferrer">cross-page posting</a>.</p>
<p>Edit: I missed the fact that you're asking about an <em>external</em> page. For that I think you'd need to have your ASP.NET page gen up an HTML form whose action is set to the remote URL and method is set to POST. (Using cross-page posting, this could even be a different page with no UI, only hidden form elements.) Then add a bit of javascript to submit the form as soon as the postback result was received on the client.</p>
| 2,715
|
<p>Should I instantiate my worker variables inside or outside my for loop</p>
<p>E.g.</p>
<p>a)</p>
<pre><code>bool b = default(bool);
for (int i = 0; i < MyCollection.Length; i++)
{
b = false;
foreach(object myObject in myObjectCollection)
{
if (object.Property == MyCollection[i].Property)
{
b = true;
break;
}
}
if (b)
{
DoSomethingWith(MyCollection[i]);
}
}
</code></pre>
<p>b)</p>
<pre><code>for (int i = 0; i < MyCollection.Length; i++)
{
bool b = default(bool);
foreach(object myObject in myObjectCollection)
{
if (object.Property == MyCollection[i].Property)
{
b = true;
break;
}
}
if (b)
{
DoSomethingWith(MyCollection[i]);
}
}
</code></pre>
<p>EDIT: Seems universally agreed that there will be no difference where the IL is concerned. But for readability and clarity of scope... inside is better</p>
|
<p>Previous answer deleted as I'd misread the code. (Using "default(bool)" anywhere is a bit odd, btw.)</p>
<p>However, unless the variable is captured by a delegate etc, I'd expect them to <em>either</em> compile to IL which is effectively the same (in terms of both behaviour and performance).</p>
<p>As ever, write the most <em>readable</em> code first. Micro-optimising things like this is asking for trouble. I agree with the others who have suggested that you restrict the scope of variables as much as you can - so if you need it after the loop, you haven't got any choice anyway; otherwise declare it inside.</p>
<p>Okay, here's a test program:</p>
<pre><code>using System;
class Test
{
static void Main() {}
static void DeclareInside()
{
for (int i=0; i < 10; i++)
{
bool x = false;
for (int j=5; j < 20; j++)
{
if (i == j)
{
x = true;
break;
}
if (x)
{
Console.WriteLine("Yes");
}
}
}
}
static void DeclareOutside()
{
bool x;
for (int i=0; i < 10; i++)
{
x = false;
for (int j=5; j < 20; j++)
{
if (i == j)
{
x = true;
break;
}
if (x)
{
Console.WriteLine("Yes");
}
}
}
}
}
</code></pre>
<p>Generated IL (just <code>csc Test.cs</code>):</p>
<pre><code>.method private hidebysig static void DeclareOutside() cil managed
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (bool V_0,
int32 V_1,
int32 V_2,
bool V_3)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.1
IL_0003: br.s IL_0045
IL_0005: nop
IL_0006: ldc.i4.0
IL_0007: stloc.0
IL_0008: ldc.i4.5
IL_0009: stloc.2
IL_000a: br.s IL_0037
IL_000c: nop
IL_000d: ldloc.1
IL_000e: ldloc.2
IL_000f: ceq
IL_0011: ldc.i4.0
IL_0012: ceq
IL_0014: stloc.3
IL_0015: ldloc.3
IL_0016: brtrue.s IL_001d
IL_0018: nop
IL_0019: ldc.i4.1
IL_001a: stloc.0
IL_001b: br.s IL_0040
IL_001d: ldloc.0
IL_001e: ldc.i4.0
IL_001f: ceq
IL_0021: stloc.3
IL_0022: ldloc.3
IL_0023: brtrue.s IL_0032
IL_0025: nop
IL_0026: ldstr "Yes"
IL_002b: call void [mscorlib]System.Console::WriteLine(string)
IL_0030: nop
IL_0031: nop
IL_0032: nop
IL_0033: ldloc.2
IL_0034: ldc.i4.1
IL_0035: add
IL_0036: stloc.2
IL_0037: ldloc.2
IL_0038: ldc.i4.s 20
IL_003a: clt
IL_003c: stloc.3
IL_003d: ldloc.3
IL_003e: brtrue.s IL_000c
IL_0040: nop
IL_0041: ldloc.1
IL_0042: ldc.i4.1
IL_0043: add
IL_0044: stloc.1
IL_0045: ldloc.1
IL_0046: ldc.i4.s 10
IL_0048: clt
IL_004a: stloc.3
IL_004b: ldloc.3
IL_004c: brtrue.s IL_0005
IL_004e: ret
} // end of method Test::DeclareOutside
.method private hidebysig static void DeclareInside() cil managed
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (int32 V_0,
bool V_1,
int32 V_2,
bool V_3)
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: stloc.0
IL_0003: br.s IL_0045
IL_0005: nop
IL_0006: ldc.i4.0
IL_0007: stloc.1
IL_0008: ldc.i4.5
IL_0009: stloc.2
IL_000a: br.s IL_0037
IL_000c: nop
IL_000d: ldloc.0
IL_000e: ldloc.2
IL_000f: ceq
IL_0011: ldc.i4.0
IL_0012: ceq
IL_0014: stloc.3
IL_0015: ldloc.3
IL_0016: brtrue.s IL_001d
IL_0018: nop
IL_0019: ldc.i4.1
IL_001a: stloc.1
IL_001b: br.s IL_0040
IL_001d: ldloc.1
IL_001e: ldc.i4.0
IL_001f: ceq
IL_0021: stloc.3
IL_0022: ldloc.3
IL_0023: brtrue.s IL_0032
IL_0025: nop
IL_0026: ldstr "Yes"
IL_002b: call void [mscorlib]System.Console::WriteLine(string)
IL_0030: nop
IL_0031: nop
IL_0032: nop
IL_0033: ldloc.2
IL_0034: ldc.i4.1
IL_0035: add
IL_0036: stloc.2
IL_0037: ldloc.2
IL_0038: ldc.i4.s 20
IL_003a: clt
IL_003c: stloc.3
IL_003d: ldloc.3
IL_003e: brtrue.s IL_000c
IL_0040: nop
IL_0041: ldloc.0
IL_0042: ldc.i4.1
IL_0043: add
IL_0044: stloc.0
IL_0045: ldloc.0
IL_0046: ldc.i4.s 10
IL_0048: clt
IL_004a: stloc.3
IL_004b: ldloc.3
IL_004c: brtrue.s IL_0005
IL_004e: ret
} // end of method Test::DeclareInside
</code></pre>
<p>The only differences are where the variables are located within the stack.</p>
|
<p>I like to declare them inside the loop, it saves a line of code (to declare and set it on the same line), and it's easier to see what variables I'm using outside and inside the scope of the loop, which is good when you're working on something complicated.</p>
| 49,525
|
<p>I'm using Team Foundation Build but we aren't yet using TFS for problem tracking, so I would like to disable the work item creation on a failed build. Is there any way to do this? I tried commenting out the work item info in the TFSBuild.proj file for the build type but that didn't do the trick.</p>
|
<p>Try adding this inside the PropertyGroup in your TFSBuild.proj:</p>
<pre><code><SkipWorkItemCreation>true</SkipWorkItemCreation>
</code></pre>
<hr>
<p>If you are curious as to how this works, Microsoft.TeamFoundation.Build.targets contians the following:</p>
<pre><code> <Target Name="CoreCreateWorkItem"
Condition=" '$(SkipWorkItemCreation)'!='true' and '$(IsDesktopBuild)'!='true' "
DependsOnTargets="$(CoreCreateWorkItemDependsOn)">
<PropertyGroup>
<WorkItemTitle>$(WorkItemTitle) $(BuildNumber)</WorkItemTitle>
<BuildLogText>$(BuildlogText) &lt;a href='file:///$(DropLocation)\$(BuildNumber)\BuildLog.txt'&gt;$(DropLocation)\$(BuildNumber)\BuildLog.txt&lt;/a &gt;.</BuildLogText>
<ErrorWarningLogText Condition="!Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')"></ErrorWarningLogText>
<ErrorWarningLogText Condition="Exists('$(MSBuildProjectDirectory)\ErrorsWarningsLog.txt')">$(ErrorWarningLogText) &lt;a href='file:///$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt'&gt;$(DropLocation)\$(BuildNumber)\ErrorsWarningsLog.txt&lt;/a &gt;.</ErrorWarningLogText>
<WorkItemDescription>$(DescriptionText) %3CBR%2F%3E $(BuildlogText) %3CBR%2F%3E $(ErrorWarningLogText)</WorkItemDescription>
</PropertyGroup>
<CreateNewWorkItem
TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
BuildUri="$(BuildUri)"
BuildNumber="$(BuildNumber)"
Description="$(WorkItemDescription)"
TeamProject="$(TeamProject)"
Title="$(WorkItemTitle)"
WorkItemFieldValues="$(WorkItemFieldValues)"
WorkItemType="$(WorkItemType)"
ContinueOnError="true" />
</Target>
</code></pre>
<p>You can override any of this functionality in your own build script, but Microsoft provide the handy SkipWorkItemCreation condition at the top, which you can use to cancel execution of the whole target.</p>
|
<p>If you are using tfs2010 or above you can do this in the build definition itself.</p>
<p>In the <strong>Process tab</strong> of Build Definition set the <code>Create Work Item on failure</code> property to <code>false</code> (under the Advanced section)</p>
| 14,850
|
<p>I created an Ajax website in Visual Studio, added a simple page with a textbox and button, when I click the button once everything works, when I click it twice I get the error</p>
<p>Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500</p>
<p>Here is my page</p>
<pre><code><form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</code></pre>
<pre>
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
TextBox1.Text = "aaa"
End Sub
</pre>
<p>Edit ~ I added a second button to the page, outside of the update panel and when I clicked the one inside the update panel and then the one outside of the panel I got the error</p>
<p>Cannot open database "ASPState" requested by the login. The login failed.
Login failed for user 'server\user'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </p>
<p>Exception Details: System.Data.SqlClient.SqlException: Cannot open database "ASPState" requested by the login. The login failed.
Login failed for user 'server\user'.</p>
<p>Why is this?</p>
<p>Edit ~ To resolve my issue I did</p>
<pre><code><sessionState mode="StateServer"
stateConnectionString="tcpip=localhost:42424"
cookieless="false"
timeout="20"/>
</code></pre>
|
<p><strong>Edit</strong> There appears to be a better LZW solution that handles Unicode strings correctly at <a href="http://pieroxy.net/blog/pages/lz-string/index.html" rel="noreferrer">http://pieroxy.net/blog/pages/lz-string/index.html</a> (Thanks to pieroxy in the comments).</p>
<hr>
<p>I don't know of any gzip implementations, but the <a href="http://jsolait.net/" rel="noreferrer">jsolait library</a> (the site seems to have gone away) has functions for LZW compression/decompression. The code is covered under the <a href="http://www.gnu.org/licenses/lgpl.txt" rel="noreferrer">LGPL</a>.</p>
<pre><code>// LZW-compress a string
function lzw_encode(s) {
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++) {
currChar=data[i];
if (dict[phrase + currChar] != null) {
phrase += currChar;
}
else {
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++) {
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
</code></pre>
|
<p>Most browsers can decompress gzip on the fly. That might be a better option than a javascript implementation.</p>
| 37,570
|
<p>I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection.</p>
<p>The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.</p>
|
<p>Grab <a href="https://proj.org" rel="nofollow noreferrer">PROJ Cartographic Projections library</a> - open source library.</p>
<p>Suggested parameters for 10TM:</p>
<blockquote>
<p>+proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27</p>
</blockquote>
<p>According to <a href="http://mapserver.gis.umn.edu/data2/wilma/mapserver-users/0311/msg00336.html" rel="nofollow noreferrer">this post</a> you may need to:</p>
<blockquote>
<p>change the ellps to GRS80 if your 10TM
data is referenced to the NAD83 datum
(instead of NAD27/clrk66). You may
also need to change the false northing
(y_0) to be -5000000 if your 10TM
coordinates for Alberta are less than
5,000,000 (an AltaLIS "standard").</p>
</blockquote>
<p>I should mention that proj.4 is <em>the library</em> to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do.</p>
<p>I also recommend reading <a href="https://pubs.er.usgs.gov/publication/pp1395" rel="nofollow noreferrer">Map Projections-A Working Manual (Paperback) by John Snyder</a> if you are into these kinds of things.. it's a classic. :) (fixed the link)</p>
|
<p>You can also use <a href="http://code.google.com/p/android-openmap-framework/" rel="nofollow">http://code.google.com/p/android-openmap-framework/</a> which can convert an Android Location to a LatLonPoint, UTMPoint, or MGRSPoint.</p>
| 6,335
|
<p>I have a console application that require to use some code that need administrator level. I have read that I need to add a Manifest file myprogram.exe.manifest that look like that :</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator">
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
</code></pre>
<p>But it still doesn't raise the UAC (in the console or in debugging in VS). How can I solve this issue?</p>
<h2>Update</h2>
<p>I am able to make it work if I run the solution in Administrator or when I run the /bin/*.exe in Administrator. I am still wondering if it's possible to have something that will pop when the application start instead of explicitly right click>Run as Administrator?</p>
|
<p>For anyone using Visual Studio, it's super easy. I was about to go set up the Windows SDK and do mt.exe post-build steps and all that before realizing it's built into VS. I figured I'd record it for posterity.</p>
<ol>
<li>Project | Add New Item -> Visual C# Items -> Application Manifest File</li>
<li>Open app.manifest, change requestedExecutionLevel.@level to "requireAdministrator"</li>
<li>Build</li>
</ol>
<p>Ta-da</p>
|
<p>You need to embed the UAC manifest as an embedded Win32 resource. See <a href="http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx" rel="noreferrer">Adding a UAC Manifest to Managed Code</a>.</p>
<p>In short, you use a Windows SDK command line tool to embed it into your executable.</p>
<p>You can automate this as a post-build step by placing the following line as a post build task in your VS project's properties:</p>
<pre><code>mt.exe -manifest "$(ProjectDir)$(TargetName).exe.manifest" -updateresource:"$(TargetDir)$(TargetName).exe;#1"
</code></pre>
| 28,110
|
<p>So I added an EXE to my project's solution. The EXE does some stuff and outputs data via stdout. I want to capture the output, but more importantly how do I execute that EXE within my program?</p>
|
<pre><code>Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "myExec.exe";
p.Start();
</code></pre>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx" rel="nofollow noreferrer"><code>Process.Start</code></a>. To capture stdout you need to redirect it via <code>ProcessStartInfo</code> - there is an example on <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx" rel="nofollow noreferrer">MSDN</a>. Make sure also that the exe is marked to be copied to the output directory (bin/release etc).</p>
<p>If you need to read from both stdout and stderr it gets tricky (with a naïve implementation there is a risk of deadlock due to buffering etc)... <a href="https://stackoverflow.com/questions/258339/pconsolestartinforedirectstandardoutput-and-pconsoleexited-event-c#258387">here's</a> an example using worker threads.</p>
| 41,281
|
<p>I'm looking for a decent lexical scanner generator for C#/.NET -- something that supports Unicode character categories, and generates somewhat readable & efficient code. Anyone know of one?</p>
<hr>
<p>EDIT: I <strong><em>need</em></strong> support for <strong>Unicode categories</strong>, not just Unicode characters. There are currently 1421 characters in just the <code>Lu</code> (Letter, Uppercase) category alone, and I need to match many different categories very specifically, and would rather not hand-write the character sets necessary for it.</p>
<p>Also, actual code is a <strong><em>must</em></strong> -- this rules out things that generate a binary file that is then used with a driver (i.e. GOLD)</p>
<hr>
<p>EDIT: ANTLR does not support Unicode categories yet. There is an <a href="http://www.antlr.org/wiki/display/ANTLR3/define+unicode+aliases+for+character+categories" rel="noreferrer">open issue</a> for it, though, so it might fit my needs someday.</p>
|
<p>GPLEX seems to support your requirements.</p>
|
<p>I just found this </p>
<p><a href="http://www.seclab.tuwien.ac.at/projects/cuplex/lex.htm" rel="nofollow">http://www.seclab.tuwien.ac.at/projects/cuplex/lex.htm</a></p>
<p>It says that it's configurable enough to support unicode ;-).</p>
<p>Herber</p>
| 20,752
|
<p>I just switched to the Duet Wifi board (used MKS Gen L 1.0 before) and now small structures look terrible. From my observations the hot end moves correctly, but almost no filament gets extruded. On the other hand larger structures look very good. With the MKS board the exact same G-code worked fine.
After that I gradually disabled many features like coasting, wiping and even retractions altogether, the quality only improved by a tiny margin.</p>
<p>Example print (the two towers should be cylinders):
<a href="https://i.stack.imgur.com/jE94g.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jE94g.jpg" alt="Example print"></a></p>
<p>Additional information:</p>
<ul>
<li>Printer: JGAurora A5</li>
<li>Material: PETG</li>
<li>Slicer: Simplify3D</li>
</ul>
<p>More info (edit):</p>
<ul>
<li>Hot end temperature: 225 °C (for the affected layers)</li>
<li>Bed temperature: 60 °C (I corrected the thermistor data, it's equivalent to 70-75 °C on other JGAurora A5 printers)</li>
<li>Nozzle diameter: 0.4 mm</li>
<li>Part cooling fan: 100% (improved cooler duct by Da Hai Zhu)</li>
<li>Print speed: 50 mm/s (50% for outline)</li>
<li>The cylinder is printed hollow because of my infill settings</li>
<li>Lubricant is fresh, belts are tightened, so there should be no mechanical issues</li>
</ul>
|
<p>The OP found the solution and shared this in comments but has not written a proper answer. The OP found:</p>
<blockquote>
<p>To complete this, the issue was related to the part cooling fan not spinning correctly. After replacing it the problem was gone.</p>
</blockquote>
|
<p>This actually just looks like heating issues. Cura has an option to set a minimum layer time and speed, and any layer that takes less than that amount of time it'll lift the head away from the print to allow the plastic to cool.</p>
<p>Unfortunately, the only things I can find for Simplify3D around head lift and minimum layer times are software feature request posts from 2017, or some features around scaling print speed for small layers, but unfortunately that'll just print the same object much slower and may not properly allow the part to cool as the melting-temperature print head is still sitting directly on top of the part.</p>
<p>I hate to be someone to suggest a software change, but you might try using Cura and seeing if you get better results with features such as this. </p>
| 1,179
|
<p>I have a generic printer with no support documentation. </p>
<p>How do I determine what firmware is in use so that I can research how to make the print run?</p>
|
<p>Send <code>M115</code> to the printer. This command is </p>
<blockquote>
<p>Request the Firmware Version and Capabilities of the current microcontroller.</p>
</blockquote>
<p>Response example:</p>
<blockquote>
<p>ok PROTOCOL_VERSION:0.1 FIRMWARE_NAME:FiveD FIRMWARE_URL:http%3A//reprap.org MACHINE_TYPE:Mendel EXTRUDER_COUNT:1</p>
</blockquote>
<p>For more info see here, <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities" rel="noreferrer">RepRapWiki- G-code - M115: Get Firmware Version and Capabilities</a>.</p>
<hr>
<p><em>Of course, this isn't guaranteed to tell the truth, just whatever your generic clone firmware had in its source code.</em></p>
|
<h1>Startup</h1>
<p>Usually, when a printer starts up, the screen shows a boot-screen. This contains usually the firmware version, but not who or what the settings are.</p>
<h1>LCD: About Printer</h1>
<p>Some printers have an LCD main menu item that is "About Printer" or similar. It would one of the last items if enabled.</p>
<p>In Marlin it is disabled by default, and you'd need to uncomment <code>#define LCD_INFO_MENU</code> in <code>Configuration_adv.h</code>.</p>
<h1>Terminal</h1>
<p>Connect a <a href="https://3dprinting.stackexchange.com/questions/10573/what-is-a-printer-console-terminal">terminal</a> and send <a href="https://reprap.org/wiki/G-code#M115:_Get_Firmware_Version_and_Capabilities" rel="nofollow noreferrer"><code>M115</code></a>. In most cases, this will tell you the current Firmware and version, as it is annotated in the firmware. This doesn't mean that those lines always were updated by who changed the files, but it is a good indication what was the basis for the installed firmware.</p>
| 679
|
<p>I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.</p>
|
<p>XBAP applications do work in google chrome, however you have to set your environments PATH variable to the directory where xpcom.dll is located.</p>
<p>for example SET PATH=PATH;"C:\Program Files\Mozilla Firefox"</p>
|
<p>At the moment, XBAPs do not work in Google Chrome. I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll. Apparently this error occurs for more than just XBAP applications. From what I've read users will have to wait for a fix seeing as Chrome is still in beta.</p>
<p><strong>Update:</strong></p>
<p>Looks like it's not going to be fixed: <a href="http://code.google.com/p/chromium/issues/detail?id=4051" rel="nofollow noreferrer">http://code.google.com/p/chromium/issues/detail?id=4051</a></p>
| 10,060
|
<p>What is a "table-driven method"?</p>
<p>As mentioned by Bill Gates in the <a href="https://www.youtube.com/watch?v=nNOohFst9Lc" rel="nofollow noreferrer">second Windows Vista commercial</a> at 1:05.</p>
|
<blockquote>
<p>Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient.</p>
</blockquote>
<p>Reference: <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="noreferrer" rel="nofollow noreferrer">McConnell, Steve. Code Complete, Second Edition. Redmond (Washington): Microsoft, 2004. Print. Page 411, Paragraph 1.</a></p>
|
<p>A table-driven method is quite simple. Use data structures instead of if-then statements to drive program logic. For example, if you are processing two types of records (tv versus cable) you might do this:</p>
<pre><code>hash[tv] = process_tv_records
hash[cable] = process_cable_records
</code></pre>
<p>In some languages, like Ruby or Perl, this technique is straightforward. In Java, you'd need to use Reflection to find method handles.</p>
<p>If you want to learn about decision tables, investigate the Fitnesse testing framework at <a href="http://fitnesse.org/" rel="nofollow noreferrer">http://fitnesse.org/</a>.</p>
| 13,083
|
<p>How can I find the parameters of an <em>undocumented</em> Dll function?</p>
<p>I have searched all over the internet and ended up finding one way: it involves decorated functions. However, I cannot find a way to get those. </p>
<p><em>Any help would be appreciated.</em></p>
|
<p>You need to disassemble the application using, as Paul noted, something like IDA Pro (or the free version of the same).</p>
<p>A good introductory resource is the Wikibook, <a href="http://en.wikibooks.org/wiki/X86_Disassembly" rel="noreferrer">x86 Disassembly</a>. Specifically, take a look at the section on <a href="http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames" rel="noreferrer">functions and stack frames</a>. Deducing function parameters can be straightforward for simple functions taking a few parameters of standard type.</p>
<p>Probably the best way to get started with this sort of thing is to create a small test DLL, create a few functions with known parameters, and then disassemble your DLL to see the patterns. Learn disassembly from your own functions (for which you have the source code and know the full signature) rather than plunging into disassembling third-party stuff.</p>
|
<p>If the only piece of information you have is the undecorated function name, then unfortunately it's not possible to deduce the function parameters from that alone.</p>
<p>If you're good with assembly it might be possible to disassemble the machine code for the function and reverse engineer it. But that's reasonably hard to do for all but the simplest functions.</p>
| 37,284
|
<p>I'm sure this is going to be a long shot, but I need help with a query involving QuickBooks Items.</p>
<p>I need to query for all QuickBooks Items that are linked to an Income account. Is there an easy way to do this, or do I need to make 2 queries (one for items ans one for accounts) and then check the account reference?</p>
<p>albeit not much, I have this:</p>
<pre>
<code>
IItemQuery query = MsgSetRequest.AppendItemQueryRq();
</code>
</pre>
<p>any ideas would be appreciated. Thanks.</p>
|
<p>You need to use at least two queries. You'll need to fetch a list of accounts, and then compare the items AccountRef FullName to the income accounts in the list. </p>
|
<p>Using the XML, at least, if you query all items you can get back the accounts of all of them, and filter for the account that you want. The full name of the account will be included in the item query response if you specifically ask for it in IncludeRetElement.</p>
| 27,687
|
<p>Using VBA i have a set of functions that return an <code>ADODB.Recordset</code> where all the columns as <code>adVarChar</code>. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7</p>
<p>Is there any methods that can sort numerics as text columns without resorting to changing the type of the column?</p>
<pre><code>Sub TestSortVarChar()
Dim strBefore, strAfter As String
Dim r As ADODB.RecordSet
Set r = New ADODB.RecordSet
r.Fields.Append "ID", adVarChar, 100
r.Fields.Append "Field1", adVarChar, 100
r.Open
r.AddNew
r.Fields("ID") = "1"
r.Fields("Field1") = "A"
r.AddNew
r.Fields("ID") = "7"
r.Fields("Field1") = "B"
r.AddNew
r.Fields("ID") = "16"
r.Fields("Field1") = "C"
r.AddNew
r.Fields("ID") = "22"
r.Fields("Field1") = "D"
r.MoveFirst
Do Until r.EOF
strBefore = strBefore & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
r.Sort = "[ID] ASC"
r.MoveFirst
Do Until r.EOF
strAfter = strAfter & r.Fields("ID") & " " & r.Fields("Field1") & vbCrLf
r.MoveNext
Loop
MsgBox strBefore & vbCrLf & vbCrLf & strAfter
End Sub
</code></pre>
<p>NB: I am using Project 2003 and Excel 2003 and referencing <strong>Microsoft ActiveX DataObject 2.8 Library</strong></p>
|
<p>Left pad with Zeros with at least as many as maximum number digits.
e.g.</p>
<p>0001
0010
0022
1000</p>
<p>You can use Right$() to accomplish this.</p>
|
<p>Use the Val() function to sort numerically on a text column. Example:</p>
<pre><code>SELECT ID, Field1
FROM tablename
ORDER BY Val(Field1);
</code></pre>
| 18,884
|
<p>I started using a Sql Compact version of my DB and during the development it occured that the DB needs to be accessible over the network.
Cause I wasn't able to find a way to share the SDF file over net without replication I need to import it into SQL Server 2008 (Express).</p>
<p>Any Ideas?</p>
|
<p>I solved my problem. GvS's advice gave the keywords to search for:
<a href="http://bembengarifin-tech.blogspot.com/2008/08/generate-script-export-data-from-sql-ce.html" rel="noreferrer">http://bembengarifin-tech.blogspot.com/2008/08/generate-script-export-data-from-sql-ce.html</a></p>
|
<p>I was looking out to see if you could use ODBC to directly access the database file, but apparently, no... According to <a href="http://www.mydatabasesupport.com/forums/ms-sqlserver/216820-odbc-driver-sql-ce.html" rel="nofollow noreferrer">this forum thread</a> your best bet is to try to access it through OLEDB/ADO.</p>
| 36,951
|
<p>Easy question this time.</p>
<p>I'm trying to test whether or not a string does not contain a character using regular expressions. I thought the expression was of the form "[^<em>x</em>]" where <em>x</em> is the character that you don't want to appear, but that doesn't seem to be working.</p>
<p>For example,</p>
<pre><code>Regex.IsMatch("103","[^0]")
</code></pre>
<p>and</p>
<pre><code>Regex.IsMatch("103&","[^&]")
</code></pre>
<p>both return true (I would expect false).</p>
<p>I started using <code>"[^&]"</code> and thought maybe the & needed to be escaped as \&, but it didn't seem to make a difference.</p>
<p>Ideas? I assume it's something small.</p>
<p>Also, I'm using .NET, so keep that in mind.</p>
<p>Edit1:</p>
<p>I found <a href="https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring">this</a>, but it doesn't seem to answer the issue I'm having.</p>
<p>Edit2:</p>
<p>I wanted to respond to <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198793">Kevin</a> and <a href="https://stackoverflow.com/questions/198781/regex-to-tell-if-a-string-does-not-contain-a-specific-character#198796">Joel</a>'s suggestions. These suggestions would indeed be faster, but they don't accomplish the flexibility I need in this case, so if you found this question through search, definitely look to see if their answers will fit your needs. In my case, the regular expression is getting passed in to a DataTable validation method that loops through each row and verifies that the contents of that row in a specific column matches the RegEx that is getting passed in. Since I'll be reusing this method for several other DataTables that are being validated, I wanted to:</p>
<ol>
<li>Use Regex to enable the widest range of validations, and</li>
<li>Always look for a positive match (i.e. instead of using !Regex.IsMatch(cell, regexvariable), I wanted to rely on always being able to use Regex.IsMatch(cell, regexvariable) since the majority of DataTables invoking this method will be using the positive match instead of the negative.</li>
</ol>
<p>Hopefully that helps.</p>
|
<p>Your solution is half right. The match you see is for the other characters. What you want to say is something like "hey! I do not want to see this character in the entire string".</p>
<p>In that case you do:</p>
<pre><code>Regex.IsMatch("103","^[^0]*$")
</code></pre>
|
<p>The first character the parser reaches is "1", which is true for [^0] and also true for [^&], so therefore it will return true in both of those examples. </p>
| 24,227
|
<p>The question is this, why do I need to add an "import" directive on my <strong>Site.Master</strong> file to get Intellisense when the html helpers work without it.</p>
<p>Using a simple C# string extension method without a namespace == no problem. However, I wanted to put this extension in a namespace to be a good programmer.</p>
<p>If I wrap it in a <strong>namespace</strong>, you have to do a couple of things. Here is my extension:</p>
<pre><code>namespace MySystemCore
{
public static class StringExtensions
{
public static string F(this string s, params object[] args)
{
return string.Format(s, args);
}
}
}
</code></pre>
<p>So through trial and error, I have it working, but wanted to share my observations. Hopefully it may help someone else in the future.</p>
<p>NOTE: I am using the extension method in <strong>Site.Master</strong></p>
<ol>
<li><p>Add "using MySystemCore;" to <strong>Site.Master.cs</strong> file (codebehind file)</p>
<ul>
<li>Runtime error, no extension method found</li>
</ul></li>
<li><p>Add "<code><add namespace="MySystemCore"></code>" to <code><namespaces></code> configuration block in <strong>web.config</strong></p>
<ul>
<li>Works, no intellisense</li>
</ul></li>
<li><p>Combine #1 and #2</p>
<ul>
<li>Works, no intellisense</li>
</ul></li>
<li><p>Add "<code><%@ Import Namespace="MySystemCore" %></code>" to <strong>Site.Master</strong> file</p>
<ul>
<li>Works, with intellisense</li>
</ul></li>
</ol>
|
<p>It's a VS limitation that when you add it to <namespaces> in <b>web.config</b>, IntelliSense doesn't show up.</p>
<p>But for the sake of completeness, I'll discuss the cause of it:
<li>Method 1 is not a correct way to do it at all, since <b>using</b> directives (<b>Imports</b> will compile down to <b>using</b> by <b>ASP.NET preprocessor</b>) are scoped to a compilation unit (i.e. a single file)</li>
<li>Method 2 runs OK since it adds the <b>using</b> directive to the compilation options, which affects all compilation units in the application. If IntelliSense doesn't show up in this case, that's because VS is not smart enough to consider <b>web.config</b>.</li>
<li>Method 3 is effectively, just like 2. Method 1 is totally unrelated to the master file, it only affects .cs file as I mentioned before. Method 2 is like adding using to all .cs files automatically.</li>
<li>Method 4 works because VS understands that you're using it in the same file as it's working on.</li></p>
|
<p>I agree that it is sometimes very annoying. But it is all with separation of concerns. You'll have to learn all your own and MS namespaces to find the correct extension methods.</p>
| 39,053
|
<p>I have experimented with a sigmoid and logarithmic fade out for volume over a period of about half a second to cushion pause and stop and prevent popping noises in my music applications.</p>
<p>However neither of these sound "natural". And by this I mean, they sound botched. Like an amateur engineer was in charge of the sound decks.</p>
<p>I know the ear is logarithmic when it comes to volumes, or at least, twice as much power does not mean twice as loud. Is there a magic formula for volume fading? Thanks.</p>
|
<p>I spent many of my younger years mixing music recordings, live concerts and being a DJ for my school's radio station and the one thing I can tell you is that where you fade is also important.</p>
<p>Fading in on an intro or out during the end of a song sounds pretty natural as long as there are no vocals, but some of these computerized radio stations will fade ANYWHERE in a song to make the next commercial break ... I don't think there's a way to make that sound good.</p>
<p>In any case, I'll also answer the question you asked ... the logarithmic attenuation used for adjusting audio levels is generally referred to as "audio taper". Here's an excellent article that describes the physiology of human hearing in relation to the electronics we now use for our entertainment. See: <a href="http://tangentsoft.net/audio/atten.html" rel="nofollow noreferrer">http://tangentsoft.net/audio/atten.html</a>.</p>
|
<p>If you're just looking to get a clean sound sound when pausing or stopping playback then there's no need to fade at all - just find a zero-crossing point and stop there (or more realistically just fill the rest of that final buffer with silence). Fading out when the user expects the sound to stop immediately will sound unnatural, as you've noticed, because the result is decoupled from the action.</p>
<p>The reason for stopping at a zero-crossing point is that zero is the steady state value while the audio is stopped, so the transition between the two states is seamless. If you stop playback when the last sample's amplitude is large then you are effectively introducing transients into the audio from the point of view of the audio hardware when it reconstructs the analogue signal, which will be audible as pops and/or clicks.</p>
<p>Another approach is to fade to zero very fast (~< 10mS), which effectively achieves the same thing as the zero-crossing technique.</p>
| 25,371
|
<p>I need a Datepicker for a WPF application. What is considered to be the best one? </p>
|
<h3>There is also the <a href="http://www.codeplex.com/wpf" rel="noreferrer">WPF Tool Kit</a> which has a DatePicker/Calendar control</h3>
<p>(i added emphasis because this is the answer)</p>
|
<p>I'm thinking of using this one: <a href="http://marlongrech.wordpress.com/2007/09/11/wpf-datepicker/" rel="nofollow noreferrer">Marlon Grech Date Picker</a>.</p>
| 7,309
|
<p>I've got a collection that implements an interface that extends both IList<T> and List. </p>
<pre><code>public Interface IMySpecialCollection : IList<MyObject>, IList { ... }
</code></pre>
<p>That means I have two versions of the indexer. </p>
<p>I wish the generic implementation to be used, so I implement that one normally:</p>
<pre><code>public MyObject this[int index] { .... }
</code></pre>
<p>I only need the IList version for serialization, so I implement it explicitly, to keep it hidden:</p>
<pre><code>object IList.this[int index] { ... }
</code></pre>
<p>However, in my unit tests, the following</p>
<pre><code>MyObject foo = target[0];
</code></pre>
<p>results in a compiler error</p>
<blockquote>
<p>The call is ambiguous between the
following methods or properties</p>
</blockquote>
<p>I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList<T> and IList to coexist within the same interface?</p>
<p><strong>Edit</strong> IList<T> does <em>not</em> implement IList, and I <strong>must</strong> implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing.</p>
<p><strong>Edit again</strong>: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList...</p>
|
<p>You can't do this with </p>
<p><code>public interface IMySpecialCollection : IList<MyObject>, IList { ... }</code></p>
<p>But you can do what you want with a class, you will need to make the implementations for one of the interfaces explicit. In my example I made IList explicit.</p>
<p><code>public class MySpecialCollection : IList<MyObject>, IList { ... }</code></p>
<p><code>IList<object> myspecialcollection = new MySpecialCollection();
IList list = (IList)myspecialcollection;</code></p>
<p>Have you considered having IMySpecialCollection implement ISerializable for serialization?
Supporting multiple collection types seems a bit wrong to me. You may also want to look at casting yout IList to IEnumerable for serialization since IList just wraps IEnumerable and ICollection. </p>
|
<p>List<T> implies IList, so it's a bad idea to use both in the same class.</p>
| 8,125
|
<p>I'm working on developing a regular dump of our database. I'm using <a href="http://davidwalsh.name/backup-mysql-database-php" rel="nofollow noreferrer">this script</a> to create the backup and then feeding it through a regular cron job. In the end we end up with a text file as well as an email archive of everything.</p>
<p>The problem we've encountered is the size of two of our tables. They each have 60k fields and grow daily. I'm thinking incremental backup are the best solution for backup, but if it ever came to restoring it... It will be a huge project.</p>
<p>My question is a two parter: </p>
<p>a) Is there a more straight forward way to backup huge tables on a daily basis and, if not, </p>
<p>b) Is there an easy way to restore a backup from daily/weekly incremental backups?</p>
<p>Thanks!</p>
|
<p>You can use a crob job to execute mysqldump to dump the tables down that you wish to backup. Then just use a differential backup on that file for the daily backup and do a full backup once a week. The backup's heavy lifting should be done by your backup engine of choice.</p>
<p>Restoring a DB is never fun, so regardless it will be a big project.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html</a></p>
<p>Let me know if this works for you.</p>
|
<p>Consider using LVM snapshots to take periodic snapshots of your datasource, then use maatkit on the snapped copy in order to store an SQL dump. Do this on a slave MySQL db so that your backups don't cause performance problems for your live platform.</p>
| 37,994
|
<p>I just started creating my data-access layer using LinqToSql. Everybody is talking about the cool syntax and I really like Linq in general. </p>
<p>But when I saw how your classes get generated if you drag some tables on the LinqContext I was amazed: So much code which nobody would need?!</p>
<p>So I looked how other people used LinqToSql, for example Rob Connery at his StoreFront Demo.</p>
<p>As I don't like the way that all this code is generated I created my domain layer by hand and used the generated classes as reference. With that solution I'm fine, as I can use the features provided by Linq (dereferred execution, lazy loading, ...) and my domain layer is quite easy to understand.</p>
<p>How are you using LinqToSql?</p>
|
<p>The created classes are not as heavy as it seems. Of course it takes quite a few lines of code, but all in all it is as lightweight as it can be for the features it's providing.</p>
<p>I used to create my own tables, too, but now instead I just use the LINQtoSQL DataContext. Why? Creating is simpler, the features are better, interoperability works, it is probably even faster than my own stuff (not in every aspect. Usually my own stuff was extremely fast in one thing, but the generic stuff was faster in everything else).<br>
But the most important part: it is easier to bring new developers into the LINQ stuff than into my own. There are tutorials, example codes, documentation, everything, which I'd have to create for my code by myself. Same with using my stuff with other technology, like WCF or data binding. There are a lot of pitfalls to be taken care of.</p>
<p>I learned not to develop myself into a corner the hard way, it looks fast and easy at the start, is a lot more fun than learning how to use the libs, but is a real pain in the a after a few months down the road, usually even for myself.</p>
<p>After some time the novelty of creating my own data containers wears off, and I noticed the pain connected to adding a feature. A feature I would have had for free, if I had used the provided classes.<br>
Next thing I had to explain my code to some other programmer. Had I used the provided classes, I could have pointed him to some web site to learn about the stuff. But for my classes, I had to train him himself, which took a long time and made it hard to get new people on a project.</p>
|
<p>Use compiled queries. Linq to SQL is dog slow otherwise. <a href="http://blogs.msdn.com/ricom/archive/2007/06/22/dlinq-linq-to-sql-performance-part-1.aspx" rel="nofollow noreferrer">Really</a>.</p>
| 29,897
|
<p>I've inherited a mobile app which sends auth credentials (userid/password) in the clear.</p>
<p>I'd imagine that I have 2 choices:
a) use TLS.
b) write my own auth protocol.</p>
<p>If I choose (b) what are the key guidelines that I must follow to make it it secure.
e.g. how to avoid replay attacks, encryption strategies.</p>
|
<p>If you use b), the key guidelines are: Don't. If you want it secure, that is.</p>
<p>Try to stick with a).</p>
|
<p>For both <em>"you can't get sued for it"</em> and <em>"reasonably protected"</em> definitions of 'safe', for a mobile application, you can assume that the line is secure vs man-in-the-middle attacks and wide open to eavesdropping. SSL/TLS sounds the easiest way to go, but this might depend on your carrier and target phones. </p>
<p>If you can't make TLS work and you need to roll your own, use <a href="http://en.wikipedia.org/wiki/Diffie-Hellman" rel="nofollow noreferrer">Diffie-Hellman</a> key exchange and established crypto library (<a href="http://www.bouncycastle.org/latest_releases.html" rel="nofollow noreferrer">Legion of the Bouncy Castle</a> have a jightweight implementation that is J2ME compliant.)</p>
| 23,921
|
<p>So I have this app that checks for updates on the server getting a JSON response, each new update is put at the top of my list on a new div that is added via insertBefore using javascript.</p>
<p>All works just fine, but i'd like to add an animation effect when the div is added, i.e. "slowly" move the existing divs down, and add the new one at the top, Any pointers on how to do that ?</p>
<p>The application actually runs in facebook not using the iframe, I tried to use jquery but it does not seem to work on facebook, and looking at the code modifications that FB do, I assume other frameworks will have a similar problem.</p>
|
<p>Since you are looking to do it yourself you'll need to use setTimeout to repeatedly change the height of your div. The basic, quick and dirty code looks something like this:</p>
<pre><code>var newDiv;
function insertNewDiv() {
// This is called when you realize something was updated
// ...
newDiv = document.createElement('div');
newDiv.style.height = "0px";
document.body.appendChild(newDiv);
setTimeout(slideInDiv, 0);
}
function slideInDiv(){
newDiv.style.height = newDiv.clientHeight + 10 + "px"; // Slowly make it bigger
if (newDiv.clientHeight < 100){
setTimeout(slideInDiv, 40); // 40ms is approx 25 fps
} else {
addContent();
}
}
function addContent(){
newDiv.innerHTML = "Done!";
}
</code></pre>
<p>Note that you may wish to make your animation code more general (pass in the ID, a callback function, etc) but for a basic animation this should get you started.</p>
|
<p>It depends on the JavaScript framework you're using; but look at <a href="http://demos.mootools.net/Fx.Slide" rel="nofollow noreferrer">MooTools</a>, <a href="http://github.com/madrobby/scriptaculous/wikis/combination-effects-demo" rel="nofollow noreferrer">Scriptaculous</a>, <a href="http://docs.jquery.com/Effects" rel="nofollow noreferrer">jQuery</a> and <a href="http://developer.yahoo.com/yui/animation/" rel="nofollow noreferrer">YUI Animation</a>. If you're just hammering out JavaScript on your own, you'll find that working with interval timers that modify the style of some element over time and then trigger an animation complete event to stop the timer and finally update the page is a fairly involved error prone process.</p>
<p>You're probably looking for something generally called <a href="http://github.com/madrobby/scriptaculous/wikis/effect-slidedown" rel="nofollow noreferrer">slide</a> <a href="http://docs.jquery.com/Effects/slideDown#speedcallback" rel="nofollow noreferrer">down</a> (try the demos).</p>
| 41,608
|
<p>In my C/C++ program, I'm using <a href="http://opencvlibrary.sourceforge.net/" rel="noreferrer">OpenCV</a> to capture images from my webcam. The camera (<a href="http://en.wikipedia.org/wiki/Quickcam" rel="noreferrer">Logitech QuickCam IM</a>) can capture at resolutions <strong>320x240</strong>, <strong>640x480</strong> and <strong>1280x960</strong>. But, for some strange reason, OpenCV gives me images of resolution <strong>320x240</strong> only. Calls to change the resolution using <strong>cvSetCaptureProperty()</strong> with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam?</p>
|
<p>There doesn't seem to be a solution. The resolution can be increased to <strong>640x480</strong> using <a href="http://tech.groups.yahoo.com/group/OpenCV/message/28735" rel="noreferrer">this hack</a> shared by <em>lifebelt77</em>. Here are the details reproduced:</p>
<p>Add to <strong>highgui.h</strong>:</p>
<pre><code>#define CV_CAP_PROP_DIALOG_DISPLAY 8
#define CV_CAP_PROP_DIALOG_FORMAT 9
#define CV_CAP_PROP_DIALOG_SOURCE 10
#define CV_CAP_PROP_DIALOG_COMPRESSION 11
#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12
</code></pre>
<p>Add the function <strong>icvSetPropertyCAM_VFW</strong> to <strong>cvcap.cpp</strong>:</p>
<pre><code>static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )
{
int result = -1;
CAPSTATUS capstat;
CAPTUREPARMS capparam;
BITMAPINFO btmp;
switch( property_id )
{
case CV_CAP_PROP_DIALOG_DISPLAY:
result = capDlgVideoDisplay(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);
break;
case CV_CAP_PROP_DIALOG_FORMAT:
result = capDlgVideoFormat(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);
break;
case CV_CAP_PROP_DIALOG_SOURCE:
result = capDlgVideoSource(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);
break;
case CV_CAP_PROP_DIALOG_COMPRESSION:
result = capDlgVideoCompression(capture->capWnd);
break;
case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:
capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
btmp.bmiHeader.biWidth = floor(value/1000);
btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;
btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *
btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *
btmp.bmiHeader.biBitCount / 8;
capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
break;
default:
break;
}
return result;
}
</code></pre>
<p>and edit <strong>captureCAM_VFW_vtable</strong> as following:</p>
<pre><code>static CvCaptureVTable captureCAM_VFW_vtable =
{
6,
(CvCaptureCloseFunc)icvCloseCAM_VFW,
(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,
(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,
(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,
(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL
(CvCaptureGetDescriptionFunc)0
};
</code></pre>
<p>Now rebuilt <strong>highgui.dll</strong>.</p>
|
<pre><code>cvQueryFrame(capture);
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, any_supported_size );
cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, any_supported_size);
cvQueryFrame(capture);
</code></pre>
<p>should be just enough!</p>
| 3,506
|
<p>How to get file name and revision number as a list starting from a designated folder?</p>
|
<p>You can use <code>cvs status</code> at the base folder of your project and grep for the appropriate line:</p>
<pre><code>> cvs status | grep Repository\ revision\:
Repository revision: 1.16 /cvsroot/module/.cvsignore,v
Repository revision: 1.1.1.1 /cvsroot/module/build.sh,v
Repository revision: 1.251 /cvsroot/module/build.xml,v
Repository revision: 1.36 /cvsroot/module/manifest.xml,v
... and on, and on...
</code></pre>
|
<p><code>cvs status</code> will give you that information in the following form per file:</p>
<pre><code>===================================================================
File: test.pas Status: Up-to-date
Working revision: 1.4
Repository revision: 1.4 /cvsroot/MyModule/test.pas,v
Expansion option: kv
Commit Identifier: 86c473d9b385950
Sticky Tag: (none)
Sticky Date: (none)
Sticky Options: (none)
Merge From: (none)
</code></pre>
<p><em>(output is from CVSNT; Commit ID and Mergepoint will not be shown by vanilla CVS)</em></p>
<p>You can write a script to extract and reformat that information.</p>
| 37,990
|
<p>How can I unit test SSIS packages? I want to be able to create and maintain unit tests for various components such as the workflow tasks, data flow tasks, event handlers, etc.</p>
<p>Are there any existing techniques, frameworks, and/or tools that can be used?</p>
|
<blockquote>
<p><a href="http://www.codeplex.com/ssisUnit" rel="noreferrer">ssisUnit</a></p>
</blockquote>
<p>A unit testing framework for SQL Server Integration Services</p>
|
<p><a href="https://github.com/BartekR/ssisUnitLearning" rel="nofollow noreferrer">ssisUnitLearning</a> is a SSIS Tester</p>
<p>SSIS project to learn SSIS-Unit testing</p>
<p>For more go to with "ssisUnit testing" series at <a href="http://blog.bartekr.net/series/" rel="nofollow noreferrer">bartekr</a></p>
| 28,027
|
<p>I was wondering how to unit test abstract classes, and classes that extend abstract classes.</p>
<p>Should I test the abstract class by extending it, stubbing out the abstract methods, and then test all the concrete methods? Then only test the methods I override, and test the abstract methods in the unit tests for objects that extend my abstract class?</p>
<p>Should I have an abstract test case that can be used to test the methods of the abstract class, and extend this class in my test case for objects that extend the abstract class?</p>
<p>Note that my abstract class has some concrete methods.</p>
|
<p>There are two ways in which abstract base classes are used.</p>
<ol>
<li><p>You are specializing your abstract object, but all clients will use the derived class through its base interface.</p></li>
<li><p>You are using an abstract base class to factor out duplication within objects in your design, and clients use the concrete implementations through their own interfaces.!</p></li>
</ol>
<hr>
<p><strong>Solution For 1 - Strategy Pattern</strong></p>
<p><img src="https://i.stack.imgur.com/Bu4Vy.png" alt="Option1"></p>
<p>If you have the first situation, then you actually have an interface defined by the virtual methods in the abstract class that your derived classes are implementing. </p>
<p>You should consider making this a real interface, changing your abstract class to be concrete, and take an instance of this interface in its constructor. Your derived classes then become implementations of this new interface. </p>
<p><img src="https://i.stack.imgur.com/wPPqA.png" alt="IMotor"></p>
<p>This means you can now test your previously abstract class using a mock instance of the new interface, and each new implementation through the now public interface. Everything is simple and testable.</p>
<hr>
<p><strong>Solution For 2</strong></p>
<p>If you have the second situation, then your abstract class is working as a helper class. </p>
<p><img src="https://i.stack.imgur.com/ABrGO.png" alt="AbstractHelper"></p>
<p>Take a look at the functionality it contains. See if any of it can be pushed onto the objects that are being manipulated to minimize this duplication. If you still have anything left, look at making it a helper class that your concrete implementation take in their constructor and remove their base class. </p>
<p><img src="https://i.stack.imgur.com/eySjQ.png" alt="Motor Helper"></p>
<p>This again leads to concrete classes that are simple and easily testable.</p>
<hr>
<p><strong>As a Rule</strong></p>
<p>Favor complex network of simple objects over a simple network of complex objects.</p>
<p>The key to extensible testable code is small building blocks and independent wiring.</p>
<hr>
<p><strong>Updated : How to handle mixtures of both?</strong></p>
<p>It is possible to have a base class performing both of these roles... ie: it has a public interface, and has protected helper methods. If this is the case, then you can factor out the helper methods into one class (scenario2) and convert the inheritance tree into a strategy pattern. </p>
<p>If you find you have some methods your base class implements directly and other are virtual, then you can still convert the inheritance tree into a strategy pattern, but I would also take it as a good indicator that the responsibilities are not correctly aligned, and may need refactoring. </p>
<hr>
<p><strong>Update 2 : Abstract Classes as a stepping stone (2014/06/12)</strong> </p>
<p>I had a situation the other day where I used abstract, so I'd like to explore why. </p>
<p>We have a standard format for our configuration files. This particular tool has 3 configuration files all in that format. I wanted a strongly typed class for each setting file so, through dependency injection, a class could ask for the settings it cared about. </p>
<p>I implemented this by having an abstract base class that knows how to parse the settings files formats and derived classes that exposed those same methods, but encapsulated the location of the settings file. </p>
<p>I could have written a "SettingsFileParser" that the 3 classes wrapped, and then delegated through to the base class to expose the data access methods. I chose not to do this <em>yet</em> as it would lead to 3 derived classes with more <em>delegation</em> code in them than anything else. </p>
<p>However... as this code evolves and the consumers of each of these settings classes become clearer. Each settings users will ask for some settings and transform them in some way (as settings are text they may wrap them in objects of convert them to numbers etc.). As this happens I will start to extract this logic into data manipulation methods and push them back onto the strongly typed settings classes. This will lead to a higher level interface for each set of settings, that is eventually no longer aware it's dealing with 'settings'. </p>
<p>At this point the strongly typed settings classes will no longer need the "getter" methods that expose the underlying 'settings' implementation.</p>
<p>At that point I would no longer want their public interface to include the settings accessor methods; so I will change this class to encapsulate a settings parser class instead of derive from it. </p>
<p>The Abstract class is therefore: a way for me to avoid delegation code at the moment, and a marker in the code to remind me to change the design later. I may never get to it, so it may live a good while... only the code can tell.</p>
<p>I find this to be true with any rule... like "no static methods" or "no private methods". They indicate a smell in the code... and that's good. It keeps you looking for the abstraction that you have missed... and lets you carry on providing value to your customer in the mean time. </p>
<p>I imagine rules like this one defining a landscape, where maintainable code lives in the valleys. As you add new behaviour, it's like rain landing on your code. Initially you put it wherever it lands.. then you refactor to allow the forces of good design to push the behaviour around until it all ends up in the valleys. </p>
|
<p>Following @patrick-desjardins answer, I implemented abstract and it's implementation class along with <code>@Test</code> as follows:</p>
<p><strong>Abstract class - ABC.java</strong></p>
<pre><code>import java.util.ArrayList;
import java.util.List;
public abstract class ABC {
abstract String sayHello();
public List<String> getList() {
final List<String> defaultList = new ArrayList<>();
defaultList.add("abstract class");
return defaultList;
}
}
</code></pre>
<p>As <strong><em>Abstract classes cannot be instantiated, but they can be subclassed</em></strong>, concrete class <strong>DEF.java</strong>, is as follows:</p>
<pre><code>public class DEF extends ABC {
@Override
public String sayHello() {
return "Hello!";
}
}
</code></pre>
<p><strong>@Test</strong> class to test both abstract as well as non-abstract method:</p>
<pre><code>import org.junit.Before;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.contains;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
import org.junit.Test;
public class DEFTest {
private DEF def;
@Before
public void setup() {
def = new DEF();
}
@Test
public void add(){
String result = def.sayHello();
assertThat(result, is(equalTo("Hello!")));
}
@Test
public void getList(){
List<String> result = def.getList();
assertThat((Collection<String>) result, is(not(empty())));
assertThat(result, contains("abstract class"));
}
}
</code></pre>
| 30,139
|
<p>It's not a matter of life or death but I wonder if this could be possible:</p>
<p>I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.</p>
<p>so now it looks like this:</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.SHOW_FORM, formListener);
addEventListener(FormEvent.SEND_FORM, formListener);
addEventListener(FormEvent.CANCEL_FORM, formListener);
}
private function formListener(event:formEvent):void {
switch(event.type){
case "show.form":
// handle show form stuff
break;
case "send.form":
// handle send form stuff
break;
case "cancel.form":
// handle cancel form stuff
break;
}
}
</code></pre>
<p>but instead of adding every event one at the time I would rather be doing something like</p>
<pre><code> private function addListeners():void {
addEventListener(FormEvent.*, formListener);
}
</code></pre>
<p>I wonder if something like this is possible, i would love it. I work with loads of events :)</p>
|
<p>You only really need one event listener in this case anyhow. That listener will be listening for any change with the form and a parameter equal to what the change was becomes available to the event listener function. I will show you, but please remember that this is a pseudo situation and normally I wouldn't dispatch an event off of something as simple as a method call because the dispatch is implied so there is no real need to listen for it.</p>
<p>First the Custom Event</p>
<pre><code>
package com.yourDomain.events
{
import flash.events.Event;
public class FormEvent extends Event
{
//Public Properties
public static const CANCEL_FORM:int = "0";
public static const SHOW_FORM:int = "1";
public static const SEND_FORM:int = "2";
public static const STATE_CHANGED:String = "stateChanged";
//Private Properties
private var formState:int;
public function FormEvent(formState:int):void
{
super(STATE_CHANGED);
formState = formState;
}
}
}
</code>
</pre>
<p>So we have just created our custom event class and we have set it up so that we can catch the state through the listener function as I will demonstrate once done with the pseudo form class that will dispatch the for said custom event.</p>
<p>Remember that this is all hypothetical as I have no idea what your code looks like or how your implementing things. What is important is to notice that when I dispatch the event I need to send a parameter with it that reflects what the new state is.</p>
<pre>
<code>
package com.yourDomain.ui
{
import flash.events.Event;
import flash.events.EventDispatcher;
import com.yourDomain.events.FormEvent;
public class Form extends EventDispatcher
{
public function Form():void
{
//Anything you want form to do upon instantiation goes here.
}
public function cancelForm():void
{
dispatchEvent(new Event(FormEvent.CANCEL_FORM);
}
public function showForm():void
{
dispatchEvent(new Event(FormEvent.SHOW_FORM);
}
public function sendForm():void
{
dispatchEvent(new Event(FormEvent.SEND_FORM);
}
}
}
</code>
</pre>
<p>And finally we create the document class that will listen for it. Please know that I realize it isn't logical to create a listener that fires when you call a method of a class because you obviously know you called the method, but for this example it will due.</p>
<pre>
<code>
package com.yourDomain.ui
{
import com.yourDomain.ui.Form;
import com.yourDomain.events.FormEvent;
//Form is in the same package so we need not import it.
public class MainDocumentClass
{
private var _theForm:Form;
public function MainDocumentClass():void
{
_theForm = new Form();
_theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);
/*
The following three method calls each cause the
FormEvent.STATE_CHANGE event to be dispatched.
onFormStateChange is notified and checks what
the last change actually was.
*/
_theForm.cancelForm();
_theForm.showForm();
_theForm.sendForm();
}
private function onFormStateChange(e:FormEvent):void
{
switch(e.formState)
{
case CANCEL_FORM:
trace('The form was canceled');
break;
case SHOW_FORM:
trace('The form was revealed');
break;
case SEND_FORM:
trace('The form was sent');
break;
}
}
}
}
</code>
</pre>
<p>I hope that this was helpful, its late and I may have to revise some things later, but this should help get an understanding of how to make your own events and to customize how things work.</p>
|
<p>I don't know of any routines that let you do that directly, but you could write your own. The syntax here won't be perfect, but here's a first pass:</p>
<pre><code>private function addMultipleEventListeners( evts:Array, callback:function ):void
{
for each( var evt:Event in evts )
{
addEventListener( evt, callback );
}
}
</code></pre>
<p>You could then call that routine like so:</p>
<pre><code>var evts:Array = [ FormEvent.SHOW_FORM, FormEvent.SEND_FORM, FormEvent.CANCEL_FORM ];
addMultipleEventListeners( evts, formListener );
</code></pre>
| 16,458
|
<p>I have a file with several thousand rows and several columns separated with tabs What I'd like to do is loop through each individually, Drop the columns into an array so that I can place them in another application individually, then move onto the next line. Unfortunately I got about as far as this:</p>
<pre><code>Open mytextfile.txt For Input As #FileHandle
Do While Not EOF(FileHandle)
Line Input #FileHandle, IndividualLine
StringToBreakup = IndividualLine
Loop
</code></pre>
<p>So how would I go about breaking individual line up into an array</p>
|
<pre><code>Dim str() as String
Open mytextfile.txt For Input As #FileHandle
Do While Not EOF(FileHandle)
Line Input #FileHandle, IndividualLine
str = Split(IndividualLine, vbTab)
Debug.Print str(0) 'First array element
Loop
</code></pre>
<p>To clarify: I would avoid the use of Variants and use vbTab.</p>
|
<p>Use the split command</p>
<pre><code>Dim StringArray as Variant
Open mytextfile.txt For Input As #FileHandle
Do While Not EOF(FileHandle)
Line Input #FileHandle, IndividualLine
StringToBreakup = IndividualLine
StringArray = Split(StringToBreakup, CHR(9))
Process array here...
Loop
</code></pre>
| 37,223
|
<h2>Update: giving a much more thorough example.</h2>
<p>The first two solutions offered were right along the lines of what I was trying to say <em>not</em> to do. I can't know location, it needs to be able to look at the whole document tree. So a solution along these lines, with /Books/ specified as the context will not work:</p>
<pre><code>SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x)
</code></pre>
<h2>Original question with better example:</h2>
<p>Using SQL Server 2005's XQuery implementation I need to select all nodes in an XML document, just once each and keeping their original structure, but only if they are missing a particular attribute, or that attribute has a specific value (passed in by parameter). The query also has to work on the whole XML document (descendant-or-self axis) rather than selecting at a predefined depth.</p>
<p>That is to say, each individual node will appear in the resultant document only if it and every one of its ancestors are missing the attribute, or have the attribute with a single specific value.</p>
<h2>For example:</h2>
<p>If this were the XML:</p>
<pre><code> DECLARE @Xml XML
SET @Xml =
N'
<Library>
<Novels>
<Novel category="1">Novel1</Novel>
<Novel category="2">Novel2</Novel>
<Novel>Novel3</Novel>
<Novel category="4">Novel4</Novel>
</Novels>
<Encyclopedias>
<Encyclopedia>
<Volume>A-F</Volume>
<Volume category="2">G-L</Volume>
<Volume category="3">M-S</Volume>
<Volume category="4">T-Z</Volume>
</Encyclopedia>
</Encyclopedias>
<Dictionaries category="1">
<Dictionary>Webster</Dictionary>
<Dictionary>Oxford</Dictionary>
</Dictionaries>
</Library>
'
</code></pre>
<p>A parameter of 1 for category would result in this:</p>
<pre class="lang-xml prettyprint-override"><code><Library>
<Novels>
<Novel category="1">Novel1</Novel>
<Novel>Novel3</Novel>
</Novels>
<Encyclopedias>
<Encyclopedia>
<Volume>A-F</Volume>
</Encyclopedia>
</Encyclopedias>
<Dictionaries category="1">
<Dictionary>Webster</Dictionary>
<Dictionary>Oxford</Dictionary>
</Dictionaries>
</Library>
</code></pre>
<p>A parameter of 2 for category would result in this:</p>
<pre class="lang-xml prettyprint-override"><code><Library>
<Novels>
<Novel category="2">Novel2</Novel>
<Novel>Novel3</Novel>
</Novels>
<Encyclopedias>
<Encyclopedia>
<Volume>A-F</Volume>
<Volume category="2">G-L</Volume>
</Encyclopedia>
</Encyclopedias>
</Library>
</code></pre>
<p>I know XSLT is perfectly suited for this job, but it's not an option. We have to accomplish this entirely in SQL Server 2005. Any implementations not using XQuery are fine too, as long as it can be done entirely in T-SQL.</p>
|
<p>It's not clear for me from your example what you're actually trying to achieve. Do you want to return a new XML with all the nodes stripped out except those that fulfill the condition? If yes, then this looks like the job for an XSLT transform which I don't think it's built-in in MSSQL 2005 (can be added as a UDF: <a href="http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx" rel="nofollow noreferrer">http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx</a>).</p>
<p>If you just need to return the list of nodes then you can use this expression:</p>
<pre><code>//Book[not(@ID) or @ID = 5]
</code></pre>
<p>but I get the impression that it's not what you need. It would help if you can provide a clearer example.</p>
<p><strong>Edit</strong>: This example is indeed more clear. The best that I could find is this:</p>
<pre><code>SET @Xml.modify('delete(//*[@category!=1])')
SELECT @Xml
</code></pre>
<p>The idea is to delete from the XML all the nodes that you don't need, so you remain with the original structure and the needed nodes. I tested with your two examples and it produced the wanted result.</p>
<p>However <em>modify</em> has some restrictions - it seems you can't use it in a select statement, it has to modify data in place. If you need to return such data with a select you could use a temporary table in which to copy the original data and then update that table. Something like this:</p>
<pre><code>INSERT INTO #temp VALUES(@Xml)
UPDATE #temp SET data.modify('delete(//*[@category!=2])')
</code></pre>
<p>Hope that helps.</p>
|
<p>The question is not really clear, but is this what you're looking for?</p>
<pre><code>DECLARE @Xml AS XML
SET @Xml =
N'
<Books>
<Book ID="1">Book1</Book>
<Book ID="2">Book2</Book>
<Book ID="3">Book3</Book>
<Book>Book4</Book>
<Book ID="5">Book5</Book>
<Book ID="6">Book6</Book>
<Book>Book7</Book>
<Book ID="8">Book8</Book>
</Books>
'
DECLARE @BookID AS INT
SET @BookID = 5
DECLARE @Result AS XML
SET @result = (SELECT @xml.query('//Book[not(@ID) or @ID = sql:variable("@BookID")]'))
SELECT @result
</code></pre>
| 11,542
|
<p>I've been building a database input form. There are three fields for notes. They were all build at the same time. They have the same logic & class system - but one of them is returning with escape marks when I update the record, e.g. I enter</p>
<pre><code>1
2
3
</code></pre>
<p>and the updated record returns </p>
<pre><code>1\r\n2\r\n3
</code></pre>
<p>I'm confused as the other return the text as formatted. Can you sugggest why this is happening?</p>
|
<p>As Konrad suggested your question lacks clarity. Are they both on the same page? If not, do both pages have the same <code>DOCTYPE</code>?</p>
<p>The simplest solution to this is to handle it regardless, <code>addslashes</code> (or <code>mysql_real_escape_string</code>) for <code>INSERT</code>s and <code>UPDATE</code>s and <code>stripslashes</code> for <code>SELECT</code>s.</p>
<p>The other scenario you have to handle is a <code>POST</code> to a page that has errors (e.g repopulated with post values). You must make sure that the <code>POST</code> value is the 'stripped' version of the slashes else you will double up on the addslashes; so only addslashes when all your post validation and verification has been completed.</p>
|
<p>As it is, your question lacks a lot of crucial information. Obviously, if everything is done identically, the data will be the same as well. Additionally, you probably don't mean that there are escape marks in your data (or do you?). In that case, you must have explicitly called a function to convert line breaks into a string containing the characters <code>'\'</code> and <code>'n'</code>.</p>
<p>Lacking any code, I assume that you display your data differently; once using a normal <code>echo</code> and once using something like <code>var_dump</code>.</p>
| 49,611
|
<p>How would I be able to get N results for several groups in
an oracle query.</p>
<p>For example, given the following table:</p>
<pre><code>|--------+------------+------------|
| emp_id | name | occupation |
|--------+------------+------------|
| 1 | John Smith | Accountant |
| 2 | Jane Doe | Engineer |
| 3 | Jack Black | Funnyman |
|--------+------------+------------|
</code></pre>
<p>There are many more rows with more occupations. I would like to get
three employees (lets say) from each occupation.</p>
<p>Is there a way to do this without using a subquery?</p>
|
<p>I don't have an oracle instance handy right now so I have not tested this:</p>
<pre><code>select *
from (select emp_id, name, occupation,
rank() over ( partition by occupation order by emp_id) rank
from employee)
where rank <= 3
</code></pre>
<p>Here is a link on how rank works: <a href="http://www.psoug.org/reference/rank.html" rel="noreferrer">http://www.psoug.org/reference/rank.html</a></p>
|
<p>I'm not sure this is very efficient, but maybe a starting place?</p>
<pre><code>select *
from people p1
join people p2
on p1.occupation = p2.occupation
join people p3
on p1.occupation = p3.occupation
and p2.occupation = p3.occupation
where p1.emp_id != p2.emp_id
and p1.emp_id != p3.emp_id
</code></pre>
<p>This should give you rows that contain 3 distinct employees all in the same occupation. Unfortunately, it will give you ALL combinations of those.</p>
<p>Can anyone pare this down please?</p>
| 16,347
|
<p>What does the following code do in C/C++?</p>
<pre><code>if (blah(), 5) {
//do something
}
</code></pre>
|
<p>Comma operator is applied and the value 5 is used to determine the conditional's true/false.</p>
<p>It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.</p>
<hr>
<p>Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.</p>
|
<p>The following was written assuming it is C code, either in a C file or within a C block of a C++ file:</p>
<p>It is a pointless <em>if</em>. It will call blah(), however the result of blah() is not considered by <em>if</em> at all. The only thing being considered is 5, thus the if will always evaluate to true. IOW you could write this code as</p>
<pre><code>blah();
// do something
</code></pre>
<p>without any <em>if</em> at all.</p>
| 18,016
|
<p>Does any one have a preference on how to check if a value is <code>DBNull</code>? I've found these two statements give me the results I want, but just wondering if there's a preference?</p>
<p><code>if (any is System.DBNull)</code></p>
<p>same as:</p>
<p><code>if (any == System.DBNull.Value)</code></p>
<p>Thanks!</p>
|
<p>I tend to use</p>
<pre><code>if (DBNull.Value.Equals(value)) {
//
}
</code></pre>
<p>or</p>
<pre><code>if (Convert.IsDBNull(value)) {
//
}
</code></pre>
|
<p>I like the "is System.DBNull" more because I hate the idea of comparing something to NULL and having it be true. Many other syntaxes (what the hell is the plural of that?) would have anything==NULL return NULL.</p>
<p>I understand that there's DBNull.Value for a reason. I know. I'm listing my PREFERENCE :)</p>
| 13,117
|
<p>I have added some code which compiles cleanly and have just received this Windows error:</p>
<pre><code>---------------------------
(MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error
---------------------------
The exception Privileged instruction.
(0xc0000096) occurred in the application at location 0x00486752.
</code></pre>
<p>I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to <code>ODCS.lib</code>, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows 2000).</p>
|
<p>To answer the question, a privileged instruction is a processor op-code (assembler instruction) which can only be executed in "supervisor" (or Ring-0) mode.
These types of instructions tend to be used to access I/O devices and protected data structures from the windows kernel.</p>
<p>Regular programs execute in "user mode" (Ring-3) which disallows direct access to I/O devices, etc...</p>
<p>As others mentioned, the cause is probably a corrupted stack or a messed up function pointer call.</p>
|
<p>I saw this with Visual c++ 6.0 in the year 2000.</p>
<p>The debug C++ library had calls to physical I/O instructions in it, in an exception handler.
If I remember correctly, it was dumping status to an I/O port that used to be for DMA base registers, which I assume someone at Microsoft was using for a debugger card.</p>
<p>Look for some error condition that might be latent causing diagnostics code to run.</p>
<p>I was debugging, backtracked and read the dissassembly. It was an exception while processing <code>std::string</code>, maybe indexing off the end.</p>
| 11,511
|
<p>Hey all. Newbie question time. I'm trying to setup JMXQuery to connect to my MBean, so far this is what I got.</p>
<p>java -classpath jmxquery org.nagios.JMXQuery -U service:jmx:rmi:///jndi/rmi://localhost:8004/jmxrmi -O java.lang:type=Memory -A "NonHeapMemoryUsage"</p>
<p>Here's what I get.</p>
<p>JMX CRITICAL Authentication failed! Credentials required</p>
<p>I got the credentials, but how do I pass them to JMXQuery?</p>
<p>/Ace</p>
|
<p>According to the source, you should be able to use -username and -password arguments.</p>
<p><a href="http://code.google.com/p/jmxquery/source/browse/trunk/src/main/java/jmxquery/JMXQuery.java?r=3" rel="nofollow noreferrer">http://code.google.com/p/jmxquery/source/browse/trunk/src/main/java/jmxquery/JMXQuery.java?r=3</a></p>
|
<p>It seems that this is an addon to the original JMX-query, look at the comment field.</p>
<blockquote>
<p>/** * * JMXQuery is used for local
or remote request of JMX attributes *
It requires JRE 1.5 to be used for
compilation and execution. * Look
method main for description how it can
be invoked. * * This plugin was
found on nagiosexchange. It lacked a
username/password/role system. * *
@author unknown * @author Ryan
Gravener (ryangravener@gmail.com) *<br>
*/</p>
</blockquote>
<p>Does that mean that there's no way to remotely access JMX with original JMXQuery? If so, what <em>can</em> you do with it?</p>
| 14,742
|
<p>I have two fields in a table. One contains values such as BTA, BEA, REA. The other contains values such as 1,2,63,103.</p>
<p>I want to combine the 2 fields so they look like this BTA001, BTA002, BTA063, BTA103.</p>
<p>Notice how if the numbers are not 3 characters in length, I want to pad some 0's to the left of the number to make it equal to 3.</p>
<p>How would I go about doing this? The fields in the table are called Type which correspond to BTA, BEA, and REA and Id is the field that corresponds to 1, 2, 63, and 103.</p>
|
<pre><code>select Type + right('00' + cast(id as varchar(10)), 3)
from ...
</code></pre>
<p>Edit: if id can be null and you would like a zero to show, you can do:</p>
<pre><code>select Type + right('00' + cast(isnull(id, 0) as varchar(10)), 3)
from ...
</code></pre>
|
<p>select
C1 + right(('000' + cast(C2 as nvarchar(10)),3) as </p>
<p>from t1</p>
| 49,132
|
<p>I would like to call python script files from my c++ program.</p>
<p>I am not sure that the people I will distribute to will have python installed.</p>
|
<p>Boost has a python interface library which could help you.</p>
<p><a href="http://www.boost.org/doc/libs/release/libs/python/doc/index.html" rel="noreferrer">Boost.Python</a></p>
|
<p>Using Inter Process Communication (IPC) over socket can be a possible solution. Use a local network socket to listen/trasfer commands between both.</p>
| 7,155
|
<p>I need to build a function which parses the domain from a URL.</p>
<p>So, with</p>
<pre><code>http://google.com/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>or</p>
<pre><code>http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>it should return <code>google.com</code></p>
<p>with</p>
<pre><code>http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html
</code></pre>
<p>it should return <code>google.co.uk</code>.</p>
|
<p>Check out <a href="http://php.net/parse_url" rel="noreferrer"><code>parse_url()</code></a>:</p>
<pre><code>$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'google.com'
</code></pre>
<p><code>parse_url</code> doesn't handle really badly mangled urls very well, but is fine if you generally expect decent urls. </p>
|
<p>Just use as like following ...</p>
<pre><code><?php
echo $_SERVER['SERVER_NAME'];
?>
</code></pre>
| 34,869
|
<p>When we create stored procedures in Visual Studio (with the extension .sql) the file encoding is automatically set to 'Unicode (UTF-8 with signature) - Codepage 65001'.</p>
<p>This causes ours DBA's problems as their scripts don't like it.</p>
<p>We have to manually go in and change them to 'Western European (windows) - Codepage 1252'.</p>
<p>This only seems to be happening since we upgraded to VS 2008 from 2005. Can anyone explain whats going on and how to stop it?</p>
|
<p>I think somebody faced a similar problem like yours and had the following workaround which is posted at</p>
<p><a href="http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=319830" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=319830</a></p>
|
<p>To summarise the link provided by Codeslayer (in case the page url changes)...</p>
<p><em>Change the sql file templates to ANSI encoding by opening with notepad and then saving it as an ANSI file. You can do the same for files already created.
\Common7\Tools\Templates\Database Project Items</em></p>
<p>You've just made our DBA's very happy!</p>
| 6,731
|
<p>I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?</p>
|
<p>In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.</p>
<pre><code><?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
</code></pre>
|
<p>Don't handle authentication in your model. Only use models to interface with your database, or ldap or whatever.</p>
<p>I created an Auth library that I use to manage authentication and authorization. You can access a library like this from your controllers.</p>
| 6,842
|
<p>I have a bunch of old classic ASP pages, many of which show database data in tables. None of the pages have any sorting functionality built in: you are at the mercy of whatever ORDER BY clause the original developer saw fit to use.</p>
<p>I'm working on a quick fix to tack on sorting via client-side javascript. I have a script already written that mostly does what I need. However, I still need to add one bit of functionality. The table rows in these pages will often have alternating row colors, and the mechanism used to achieve this varies among the pages. It might be as simple as changing a CSS class or the styles may have been rendered inline by the ASP code.</p>
<p>Right now after sorting the table each row keeps the coloring scheme is was rendered with and so the alternating rows no longer alternate. I was hoping to fix it with something simple like this:</p>
<pre><code>/* "table" is a var for the table element I'm sorting.
I've already verified it exists, and that there are at least three rows.
At this point the first row (index 0) is always the header row.
*/
// check for alternating row styles:
var RowStyle = table.rows[1].style;
var AltStyle = table.rows[2].style;
// SORT HAPPENS HERE!!
// snip
// Apply alternating row styles
if (RowStyle === AltStyle) return true;
for (var i=1,il=table.rows.length;i<il;i+=1)
{
if (i%2==0) table.rows[i].style=RowStyle;
else table.rows[i].style=AltStyle;
}
</code></pre>
<p>Unfortunately, you can't just set to an element's style property like this. It complains that the object has no setter. How else can I do this simply? No frameworks like jQuery allowed here- that's out of my hands.</p>
<p><strong>Update:</strong><br>
While it would be the best solution, it's just not practical to refactor 100+ pages to all use classes rather than inline style. Also, sometimes there's more involved than just the background color. For example, a row may be much darker or lighter than the alternating row, with one style having a different foreground color as well to accommodate. Or an alternating style may set borders differently. I really don't know what is used on all of these pages, so I need something that will generically apply <em>all</em> styles from one row to another.</p>
|
<p>You can try grabbing the <code>cssText</code> and <code>className</code>.</p>
<pre><code>var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;
// sort
// loop
if (i%2==0) {
table.rows[i].style.cssText = css1;
table.rows[i].className = class1;
} else {
table.rows[i].style.cssText = css2;
table.rows[i].className = class2;
}
</code></pre>
<p>Not entirely sure about browser compatibility with <code>cssText</code>, though.</p>
|
<p>Don't set the style object itself, set the background color property of the style object that is a property of the element.</p>
<p>And yes, even though you said no, jquery and <a href="http://www.tablesorter.com" rel="nofollow noreferrer">tablesorter</a> with its zebra stripe plugin can do this all for you in 3 lines of code.</p>
<p>And just setting the class attribute would be better since then you have non-hard-coded control over the styling which is more organized</p>
| 44,765
|
<p>I used to work with Subversion and a system tray tool (<a href="http://svnnotifier.tigris.org/" rel="nofollow noreferrer">SVN Notifier</a>) to monitor the repository so I would immediately see when my local copy was not up-to-date anymore, and I am wondering if some equivalent was available for Perforce (on Windows).</p>
|
<p>stimms answer will certainly do exactly as you ask.</p>
<p>But if you want to go a little further an alternative would be to use the P4 Review mechanism, where you can get Perforce to send you an email if changes are made to a user specified part of the depot. It will need setting up on the server, but is trivial to do. See the Perforce documentation and website and look for "review daemon".</p>
|
<p>I haven't seen such a thing but it would be pretty trivial to write. Just check to see if the output of p4 sync -n contains any informaiton. </p>
| 20,163
|
<p>How can I open a cmd window in a specific location without having to navigate all the way to the directory I want?</p>
|
<p>This might be what you want: </p>
<pre><code>cmd /K "cd C:\Windows\"
</code></pre>
<p>Note that in order to change drive letters, you need to use <code>cd /d</code>. For example:</p>
<pre><code>C:\Windows\System32\cmd.exe /K "cd /d H:\Python\"
</code></pre>
<p><a href="http://ss64.com/nt/cd.html" rel="noreferrer">(documentation)</a></p>
|
<p>For a better experience using a terminal in windows system, <a href="http://cmder.net/" rel="nofollow noreferrer">cmder</a> may help for a shortcut usage:</p>
<ol>
<li>Download <a href="http://cmder.net/" rel="nofollow noreferrer">cmder</a> into your system</li>
<li>Make shortcut</li>
<li>type <code>path_of_the_cmder</code> <code>/START</code> <code>target_path_wish_to_run</code></li>
</ol>
<p>For an instance:</p>
<p><strong><code>TARGET</code></strong> -> <code>C:\Users\<username>i\AppData\Roaming\cmder\Cmder.exe /START C:\SOURCE\</code></p>
| 8,597
|
<p>I'm trying to run dot net console application via Java:</p>
<pre><code>process = Runtime.getRuntime().exec(commandLine);
</code></pre>
<p>I get the following output:</p>
<pre><code>Detecting
The handle is invalid.
</code></pre>
<p>when running it directly via the console (windows) there is no problem:</p>
<pre><code>Detecting
100%
Done.
100%
</code></pre>
<p>I'm running more applications in this form but have no problem .</p>
<p>Got this stack trace:</p>
<pre><code>Detecting at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Console.GetBufferInfo(Boolean throwOnNoConsole, Boolean& succeeded)
at System.Console.get_CursorTop()
at AutomaticImageOrientation.HelperClasses.General.WriteProgressToConsole(Int32 lastIndex, Int32 totalImages)
at AutomaticImageOrientation.MainManager.DetectImage(String[] files, String outputPath, String& globalErrorMessage, Dictionary`2& foundRotations)
</code></pre>
<p>The problem is when the .net app trying to write to the console What is the solution?</p>
<p>found the line that cause the problem:</p>
<pre><code>Console.CursorLeft = 0;
</code></pre>
<p>Do you know why?</p>
|
<p>The console application is trying to set the cursor position for a console. This isn't possible, since there is in fact no console. All operations which don't result in a simple read or write are likely to cause errors when there is no console (since most of them require a console output buffer to work).</p>
<p>It is a bad idea to do stuff like setting the cursor position or clearing the screen in console applications you wish to automate. A basic workaround is to just put the offending statement in a try-catch, and discard the exception. From the <a href="http://msdn.microsoft.com/en-us/library/system.console.aspx" rel="noreferrer">MSDN page on System.Console</a>:</p>
<blockquote>
<p>You should not use the Console class
to display output in unattended
applications, such as server
applications. Similarly, calls to
methods such as Write and WriteLine
have no effect in Windows
applications.</p>
<p>Console class members that work
normally when the underlying stream is
directed to a console might throw an
exception if the stream is redirected,
for example, to a file. Consequently,
program your application to catch
System.IO.IOException if you redirect
a standard stream.</p>
</blockquote>
|
<p>Hard to diagnose without more detail - perhaps permissions... a little bit of exception handling (perhaps writing stack-trace to stderr) would help enormously. but not much help if you don't own the app.</p>
<p>If you don't get anywhere, you could try using <a href="http://www.red-gate.com/products/reflector/" rel="nofollow noreferrer">reflector</a> to see what the .NET app is doing during "Detecting" - it might help identify the cause.</p>
| 42,425
|
<p>When creating a new list do you specify an initial size or leave it blank? I know by specifying an initial size you avoid having the list reallocate the underlying array every-time you add x number of items but you also add verbosity to your code. Is the minimal performance gain worth adding verbosity and complexity to your code. What happens when that list needs one more item and you forget to add one to the initialization you still suffer from the performance overhead of reallocation and now the number may not make sense to new developers.</p>
|
<p>If you know something about how it's going to be used you should always specify an initial size since C# starts lists with a size of four (!) and doubles in size as the list grows. It just isn't a micro-optimization, since it takes so little effort to give .Net the hint. And readability just isn't an issue, especially if you can avoid <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" rel="nofollow noreferrer">magic numbers</a>.</p>
|
<p>If you really can't accurately (and easily) predict the size of the list, don't bother.</p>
<p>Don't build any code around determining it in advance (less code == better code).</p>
<p>Also, doubling is a pretty effective way to grow the list with respect to performance.</p>
<p>4 8 16 32 64 128 256 512 1024...you get the idea.</p>
| 43,404
|
<p>Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#.</p>
<p>What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings.</p>
<p>Also if anyone could list the types of encryption-providers and what is the difference between them.</p>
<p>I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET.</p>
|
<p>To summarize the answers and what I've found so far, here are some good links to answer this question:</p>
<ul>
<li><a href="https://web.archive.org/web/20211029043331/https://aspnet.4guysfromrolla.com/articles/021506-1.aspx" rel="nofollow noreferrer">Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms998280.aspx" rel="nofollow noreferrer">How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN</a></li>
</ul>
<p>Please feel free to complement with other links, maybe some to WinForms- or WPF-applications.</p>
|
<p>I haven't used it myself, but the Microsoft Enterprise library has good encryption support that will possibly suit your needs:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/cc309503.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc309503.aspx</a></p>
| 4,198
|
<p>How do you split a string?</p>
<p>Lets say i have a string "dog, cat, mouse,bird"</p>
<p>My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.</p>
<p>but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?</p>
<p>im using asp c#</p>
|
<pre><code> string[] tokens = text.Split(',');
for (int i = 0; i < tokens.Length; i++)
{
yourListBox.Add(new ListItem(token[i], token[i]));
}
</code></pre>
|
<p>It gives you a string array by strVar.Split</p>
<pre><code>"dog, cat, mouse,bird".Split(new[] { ',' });
</code></pre>
| 30,057
|
<p>What I'm looking for looks like this in jQuery:</p>
<pre><code>jQuery.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader("Accept", "text/javascript");
}
});
...
$("#my_form").submit({
$.post($(this).attr("action", $(this).serialize(), null, "script");
return false;
});
</code></pre>
<p>Then, when my server returns some Javascript (the Accept-header bit), jQuery executes it (that last "script" parameter).</p>
<p>I'm trying to get the same effect in Dojo. My best guess is:</p>
<pre><code>form = dojo.byId("my_form")
form.onsubmit = function() {
dojo.xhrGet({
url: form.action,
form: form,
handleAs: "javascript"
})
}
</code></pre>
<p>The <code>handleAs: "javascript"</code> should cause Dojo to execute the response as JS. My problem is that I can't figure out how to set the header so that my web server (a <code>respond_to do |format|</code> block in Rails) knows what to return.</p>
|
<p>I believe the answer is:</p>
<pre><code>form = dojo.byId("my_form")
form.onsubmit = function() {
dojo.xhrGet({
url: form.action,
form: form,
handleAs: "javascript",
headers: { "Accept": "text/javascript" }
})
}
</code></pre>
|
<p>Not sure about dojo myself but I do know that phiggins (lead dojo dev) is available on the #dojo channel over on freenode irc, that is if nobody else can give you an answer.</p>
| 38,488
|
<p>I just set up SSHd through Cygwin on a Windows XP Pro box overseas using a RAT and discluded the openssh package from the install.
I ran the cywin shell (from c:\cywin) and ran
Now, It's under a port I know is safe and fowarded properly, but I won't share it's number. It's not a common port, but it's under 40000.
Firewalls are off etc etc.
I'm on the first Admin account made on the box. (It's full admin)
I've run the following commands</p>
<p><code>chmod +r /etc/passwd<br>
chmod +r /etc/group<br>
hmod 777 /var<br>
/*Created New Admin User Account To Be Used via SSH*/<br>
mkpasswd -cl > /etc/passwd<br>
mkgroup --local > /etc/group</code> </p>
<p>I can connect locally, but not externally.
I know my ports etc are fine.</p>
<p>Any possible problems, as i really need this tunnel up :P</p>
|
<p>Profile before attempting any optimisation. </p>
<p>9 times out of 10, the time won't be consumed where you might guess it is.</p>
<p>The usual unsuccessful strategy is micro-optimisation, when what is actually required is the appropriate algorithm.</p>
<p>Obligatory Donald Knuth quote:</p>
<blockquote>
<p><em>"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"</em></p>
</blockquote>
|
<p>Be sure to have enough unit test to make sure any optimization you will make will not break anything</p>
<p>Make sure to qualify your <em>execution environment</em>. Sometime, a simple change in the execution options can go a long way.</p>
<p>Then and only then, start analyzing the code.</p>
<p>The rewrite decision (for an already <em>working</em> code) should only be considered if there is enough future evolutions which may not be supported by the current architecture.<br>
If simple fixes can speed up a code which is not supposed to evolve much, no complete rewrite should be necessary.</p>
<p>The criteria to stop is usually determined in collaboration with the end user (the client), but I would suggest a <em>formal document</em> fixing the goals to achieve with this optimization process.</p>
| 42,119
|
<p>We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.</p>
<p>The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can still use boost::shared_ptr etc.</p>
<p>But there are also some boost containers designed explicitly to hold pointers safely:<br>
See <a href="http://www.boost.org/doc/libs/1_36_0/libs/ptr_container/doc/reference.html" rel="nofollow noreferrer">Pointer Container Library</a><br></p>
<p>The question is:
Under what conditions should I prefer to use the ptr_containers over a container of smart_pointers?</p>
<pre><code>boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
</code></pre>
|
<p>Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr_vector<X>. YMMV.</p>
|
<p>Well, overhead is one case.</p>
<p>A vector of shared pointers will do a lot of extraneous copying that involves creating a new smart pointer, incrementing a reference, decrementing a reference, etc on a resize. All of this is avoided with a pointer container. </p>
<p>Requires profiling to ensure the container operations are the bottleneck though :)</p>
| 14,141
|
<p>A friend of mine brought up this questiont he other day, he's recently bought a garmin heart rate moniter device which keeps track of his heart rate and allows him to upload his heart rate stats for a day to his computer.</p>
<p>The only problem is there are no linux drivers for the garmin USB device, he's managed to interpret some of the data, such as the model number and his user details and has identified that there are some binary datatables essentially which we assume represent a series of recordings of his heart rate and the time the recording was taken.</p>
<p>Where does one start when reverse engineering data when you know nothing about the structure? </p>
|
<p>I had the same problem and initially found this project at Google Code that aims to complete a cross-platform version of tools for the Garmin devices ... see: <a href="http://code.google.com/p/garmintools/" rel="nofollow noreferrer">http://code.google.com/p/garmintools/</a>. There's a link on the front page of that project to the protocols you need, which Garmin was thoughtful enough to release publically.</p>
<p>And here's a direct link to the Garmin I/O specification: <a href="http://www.garmin.com/support/pdf/IOSDK.zip" rel="nofollow noreferrer">http://www.garmin.com/support/pdf/IOSDK.zip</a></p>
|
<p>Can you synthesize a heart beat using something like a computer speaker? (I have no idea how such devices actually work). Watch how the binary results change based on different inputs.</p>
<p>Ripping apart the device and checking out what's inside would probably help too.</p>
| 14,120
|
<p>Is there an event that fires when a WCF service gets started or shut down? Hopefully, independent of whether it is self hosted or hosted in IIS?</p>
|
<p>Sure, the constructor of your object (especially if you are using a Singleton style). Please pardon the shameless self promotion, but I've written two articles on how to get started with a WCF (Net.Tcp) client/server system... The first is non-IIS (to which the service starts on your own terms), the latter is how to modify the first to be hosted in IIS to which my first sentense would apply:</p>
<p>1) <a href="http://www.singingeels.com/Articles/Client_Server_Programming_with_WCF.aspx" rel="nofollow noreferrer">Client Server Programming with WCF</a></p>
<p>2) <a href="http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx" rel="nofollow noreferrer">Duplex WCF Services Hosted in IIS Using Net.Tcp</a></p>
|
<p>ServiceHost exposes quite a few events:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost_events.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehost_events.aspx</a></p>
<p>You could hook into these events by using a custom service behavior:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.servicemodel.description.iservicebehavior.aspx</a></p>
| 32,420
|
<p>I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7.</p>
<p>The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is</p>
<pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
EIPortal_DEV_2_0_5_4[1].expd"
</code></pre>
<p>This unfortunately does not resolve to the physical file when calling <code>FileExists()</code> or when attempting to create a <code>TFileStream</code> object.</p>
<p>The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of <code>"Content.IE5\ALBKHO3Q"</code> whose absolute path would be expressed as</p>
<pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\
Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd"
</code></pre>
<p>Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing.</p>
<p>Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of <code>"application/x-expeditors"</code>. The registration of the <code>".expd"</code> / <code>"application/x-expeditors"</code> mime-type looks like this.</p>
<pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd]
@="ExpeditorsInstaller"
"Content Type"="application/x-expeditors"
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller]
"EditFlags"=hex:00,00,01,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell]
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open]
@=""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command]
@="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\""
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors]
"Extension"=".expd"
</code></pre>
<p>I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix <code>"[n]"</code> may be the unique key.</p>
<p>I have tried wininet method <code>GetUrlCacheEntryInfo</code> but that requires the URL, not the virtual path handed over by IE.</p>
<p>My hope is that there is a Shell function that given a virtual path will hand back the physical path.</p>
|
<p><code>enum</code> defines a syntactical element.</p>
<p><code>#define</code> is a pre-preprocessor directive, executed <em>before</em> the compiler sees the code, and therefore is not a language element of C itself.</p>
<p>Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a <code>#define</code> made by another. This can be hard to track down.</p>
|
<p>There is little difference. The C Standard says that enumerations have integral type and that enumeration constants are of type int, so both may be freely intermixed with other integral types, without errors. (If, on the other hand, such intermixing were disallowed without explicit casts, judicious use of enumerations could catch certain programming errors.)</p>
<p>Some advantages of enumerations are that the numeric values are automatically assigned, that a debugger may be able to display the symbolic values when enumeration variables are examined, and that they obey block scope. (A compiler may also generate nonfatal warnings when enumerations are indiscriminately mixed, since doing so can still be considered bad style even though it is not strictly illegal.) A disadvantage is that the programmer has little control over those nonfatal warnings; some programmers also resent not having control over the sizes of enumeration variables. </p>
| 16,569
|
<p>What is the <em>best</em> way to print the cells of a <code>String[][]</code> array as a right-justified table? For example, the input</p>
<pre><code>{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }
</code></pre>
<p>should yield the output</p>
<pre><code> x xxx
yyy y
zz zz
</code></pre>
<p>This seems like something that one <em>should</em> be able to accomplish using <code>java.util.Formatter</code>, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.</p>
|
<p>Indeed, if you specify a width for the fields, it should be right-justified.<br>
If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.</p>
|
<p>find the length of the longest string..<br>
left pad all the strings with spaces until they r that length + 1<br>
System.out.print them using 2 nested for loops</p>
| 34,699
|
<p>We have some old C code here that's built with nmake.</p>
<p>Is there an automated way to pull the Makefile into Visual Studio 2005 and create a project? Some searching on MSDN indicates <a href="http://msdn.microsoft.com/en-us/library/aa269915(VS.60).aspx" rel="noreferrer">VS6</a> could do this, but it looks like VS7/8 dropped the feature.</p>
<p>If necessary I can build the project from scratch using the project.mak file as a reference, but for more complex projects this may not be viable.</p>
|
<p>Here is a link to the <a href="http://msdn.microsoft.com/en-us/library/txcwa2xx(VS.80).aspx" rel="nofollow noreferrer">VS 2005 docs on the subject</a>. It also has links to VS 2003 & 2008, which are probably the same.</p>
<p><b>Edit:</b> I would only want to do this with old code that would not change much, especially in the way of compile and link parameters, as hand editing the make file is the only way to change how the code compiles.</p>
|
<p>This ought to be possible using Visual Studio's COM-interface, but I can't help you with any details.</p>
| 18,653
|
<p>I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token).</p>
<p>Here's what I've come up with:</p>
<pre><code>ActionController::Base.session.first[:secret]
</code></pre>
<p>This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this:</p>
<pre><code>[{:session_key=>"_new_app_session", :secret=>"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
</code></pre>
<p>This strikes me as being no good.</p>
<p>Is there a better way to access the session secret?</p>
|
<p>For Rails4</p>
<pre><code>Rails.configuration.secret_token
Rails.configuration.secret_key_base
</code></pre>
<p>For Rails3</p>
<pre><code>Rails.configuration.secret_token
</code></pre>
<p>But if for Rails2.x, like Don Parish mentioned</p>
<pre><code>ActionController::Base.session_options[:secret]
</code></pre>
|
<p>For Rails 3, Rails.configuration is same to Rails.application.config, so Rails.configuration.secret_token acts just as what choonkeat provided.</p>
| 23,355
|
<p>I have a linker command file that assigns the top address of the stack into a variable </p>
<pre><code>_stack = . + 0x80000;
</code></pre>
<p>I want to use this address in a 'c' program - I want to copy the stack to another location and then update the stack pointer to point to the new location before doing a destructive memory test on the orginal bank of RAM.</p>
<p>I'm finding that if I do something like</p>
<pre><code>extern u32 *_stack;
myFunction(_stack);
</code></pre>
<p>Then the function seems to get passed the value stored at the stack location </p>
<pre><code>lwz r3,0(r8)
</code></pre>
<p>Rather than the address of the stack itself.
Can anyone help?</p>
|
<p>Try</p>
<pre><code>extern u32 _stack;
U32 * stackPtr;
stackPtr = &_stack;
</code></pre>
|
<p><em>myFunction(&_stack);</em> should pass myFunction the address of the variable * _stack*.
Else, it will pass the value contained in the variable <em>_stack</em>. </p>
| 22,740
|
<p>I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:</p>
<ul>
<li>1 item: $100</li>
<li>2 items: +90 = $190</li>
<li>3 items: + 80 = $270</li>
<li>4 items: + 70 = $340</li>
<li>5 items: + 60 = $400</li>
<li>6 items: + 50 = $450</li>
<li>7 items: + 50 = $500</li>
</ul>
<p>And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :( </p>
|
<p>Check out Yahoo! UI. they have a slider widget: <a href="http://developer.yahoo.com/yui/slider/" rel="noreferrer">http://developer.yahoo.com/yui/slider/</a></p>
<p>The following example should get you started: <a href="http://developer.yahoo.com/yui/examples/slider/slider-ticks.html" rel="noreferrer">http://developer.yahoo.com/yui/examples/slider/slider-ticks.html</a>.</p>
<p>All JavaScript frameworks (<a href="http://docs.jquery.com/UI/Slider" rel="noreferrer">jQuery</a>, <a href="http://demos.mootools.net/Slider" rel="noreferrer">MooTools</a>) seem to offer a slider. The YUI will give you a lot of control and a loader so you don't have to host the script on your server. Beware that YUI does not make implementation as painless as with the two other i mentioned.</p>
<p>Here is a MooTools example:</p>
<pre><code>// First example of http://demos.mootools.net/Slider
<div class="slider" id="myslider">
<div class="knob" style="position: relative;"/>
</div>
</code></pre>
<p>And the JavaScript:</p>
<pre><code>var el = $('myslider'); // The slider graphic
new Slider(el, el.getElement('.knob'), {
steps: 7, // There are 7 choices
range: [1, 7], // Minimum value is 1, maximum is 7
onChange: function(value){
// Calculation of the value goes here
}
});
</code></pre>
|
<p>While there are presumably endless ways of getting a slider done with JS, I think the easiest way to calculate the prices are just hard-coding (or listing) them somewhere, and just <code>else-if</code>:ing through them.</p>
<p>You <em>could</em> do an algorithm that counts <code>100-(i*10)</code> for the five first items, <code>50</code> for the rest, but that's probably harder to change in the future than the hard-listed way.</p>
| 23,818
|
<p>I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?</p>
|
<p>Try -V which "Print the version and build parameters of httpd, and then exit."</p>
<pre><code>httpd -V
</code></pre>
<p>Also, you can see the options for httpd via:</p>
<pre><code>httpd -h
</code></pre>
|
<p>I re-compiled apache 2.4.3 recently and change the MPM from worker to prefork, what you have to do if you still keep your original compiled directory without ran "make distclean" (if you ran "make clean" it still OK). You can use the SAME configure option to re-configure by exec ./config.status or you can find and copy './configure' from ./config.status (yes, all the original options that you used to run configure still there).</p>
<p>Here is part of my config.status...</p>
<pre><code>if $ac_cs_silent; then
exec 6>/dev/null
ac_configure_extra_args="$ac_configure_extra_args --silent"
fi
if $ac_cs_recheck; then
set X /bin/sh **'./configure' '--enable-file-cache' '--enable-cache' '--enable-disk-cache' '--enable-mem-cache' '--enable-deflate' '--enable-expires' '--enable-headers' '--enable-usertrack' '--enable-cgi' '--enable-vhost-alias' '--enable-rewrite' '--enable-so' '--with-apr=/usr/local/apache/' '--with-apr-util=/usr/local/apache/' '--prefix=/usr/local/apache' '--with-mpm=worker' '--with-mysql=/var/lib/mysql' '--with-mysql-sock=/var/run/mysqld/mysqld.sock' '--enable-mods-shared=most' '--enable-ssl' 'CFLAGS=-Wall -O3 -ffast-math -frename-registers -mtune=corei7-avx' '--enable-modules=all' '--enable-proxy' '--enable-proxy-fcgi'** $ac_configure_extra_args --no-create --no-recursion
shift
$as_echo "running CONFIG_SHELL=/bin/sh $*" >&6
CONFIG_SHELL='/bin/sh'
export CONFIG_SHELL
exec "$@"
fi
</code></pre>
| 16,592
|
<p>I've got a fairly large MFC application that has just been migrated from VS6.0 to VS2008. It was a pretty painful process, but now I'd like to explore any managed-code options that may be available. I was able to successfully build the project using the /clr switch which seems to give me access to managed types. </p>
<p>I'd like to know if conversion between System::String and CString is automatic or not. The MSDN documentation that I've found suggests that this conversion isn't automatic but I haven't found this to be the case. All three of the examples below work and both 1 and 2 are documented by the MSDN. What I'm curious about is example 3 which also works but I don't know why. The CurrentDirectory property is returning a pointer into the managed heap, String^, but why am I able to assign it to a CString? Exactly what is example 3 doing and what are the memory management implications?</p>
<p>Example 1) </p>
<pre>
marshal_context ^ context = gcnew marshal_context();
String ^env = System::Environment::CurrentDirectory;
const char* env2 = context->marshal_as(env);
AfxMessageBox(env2);
delete context;
</pre>
<p>Example 2) </p>
<pre>
CString s(System::Environment::CurrentDirectory);
AfxMessageBox(s);
</pre>
<p>Example 3) </p>
<pre>
CString s = System::Environment::CurrentDirectory;
AfxMessageBox(s);
</pre>
|
<p>Option 3 works for pretty much the same reason option 2 does. CString::operator= has an overload for System::String. Don't forget that the assignment operator can do a lot more than copy a reference.</p>
<p>This page:
<a href="http://msdn.microsoft.com/en-us/library/ms235631.aspx" rel="nofollow noreferrer">How to: Convert Between Various String Types</a>
is <em>very</em> useful for mixed apps. <a href="http://msdn.microsoft.com/en-us/library/1dz8byfh(VS.80).aspx" rel="nofollow noreferrer">pin_ptr</a> is great.</p>
<p>Be wary of sprinkling managed code around. I also work on a large MFC application that went /clr and I sometimes wish that we had done it in select libraries only. It can make debugging painful when there are a lot of managed-native transitions on the callstack. There are <a href="http://msdn.microsoft.com/en-us/library/ky8kkddw.aspx" rel="nofollow noreferrer">performance considerations</a> as well.</p>
|
<p>You can go from a system::String to CString because they share a common conversion (lptstr?) going to a System::String from CString will always need System::String^ test = gcnew System::String( CStringVar );</p>
| 39,066
|
<p>Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.</p>
<p>Now, I <em>want</em> most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this?</p>
|
<p>This will work for all well-behaving search engines, just add it to the <code><head></code>:</p>
<pre><code><meta name="robots" content="noindex, nofollow" />
</code></pre>
|
<p>You can disallow search engines to read or index your content by restricting robot meta tags. In this way, spider will consider your instructions and will index only such pages that you want.</p>
| 6,560
|
<p>Do you have any advice/rules on selecting a multiplier to use in a (multiplicative) hash function. The function is computing the hash value of a string.</p>
|
<p>You want to use something that is relatively prime to the size of your set. That way, when you loop around, you won't end up on the same numbers you just tried.</p>
|
<p>Historically 33 seems like a popular choice, and it tends to work pretty well. No one knows why though. For more details, <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow noreferrer">look here</a></p>
| 3,757
|
<p>I need to check CPU and memory usage for the server in java, anyone know how it could be done?</p>
|
<p>If you are looking specifically for memory in JVM:</p>
<pre><code>Runtime runtime = Runtime.getRuntime();
NumberFormat format = NumberFormat.getInstance();
StringBuilder sb = new StringBuilder();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024) + "<br/>");
</code></pre>
<p>However, these should be taken only as an estimate...</p>
|
<p>For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. <a href="http://eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html" rel="nofollow">more information</a></p>
| 10,033
|
<p>As the title says on a website is it possible to tell if a user has viewed a portion of the page?</p>
|
<p>Will moving that portion to a separate iframe work? then if they scroll to the bottom, issue a get request for a small image file..forgot the name of the technique..</p>
<p>Update: It is called <a href="http://en.wikipedia.org/wiki/Web_bug" rel="nofollow noreferrer">Web Bug</a>..A Web bug is an object that is embedded in a web page or e-mail and is usually invisible to the user but allows checking that a user has viewed the page or e-mail. One common use is in e-mail tracking. Alternative names are Web beacon, tracking bug, tracking pixel, pixel tag, 1×1 gif, and clear gif.</p>
|
<p>Unless you require a user action of some kind, all you will be able to tell is that they downloaded some portion, not that they actually looked at it.</p>
| 12,964
|
<p>I'm considering supporting both <strong><a href="http://textism.com/tools/textile/" rel="nofollow noreferrer">Textile</a></strong> and <strong><a href="http://daringfireball.net/projects/markdown/" rel="nofollow noreferrer">Markdown</a></strong> on a current project. I would prefer not forcing users to choose one or the other. Is there a way to auto-detect which the user is using? How would you go about this? I'd like to find / develop both a JavaScript and a PHP solution so I can provide live previews as well as process the user input on the server-side.</p>
|
<p>Consider that users might only use one specific syntax element in a posting, so you'd have to check for everything. Looking for "h1." obviously only works if the user uses exactly that element. </p>
<p>It's pretty easy with things like headers, but consider that markdown formats <code>*this*</code> as <code><em>this</em></code> and Textile will convert that to <code><strong>this</strong></code> instead. So you'd have ambiguous syntax constructs that would yield different results in each language.</p>
<p>I'd suggest going with a user choice. Try to find out what syntax is generally preferred by your users (or you), offer an "use x instead of y" checkbox for those who want the other choice.</p>
|
<p>Auto-detection, I don't know, both are based on "natural" typing.<br>
Perhaps you can ask the user to choose a format, with a pair of radio-buttons or something.</p>
| 16,723
|
<p>I'm using T4 for generating repositories for LINQ to Entities entities. </p>
<p>The repository contains (amongst other things) a List method suitable for paging. The documentation for <a href="http://msdn.microsoft.com/en-us/library/bb738474.aspx" rel="nofollow noreferrer">Supported and Unsupported Methods</a> does not mention it, but you can't "call" <code>Skip</code> on a unordered <code>IQueryable</code>. It will raise the following exception:</p>
<blockquote>
<p>System.NotSupportedException: The method 'Skip' is only supported for
sorted input in LINQ to Entities. The method 'OrderBy' must be called before
the method 'Skip'..</p>
</blockquote>
<p>I solved it by allowing to define a default sorting via a partial method. But I'm having problems checking if the expression tree indeed contains an <code>OrderBy</code>.</p>
<p>I've reduced the problem to as less code as possible:</p>
<pre><code>public partial class Repository
{
partial void ProvideDefaultSorting(ref IQueryable<Category> currentQuery);
public IQueryable<Category> List(int startIndex, int count)
{
IQueryable<Category> query = List();
ProvideDefaultSorting(ref query);
if (!IsSorted(query))
{
query = query.OrderBy(c => c.CategoryID);
}
return query.Skip(startIndex).Take(count);
}
public IQueryable<Category> List(string sortExpression, int startIndex, int count)
{
return List(sortExpression).Skip(startIndex).Take(count);
}
public IQueryable<Category> List(string sortExpression)
{
return AddSortingToTheExpressionTree(List(), sortExpression);
}
public IQueryable<Category> List()
{
NorthwindEntities ent = new NorthwindEntities();
return ent.Categories;
}
private Boolean IsSorted(IQueryable<Category> query)
{
return query is IOrderedQueryable<Category>;
}
}
public partial class Repository
{
partial void ProvideDefaultSorting(ref IQueryable<Category> currentQuery)
{
currentQuery = currentQuery.Where(c => c.CategoryName.Contains(" ")); // no sorting..
}
}
</code></pre>
<p>This is not my real implementation!</p>
<p>But my <strong>question</strong> is, how could I implement the <code>IsSorted</code> method? The problem is that LINQ to Entities query's are always of the type <code>ObjectQuery</code>, which implements <code>IOrderedQueryable</code>.</p>
<p>So how should I make sure an <code>OrderBy</code> method is present in the expression tree? Is the only option to parse the tree?</p>
<p><strong>Update</strong><br>
I've added two other overloads to make clear that it's not about how to add sorting support to the repository, but how to check if the <code>ProvideDefaultSorting</code> partial method has indeed added an <code>OrderBy</code> to the expression tree.</p>
<p>The problem is, the first partial class is generate by a template and the implementation of the second part of the partial class is made by a team member at another time. You can compare it with the way the .NET Entity Framework generates the EntityContext, it allows extension points for other developers. So I want to try to make it robust and not crash when the <code>ProvideDefaultSorting</code> is not implemented correctly.</p>
<p>So maybe the question is more, how can I confirm that the <code>ProvideDefaultSorting</code> did indeed add sorting to the expression tree.</p>
<p><strong>Update 2</strong><br>
The new question was answered, and accepted, I think I should change the title to match the question more. Or should I leave the current title because it will lead people with the same problem to this solution?</p>
|
<p>Paging depends on Ordering in a strong way. Why not tightly couple the operations? Here's one way to do that:</p>
<p>Support objects</p>
<pre><code>public interface IOrderByExpression<T>
{
ApplyOrdering(ref IQueryable<T> query);
}
public class OrderByExpression<T, U> : IOrderByExpression<T>
{
public IQueryable<T> ApplyOrderBy(ref IQueryable<T> query)
{
query = query.OrderBy(exp);
}
//TODO OrderByDescending, ThenBy, ThenByDescending methods.
private Expression<Func<T, U>> exp = null;
//TODO bool descending?
public OrderByExpression (Expression<Func<T, U>> myExpression)
{
exp = myExpression;
}
}
</code></pre>
<p>The method under discussion:</p>
<pre><code>public IQueryable<Category> List(int startIndex, int count, IOrderByExpression<Category> ordering)
{
NorthwindEntities ent = new NorthwindEntities();
IQueryable<Category> query = ent.Categories;
if (ordering == null)
{
ordering = new OrderByExpression<Category, int>(c => c.CategoryID)
}
ordering.ApplyOrdering(ref query);
return query.Skip(startIndex).Take(count);
}
</code></pre>
<p>Some time later, calling the method:</p>
<pre><code>var query = List(20, 20, new OrderByExpression<Category, string>(c => c.CategoryName));
</code></pre>
|
<pre><code> ProvideDefaultSorting(ref query);
if (!IsSorted(query))
{
query = query.OrderBy(c => c.CategoryID);
}
</code></pre>
<p>Change to:</p>
<pre><code> //apply a default ordering
query = query.OrderBy(c => c.CategoryID);
//add to the ordering
ProvideDefaultSorting(ref query);
</code></pre>
<p>It's not a perfect solution.</p>
<p>It doesn't solve the "filter in the ordering function" problem you've stated. It does solve "I forgot to implement ordering" or "I choose not to order".</p>
<p>I tested this solution in LinqToSql:</p>
<pre><code> public void OrderManyTimes()
{
DataClasses1DataContext myDC = new DataClasses1DataContext();
var query = myDC.Customers.OrderBy(c => c.Field3);
query = query.OrderBy(c => c.Field2);
query = query.OrderBy(c => c.Field1);
Console.WriteLine(myDC.GetCommand(query).CommandText);
}
</code></pre>
<p>Generates (note the reverse order of orderings):</p>
<pre><code>SELECT Field1, Field2, Field3
FROM [dbo].[Customers] AS [t0]
ORDER BY [t0].[Field1], [t0].[Field2], [t0].[Field3]
</code></pre>
| 27,870
|
<p>What is the best way to overwrite a specific line in a file? I basically want to search a file for the string '@parsethis' and overwrite the rest of that line with something else.</p>
|
<p>If the file isn't too big, the best way would probably be to read the file into an array of lines with <a href="http://php.net/file" rel="noreferrer">file()</a>, search through the array of lines for your string and edit that line, then <a href="http://php.net/implode" rel="noreferrer">implode()</a> the array back together and <a href="http://php.net/fwrite" rel="noreferrer">fwrite()</a> it back to the file.</p>
|
<p>I'd most likely do what Jeremy suggested, but just for an alternate way to do it here is another solution. This has not been tested or used and is for *nix systems.</p>
<pre><code>$cmd = "grep '@parsethis' " . $filename;
$output = system($cmd, $result);
$lines = explode("\n", $result);
// Read the entire file as a string
// Do a str_repalce for each item in $lines with ""
</code></pre>
| 29,162
|
<p>What is the "functional body" of a program?</p>
<p>I thought it was its functions' prototypes, is it?</p>
|
<p>It's the code that actually gets executed, so that would be the code inside your methods.</p>
|
<p>Unfortunately, many programs have no functional parts.</p>
<p>Seriously, you are over-thinking this. It doesn't mean much. It's the human code that actually generates machine code. The machine finds all our comments rather useless and non-functional. </p>
| 30,857
|
<p>How can I make the command button in my VC++ 6.0 dialog visible or invisible on load?</p>
|
<p>From the resource editor once you select the button, you can see its properties in the properties window. Here you can set the visible property to true / false. (assuming this functionality is present in 6.0 - i use 2003 now and cannot remember if this used to be present in 6.0)</p>
<p><strong>Add CButton variable</strong> </p>
<p>If you want to dynamically change the buttons visibility during load, add a variable for your button using the MFC class wizard. (you are lucky to have this - this wizard seems to have been removed from Visual Studio .NET)</p>
<p><strong>Override CDialog InitDialog</strong></p>
<p>Next override the initdialog function of your dialog box and then once the base InitDialog function has been successfully called, set the buttons showwindow property to SW_HIDE / before showing the dialog box. </p>
<p><strong>Code</strong></p>
<pre><code>BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
if (ConditionShow)
m_MyButton.ShowWindow(SW_SHOW);
else
m_MyButton.ShowWindow(SW_HIDE);
return TRUE;
}
</code></pre>
|
<p>What do you mean by 'commnad button' exactly ? </p>
<p>Anyway, you need to obtain the handle of the button then call ShowWindow function:</p>
<pre><code>BOOL prevState = ShowWindow( itemHandle, SW_HIDE );
</code></pre>
| 32,198
|
<p>Is it possible to specify a Java <code>classpath</code> that includes a JAR file contained within another JAR file?</p>
|
<p>If you're trying to create a single jar that contains your application and its required libraries, there are two ways (that I know of) to do that. The first is <a href="http://one-jar.sourceforge.net/" rel="noreferrer">One-Jar</a>, which uses a special classloader to allow the nesting of jars. The second is <a href="http://classworlds.codehaus.org/uberjar.html" rel="noreferrer">UberJar</a>, (or <a href="http://maven.apache.org/plugins/maven-shade-plugin/" rel="noreferrer">Shade</a>), which explodes the included libraries and puts all the classes in the top-level jar.</p>
<p>I should also mention that UberJar and Shade are plugins for Maven1 and Maven2 respectively. As mentioned below, you can also use the assembly plugin (which in reality is much more powerful, but much harder to properly configure).</p>
|
<p>Extracting into an Uber-dir works for me as we s should all be using root:\java and have outlets code in packages with versioning. Ie ca.tecreations-1.0.0. Signing is okay because the jars are intact from their downloaded location. 3rd party signatures intact, extract to c:\java. There’s my project dir. run from launcher so java -cp c:\java Launcher</p>
| 22,158
|
<p>Currently I am using FOP to generate a pdf from java code and an xslt document. The FOP spits out a PDF file that is displayed (embeded) into a webpage. The documents can range between one and several thousand pages long, and it can take some time to generate them. </p>
<p>Is there a better tool that and do this? Is FOP the best option in the opensource and free world? </p>
|
<p>We use <a href="http://www.lowagie.com/iText/" rel="nofollow noreferrer">iText</a>.</p>
<p>Here is a blog entry <a href="http://blog.xebia.com/2008/03/03/comparing-apache-fop-with-itext/" rel="nofollow noreferrer">Comparing Apache FOP with iText</a>.</p>
<p>Judging by your usage (generate a pdf from java code and an xslt document) it seems like FOP is the better choice for you.</p>
<p>EDIT: This forum post about <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=64&t=001845" rel="nofollow noreferrer">FOP Vs IText</a> includes the following:</p>
<blockquote>
<p>iText is more feature rich than FOP as far as PDF is concerned: you can add annotations, create AcroForms, digitally sign a PDF document. <strong>Also iText is the only solution if you need to generate PDF documents containing thousands or ten thousands of pages.</strong></p>
</blockquote>
|
<p>Adobe ColdFusion has the <a href="http://www.adobe.com/products/coldfusion/features/pdf_features/" rel="nofollow noreferrer">best built-in PDF support</a>.</p>
| 47,554
|
<p>(mingw32, windows xp)
Hello, I am attempting to migrate from Java to c++. I am confused and frustrated about finding, installing, and compiling non-standard c++ libraries. in Java it's so convenient they stuffed every functionality and documentation ever needed in java's standard api. Is there a list of essential c++ library such as Threading, gui, networking, image\ audio processing, xml, etc.etc. in one place? or possibly, offered as a single package? </p>
<p>I tried installing QT library for weeks and it wont even compile. in Java i used to learn by trial-and-error to learn new aspect of functionality, but that would be impossible if i can't fetch and run new api in the first place.</p>
<p>please, i need your suggestion, originally i wanted to break free of Java's abstraction, but now i just want to be able to use c++ before I decided shooting myself in the head.</p>
|
<p>The C++ standard library is extremely light. It contains nowhere near the functionality offered by the Java runtimes or by the .NET CLR.</p>
<p>The <a href="http://www.boost.org/" rel="nofollow noreferrer">Boost</a> libraries add a whole bunch of functionality to C++, but not much (if any) in the area of user interface.</p>
<p>For UI, there's the question of which platform you're targetting. If it's Win32, then you can use the straight Win32 API (mostly designed for C, but there are some C++ wrappers for parts of it). If you want cross-platform, then you're looking at QT or GTK (although there are others).</p>
<p>But, as Andrew already said: "why do you want to learn C++ anyway?". Don't get me wrong: I program in C++ for a living, and actually enjoy it (although I'm beginning to suspect a case of Stockholm Syndrome). If I had to start again, I'd go with a more modern language and environment (Java or C#; or Ruby or Python).</p>
|
<p>Threading, XML, Networking, some image generation, encoding and processing - <a href="http://boost.org" rel="nofollow noreferrer">boost</a> provides those. As for XML, there's for example <a href="http://www.jezuk.co.uk/cgi-bin/view/arabica" rel="nofollow noreferrer">Arabica</a> - it abstracts away platform-specific libraries by wrapping them with a nice standard C++ scent.</p>
<p>The GUI part is a different problem.</p>
<p>There's Qt, wxWidgets, gtk with c++ bindings (gtkmm), native libraries for each platform and their C++ wrappers (WTL is an excellent library for Win32), but as the C++ standard evolved and boost is becoming part of the standard (C++0x coming soon), there are no GUI frameworks that leverage those standard facilities and introduce their own instead. They do their job very well though.</p>
| 28,313
|
<p>I've got an Apache server that has one access log file that is topping 600MB. This makes it really hard to search the file or parse it.<br>
What software or modules for Apache are available that will make a daily copy of my access file to make it more manageable?</p>
|
<p>Have you looked at <a href="https://linux.die.net/man/8/logrotate" rel="noreferrer">logrotate</a> - this is probably the simplest, most widely available and well understood method of achieving this. It is highly configurable and will probably do 90% of what you need.</p>
|
<p>I have a module that does this for you without the need for external pipes etc :</p>
<p><a href="http://www.poptart.org/bin/view/Poptart/ModAutorotate" rel="nofollow">http://www.poptart.org/bin/view/Poptart/ModAutorotate</a></p>
<p>I've tried to add it to the Apache modules collection but that seems to have been broken for a while now.</p>
| 6,568
|
<p>Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent.</p>
<p>For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server.</p>
|
<p>Why won't any old proxy software work for this? Why does it need to be an ASP.NET application? There are TONS of tools out there (both Windows and *nix) that will get the job done quite easily. Check <a href="http://www.squid-cache.org/" rel="nofollow noreferrer">Squid</a> or <a href="https://web.archive.org/web/20090601113940/http://www.grok.co.uk:80/netproxy/" rel="nofollow noreferrer">NetProxy</a> for starters.</p>
<p>If you need to integrate with IIS, <a href="http://www.iisproxy.net/" rel="nofollow noreferrer">IISProxy</a> looks like it would do the trick too.</p>
|
<p>I use apache mod_proxy and mod_proxy_balancer. Works awesome running 5 domains a cluster of 4 web boxes.</p>
| 3,257
|
<p>In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command <code>ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;</code>?</p>
<p>I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.</p>
|
<pre><code>SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
</code></pre>
<p>Return value:</p>
<ul>
<li><strong>1</strong>: <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>ON</strong>. Read operations under the <code>READ COMMITTED</code> isolation level are based on snapshot scans and do not acquire locks.</li>
<li><strong>0</strong> (default): <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>OFF</strong>. Read operations under the <code>READ COMMITTED</code> isolation level use <a href="https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)" rel="noreferrer">Shared (S) locks</a>.</li>
</ul>
|
<p>Neither on SQL2005 nor 2012 does <code>DBCC USEROPTIONS</code> show <code>is_read_committed_snapshot_on</code>:</p>
<pre><code>Set Option Value
textsize 2147483647
language us_english
dateformat mdy
datefirst 7
lock_timeout -1
quoted_identifier SET
arithabort SET
ansi_null_dflt_on SET
ansi_warnings SET
ansi_padding SET
ansi_nulls SET
concat_null_yields_null SET
isolation level read committed
</code></pre>
| 7,521
|
<p>I need to migrate Access databases to SQL Server 2005. Since this needs to be done from within a setup so that a customers' installation is transparently migrated to SQL Server 2005, I wonder if it is possible to automate the SSMA toolkit from Microsoft.</p>
|
<p>I continued work on the library that was mentioned by <a href="https://stackoverflow.com/questions/217961/serializing-and-deserializing-expression-trees-in-c/1486253#1486253">Serializing and Deserializing Expression Trees in C#</a></p>
<p>It looks like the project was abandoned (2008) but I did some work on it and now it works with .NET 4.0 and Silverlight. I made bug fixes to their code and also made it more DAL-independent.</p>
<p><a href="http://expressiontree.codeplex.com/" rel="noreferrer">http://expressiontree.codeplex.com/</a></p>
|
<p>I was working on a project for serializing expressions. It's OK and you can use it.
<a href="http://www.codeproject.com/Articles/851187/ServicePredicateBuilder-for-creating-Serializable" rel="nofollow">http://www.codeproject.com/Articles/851187/ServicePredicateBuilder-for-creating-Serializable</a> </p>
| 26,804
|
<p>Could any one give an explanation on how a DHT works?</p>
<p>Nothing too heavy, just the basics.</p>
|
<p>Ok, they're fundamentally a pretty simple idea. A DHT gives you a dictionary-like interface, but the nodes are distributed across the network. The trick with DHTs is that the node that gets to store a particular key is found by hashing that key, so in effect your hash-table buckets are now independent nodes in a network.</p>
<p>This gives a lot of fault-tolerance and reliability, and possibly some performance benefit, but it also throws up a lot of headaches. For example, what happens when a node leaves the network, by failing or otherwise? And how do you redistribute keys when a node joins so that the load is roughly balanced. Come to think of it, how do you evenly distribute keys anyhow? And when a node joins, how do you avoid rehashing everything? (Remember you'd have to do this in a normal hash table if you increase the number of buckets).</p>
<p>One example DHT that tackles some of these problems is a logical ring of n nodes, each taking responsibility for 1/n of the keyspace. Once you add a node to the network, it finds a place on the ring to sit between two other nodes, and takes responsibility for some of the keys in its sibling nodes. The beauty of this approach is that none of the other nodes in the ring are affected; only the two sibling nodes have to redistribute keys.</p>
<p>For example, say in a three node ring the first node has keys 0-10, the second 11-20 and the third 21-30. If a fourth node comes along and inserts itself between nodes 3 and 0 (remember, they're in a ring), it can take responsibility for say half of 3's keyspace, so now it deals with 26-30 and node 3 deals with 21-25. </p>
<p>There are many other overlay structures such as this that use content-based routing to find the right node on which to store a key. Locating a key in a ring requires searching round the ring one node at a time (unless you keep a local look-up table, problematic in a DHT of thousands of nodes), which is O(n)-hop routing. Other structures - including augmented rings - guarantee O(log n)-hop routing, and some claim to O(1)-hop routing at the cost of more maintenance. </p>
<p>Read the wikipedia page, and if you really want to know in a bit of depth, check out this <a href="http://www.eecs.harvard.edu/~mema/courses/cs264/cs264.html" rel="noreferrer">coursepage</a> at Harvard which has a pretty comprehensive reading list.</p>
|
<p>The core of a DHT is a hash table. Key-value pairs are stored in DHT and a value can be looked up with a key. The keys are unique identifiers to values that can range from blocks in a blockchain to addresses and to documents.</p>
<p><strong>What differentiates a DHT from a normal hash table is the fact that storage and lookup on DHT are distributed across multiple (can be millions) nodes or machines.</strong> This very characteristic of DHT makes it look like distributed databases used for storage and retrieval. There is no master-slave hierarchy or a centralized control among the participating nodes. All the nodes are treated as peers.</p>
<p>DHT provides freedom to the participating nodes such that the nodes can join or leave the network anytime. Due to this reason, DHTs are widely used in Peer-to-Peer (P2P) networks. In fact, part of the motivation behind the research of DHT stems from its usage in P2P networks.</p>
<p><strong>Characteristics of DHT</strong></p>
<ol>
<li><p>Decentralized: Since there is no central authority or coordination</p>
</li>
<li><p>Scalable: The system can easily scale up to millions of nodes</p>
</li>
<li><p>Fault-tolerant: DHT replicates the data storage on all the nodes.
Therefore, even if one node leaves the network, it should not affect other nodes in the network.</p>
</li>
</ol>
<p>Let’s see how lookup happens in a popular DHT protocol like Chord. Consider a circular doubly-linked list of nodes. Each node has a reference pointer to the node previous as well as next to it. The node next to the node in question is called the successor. The node that is previous to the node in question is called the predecessor.</p>
<p>Speaking in terms of a DHT, each node has a unique node ID of k bits and these nodes are arranged in the increasing order of their node IDs.
Assume these nodes are arranged in a ring structure called identifier ring. For each node, the successor has the shortest distance clockwise away. For most nodes, this is the node whose ID is closest to but still greater than the current node’s ID.
To find out the node appropriate for a particular key, first hash the key K and all the nodes to exactly k bits using consistent hashing techniques like SHA-1.</p>
<p><a href="https://i.stack.imgur.com/Duaij.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Duaij.png" alt="SHA1" /></a></p>
<p>Start at any point in the ring and traverse clockwise till you catch the node whose node ID is closer to the key K, but can be greater than K. This node is the one responsible for storage and lookup for that particular key.</p>
<p><a href="https://i.stack.imgur.com/AtNFZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AtNFZ.png" alt="Basic Lookup in DHT" /></a></p>
<p>In an iterative style of lookup, each node Q queries its successor node for KV (key-value) pair. If the queried node does not have the target key, it will return a set of nodes S that can be closer to the target. The querying node Q then queries the nodes in S which are closer to itself. This continues until either the target KV pair is returned or when there are no more nodes to query.</p>
<p>This lookup is very suitable for an ideal scenario where all the nodes have a perfect uptime. But how to handle scenarios when nodes leave the network either intentionally or by failure? This calls for the need for a robust join/leave protocol.</p>
<p><strong>Popular DHT protocols and implementations</strong></p>
<ol>
<li>Chord</li>
<li>Kademlia</li>
<li>Apache Cassandra</li>
<li>Koorde TomP2P</li>
<li>Voldemort</li>
</ol>
<p>References:</p>
<ol>
<li><a href="https://en.wikipedia.org/wiki/Distributed_hash_table" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Distributed_hash_table</a></li>
<li><a href="https://steffikj19.medium.com/dht-demystified-77dd31727ea7" rel="nofollow noreferrer">https://steffikj19.medium.com/dht-demystified-77dd31727ea7</a></li>
<li><a href="https://www.linuxjournal.com/article/6797" rel="nofollow noreferrer">https://www.linuxjournal.com/article/6797</a></li>
</ol>
| 17,412
|
<p>I am just starting with SL and WPF. I am using the DataGrid control and I need to remove the mouseover effect (I actually will need to do more customizations than that). How do I do this. I think I need to do it with a control template but not sure how. I'm researching and reading right now. Any help would be appreciated.</p>
|
<p>Yeah You have to change the Style and ControlTemplate , But are you using experssion blend to edit XAML? Blend is the easiest tool to do this.</p>
<p>Try changing the ControlTemplate for a Standard Button or ListBox and once you are comfortable then go to DatGrid. Why I am suggesting this is DataGrid is a complex combination of different UIElements so the control template will be hard to understand for a beginner.</p>
<p>Specific to MouseOver effect removal - There will be a <strong>VSM</strong> tag in the control template which has some storyboards , just remove the one with <code><vsm:VisualState x:Name="MouseOver"></code>and you are good to go.</p>
|
<p>Yeah You have to change the Style and ControlTemplate , But are you using experssion blend to edit XAML? Blend is the easiest tool to do this.</p>
<p>Try changing the ControlTemplate for a Standard Button or ListBox and once you are comfortable then go to DatGrid. Why I am suggesting this is DataGrid is a complex combination of different UIElements so the control template will be hard to understand for a beginner.</p>
<p>Specific to MouseOver effect removal - There will be a <strong>VSM</strong> tag in the control template which has some storyboards , just remove the one with <code><vsm:VisualState x:Name="MouseOver"></code>and you are good to go.</p>
| 18,885
|
<p>I've been thinking about this object oriented design question for a while now and have unable to come up with a satisfactory solution, so thought I'd throw it open to the crowds here for some opinions.</p>
<p>I have a <em>Game</em> class that represents a turn based board game, we can assume it's similar to Monopoly for the purposes of this question.
In my design I have a <em>Player</em> class containing a method <em>TakeTurn</em>.</p>
<p>The <em>Game</em> loops through all <em>Player</em>s and calls the TakeTurn method to do all the necessary things to complete the turn.
I want to be able to have n number of players, and be able to set an arbitrary number of them to be computer players.
So, my thought was to have a HumanPlayer class and a <em>ComputerPlayer</em> class, both of which derive from Player.</p>
<p>The <em>Game</em> knows only the <em>Player</em> class and simply calls the <em>TakeTurn</em> method on each <em>Player</em> in turn.
My problem comes in the fact that <em>ComputerPlayer</em> objects can be completely automated, i.e. keeping with the Monopoly example, can decide to buy a property using some piece of logic.
Now, with the <em>HumanPlayer</em> object, it needs to get an input from the actual user to be able to buy a property for instance, which seems to imply a different interface and potentially mean they shouldn't derive</p>
<p>I haven't been able to come up with a good solution to the problem without having the <em>Game</em> class know the actual implementations of the various <em>Player</em> classes explicitly.
I could always make the assumption in the <em>Game</em> class that there will only ever be human and computer players and effectively close it for extension, but it doesn't seem like good OO programming.</p>
<p>Any opinions on this would be appreciated.</p>
|
<p>I think you should not let the Game class handle IO.
this way, the (blocking) TakeTurn method will hide from the game board the means of implementation. it can use other objects to communicate with the user.</p>
<p>All the Game class should concern itself with is the state of the board and the turn. the players should all implement a single Player interface, and hide all implementation from the Game.</p>
|
<p>I think the <code>Game</code> Class should not concern about any implementations of the Player classes, and also ignore the User Interface.</p>
<p>Any user input needs to be handled by the <code>HumanPlayer</code> class.</p>
| 11,645
|
<p>This one has me stumped regularly while creating top level class diagrams for documentation. Methods and attributes/fields are easy to model.
I usually end up adding a method named EvChanged to indicate a .Net event Changed.</p>
<p>What is the right way to show that a type publishes a specific event?</p>
|
<p>Just add an «event» stereotype to a classifier attribute.</p>
|
<p>Not the type of answer that I like to give, but <a href="http://office.microsoft.com/en-us/visio/HP815503691033.aspx" rel="nofollow noreferrer">Microsoft</a> has an answer on the Office website.</p>
| 7,452
|
<p>EDIT1: Tried to clear the question up by renaming the tables AND their relationships.
EDIT2: Please don't look at the what TYPE of data i'm holding in the three DB tables. They were made up on the fly. They are NOT my real world scenarios (and no, I can't talk about my real world data .. in fact it's 1 parent and 6 children, currently). Please just ignore what type of data and just look at the fact that some data is required.
EDIT3: The two FKs are a 0 or 1 to 1 relationship. NOT 0 to many. Not 1 to 1. I'm trying to avoid the 0 or 1 to 1 relationship to a 1 to 1 relationship so i don't need to have OUTER JOINS but instead have an INNER JOIN.</p>
<p>Question: I need to know if the proposed database design is good/bad/lame/etc..</p>
<p>Problem: today i tried to make an <em>indexed view</em>, but failed 'cause my tables have outer joins. Sigh. So i was wondering if i can refix this up to be like the following design:</p>
<ul>
<li>Three tables.</li>
<li>table_User has a FK on table_Address</li>
<li>table_User has an FK on table_Vehicle</li>
<li>etc..</li>
</ul>
<p>and table B and C (which sorta act like lookup tables now) have..</p>
<ul>
<li>Id INT IDENTITY PK</li>
<li>Description NVARCHAR(100) <em>NULLABLE</em></li>
</ul>
<p>notice the nullable? this way, something in table_User doesn't exist in table_Address ... the the field is null (because of the inner join).</p>
<p>Before, i made that an LEFT OUTER JOIN, so if there was no data in table_b, i'll get nulls are the result for each field.</p>
<p>I'll throw some data examples here...</p>
<p>Table_User</p>
<ul>
<li>ID: 1, Name: Fred, AddressID: 1 (NULL)</li>
<li>ID: 2, Name: Joe, AddressID: 2 (1 smith street.....)</li>
<li>ID: 3, Name: Jane, AddressID: 2 (1 smith street.....)</li>
</ul>
<p>Table_Address</p>
<ul>
<li>ID: 1, Description = NULL</li>
<li>ID: 2, Description = 1 smith street</li>
</ul>
<p>etc.</p>
<p>So then i can finally put this all into an indexed view. (my real life scenario has around 8 tables).</p>
<p>NOTE: DB is Microsoft Sql Server 2008, but this could be for any DB.</p>
<p>Q1: Does that design seem ok?</p>
<p>Q2: So what i'm doing here is i'm normalising the data, right? by keeping the inner joins together.</p>
<p>Q3:Lastly, if this is an ok way about it .. can i also make sure the data in the tables are unique (eg. the street addresses) by having some unique constraints or keys or indexes or what (i'm not sure of the proper terminology).</p>
<p>thanks gurus!</p>
|
<p>I find your question confusing, but maybe I can help a little.</p>
<p>First of all, tables don't have joins, queries have. You don't make a table with a join to another table. There are just 2 tables that may be related, and you can query those tables using joins.</p>
<p>I recommend you to read about db normalization. Wikipedia has a great article: <a href="http://en.wikipedia.org/wiki/Database_normalization" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Database_normalization</a></p>
<p>About your current case, I'm not sure of what are you trying to do. Having an ID for an address seems ok if that address is repeated in different rows. However, needing several "address tables" seems weird. The most important things to remember when designing are:
- Have a correct primary key in every table, so you can correctly join tables.
- Do not repeat data unless you have a very very good reason.
But I again recommend the previous article.</p>
<p>hope that helps! :)</p>
|
<p>So you are basically adding bogus records in tables B and C in order to have the same number of rows as in A? I wouldn't do it if I were you, because if your dataset is large, then you are increasing the number of rows without any real need and also you are running a risk of an inconsistency (your layout heavily depends on your ability to have these bogus records inserted). Apart from that, what do you want to achieve with an indexed view? Performance gain? You are not writing what DBMS you are using, but from my experience in MSSQL this ain't going to give you a lot of gain, because provided that you have proper indexes in tables A, B and C the server will be able to use them to build a good query plan even without an indexed view.</p>
| 41,387
|
<p>I'm getting near completely different objects from the same WSDL file when I try to Add a Web Reference depending if I am using Express or Pro version of the vs2008 .NET IDE.</p>
<p>1) Why is this happening? I'd expect the WSDL's to act the same across platforms--clearly they are not!
2) How do I determine what tool/wizard the IDE is calling when I select "Add Service Reference".</p>
<p>Details:
The VB.NET Express version is adding objects that are desired and expected. I'd like to use the IDE to add the service (not muck with wsdl.exe or svcutil.exe). </p>
<p>I'm using vs2008 Pro v9.0.30729.1 on Windows Server 2003. Express version 9.0.21022.8 RTM on XP.The respective Reference.vb shows the same header "This code was generated by a tool. Runtime Version:2.0.50727.3053". </p>
<p>The wizard UI's to add the service WSDL are visually different between the two IDEs. </p>
<p>Express has Strict On and Pro has Strict Off. The general IDE Strict settings seem to have no control over this.</p>
<p>Java/Eclipse are having no issues with these WSDLs.</p>
|
<p>I'm sorry to say that the proxies visual studio generates are pretty bad.</p>
<p>The real solution for this right now is to write your own contracts and proxies. I know, it's not great news, but 30 minutes of typing might save you from a world of hurt.</p>
<p>Check out the helper classes at <a href="http://www.idesign.net" rel="nofollow noreferrer">idesign.net</a></p>
|
<p>I have seen in the past where wsdl.exe would produce different proxy classes than the VS IDE wizard does. This is probably the explanation.</p>
| 12,904
|
<p>I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?</p>
|
<p><strong>Declaration</strong></p>
<p>A prototype for a function which takes a function parameter looks like the following:</p>
<pre><code>void func ( void (*f)(int) );
</code></pre>
<p>This states that the parameter <code>f</code> will be a pointer to a function which has a <code>void</code> return type and which takes a single <code>int</code> parameter. The following function (<code>print</code>) is an example of a function which could be passed to <code>func</code> as a parameter because it is the proper type:</p>
<pre><code>void print ( int x ) {
printf("%d\n", x);
}
</code></pre>
<p><strong>Function Call</strong></p>
<p>When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:</p>
<pre><code>func(print);
</code></pre>
<p>would call <code>func</code>, passing the print function to it.</p>
<p><strong>Function Body</strong></p>
<p>As with any parameter, <code>func</code> can now use the parameter's name in the function body to access the value of the parameter. Let's say that <code>func</code> will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:</p>
<pre><code>for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
</code></pre>
<p>Since <code>func</code>'s parameter declaration says that <code>f</code> is the name for a pointer to the desired function, we recall first that if <code>f</code> is a pointer then <code>*f</code> is the thing that <code>f</code> points to (i.e. the function <code>print</code> in this case). As a result, just replace every occurrence of print in the loop above with <code>*f</code>:</p>
<pre><code>void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
</code></pre>
<p><a href="http://math.hws.edu/bridgeman/courses/331/f05/handouts/c-c++-notes.html" rel="noreferrer">Source</a></p>
|
<p>It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.</p>
<pre><code>#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}
</code></pre>
| 3,083
|
<p>How do I create a toolbar for Excel using an XLA document?</p>
|
<p>To make a toolbar, in the onload event, you are going to do something like:</p>
<pre><code>Dim myBar As CommandBar, myButt As CommandBarControl
'Delete the toolbar if it already exists'
On Error Resume Next
CommandBars("My Toolbar").Delete
On Error Goto 0
Set myBar = CommandBars.Add(Name:="My Toolbar", _
Position:=msoBarFloating, Temporary:=True)
myBar.Visible = True
' Create a button with text on the bar and set some properties.'
Set myButt = ComBar.Controls.Add(Type:=msoControlButton)
With myButt
.Caption = "Macro1"
.Style = msoButtonCaption
.TooltipText = "Run Macro1"
.OnAction = "Macro1"
End With
' Create a button with an image on the bar and set some properties.'
Set myButt = ComBar.Controls.Add(Type:=msoControlButton)
With myButt
'the faceId line will let you choose an icon'
' If you choose to use the faceId then the caption is not displayed'
.FaceId = 1000
.Caption = "Icon Button"
.TooltipText = "Run Macro2"
.OnAction = "Macro2"
End With
</code></pre>
<p>The polite thing to do is delete the toolbar on exit, also.</p>
|
<p>Not sure if this is what you're looking for but I thought this might help you out:</p>
<p><a href="http://www.contextures.com/xlToolbar02.html" rel="nofollow noreferrer">Excel -- Macro Toolbar</a></p>
<p>Since you don't specify a version of Excel I'm not sure if this will work for you or not but perhaps it will furnish you with a good starting point.</p>
| 32,819
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.