instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Normally, I'm all fine with my printer and filament. But today I changed the filament for another brand and no matter what, it sticks to the nozzle so nothing comes to the bed and soon my nozzle is full of PLA... I use a sheet of paper for printer to level the bed at 0.1 mm. While leveling, I get the nozzle close enough to feel a bit of resistance from the paper while moving that sheet. Please help me...</p>
|
<p>I believe the problem is not so much that the filament is sticking to the nozzle; it's that the filament is not sticking to the bed.</p>
<p>You've confirmed that you have correct clearance for the nozzle to bed distance. The next considerations are bed temperature and nozzle temperature. New brands often require new parameters.</p>
<p>Consider to raise the bed temperature 5 °C. If you're not using any adhesive medium, perhaps a bit of glue stick will help to have the filament stick better/properly.</p>
<p>It's unlikely that the nozzle temperature is incorrect, as too low would result in a nozzle clog, while too high would "drizzle out" and be everywhere, but don't reject too-high entirely.</p>
<p>If you can get the bed adhesion correct, your nozzle should remain clear.</p>
|
<p>I believe the problem is not so much that the filament is sticking to the nozzle; it's that the filament is not sticking to the bed.</p>
<p>You've confirmed that you have correct clearance for the nozzle to bed distance. The next considerations are bed temperature and nozzle temperature. New brands often require new parameters.</p>
<p>Consider to raise the bed temperature 5 °C. If you're not using any adhesive medium, perhaps a bit of glue stick will help to have the filament stick better/properly.</p>
<p>It's unlikely that the nozzle temperature is incorrect, as too low would result in a nozzle clog, while too high would "drizzle out" and be everywhere, but don't reject too-high entirely.</p>
<p>If you can get the bed adhesion correct, your nozzle should remain clear.</p>
| 1,791
|
<p>I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using <code>STL</code> techniques such as vectors.</p>
<p>Essentially I want my integer array dimensions to look like:</p>
<pre><code>[ x ][ y ][ z ]
</code></pre>
<p>x and y are in the range 20-6000
z is known and equals 4.</p>
|
<p>Have a look at the Boost <a href="http://www.boost.org/doc/libs/release/libs/multi_array" rel="noreferrer">multi-dimensional array</a> library. Here's an example (adapted from the Boost documentation):</p>
<pre><code>#include "boost/multi_array.hpp"
int main() {
// Create a 3D array that is 20 x 30 x 4
int x = 20;
int y = 30;
int z = 4;
typedef boost::multi_array<int, 3> array_type;
typedef array_type::index index;
array_type my_array(boost::extents[x][y][z]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != x; ++i) {
for (index j = 0; j != y; ++j) {
for (index k = 0; k != z; ++k) {
my_array[i][j][k] = values++;
}
}
}
}
</code></pre>
|
<p>Pieter's suggestion is good of course, but one thing you've to bear in mind is that in case of big arrays building it may be quite slow. Every time vector capacity changes, all the data has to be copied around ('n' vectors of vectors).</p>
| 8,798
|
<p>I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).</p>
<p>What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.</p>
<p>I know that <code><a href="url" target="_blank"></code> is out. I also know that <code><a href="#" onclick="window.open(url);"></code> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <code><span onclick="window.open(url);"></code> and then style the SPAN to look like a link.</p>
<p>One solution I'm leaning towards is <code><a href="url" rel="external"></code> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.</p>
<p>Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.</p>
<p>UPDATE: I say target="_blank" is a no no, because I've read in <a href="http://www.sitepoint.com/article/standards-compliant-world/3/" rel="noreferrer">several places</a> that the target attribute is going to be phased out of XHTML.</p>
|
<p>I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:</p>
<pre><code>$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
</code></pre>
<p>I find this the best method because:</p>
<ul>
<li>it is very clear semantically: you have a link to an external resource</li>
<li>it is standards-compliant</li>
<li>it degrades gracefully (you have a very simple link with regular <code>href</code> attribute)</li>
<li>it still allows user to middle-click the link and open it in new tab if they wish</li>
</ul>
|
<p>If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...</p>
<p>Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():</p>
<p>In plain html:</p>
<pre><code><a href="..." target="_blank" onclick="window.open(this.href, 'newWin'); return false;">link</a>
</code></pre>
<p>If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...</p>
<p>-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)</p>
| 28,898
|
<p>I have an <code>ArrayList<String></code>, and I want to remove repeated strings from it. How can I do this?</p>
|
<p>If you don't want duplicates in a <code>Collection</code>, you should consider why you're using a <code>Collection</code> that allows duplicates. The easiest way to remove repeated elements is to add the contents to a <code>Set</code> (which will not allow duplicates) and then add the <code>Set</code> back to the <code>ArrayList</code>:</p>
<pre><code>Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
</code></pre>
<p>Of course, this destroys the ordering of the elements in the <code>ArrayList</code>.</p>
|
<p>In Java, List permits ordered access of their elements. They can have duplicates because their lookup key is the position not some hash code, every element can be modified while they remain in the list where as Set represents a collection of unique elements and while elements are in set, they must not be modified.While there is no restriction preventing you from modifying elements in a set, if an element is modified, then it could become forever lost in the set.</p>
<pre><code>public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("A");
l.add("B");
l.add("C");
l.add("A");
System.out.println("Before removing duplicates: ");
for (String s : l) {
System.out.println(s);
}
Set<String> set = new HashSet<String>(l);
List<String> newlist = new ArrayList<String>(set);
System.out.println("after removing duplicates: ");
for (String s : newlist) {
System.out.println(s);
}
}
</code></pre>
<p>for reference, refer this link <a href="http://techno-terminal.blogspot.in/2015/11/how-to-remove-duplicates-from-arraylist.html" rel="nofollow noreferrer">How to remove duplicates from ArrayList</a></p>
| 24,953
|
<p>I need to dynamically construct an XPath query for an element attribute, where the attribute value is provided by the user. I'm unsure how to go about cleaning or sanitizing this value to prevent the XPath equivalent of a SQL injection attack. For example (in PHP):</p>
<pre><code><?php
function xPathQuery($attr) {
$xml = simplexml_load_file('example.xml');
return $xml->xpath("//myElement[@content='{$attr}']");
}
xPathQuery('This should work fine');
# //myElement[@content='This should work fine']
xPathQuery('As should "this"');
# //myElement[@content='As should "this"']
xPathQuery('This\'ll cause problems');
# //myElement[@content='This'll cause problems']
xPathQuery('\']/../privateElement[@content=\'private data');
# //myElement[@content='']/../privateElement[@content='private data']
</code></pre>
<p>The last one in particular is reminiscent to the SQL injection attacks of yore.</p>
<p>Now, I know for a fact there will be attributes containing single quotes and attributes containing double quotes. Since these are provided as an argument to a function, what would be the ideal way to sanitize the input for these?</p>
|
<p>XPath does actually include a method of doing this safely, in that it permits <a href="http://www.w3.org/TR/xpath#section-Expressions" rel="noreferrer">variable references</a> in the form <code>$varname</code> in expressions. The library on which PHP's SimpleXML is based <a href="http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterVariable" rel="noreferrer">provides an interface to supply variables</a>, however this <a href="http://php.net/manual/en/function.simplexml-element-xpath.php" rel="noreferrer">is not exposed by the xpath function</a> in your example.</p>
<p>As a demonstration of really how simple this can be:</p>
<pre><code>>>> from lxml import etree
>>> n = etree.fromstring('<n a=\'He said "I&apos;m here"\'/>')
>>> n.xpath("@a=$maybeunsafe", maybeunsafe='He said "I\'m here"')
True
</code></pre>
<p>That's using <a href="http://codespeak.net/lxml/" rel="noreferrer">lxml</a>, a python wrapper for the same underlying library as SimpleXML, with a similar <a href="http://codespeak.net/lxml/xpathxslt.html#the-xpath-method" rel="noreferrer">xpath function</a>. Booleans, numbers, and node-sets can also be passed directly.</p>
<p>If switching to a more capable XPath interface is not an option, a workaround when given external string would be something (feel free to adapt to PHP) along the lines of:</p>
<pre><code>def safe_xpath_string(strvar):
if "'" in strvar:
return "',\"'\",'".join(strvar.split("'")).join(("concat('","')"))
return strvar.join("''")
</code></pre>
<p>The return value can be directly inserted in your expression string. As that's not actually very readable, here is how it behaves:</p>
<pre><code>>>> print safe_xpath_string("basic")
'basic'
>>> print safe_xpath_string('He said "I\'m here"')
concat('He said "I',"'",'m here"')
</code></pre>
<p>Note, you can't use escaping in the form <code>&apos;</code> outside of an XML document, nor are generic XML serialisation routines applicable. However, the XPath concat function can be used to create a string with both types of quotes in any context.</p>
<p>PHP variant:</p>
<pre><code>function safe_xpath_string($value)
{
$quote = "'";
if (FALSE === strpos($value, $quote))
return $quote.$value.$quote;
else
return sprintf("concat('%s')", implode("', \"'\", '", explode($quote, $value)));
}
</code></pre>
|
<pre><code>function xPathQuery($attr) {
$xml = simplexml_load_file('example.xml');
$to_encode = array('&', '"');
$to_replace = array('&amp;','&quot;');
$attr = replace($to_encode, $to_replace, $attr);
return $xml->xpath("//myElement[@content=\"{$attr}\"]");
}
</code></pre>
<p>Ok, what does it do?</p>
<p>It encodes all occurences of & and " as &amp; and &quot; in the string, which should give you a safe selector for that particular use. Note that I also replaced the inner ' in the xpath with ". EDIT: It has since been pointed out that ' can be escaped as &apos;, so you could use whichever string quoting method you prefer.</p>
| 22,898
|
<p>I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.</p>
<p>With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.</p>
<p>At the moment the code looks like (code simplified to aid clarity!): </p>
<pre><code><select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</code></pre>
<p>What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!</p>
<p>Any assistance much appreciated :)</p>
<p>Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!</p>
|
<p>Setup the <code>onchange</code> event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.</p>
<pre><code> <html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
</code></pre>
<p>Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question.</p>
|
<p>Tom's answer is elegant, and neatly puts the JS away from the HTML markup. As mentioned, it could be even moved to an external file. However it adds quite much "nonsense" to the code, like multiple anonymous function assignments etc.</p>
<p>If you want quick solution, you can put it all in the onchange() inside the select tag as well. Pick the one you see more fit.</p>
<pre><code><select id="transfer_reason" name="transfer_reason" onchange="document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</code></pre>
| 48,071
|
<p>I'm writing a function for an installer DLL to verify the Authenticode signature of EXE files already installed on the system.</p>
<p>The function needs to:</p>
<blockquote>
<p>A) verify that the signature is valid.<br>
B) verify that the signer is our organization.</p>
</blockquote>
<p>Because this is in an installer, and because this needs to run on older Win2k installations, I <strong>don't</strong> want to rely on CAPICOM.dll, as it may not be on the target system.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa388208(VS.85).aspx" rel="noreferrer">WinVerifyTrust</a> API works great to solve (A).</p>
<p>I need to find a way to compare a known certificate (or properties therein) to the one that signed the EXE in question.</p>
|
<p>You should use <a href="http://msdn.microsoft.com/en-us/library/aa380264(VS.85).aspx" rel="nofollow noreferrer">CryptQueryObject</a>.</p>
<p>This KB-article demonstrates the use: <a href="https://support.microsoft.com/kb/323809" rel="nofollow noreferrer">How To Get Information from Authenticode Signed Executables</a>.</p>
<p>To the commenter that asked about how to do it without the Windows-APIs, I am not aware of any library that can do it, but the format is documented here: <a href="http://www.microsoft.com/whdc/winlogo/drvsign/Authenticode_PE.mspx" rel="nofollow noreferrer">Windows Authenticode Portable Executable Signature Format</a></p>
|
<p>If the signature is valid, its certificate chain will contain your certificate. <a href="http://msdn.microsoft.com/en-us/library/aa376078%28VS.85%29.aspx" rel="nofollow noreferrer">CertGetCertificateChain</a> will get that chain.</p>
| 38,597
|
<p>Anyone know of a good memory/disk caching library for AIR? Extra points for being compatible with Flash CS3, and being free (as in beer).</p>
<p>I'd like to cache results of http requests: both binary and text (xml).</p>
|
<p>The <a href="http://code.google.com/p/bulk-loader/" rel="nofollow noreferrer">bulk-loader</a> project might have what you're looking for. I haven't used it myself but in the description it says (among other things):</p>
<ul>
<li>Cache management</li>
<li>Various asset types (XML, NetStreams, Swfs, Images, Sound, Text Files)</li>
</ul>
<p>From quickly looking at the code and some of the examples in the wiki it looks like it has memory (but not disk) caching capabilities.</p>
|
<p>You can find a class that handles content caching (text and binary) here:</p>
<p><a href="http://www.mikechambers.com/blog/2007/03/19/simple-apollo-offline-caching-example/" rel="nofollow noreferrer">http://www.mikechambers.com/blog/2007/03/19/simple-apollo-offline-caching-example/</a></p>
<p>That links includes links to complete code, and sample apps that use it.</p>
<p>mike</p>
| 22,432
|
<p>Why main must be declared as if it has external linkage?
<p>Why it should not be static?
<p>what is meant by external linkage??</p>
|
<p>Because you link the startup files to your program, which contains (usually) assembler code that calls your main. If main were static, that code wouldn't be able to call main.</p>
<p><code>external linkage</code> means that other so-called <code>translation-units</code> can see your symbol declared extern in its own translation-unit. So, your main is extern, and it will have an entry in its translation-units symbol table that states its address. Other translation-units will then be able to jump to that address when they want to call main. </p>
<p><code>static linkage</code> means your symbol is strictly translation-unit local. This means other <code>translation units</code> will not be able to see that symbol. Thus, symbols with static linkage can occur in different translation units multiple times, and they won't clash with each other because they are local.</p>
<p><strong>Edit</strong>: Generally, files generated by the compiler from translation units are specific to that particular compiler. For gcc on linux, often the ELF object format is used. You can view its symbol table using <code>readelf -sW <file>.o</code> (simple test-file below):</p>
<p><em>test.c</em></p>
<pre><code>void bar(void);
static int foo(void) {
return 1;
}
int main(void) {
bar();
return foo();
}
</code></pre>
<p>Here is the output of readelf:</p>
<pre><code>Symbol table '.symtab' contains 10 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS test.c
2: 00000000 0 SECTION LOCAL DEFAULT 1
3: 00000000 0 SECTION LOCAL DEFAULT 3
4: 00000000 0 SECTION LOCAL DEFAULT 4
5: 00000000 10 FUNC LOCAL DEFAULT 1 foo
6: 00000000 0 SECTION LOCAL DEFAULT 6
7: 00000000 0 SECTION LOCAL DEFAULT 5
8: 0000000a 36 FUNC GLOBAL DEFAULT 1 main
9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar
</code></pre>
<p>You see the main function, and a static foo function, called by main. Also there is a function called which is not defined in the file, but which is defined in another object file. As the object file wasn't finally linked yet, the functions don't have final addresses assigned yet. After the final link, these will be arranged into the executable and will have addresses assigned. The object file has entries for calls to not-yet defined functions, so that when the file is linked, those call instructions can have the final addresses stored (<code>readelf -r <file>.o</code>):</p>
<pre><code>Relocation section '.rel.text' at offset 0x308 contains 1 entries:
Offset Info Type Sym.Value Sym. Name
0000001c 00000902 R_386_PC32 00000000 bar
</code></pre>
|
<p>The real starting point of the code is buried in the C runtime library. This runtime library calls your main() routine. In order for the linker to connect the C RTL call with your main() function, it needs to be visible outside the file.</p>
<p>External linkage is just this: it means that the name in question is visible as part of the exports of the object file. The job of the linker is to join up all of the imports and exports so that there are no outstanding imports.</p>
| 41,452
|
<p>I have a JPanel full of JTextFields...</p>
<pre><code>for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
}
</code></pre>
<p>How do I later get the JTextFields in that JPanel? Like if I want their values with </p>
<pre><code>TextField.getText();
</code></pre>
<p>Thanks</p>
|
<p>Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime ) </p>
<p>In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here:</p>
<pre><code>List<JTextField> list = new ArrayLists<JTextField>();
// your code...
for (int i=0; i<maxPoints; i++) {
JTextField textField = new JTextField();
points.add(textField);
list.add( textField ); // keep a reference to those fields.
}
</code></pre>
<p>// Later </p>
<pre><code>for( JTextField f : list ) {
System.out.println( f.getText() ) ;
}
</code></pre>
<p>Wasn't that easy?</p>
<p>Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface.</p>
<p>Let's say you want to get the array of texts, instead of </p>
<pre><code> public List<JTextField> getFields();
</code></pre>
<p>You should consider:</p>
<pre><code> public List<String> getTexts(); // get them from the textfields ...
</code></pre>
|
<p>Your problem is writing the tedious code text. Why not just generate it and paste in the program!!...</p>
<pre><code>for(int i=1 ; i<=maxpoints ;i++){
System.out.println("JTextField tf"+i+" = new JTextField()"+";");
System.out.println("points.add(tf"+i+")"+";");
}
</code></pre>
<p>Paste the output of the above code in your program and you are done.
Now, to access the content of text fields you can generate the tedious code text in a similar way....</p>
<pre><code>for(int i=1 ; i<=maxpoints ;i++){
System.out.println("String s"+i+" = JTextField tf"+i+".getText()"+";");
}
</code></pre>
| 48,375
|
<p>Where is the correct Marlin firmware file and location to add code that I want to shop up in the LCD menu of my printer, and then execute the function I write when the button is pressed?</p>
<p>For example I want to add a menu item that says "Preheat Custom" that is in the same menu as "preheat PLA" and "preheat ABS" and then runs code to heat to values I specify.</p>
<p><em>I'm running Marlin Firmware version 1.1.9 on a Creality Ender 3.</em></p>
|
<p>The answer to your question (baring in mind that the question is raised for Marlin 1.1.9) is the file <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a>. Nowadays, you can also enable extra option through the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration_adv.h#L1546" rel="nofollow noreferrer">Configuration_adv.h</a> file, just enable:</p>
<pre><code>#define CUSTOM_USER_MENUS
</code></pre>
<p>and edit the options beneath it to your needs (otherwise it will use the preset values from the <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/Configuration.h#L1255" rel="nofollow noreferrer">Configuration.h</a> file).</p>
<hr />
<p><strong>Add custom items using ultralcd.cpp</strong></p>
<p>This is how I used to do it if you want to add items to the menu in Marlin Firmware through the ultralcd.cpp. It is best to first look at the current implementation of the menu items. As you already mention <code>Preheat PLA</code>, that would be the first to search for. Searching in files is easy when you go to the github website with the Marlin firmware sources, functionality is available for searching in the files. Alternatively, download a copy of the firmware and use a free "grep" utility to search in files.</p>
<p>Searching for <code>Preheat PLA</code> will show you a bunch of language translation files. These point to the use of a constant <code>MSG_PREHEAT_1</code> which finds its presence in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a>. This hints to function <code>lcd_preheat_m1_menu</code> that is called by <code>MENU_ITEM</code> which adds menu items to LCD. You could start there to add your own option.</p>
<hr />
<p><strong>Demonstration</strong></p>
<p>As a quick demonstration, I've added a <code>CUSTOM PREHEAT</code> item by copying the <code>lcd_preheat_m2_menu</code> function in <a href="https://github.com/MarlinFirmware/Marlin/blob/1.1.x/Marlin/ultralcd.cpp" rel="nofollow noreferrer">ultralcd.cpp</a> and renamed this <code>lcd_preheat_m3_menu</code> (a full functional item needs changes within the <code>lcd_preheat_m3_menu</code> as it now uses the constants from the ABS preheat option).</p>
<p>You then add the item to the menu by changing this part of the code:</p>
<pre>
//
// Preheat for Material 1 and 2
//
#if TEMP_SENSOR_1 != 0 || TEMP_SENSOR_2 != 0 || TEMP_SENSOR_3 != 0 || TEMP_SENSOR_4 != 0 || HAS_HEATED_BED
MENU_ITEM(submenu, MSG_PREHEAT_1, lcd_preheat_m1_menu);
MENU_ITEM(submenu, MSG_PREHEAT_2, lcd_preheat_m2_menu);
// ADD THIS LINE:
MENU_ITEM(submenu, "CUSTOM PREHEAT", lcd_preheat_m3_menu);
#else
MENU_ITEM(function, MSG_PREHEAT_1, lcd_preheat_m1_e0_only);
MENU_ITEM(function, MSG_PREHEAT_2, lcd_preheat_m2_e0_only);
#endif
</pre>
<p>After compiling and uploading to the printer board, enter the <code>Prepare</code> menu and scroll down to see:</p>
<p><a href="https://i.stack.imgur.com/X5eUD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/X5eUD.jpg" alt="LCD showing custom preheat option" /></a></p>
|
<p>Preheat Constants - Up to 5 are supported without changing the code just add a new one and then build</p>
<pre><code>#define PREHEAT_1_LABEL "PLA"
#define PREHEAT_1_TEMP_HOTEND 215
#define PREHEAT_1_TEMP_BED 70
#define PREHEAT_1_TEMP_CHAMBER 35
#define PREHEAT_1_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_2_LABEL "PETG"
#define PREHEAT_2_TEMP_HOTEND 235
#define PREHEAT_2_TEMP_BED 70
#define PREHEAT_2_TEMP_CHAMBER 35
#define PREHEAT_2_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_3_LABEL "ABS"
#define PREHEAT_3_TEMP_HOTEND 270
#define PREHEAT_3_TEMP_BED 100
#define PREHEAT_3_TEMP_CHAMBER 35
#define PREHEAT_3_FAN_SPEED 0 // Value from 0 to 255
#define PREHEAT_4_LABEL "NYLON"
#define PREHEAT_4_TEMP_HOTEND 260
#define PREHEAT_4_TEMP_BED 65
#define PREHEAT_4_TEMP_CHAMBER 35
#define PREHEAT_4_FAN_SPEED 0 // Value from 0 to 255
<span class="math-container">```</span>
</code></pre>
| 1,132
|
<p>I have a requirement for an admin user to set up an export directory on the web server, or relative to the web server using a UNC. Is there anything already out there that I can use for this, or must I recurs a limited directories and populate a home-rolled directory browser on the client?</p>
|
<p>I noticed this today ...a JQuery File Tree plugin. The link includes "connector scripts" in a number of server side languages including asp.net:</p>
<p><a href="http://abeautifulsite.net/notebook.php?article=58" rel="nofollow noreferrer">http://abeautifulsite.net/notebook.php?article=58</a></p>
<p>Looks awesome (and well documented) but I have not tried. I would love to hear feedback if anyone has...</p>
|
<p>Every solution to this problem I have seen is a home-rolled implementation of directory browsing. </p>
<p>When attaching a database on a SQL server, Microsoft uses a "custom" treeview to show drives/folders/files available to be attached.</p>
<p>Also, on DotNetNuke (an Open Source ASP.NET Content Management System) they have a home-rolled implementation as well for uploading files to Portal Folders...</p>
| 36,077
|
<p>I'm just in the process of upgrading my Preview 5 application to Beta 1, and I'm nearly there save for this one error when trying to render a control:</p>
<blockquote>
<p>'System.Web.Mvc.HtmlHelper' does not
contain a definition for
'RenderPartial' and no extension
method 'RenderPartial' accepting a
first argument of type
'System.Web.Mvc.HtmlHelper' could be
found (are you missing a using
directive or an assembly reference?)</p>
</blockquote>
<p>My markup (in the .aspx View Content Page) is:</p>
<pre><code><% Html.RenderPartial("Controls/UserForm", ViewData); %>
</code></pre>
<p>I've tried using Microsoft.Web.Mvc but to no avail. Does anyone know where Html.RenderPartial has gone, or what alternative I could use?</p>
|
<p>And also don't forget to add namespaces like below to the web config, I think preview 5 default web.config does not have System.Web.Mvc.Html in it:</p>
<pre><code><namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>
</code></pre>
|
<p>In addition to adding the assembly reference I also had to add the line</p>
<pre><code> <add namespace="System.Web.Mvc.Html"/>"
</code></pre>
<p>to the pages/namespaces section in web.config file.</p>
| 25,991
|
<p>I'm trying to show someone a use for interfaces in a crazy situation they've created. They have several unrelated objects in lists, and need to perform an operation on two string properties in each object. I'm pointing out that if they define the properties as part of an interface, they can use the interface object as the type for a method parameter that acts on it; for example:</p>
<pre><code>void PrintProperties(IEnumerable<ISpecialProperties> list)
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}</code></pre>
<p>This seems like it's all good, but the lists that need to be worked on aren't (and shouldn't) be declared with the interface as the type parameter. However, it doesn't seem like you can cast to a different type parameter. For example, this fails and I can't understand why:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Test> myList = new List<Test>();
for (int i = 0; i < 5; i++)
{
myList.Add(new Test());
}
PrintList((IEnumerable<IDoSomething>)myList);
}
static void PrintList(IEnumerable<IDoSomething> list)
{
foreach (IDoSomething item in list)
{
item.DoSomething();
}
}
}
interface IDoSomething
{
void DoSomething();
}
public class Test : IDoSomething
{
public void DoSomething()
{
Console.WriteLine("Test did it!");
}
}
}</code></pre>
<p>I <em>can</em> use the <code>Enumerable.Cast<T></code> member to do this, but I was looking for a method that might work in .NET 2.0 as well. It seems like this should be possible; what am I missing? </p>
|
<p>The problem is with the method, not with how it's called.....</p>
<pre><code>void PrintProperties<SP>(IEnumerable<SP> list) where SP: ISpecialProperties
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}
</code></pre>
|
<p>This doesn't answer your question (or the point of the exercise I guess :), but I'd just use reflection in this case by attaching special attributes to the properties of interest.</p>
| 22,889
|
<p>I want to do validation on my business code. I'm thinking of 2 ways to do this.</p>
<p>One, do the validation on my class property setters in the following fashion</p>
<pre><code>class Student{
public string Name{
get { return _name; }
set {
if (value.IsNullOrEmpty) throw exception ...
}
}
}
</code></pre>
<p>Now, the problem with this approach is that, validation code is run every time Name gets assigned, which we may not need, like when fill it in with data from DB.</p>
<p>Two, which I prefer, put static methods on these entity classes, like</p>
<pre><code>class Student {
public **static** void ValidateName(**string name**) {
if (string.IsNullorEmpty(name))
{
throw ...
}
...
}
</code></pre>
<p>Notice I'm using a static method instead of a instance method, like</p>
<pre><code>class Student{
public void Validate() {
// validation logic on instance properties
if (string.IsNullorEmpty(Name))
{
throw ...
}
...
}
</code></pre>
<p>is because I'm not always getting a Student obj passed in, I do get primitive types like string name passed into a method often time, like</p>
<pre><code>public static FindStudentByName(string name)
{
// here I want to first do validation
Student.ValidateName(name);
// query DB
...
}
</code></pre>
<p>If I do get passed in a student obj, then of course I can do</p>
<pre><code>public static AddStudent(Student s)
{
// call the instance method
s.Validate();
}
</code></pre>
<p>Now, I'd like to keep things very simple, so I <strong>don't want</strong> to go any one of the following approaches</p>
<ol>
<li><p>Use attributes on properties, like [StringLength(25)]. </p>
<p>One, because this requires reflection and affects performance, there are tricks to get performance hit low, but again I want to keep it simpler the better. </p>
<p>Two, I want my site to be able to run in Medium Trust. As reflection as I understand it requires Full Trust.</p></li>
<li><p>Use any of the validation blocks out there, like MS. Enterprise Library etc found on CodePlex.</p></li>
</ol>
<p>Now, I want to get your opinion on this, </p>
<p>what are some of the potential problems with the approach I'm going with?<br>
Would this approach perform better, more readable, easier to maintain than the other approaches? </p>
<p>How are you doing validation on your middle tier?</p>
<p>Thank a bunch!</p>
<p>Ray. </p>
|
<p>I perform domain validation in the middle tier with a rules engine, very similar to the one <a href="http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx" rel="nofollow noreferrer">written about here</a>. A friend's project uses an approach similar to what you're proposing in your latter example and the end result is unmaintainable (brittle, hard to implement generic validation UIs). The rules engine approach is maintainable because it localizes all the validation and persistence rules in a single well organized location AND has each rule as a fully fledged class - but exposes the validation on domain classes similar to what you have proposed. Some people like dynamically compiling so they store them in a database for a high level of post-deployment configuration; in my case I like them compile time checked so there are rule definitions with lambdas exposed on a static class.</p>
<p>I know this isn't in line with what you want to do, but asking how I would do it and saying other approaches aren't simple enough would be like saying "how can you write reliable code, I want to keep it simple so unit tests are out of the question." To me treating each rule as its own class is good because its easier to maintain and document albeit more complex to implement.</p>
|
<p>Option two is something that doesn't actually enforce validation, at least not without you manually calling validate. Therefore consumers of your objects could violate the rules.</p>
<p>I personally would go with something similar to your first example, as it ensures that ALL data is valid. it is an additional check on the DB side of things, but from what i have noticed, typically isn't a big deal.</p>
| 31,274
|
<p>This is printing PETG extruding at 250 °C, 1st layer bed at 80 °C then 60 °C on other layers. Nozzle is 0.4 mm; printer is German Reprap X400. The all metal extruder is clean with no oozing. The print gets a blob when the wall width changes from 2 mm to 1 mm. The extruder squishes the blob out the sides of the wall with subsequent layers. Images below show both sides of wall. I'm looking for the cause to come up with a fix. I consistently get the same results in the same location when printing this file. The reduced area of the layer does cause reduced speed to increase the print time for the layer (speed reduced when layer would print in less than 30 seconds; minimum speed 15 mm/s).</p>
<p>When I printed two, there was only one blob on one of two. Below shows the speed settings. The perimeters are three vertical shells, so the walls are all perimeters. My understanding of the setting is the 2 mm wall printed at 20 mm/s and the 1 mm wall at 15 mm/s.</p>
<p>Printing similarly with 2 mm walls only and the same settings, the print is nearly perfect with only a few stringers. Printing with only 1 mm walls does not have the blob, but does have stringers.</p>
<p>See solution at the end.</p>
<p></p>
<p><a href="https://i.stack.imgur.com/T0WBA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T0WBA.jpg" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/xDyNO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xDyNO.jpg" alt="enter image description here" /></a></p>
<p><strong>Solution:</strong></p>
<p>Speeding up the print speeds and using thicker walls not only eliminated the blogs, but also completely eliminated stringers, and gave a near perfect print. Apparently, the actual temperature that PETG extrudes is highly dependent on how fast it extrudes. Printing too fast clogs the nozzle because the filament doesn't have time to melt. Printing too slow causes the hotend to stop extruding from heat creep. Here, the actual temperature of the extruded PETG was decreased by speeding up the extrusion.</p>
<p><a href="https://i.stack.imgur.com/7STxh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7STxh.png" alt="enter image description here" /></a>s://i.stack.imgur.com/Uhv61.png</p>
|
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p>
<p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p>
<p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
|
<p>If you use a build surface such as PEI, acetone frosts your surface, leaving a white film appearance. If you have no additional surface on a glass or metal bed, it is incomplete cleaning. If incomplete cleaning, you could try isopropyl alcohol (IPA) immediately after acetone, followed immediately by a water based cleaner or DI/distilled water. (IPA dissolves acetone and water dissolves IPA. Once the film dries the next step may not work.)</p>
<p>You can't clean off a frosted surface. The black surface of the hot bed in images of the CR-10S Pro appears to indicate that the steel bed has a build surface with a plastic material such as PEI. Reviews of the build surface being difficult to remove prints also implies a plastic build surface on the steel. Thus, it appears that the white film after cleaning with acetone is actually a frosted surface.</p>
<p>If you use an Elmer's washable glue stick or one with PWP, it will form a barrier between your print and the build surface, that not only will protect your build surface, but will make it easier to clean your build surface with IPA or water based cleaners.</p>
| 1,870
|
<p>I have a SSRS 2005 report that has a number of images in it. The way that I have the images included is I have an image object with the URL set in the value property. The actual images are hosted by an IIS virtual directory on the same server. I'm doing it this way because I need to dynamically change the image source using an expression depending on the data within the report. </p>
<p>The problem is that the images work great when previewing the report in Visual Studio but do not display when the report is deployed. When I look at the HTML rendered by SSRS the SRC attribute of the image tag is an empty string.</p>
|
<p>I have had this problem before.</p>
<p>You should check to see if you have any warnings being thrown when you deploy the reports. A rsWarningFetchingExternalImages warning means that reporting services is having problems anonymously accessing the images. This could be because anonymous access is not properly configured in IIS or, as in my case, you could possibly have a problem with the MIME type for the image you're hosting. I was trying to host PNG files and it worked when I changed the images to GIFs.</p>
|
<p>I am by no means an IIS expert, that's why I just gave up and went with converting to GIF files, but from the research I did before giving up, I can tell you that not all versions of IIS support the PNG MIME type by default. I have tried following the directions at <a href="http://www.hostmysite.com/support/dedicated/IIS/newmime/" rel="nofollow noreferrer">http://www.hostmysite.com/support/dedicated/IIS/newmime/</a> to add the PNG MIME Type to my virtual directory, but it didn't work for me. (Remember to redeploy after trying this, as I think this is when RS reconciles the image URLs) Perhaps someone with more knowledge on MIME Types is IIS might have some input.</p>
| 35,608
|
<p>What exactly is the purpose of the 'obj' directory in .NET?</p>
|
<p>The <strong>"obj" folder</strong> is used to store temporary object files and other files used in order to create the final binary during the compilation process.</p>
<p>The <strong>"bin" folder</strong> is the output folder for complete binaries (assemblies).</p>
|
<p>In addition to <a href="https://stackoverflow.com/questions/233081/whats-the-obj-directory-for-in-net#233085">splattne's answer</a>, I believe the <em>reason</em> for having it (and not cleaning it up after the build) is to support incremental compilation. If you've already compiled 100 classes and change one of them, it's much more efficient to just recompile the code for the one changed class and reassemble the exe/dll from a mixture of the new and old code.</p>
<p>Of course, incremental compilation is a lot more complex than just that - it has to keep track of everything so it can detect when it needs to recompile a class even if that class itself hasn't changed. (e.g. if a new overload becomes available in a class - some callers may need to be recompiled.)</p>
| 28,848
|
<p>I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:</p>
<pre><code>DOMAIN\USER
DOMAIN\GROUP
</code></pre>
<p>I have a list of users in active directory format that I need to add:</p>
<pre><code>ou=group1;ou=group2;ou=group3
</code></pre>
<p>I have tried adding DOMAIN\Group1, but I get a 'user not found' error.</p>
<p>P.S. should also be noted that I'm not a Lan admin </p>
|
<p>Programatically or Manually?</p>
<p>Manually, i prefer <a href="http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx" rel="noreferrer">AdExplorer</a>, which is a nice Active directory Browser. You just connect to your domain controller and then you can look for the user and see all the details. Of course, you need permissions on the Domain Controller, not sure which though.</p>
<p>Programatically, it depends on your language of couse. On .net, the <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx" rel="noreferrer">System.DirectoryServices</a> Namespace is your friend. (I don't have any code examples here unfortunately)</p>
<p>For Active Directory, I'm not really an expert apart from how to query it, but here are two links I found useful:</p>
<p><a href="http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm" rel="noreferrer">http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm</a></p>
<p><a href="http://en.wikipedia.org/wiki/Active_Directory" rel="noreferrer">http://en.wikipedia.org/wiki/Active_Directory</a> (General stuff about the Structure of AD)</p>
|
<p>OU is an Organizational Unit (sort of like a Subfolder in Explorer), not a Group, Hence group1, 2 and 3 are not actually groups.</p>
<p>You are looking for the DN Attribute, also called "distinguishedName". You can simply use DOMAIN\DN once you have that.</p>
<p>Edit: For groups, the CN (Common Name) could also work. </p>
<p>The full string from Active Directory normally looks like this:</p>
<blockquote>
<p>cn=Username,cn=Users,dc=DomainName,dc=com</p>
</blockquote>
<p>(Can be longer or shorter, but the important bit is that the "ou" part is worthless for what you're trying to achieve.</p>
| 4,351
|
<p>In my <code>urls.py</code> file, I have:</p>
<pre><code>from myapp import views
...
(r'^categories/$', views.categories)
</code></pre>
<p>Where <code>categories</code> is a view function inside <code>myapp/views.py</code>. No other URLconf lines reference <code>views.categories</code>.</p>
<p>In a unit test file, I’m trying to grab this URL using <code>django.core.urlresolvers.reverse()</code>, instead of just copying '/categories/' (DRY and all that). So, I have:</p>
<pre><code>from django.core.urlresolvers import reverse
from myapp import views
...
url = reverse(views.categories)
</code></pre>
<p>When I run my tests, I get a <code>NoReverseMatch</code> error:</p>
<pre><code>NoReverseMatch: Reverse for '<function categories at 0x1082f30>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>It matches just fine if I make the URL pattern a named pattern, like this:</p>
<pre><code>url(r'^categories/$', views.categories, 'myapp-categories')
</code></pre>
<p>And use the pattern name to match it:</p>
<pre><code>url = reverse('myapp-categories')
</code></pre>
<p>But as far as I can tell from <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse" rel="noreferrer">the <code>reverse</code> documentation</a>, I shouldn’t need to make it a named URL pattern just to use <code>reverse</code>.</p>
<p>Any ideas what I’m doing wrong?</p>
|
<p>After futher investigation, turns out it was an issue with how I was importing the views module:</p>
<p><a href="https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function">How do I successfully pass a function reference to Django’s reverse() function?</a></p>
<p>Thanks for the help though, guys: you inspired me to look at it properly.</p>
|
<p>The reverse function actually uses the "name" of the URL. This is defined like so:</p>
<pre><code>urlpatterns = patterns('',
(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
(r'^admin/(.*)', admin.site.root),
)
</code></pre>
<p>Now you would call reverse with the string "no-monkeys" to get the correct url.</p>
<p>Ninja Edit: <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#id2" rel="nofollow noreferrer">Here is a link</a> to the django docs on the subject.</p>
| 16,298
|
<p>I was curious if anyone had any problems creating unit tests around using the ResourceManager. I am using Visual Studio test edition and it appears that the satellite assemblies don't get loaded during the test. When I try to get a resource for another culture, the test always fails and the resource manager always falls back to the default culture. The exact same code runs fine within the normal application.</p>
|
<p>That got me going in the right direction. Adding the files to the deployment config didn't help, but disabling deployment did work.</p>
<p>For future reference, Visit <a href="http://stephenwalther.com/blog/archive/2008/03/20/tdd-test-driven-development-with-visual-studio-2008-unit-tests.aspx" rel="nofollow noreferrer">this blog post</a> and scroll down to the section "Managing Test Runs" for details of creating a test configuration and how to disable the deployment</p>
|
<p>I've had similar problems in the past with satellite assemblies. Try
adding the satellite assemblies to the unit projects dependecies. In Visual Studio
Test -- Edit Test Run configuration. Select Deployment and add the files
here.</p>
<p>On executing all applications, dlls, etc are copied to a special directory.
Strong named dll's may be ignored as these are expected to be in the GAC.</p>
| 12,485
|
<p>I'm trying to use the <code>this</code> keyword in a static method, but the compiler won't allow me to use it.</p>
<p>Why not?</p>
|
<p>That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more <a href="http://msdn.microsoft.com/en-us/library/98f28cdx(printer).aspx" rel="noreferrer">in depth explanation</a> of what static members are and why/when to use them in the MSDN docs.</p>
|
<p>There is no <code>this</code> object reference in the static method.</p>
| 16,250
|
<p>In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated.</p>
<p>What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value?</p>
|
<p>In later versions of MySQL you can use the <code>information_schema</code> database to tell you when another table was updated:</p>
<pre><code>SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME = 'tabname'
</code></pre>
<p>This does of course mean opening a connection to the database.</p>
<hr>
<p>An alternative option would be to "touch" a particular file whenever the MySQL table is updated:</p>
<p>On database updates:</p>
<ul>
<li>Open your timestamp file in <code>O_RDRW</code> mode</li>
<li><code>close</code> it again</li>
</ul>
<p>or alternatively</p>
<ul>
<li>use <a href="http://us3.php.net/manual/en/function.touch.php" rel="noreferrer"><code>touch()</code></a>, the PHP equivalent of the <code>utimes()</code> function, to change the file timestamp.</li>
</ul>
<p>On page display:</p>
<ul>
<li>use <code>stat()</code> to read back the file modification time.</li>
</ul>
|
<p>Cache the query in a global variable when it is not available.</p>
<p>Create a webpage to force the cache to be reloaded when you update it.</p>
<p>Add a call to the reloading page into your deployment scripts.</p>
| 39,568
|
<p>Using subversion 1.5 I have branch B which was branched off of branch A. After doing work in both branches I go to merge changes from A into B (using <code>svn merge http://path/to/A</code> in the working directory of B) and get <code>svn: Target path does not exist</code>. What does this mean?</p>
|
<p>It means that there was a change in a file in branch A which Subversion tried to merge into branch B, but the file does not exist in branch B, so it has nowhere to merge the change. For example:</p>
<ul>
<li>Create branch B</li>
<li>Change A/README</li>
<li>Delete B/README</li>
<li>Merge A -> B</li>
</ul>
<p>Now the change in README cannot be applied in branch B, because the file has been removed there.</p>
<p>EDIT: This will result in a <strong>tree conflict</strong> in Subversion 1.6.</p>
|
<p>I was getting this error with svn 1.5.4 even when there were no incompatible changes. Upgrading to 1.5.5 fixed it for me.</p>
| 26,143
|
<p>I am using Borland Builder C++. I have a memory leak and I know it must be because of this class I created, but I am not sure how to fix it. Please look at my code-- any ideas would be greatly appreciated!</p>
<p>Here's the .h file:</p>
<pre><code>#ifndef HeaderH
#define HeaderH
#include <vcl.h>
#include <string>
using std::string;
class Header {
public:
//File Header
char FileTitle[31];
char OriginatorName[16];
//Image Header
char ImageDateTime[15];
char ImageCordsRep[2];
char ImageGeoLocation[61];
NitfHeader(double latitude, double longitude, double altitude, double heading);
~NitfHeader();
void SetHeader(char * date, char * time, double location[4][2]);
private:
void ConvertToDegMinSec (double angle, AnsiString & s, bool IsLongitude);
AnsiString ImageDate;
AnsiString ImageTime;
AnsiString Latitude_d;
AnsiString Longitude_d;
double Latitude;
double Longitude;
double Heading;
double Altitude;
};
</code></pre>
<p>And here is some of the .cpp file:</p>
<pre><code>void Header::SetHeader(char * date, char * time, double location[4][2]){
//File Header
strcpy(FileTitle,"Cannon Powershot A640");
strcpy(OperatorName,"Camera Operator");
//Image Header
//Image Date and Time
ImageDate = AnsiString(date);
ImageTime = AnsiString(time);
AnsiString secstr = AnsiString(ImageTime.SubString(7,2));
AnsiString rounder = AnsiString(ImageDate.SubString(10,1));
int seconds = secstr.ToInt();
//Round off seconds - will this be necessary with format hh:mm:ss in text file?
if (rounder.ToInt() > 4) {
seconds++;
}
AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2)
+ ImageTime.SubString(4,2) + AnsiString(seconds);
strcpy(ImageDateTime,dateTime.c_str());
//Image Coordinates Representation
strcpy(ImageCordsRep,"G");
//Image Geographic Location
AnsiString lat;
AnsiString lon;
AnsiString locationlat_d;
AnsiString locationlon_d;
AnsiString corner;
for (int i = 0; i < 4; i++){
ConvertToDegMinSec(location[i][0],lat,false);
ConvertToDegMinSec(location[i][1],lon,true);
if(location[i][0] < 0){
locationlat_d = 'S';
ConvertToDegMinSec(-location[i][0],lat,false);
}else if(location[i][0] > 0){
locationlat_d = 'N';
}else locationlat_d = ' ';
if(location[i][1] < 0){
locationlon_d = 'W';
ConvertToDegMinSec(-location[i][1],lon,true);
}else if(location[i][1] > 0){
locationlon_d = 'E';
}else locationlon_d = ' ';
corner += lat + locationlat_d + lon + locationlon_d;
}
strcpy(ImageGeoLocation,corner.c_str());
}
</code></pre>
<p>Now when I use the class in main, basically I just create a pointer:</p>
<pre><code>Header * header = new Header;
header->SetHeader(t[5],t[6],corners->location);
char * imageLocation = header->ImageGeoLocation;
//do something with imageLocation
delete header;
</code></pre>
<p>Where corners->location is a string from another class, and t[5] and t[6] are both strings. The problem is that imageLocation doesn't contain what is expected, and often just garbage. I have read a lot about memory leaks and pointers, but I am still very new to programming and some of it is quite confusing. Any suggestions would be fabulous!!</p>
|
<p>I'm afraid there are a number of issues here.</p>
<p>For starters <code>char ImageCordsRep[1];</code> doesn't work ... a string is always null terminated, so when you do <code>strcpy(ImageCordsRep,"G");</code> you are overflowing the buffer.</p>
<p>It would also be good practice to terminate all those string buffers with a null in your constructor, so they are always valid strings.</p>
<p>Even better would be to use a string class instead of the char arrays, or at least use 'strncpy' to prevent buffer overruns if the incoming strings are larger than you expect.</p>
|
<p>Something else...</p>
<p>Be careful not to use imageLocation after the header object is deleted. It's often better to copy the string from the object instead of getting a pointer to it. It could be OK in this case depending on the rest of the code.</p>
<pre><code>Header * header = new Header;
header->SetHeader(t[5],t[6],corners->location);
char * imageLocation = header->ImageGeoLocation;
</code></pre>
| 19,756
|
<p>I would guess most people on this site are familiar with tail, if not - it provides a "follow" mode that as text is appended to the file tail will dump those characters out to the terminal.</p>
<p>What I am looking for (and possibly to write myself if necessary) is a version of tail that works on binary files. Basically I have a wireless link that I would like to trickle a file across as it comes down from another network link. Looking over the tail source code it wouldn't be too hard to rewrite, but I would rather not reinvent the wheel! This wouldn't strictly be "tail" as I would like the entire file to be copied, but it would watch as new bytes were added and stream those.</p>
<p>Ideas?</p>
|
<p>Pipe it to hexdump:</p>
<pre><code>tail -f somefile | hexdump -C
</code></pre>
|
<p>This isn't tail -- this is progressively copying a file. Look at rsync.</p>
| 28,740
|
<p>The question should be interpreted from a general point of view and not targeted solely at web apps or desktop apps.</p>
<p>I have been looking around to find a simple and easy way of creating interactive prototypes for web applications. I'd like to use a technique that allows simple UI creation and especially UI recreation and modification in further iterations. Filling the UI with mockup data should be very simple. The technique may require a simple form of programming, e.g. to specify a drag and drop behaviour from UI element A to UI element B.</p>
<p>One tool i currently use is the Adobe Flex Builder. The included GUI-designer is very good and i have accomplished some skills with AS3 so far. The problem is adding data to the UI. It always results in me programming code for checking and parsing of XML-trees structures, and mainly debugging this section of the prototype. Too cumbersome!</p>
<p>Another tool many people use is PowerPoint which involves a really cumbersome way of creating a GUI by drawing every part of an interaction in a separate slide. No way! I would be much faster with paper prototypes. Other (better!) free form drawing tools are also part of this category (i'm a happy heavy weight inkscape user) but Prototyping and Mockup are obviously not their main purpose. The UI-stencil palette for Viso makes it a bit better than the drawing competition.</p>
<p>The main competitors in rapid prototyping as far i know are:</p>
<ul>
<li>iRise</li>
<li>Axure</li>
<li>Serena and other ?</li>
<li>Viso</li>
<li>Powerpoint, Illustrator, Inkscape or any other free form drawing tool</li>
<li>paper prototyping</li>
<li>IDE with good GUI builders (such as Flex Builder Designer and Netbeans Matisse)</li>
</ul>
<p>My opinion is that real GUI-builders are a good staring point. What are your current approaches? Please outline your process and the pros and cons as an answer here.</p>
|
<p>Real GUI builders are:</p>
<ul>
<li>Much slower</li>
<li>Only programmers can use them (try to explain to analyst how to populate a table in VB)</li>
<li>They don't let you annotate your mockups on the fly</li>
<li>Don't have skins (e.g. black&white) to create screens which can't be mistaken for "almost done" application</li>
</ul>
<p>While specialized mockup tools are usually:</p>
<ul>
<li>Communication oriented</li>
<li>Can print or export your mockups (together with your notes) to PDF/HTML/Word etc</li>
<li>Better ones have some variant of "master screens" so you can derive hundreds of mockups from only a handful of main application screens (you quickly get to quite a lot of mockups when you try to discuss real scenarios with your client)</li>
<li>Fast enough so you can prototype realtime in a meeting</li>
</ul>
<p>Almost a decade ago I got frustrated by all of the above and created my own tool: <a href="http://MockupScreens.com" rel="nofollow">MockupScreens</a>. It became pretty popular quickly :-)</p>
<p>And here is the most complete list of such specialized tools I know of. Many of those are free: <a href="http://c2.com/cgi/wiki?GuiPrototypingTools" rel="nofollow">http://c2.com/cgi/wiki?GuiPrototypingTools</a></p>
|
<p>Expression Blend (<a href="http://www.microsoft.com/expression/products/overview.aspx?key=blend" rel="nofollow noreferrer">http://www.microsoft.com/expression/products/overview.aspx?key=blend</a>) can be used to create quick mockups in XAML. You can store data for the mockup as inline XML in the XAML, or you can quickly convert it to WPF/Silverlight application and build basic business logic behind your mockup using Visual C# Express (<a href="http://www.microsoft.com/express/vcsharp/" rel="nofollow noreferrer">http://www.microsoft.com/express/vcsharp/</a>) or Visual Studio 2008.</p>
| 16,879
|
<p>Obviously, that's 64-bit windows.</p>
<p>Also, what's the maximum amount of memory a single 64-bit process can use?
I was kind of counting on using it all...
(Yes, I know what I'm doing, please don't tell me that if I need that much RAM i must be doing something wrong)</p>
<p>Also, is this the same for a .Net 2.0 process? Or is there a lower limit for .Net?</p>
|
<p>What version of windows? it differs from XP to vista and from home to business versions of vista, and I would guess again for server.</p>
<p>see <a href="http://msdn.microsoft.com/en-us/library/aa366778.aspx" rel="nofollow noreferrer">here for more info on maximum ram for diffrent windows versions</a></p>
<p>for Windows Server 2008 Datacenter MS quote 2 TB of physical memory.</p>
|
<p>Something we found out recently: with MySQL running on Win32, you can only use up to 2GB per process. On Win64, the memory is not managed as well and a single MySQL instance will run your memory into the ground. Ours used up all 16GB we have. So regarding how much memory 1 64-bit process can use: the answer is however much the OS allows.</p>
| 5,370
|
<p>Ok, so we have clients and those clients get to customize their web facing page. One option we are giving them is to be able to change the color of a graphic (it's like a framish-looking bar) using one of those hex wheels or whatever. </p>
<p>So, I've thought about it, and I don't know where to start. I am sending comps out this week to my xhtml guy and I want to have the implementation done at least in my mind before I send things out. </p>
<p>Something about System.Drawing sounds about right, but I've never worked with that before and it sounds hella complicated. Does anyone have an idea? </p>
<p><strong>UPDATE:</strong> The color of an image will be changing. So if I want image 1 to be green, and image 2 to be blue, I go into my admin screen and enter those hex values (probably will give them an interface for it) and then when someone else looks at their page they will see the changes they made. Kind of like customizing a facebook or myspace page (OMFGz soooo Werb 2.0)</p>
|
<p>I'm sort of intuiting that you'll have a black on white bitmap that you use as the base image. The client can then select any other color combination. This may not be exactly your situation, but it should get us started. (The code below is VB -- it's what I know, but converting to C# should be trivial for you.)</p>
<pre><code>Imports System.Drawing
Private Function createImage(ByVal srcPath As String, ByVal fg As Color, ByVal bg As Color) As Bitmap
Dim img As New Bitmap(srcPath)
For x As Int16 = 0 To img.Width
For y As Int16 = 0 To img.Height
If img.GetPixel(x, y) = Color.Black Then
img.SetPixel(x, y, fg)
Else
img.SetPixel(x, y, bg)
End If
Next
Next
Return img
End Function
</code></pre>
<p>And then you can do whatever with the image...</p>
|
<p>I've done stuff like this in PHP before, and I used ImageMagick and GD libraries. I'm not sure if ASP and C# can plug into that using the .NET framework, but it's a start.</p>
| 14,790
|
<p>I'm trying to use <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">Jeditable</a> as an inline editing solution.</p>
<p>The default behavior (click on the element to edit it) works quite well, but I would like to activate an element by clicking on another element.</p>
<p>For example clicking on a.activateEdit will activate the next div.edit (obviously should be done using jQuery selectors).</p>
<p>I've looked into Jeditable docs for this, but couldn't find the right syntax</p>
<p>FYI, the default Jeditable syntax is something along the lines of:</p>
<pre><code> $(document).ready(function() {
$('.edit').editable('http://www.example.com/save.php');
});
</code></pre>
<p><strong>*Edit: found <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/33c18dcf32276c89/7711363c7496fcb3?hide_quotes=no" rel="nofollow noreferrer">a better solution</a> *</strong></p>
|
<p>Above code is not quite correct either. It triggers click event on ALL Jeditable instances.</p>
<p>There are many ways to do it and it all depends on your HTML, but for example if you have following HTML:</p>
<pre><code><div class="edit" id="unique_id">Editable text</div>
<a href="#" class="edit_trigger">Edit me!!</a>
</code></pre>
<p>Then you can use following JavaScript:</p>
<pre><code>/* Bind Jeditable instances to "edit" event. */
$(".edit").editable("http://www.example.com/save.php", {
event : "edit"
});
/* Find and trigger "edit" event on correct Jeditable instance. */
$(".edit_trigger").bind("click", function() {
$(this).prev().trigger("edit");
});
</code></pre>
|
<p>I've combined the powers of the previous two responses to target the next editable element like so:</p>
<p><code>
/* Find and trigger "edit" event on next Jeditable instance. */
$(".edit_trigger").livequery( 'click', function() {
$(this).next().click();
});
</code></p>
| 47,844
|
<p>I'm getting an error compiling my VSTO (Visual Studio Tools for Office) project in VS.</p>
<p>It says <strong>"Value does not fall within the expected range."</strong> and <strong>"There was an error during installation"</strong></p>
|
<p>Gotcha. The <strong>path</strong> of my project was <strong>too deep.</strong> </p>
<p><strong>Ans:</strong> Move it a few folders above <em>(in the Windows Explorer folder tree)</em> and try <strong>re-building</strong>/ re-running again.</p>
|
<p>I got the same problem before when I tied to install the <code>vsto</code> with the <code>vsto</code> file.</p>
<p>Publish your application and install the setup and the problem disappeared.</p>
<p>To publishing => <em>Project Properties / Publish / Select Folder Path / Publish Now</em></p>
| 44,030
|
<p>I've created some MbUnit Test Fixtures that have SetUp methods marked with the SetUp attribute. These methods run before the tests just fine using the MbUnit GUI, the console runner, and the ReSharper MbUnit plugin. However, when I run the tests with TestDriven.NET it does not run the SetUp methods at all. </p>
<p>Does anyone know if this is a bug with TestDriven.NET or if I have something setup wrong?</p>
|
<p>No longer an issue with recent versions of Gallio since v3.0.4. Just make sure to use the 64-bit installer.</p>
|
<p>I came across a similar issue with NUnit and TestDriven.NET that took me hours to figure out.
I installed the Visual Studio Extension below and it hit breakpoint in the Tests but skipped the one in the one in the [TestFixtureSetUp].</p>
<p><a href="https://i.stack.imgur.com/sl5xw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sl5xw.png" alt="enter image description here"></a></p>
<p>It turned out that I also needed the actual TestDriven.NET software to be installed at C:\Program Files (x86)\TestDriven.NET 4</p>
<p>This is available from <a href="https://www.testdriven.net/download.aspx" rel="nofollow noreferrer">https://www.testdriven.net/download.aspx</a></p>
| 2,601
|
<p>I'm modifying some code in which the original author built a web page by using an array thusly:</p>
<pre><code> $output[]=$stuff_from_database;
$output[]='more stuff';
// etc
echo join('',$output);
</code></pre>
<p>Can anyone think of a reason why this would be preferable (or vice versa) to:</p>
<pre><code> $output =$stuff_from_database;
$output .='more stuff';
// etc
echo $output;
</code></pre>
|
<p>It was probably written by someone who comes from a language where strings are immutable and thus concatenation is expensive. PHP is not one of them as the following tests show. So the second approach is performance wise, better. The only other reason that I can think of to use the first approach is to be able to replace some part of the array with another, but that means to keep track of the indexes, which is not specified.</p>
<pre><code>~$ cat join.php
<?php
for ($i=0;$i<50000;$i++) {
$output[] = "HI $i\n";
}
echo join('',$output);
?>
~$ time for i in `seq 100`; do php join.php >> outjoin ; done
real 0m19.145s
user 0m12.045s
sys 0m3.216s
~$ cat dot.php
<?php
for ($i=0;$i<50000;$i++) {
$output.= "HI $i\n";
}
echo $output;
?>
~$ time for i in `seq 100`; do php dot.php >> outdot ; done
real 0m15.530s
user 0m8.985s
sys 0m2.260s
</code></pre>
|
<p>The bottom will reallocate the $output string repeatedly, whereas I believe the top will just store each piece in an array, and then join them all at the end. The original example may end up being faster as a result. If this isn't performance sensitive, then I would probably append, not join.</p>
| 13,641
|
<p>My application caches some data on disk. Because the cache may be large, it should not be stored on a network drive. It should persist between invocations of the application. I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.</p>
<p>What is the appropriate location for such a cache? Is there an API for determining the appropriate location? How do I call it from Python?</p>
|
<p>Have a look here: <a href="http://en.wikipedia.org/wiki/Environment_variable#User_management_variables" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Environment_variable#User_management_variables</a>. Anything that's under the users directory is good. If its for all users, then it should be: %ALLUSERSPROFILE%. If its for a specific user, make sure the permissions are right.</p>
<p>Check out MSDN for more info about other Windows Versions. Environment variables can vary from systems to systems.</p>
|
<p>Does the app have any preferences, settings or options that the user can specify? If so, add an option where the user can specify the location of the data, with a default of the current Windows temp directory.</p>
<p>There's always a chance they may not have enough space on the drive with the temp directory, and would need to use a different drive/directory.</p>
| 39,320
|
<p>I’m developing a website of a client and they are sending out newsletters to their customers (through the website administration interface)
The newsletters are personal to each of the subscribed recipients/customers.
Each recipient/ customer is also a user with a username/password that enables them to sign in on the website and manage their newsletter subscriptions and participate in the sites community.</p>
<p>This all works like a charm.
Now my client want a “Manage my subscriptions” link in the newsletter email that when pressed automatically signs the recipient/customer in on the website with no need to remember username and password.</p>
<p>This could be easily solved be making a link like this: </p>
<p><a href="http://mysite.com/manage.aspx?user=peter&password=hounddog" rel="nofollow noreferrer">http://mysite.com/manage.aspx?user=peter&password=hounddog</a></p>
<p>Of course information should not be clear text but encrypted in some way.</p>
<p>This however poses a problem since the only way a user can be authenticated on the website if by providing a valid username and password.
In the name of security, passwords are stored as hashed values in the database making it impossible for me to insert the password in the link.</p>
<p>What is the best way to accomplish this without compromising the security?</p>
|
<p>You <em>will</em> have to compromise your security somewhat, if you want people to be able to login without entering password. Note that even if you had access to the password (as in your example), you would have to embed it in a mail massage which would be transmitted in plaintext.</p>
<p>You can create a Guid associated with each user and message, and append it to the URL, and allow that to login automatically. </p>
<p>You could perhaps isolate the permissions so that a login through a newsletter guid link <em>only</em> allows the user to manage subscriptions, but that a real password-login is still required to participate in the forum. In that case its pretty limited what havoc can be wrecked if someone gets access to a Guid from a mail message.</p>
|
<p>What about using an encrypted cookie that contains an access token ?
This cookie would be delivered after a successfull authentication by a separate page.</p>
<p>This kind of token can also be part of the URL query string.</p>
<p>Also you might consider using secured https instead of http.</p>
| 21,479
|
<p>I am reading about COFF file formats, which is commonly used to create an executable file format (it has some variants also). </p>
<p>While reading, I came across the relocation section of the format. How is this relocation section used to create an executable file.</p>
<p>It would be very useful if you point me to some links which will help me.</p>
|
<p>Relocation is used to place executable code in its own memory space in a process. For example, if you try to load two dlls that both request the same base address (ie, the same place in memory), then one of the dlls will have to be relocated to another address.
<a href="http://www.ntcore.com/" rel="nofollow noreferrer">NTCore</a> is a useful site for exploring Portable Executable (PE) files, which is what COFF is now called. <a href="http://www.cim.mcgill.ca/~franco/OpSys-304-427/lecture-notes/node36.html" rel="nofollow noreferrer">Here</a> is another site that explains relocation pretty well.</p>
|
<p>An unintended addition use of relocation is (de-)obfuscating binaries at run time with no additional unpacking code. See <a href="http://www.uninformed.org/?v=6&a=3&t=pdf" rel="nofollow noreferrer">this paper</a>.</p>
| 11,876
|
<p>Our software manages a lot of data feeds from various sources: real time replicated databases, files FTPed automatically, scheduled running of database stored procedures to cache snapshots of data from linked servers and numerous other methods of acquiring data. </p>
<p>We need to verify and validate this data: </p>
<ul>
<li>has an import even happened</li>
<li>is the data reasonable (null values, number of rows, etc.) </li>
<li>does the data reconcile with other values (perhaps we have multiple sources for similar data) </li>
<li>is it out of data and the import needs manually prompting</li>
</ul>
<p>In many ways this is like Unit Testing: there are many types of check to make, just add a new check to the list and just re-run each class of test in response to a particular event. There are already nice GUIs for running tests, perhaps even being able to schedule them. </p>
<p>Is this a good approach? Are there better, similarly generalised, patterns for data validation? </p>
<p>We're a .NET shop, would Windows Workflow (WF) be a better more flexible solution? </p>
|
<p>Unit testing is not analogous to what you need to do. Its more along the lines of integration testing or acceptance testing. But that's beside the point.</p>
<p>Your system has a heavy requirement for validation of data coming into the system. Data comes into the system by various means, and I would assume it needs to be verified in different ways.</p>
<p>Workflow is good for designing and controlling business processes (logic) that are apt to change or require human intervention. It is agnostic when it comes to the subject of validation. However, hosting your validation process as a workflow may be a good idea, as workflows are designed to be flexible, long living and capable of human intervention. Hosting your validation process within a workflow state machine framework would allow you to define validation strategies for different types of data import at runtime. </p>
<p>You need to design a validation framework that relies heavily on composition over inheritance for its logic. Break apart all the different ways that data can be imported into the system and validated into atomic steps. Group those steps by responsibility and create interfaces with the barest, most minimum properties and methods required for an implementing object to perform each. Create base classes that are composed of these different interfaces. From this framework you can mix and match implementations that suit the particular import or validation step.</p>
<p>One last thing. Workflows are serialized to xaml for long term storage. Your classes should be xaml serializable as well to make the transition from activity to repository and back again as smooth and simple as possible.</p>
|
<p>Testing this data for validity seems reasonable. You may or may not call it Unit Testing, that's your choice. I wouldn't. Use the tool you find best for this job - I don't know what do you mean by WF (WebForms?).</p>
<p>The most benefit you get by testing this <strong>automatically.</strong> Whatever is automatic and works for you, is good.</p>
| 15,353
|
<p>I was always wondering about this seemingly utopic world of open source.</p>
<p>Assuming the vast majority of users here are professional software engineers which need some sort of income source, I assume most of us hold stable, money-making jobs.</p>
<p>So who are the key players in the open source community? Who are the people which devote their precious time to these projects? What is their benefit? Are the majority just people who see a bug, fix it, submit, and forget about the project? Or are they people constantly involved in the process of building the product?</p>
<p>How do you find yourself contributing to open source projects?</p>
|
<p>I earn my living doing professional projects that are based on either open source frameworks or commercial products, and quite often a combination of both.</p>
<p>A lot of the commercial products I have used over the years end up being really very expensive in the end. Let's say you buy a Single-Sign-On solution for web apps. By the time you're finished with what you have to do, I and a lot of others have experienced that you end up re-implementing 2/3ds of it, and sometimes there's almost nothing left of the commercial product you thought you were going to use.</p>
<p>So the problem with buying stuff is that it never fits, and quite often the purchase decision is based upon function-matrices that compare features whilst not actually considering the suitability of those features in your own environment.</p>
<p>What I'm trying to get at is that mature organizations understand that there's no such thing as a free lunch, even after you paid for the product license. The fact that you spent $1M for a content management system does not mean you're not going to spend another $2M doing 50% planned and 50% unplanned activities related to that.</p>
<p>So we can, will and do write patches for all OSS projects we're involved with. Sometimes we rework subsystems, and most of the time we submit it back. Sometimes we decide we only want 50% of the framework and we just fork of the rest for ourself. But we still want to stay with the framework for that 50% which we use. Try doing that with a commercial product ;) In general we try to stay on the "developers " mailing list, but we seldom bother to get commit rights for the projects.</p>
|
<p>I've been working exclusively on Open Source now for three years, in addition before that I did FOSS as "hobby projects". We're using our own <a href="http://ra-ajax.org" rel="nofollow noreferrer">Ra-Ajax</a> to get consultancy gigs. This first of all makes it possible for us to create OSS which is <em>very</em> rewarding and fun! Second of all it create better tools for ourselves in addition to that we since we know the tools in and out often can charge better prices then if we were working with some "random thing" which "someone else made"...</p>
| 45,049
|
<p>I have an ASPX page that creates an XMLDocument object from SQL data and then transforms it into another XML document (RSS feed) using an XSLT file with XPathNavigator and XslCompiledTransform. Occasionally the data will contain smart quotes (\u2019) which results in an error (Unable to translate Unicode character \u2019 at index 947 to specified code page). I'm not sure how all the encoding settings work, but is there a way to prevent this without having to check for these types of characters in all the data as I'm creating the XML attributes? </p>
<p>My XSLT file looks like this...</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="iso-8859-1"/>
</code></pre>
<p>I've tried changing the xsl:output encoding to utf-8 and utf-16 but still get the same problem. Any ideas? </p>
<p>Here's my code if that helps...</p>
<pre><code>XmlDocument xdoc = new XmlDocument();
XmlNode xnode = requests.XMLNode(xdoc, imageType, Request, promotionPageId, eventPageId);
xdoc.AppendChild(xnode);
Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Type", "text/xml");
if (xsltFile != string.Empty)
{
XPathNavigator xnav = xdoc.CreateNavigator();
XslCompiledTransform xslTransform = new XslCompiledTransform();
xslTransform.Load(Server.MapPath(string.Format("~/xslt/{0}.xslt", xsltFile)));
xslTransform.OutputSettings.Encoding.
xslTransform.Transform(xnav, null, Response.OutputStream);
}
else
{
xdoc.Save(Response.OutputStream);
}
Response.End();
</code></pre>
|
<p>Your transform is working fine. The problem is that the transform is emitting a character that isn't supported by the content encoding of the output stream. Set the <code>ContentEncoding</code> on the <code>HttpResponse</code> to <code>Encoding.UTF16</code> and this problem should go away.</p>
|
<p>What's the document encoding of the input XML your XSL is working on? You should be able to set that, then the XSL will know what to expect. </p>
| 23,475
|
<p>In my program, how can I read the properties set in AssemblyInfo.cs:</p>
<pre><code>[assembly: AssemblyTitle("My Product")]
[assembly: AssemblyDescription("...")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Radeldudel inc.")]
[assembly: AssemblyProduct("My Product")]
[assembly: AssemblyCopyright("Copyright @ me 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
</code></pre>
<p>I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.</p>
|
<p>This is reasonably easy. You have to use reflection. You need an instance of Assembly that represents the assembly with the attributes you want to read. An easy way of getting this is to do:</p>
<pre><code>typeof(MyTypeInAssembly).Assembly
</code></pre>
<p>Then you can do this, for example:</p>
<pre><code>object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
AssemblyProductAttribute attribute = null;
if (attributes.Length > 0)
{
attribute = attributes[0] as AssemblyProductAttribute;
}
</code></pre>
<p>Referencing <code>attribute.Product</code> will now give you the value you passed to the attribute in your AssemblyInfo.cs. Of course, if the attribute you look for can occur more than once, you may get multiple instances in the array returned by GetCustomAttributes, but this is not usually an issue for assembly level attributes like the ones you hope to retrieve.</p>
|
<p>I use this:</p>
<pre><code>public static string Title
{
get
{
return GetCustomAttribute<AssemblyTitleAttribute>(a => a.Title);
}
}
</code></pre>
<p>for reference:</p>
<pre><code>using System;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Extensions
{
public static class AssemblyInfo
{
private static Assembly m_assembly;
static AssemblyInfo()
{
m_assembly = Assembly.GetEntryAssembly();
}
public static void Configure(Assembly ass)
{
m_assembly = ass;
}
public static T GetCustomAttribute<T>() where T : Attribute
{
object[] customAttributes = m_assembly.GetCustomAttributes(typeof(T), false);
if (customAttributes.Length != 0)
{
return (T)((object)customAttributes[0]);
}
return default(T);
}
public static string GetCustomAttribute<T>(Func<T, string> getProperty) where T : Attribute
{
T customAttribute = GetCustomAttribute<T>();
if (customAttribute != null)
{
return getProperty(customAttribute);
}
return null;
}
public static int GetCustomAttribute<T>(Func<T, int> getProperty) where T : Attribute
{
T customAttribute = GetCustomAttribute<T>();
if (customAttribute != null)
{
return getProperty(customAttribute);
}
return 0;
}
public static Version Version
{
get
{
return m_assembly.GetName().Version;
}
}
public static string Title
{
get
{
return GetCustomAttribute<AssemblyTitleAttribute>(
delegate(AssemblyTitleAttribute a)
{
return a.Title;
}
);
}
}
public static string Description
{
get
{
return GetCustomAttribute<AssemblyDescriptionAttribute>(
delegate(AssemblyDescriptionAttribute a)
{
return a.Description;
}
);
}
}
public static string Product
{
get
{
return GetCustomAttribute<AssemblyProductAttribute>(
delegate(AssemblyProductAttribute a)
{
return a.Product;
}
);
}
}
public static string Copyright
{
get
{
return GetCustomAttribute<AssemblyCopyrightAttribute>(
delegate(AssemblyCopyrightAttribute a)
{
return a.Copyright;
}
);
}
}
public static string Company
{
get
{
return GetCustomAttribute<AssemblyCompanyAttribute>(
delegate(AssemblyCompanyAttribute a)
{
return a.Company;
}
);
}
}
public static string InformationalVersion
{
get
{
return GetCustomAttribute<AssemblyInformationalVersionAttribute>(
delegate(AssemblyInformationalVersionAttribute a)
{
return a.InformationalVersion;
}
);
}
}
public static int ProductId
{
get
{
return GetCustomAttribute<AssemblyProductIdAttribute>(
delegate(AssemblyProductIdAttribute a)
{
return a.ProductId;
}
);
}
}
public static string Location
{
get
{
return m_assembly.Location;
}
}
}
}
</code></pre>
| 22,707
|
<p>Microsoft, of Cairo fame, is working on Oslo, a <a href="http://www.microsoft.com/soa/products/oslo.aspx" rel="nofollow noreferrer">new modeling platform</a>. Bob Muglia, Senior Vice President of Microsoft Server & Tools Business, states that the benefits of modeling have always been clear.</p>
<p>In simple, practical terms, what are the clear benefits that Oslo bestows upon its users?</p>
|
<p>In theory, there are a few benefits:</p>
<ul>
<li>The people with the business knowledge can create the software models so you're less likely to lose anything in translation.</li>
<li>When non-technical shareholders create models, it forces them to "think like a developer". They see that what they considered obvious and easy is actually difficult when you formalize it.</li>
<li>It's more efficient. Business people have business knowledge and technical people have technical knowledge so, why not let each group design a system in their area of expertise? No more games of telephone as business experts re-explain what they mean to a developer. Developers are no longer distracted by cryptic business needs. They can focus on the interaction between highly technical systems.</li>
</ul>
<p>In practice, it's a lot trickier:</p>
<ul>
<li>Models are hard and that's that. Just because you push model creation to a different group doesn't mean you get foolproof models. Software development is all about modeling so developers are used to it. You may actually lose efficiency as a second group comes to grips with formalizing their understanding of a business need.</li>
<li>Model driven dev is tightly linked to OO concepts. OO is good for a lot of things, but not everything. What happens if what you really need falls outside the abilities of your modeling tool?</li>
<li>In my experience, the division between business and technical people is artificial. The most effective people are technical-minded business people or business-minded technical people. They make things happen. If you separate business tasks from technical tasks, you ruin the opportunity for cross-training and cross-thinking.</li>
</ul>
|
<p>I think modeling is just about the next abstraction level. Once it is established it will lead to higher productivity.</p>
<p>MDSD Today - mostly in form of code generation - saves time. Duplicating working patterns for different parts of your software and only writing real business code manually boosts productivity a little bit, but most likely leads to better software quality and more clean architecture. </p>
| 39,782
|
<p>I'm having issues getting Firefox to update a webpage when its class is changed dynamically.</p>
<p>I'm using an HTML <code>table</code> element. When the user clicks a cell in the table header, my script toggles the class back and forth between <code>sorted_asc</code> and <code>sorted_des</code>. I have pseudo element which adds an arrow glyph (pointing up or down) depending on which class the cell currently is.</p>
<pre><code>.thead .tr .sorted_asc .cell:after {
content: ' \25B2';
}
</code></pre>
<p>The problem is, that when you click the cell header a second time, the page doesn't update the arrow... until the user mouses away from the element. I think it's a bug as it works fine in Safari, and as I don't see any <code>:hover</code> tags in my CSS or other entries that might interfere.</p>
<p>Anyone seen this before, or know how to work around the issue?</p>
|
<p>It's kind of cheesy, but since you're using javascript anyway, try this after you changed the className:</p>
<pre><code>document.body.style.display = 'none';
document.body.style.display = 'block';
</code></pre>
<p>This will re-render the layout and often solves these kind of bugs. Not always, though.</p>
|
<p>Would you be able to use different CSS to accomplish the same thing without relying on the :after pseudo-selector? You might be able to simple define a background-image which you align as needed (I assume you would want the arrow on the right hand side).</p>
<p>For example:</p>
<pre><code>.thead .tr .sorted_asc .sorted_asc {
background: url(images/down_arrow.png) no-repeat right;
}
.thead .tr .sorted_asc .sorted_des {
background: url(images/up_arrow.png) no-repeat right;
}
</code></pre>
<p>I only suggest this since I assume there isn't a specific reason why you need to use the :after pseudo-class. If you do need to use it, please update.</p>
| 47,845
|
<p>In the SSW rules to better SQL Server Database there is an example of a full database maintenance plan: <a href="http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterSQLServerDatabases.aspx#MaintenancePlan" rel="noreferrer">SSW</a>. In the example they run both a Reorganize Index and then a Rebuild Index and then Update Statistics. Is there any point to this? I thought Reorganize Index was a fast but less effective version of Rebuild Index? and that an index rebuild would also update the statistics automatically (on the clustered index at least).</p>
|
<p>Doing a <code>REORGANIZE</code> and then a <code>REBUILD</code> on the same indexes is pointless, as any changes by the <code>REORGANIZE</code> would be lost by doing the <code>REBUILD</code>.</p>
<p>Worse than that is that in the maintenance plan diagram from SSW, it performs a <code>SHRINK</code> first, which fragments the indexes as a side effect of the way it releases space. Then the <code>REBUILD</code> allocates more space to the database files again as working space during the <code>REBUILD</code> operation.</p>
<ul>
<li><p><code>REORGANIZE</code> is an online operation that defragments leaf pages in a clustered or non-clustered index page by page using little extra working space.</p></li>
<li><p><code>REBUILD</code> is an online operation in Enterprise editions, offline in other editions, and uses as much extra working space again as the index size. It creates a new copy of the index and then drops the old one, thus getting rid of fragmentation. Statistics are recomputed by default as part of this operation, but that can be disabled.</p></li>
</ul>
<p>See <a href="http://msdn.microsoft.com/en-us/library/ms189858.aspx" rel="noreferrer">Reorganizing and Rebuilding Indexes</a> for more information.</p>
<p>Don't use <code>SHRINK</code> except with the <code>TRUNCATEONLY</code> option and even then if the file will grow again then you should think hard as to whether it's necessary:</p>
<p><a href="http://www.sqlservercentral.com/articles/SHRINKFILE/71414/" rel="noreferrer">sqlservercentral_SHRINKFILE</a> </p>
|
<p>My two cents... This method follows the spec outlined on tech net: <a href="http://technet.microsoft.com/en-us/library/ms189858(v=sql.105).aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms189858(v=sql.105).aspx</a></p>
<pre><code>USE [MyDbName]
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE [maintenance].[IndexFragmentationCleanup]
AS
DECLARE @reIndexRequest VARCHAR(1000)
DECLARE reIndexList CURSOR
FOR
SELECT INDEX_PROCESS
FROM (
SELECT CASE
WHEN avg_fragmentation_in_percent BETWEEN 5
AND 30
THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REORGANIZE;'
WHEN avg_fragmentation_in_percent > 30
THEN 'ALTER INDEX [' + i.NAME + '] ON [' + t.NAME + '] REBUILD with(ONLINE=ON);'
END AS INDEX_PROCESS
,avg_fragmentation_in_percent
,t.NAME
FROM sys.dm_db_index_physical_stats(NULL, NULL, NULL, NULL, NULL) AS a
INNER JOIN sys.indexes AS i ON a.object_id = i.object_id
AND a.index_id = i.index_id
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE i.NAME IS NOT NULL
) PROCESS
WHERE PROCESS.INDEX_PROCESS IS NOT NULL
ORDER BY avg_fragmentation_in_percent DESC
OPEN reIndexList
FETCH NEXT
FROM reIndexList
INTO @reIndexRequest
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN TRY
PRINT @reIndexRequest;
EXEC (@reIndexRequest);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT @ErrorMessage = 'UNABLE TO CLEAN UP INDEX WITH: ' + @reIndexRequest + ': MESSAGE GIVEN: ' + ERROR_MESSAGE()
,@ErrorSeverity = 9
,@ErrorState = ERROR_STATE();
END CATCH;
FETCH NEXT
FROM reIndexList
INTO @reIndexRequest
END
CLOSE reIndexList;
DEALLOCATE reIndexList;
RETURN 0
GO
</code></pre>
| 2,912
|
<p>I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer:</p>
<p>1) ORM (if so, which one?)</p>
<p>2) Linq2Sql</p>
<p>3) Stored Procedures</p>
<p>4) Parametrized Queries</p>
<p>I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently.</p>
<p>Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above.</p>
|
<p>One key thing to be aware of here is that if the database schema is changing frequently, you want to have some level of compile time type safety. I've found this to be a problem with NHibernate because it uses xml mapping files so if you change something in your database schema, you don't know until runtime that the mapping is broken.</p>
<p>It will also be a problem with stored procs.</p>
<p>Using Linq2Sql will give you the advantage of knowing where exactly your code is breaking when you change a schema at compile time. This for me, is something that would take precedence over everything else if I'm working with a frequently changing schema</p>
|
<p>You're already happy with stored procs and they might be enough to abstract away the changing schema. If ORMs aren't happy with stored procs then maybe they'd work with Views that you keep current on top of the changing schema.</p>
| 3,298
|
<p>I use a <code>System.Timers.Timer</code> in my Asp.Net application and I need to use the <code>HttpServerUtility.MapPath</code> method which seems to be only available via <code>HttpContext.Current.Server.MapPath</code>.
The problem is that <code>HttpContext.Current</code> is <code>null</code> when the <code>Timer.Elapsed</code> event fires.</p>
<p>Is there another way to get a reference to a HttpServerUtility object ?
I could inject it in my class' constructor. Is it safe ? How can I be sure it won't be Garbage Collected at the end of the current request?</p>
<p>Thanks!</p>
|
<p>It's possible to use <code>HostingEnvironment.MapPath()</code> instead of <code>HttpContext.Current.Server.MapPath()</code></p>
<p>I haven't tried it yet in a thread or timer event though.</p>
<hr>
<p>Some (non viable) solutions I considered;</p>
<ul>
<li><p>The only method I care about on <code>HttpServerUtility</code> is <code>MapPath</code>. So as an alternative I could use <code>AppDomain.CurrentDomain.BaseDirectory</code> and build my paths from this. <strong>But this will fail if your app uses virtual directories</strong> (Mine does).</p></li>
<li><p>Another approach:
Add all the paths I need to the the <code>Global</code> class. Resolve these paths in <code>Application_Start</code>.</p></li>
</ul>
|
<p>I think the reason for why it is null at that time (if you think about it), is that the timer elapsed event doesn't occur as part of a HTTP request (hence there is no context). It is caused by something on your server. </p>
| 13,709
|
<p>I have an app that I've written in C#/WinForms (<a href="http://www.thekbase.com" rel="nofollow noreferrer" title="TheKBase">my little app</a>). To make it cross-platform, I'm thinking of redoing it in Adobe AIR. Are there any arguments in favor of WinForms as a cross-platform app? Is there a cross-platform future for Winforms (e.g., Mono, etc.)? Suggestions for cross-platform UI development?</p>
<p>By cross-platform I mean, currently, Mac OSX, Windows and Linux.</p>
<p>This question was <a href="https://stackoverflow.com/questions/116468/winforms-for-mono-on-mac-linux-and-pc-redux">asked again and answered with better success</a>.</p>
|
<p>As far as my experience in Flex/AIR/Flash actionscripting goes, Adobe AIR development environment and coding/debugging toolsets are far inferior to the Visual Studio and .NET SDK as of the moment. The UI toolsets are superior though.</p>
<p>But as <em>you already have a working C# code</em>, porting it to ActionScript might requires a redesign due to ActionScript having a different way of thinking/programming, they use different primitive data types, for example, they use just a <code>Number</code> instead of <code>int float double</code> etc. and the debugging tools are quiet lacking compared to VS IMO.</p>
<p>And I heard that <a href="http://www.mono-project.com/GtkSharp" rel="nofollow noreferrer">Mono's GtkSharp</a> is quiet a decent platform.</p>
<p>But if you don't mind the coding/debugging tooling problems, then AIR is a great platform. I like how Adobe integrates the Flash experience into it e.g. you can start an installation of AIR application via a button click in a flash movieclip, that kind of integration.</p>
|
<p>I don't think there is a future for WinForms at all. Since it appears to have been a stop-gap solution even in MSFT world ( a very thin wrapper around Win32). And virtually no changes seem to have been made to System.Windows.Forms in both .NET 3.0 and 3.5</p>
<pre><code></speculation>
</code></pre>
<p>I would use Java or Air.</p>
| 9,821
|
<p>how to change connection string dynamically in object datasource in asp.net ?</p>
|
<pre><code>protected void ObjectDataSource1_ObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
if (e.ObjectInstance != null)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = MyConnectionManager.ConnectionString;
e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);
}
}
</code></pre>
<p>I hope it helps.</p>
|
<p>Here's an approach that will work for all generated table adapters, using reflection: </p>
<pre><code>void OnObjectDataSourceObjectCreated(object sender, ObjectDataSourceEventArgs e)
{
if (e.ObjectInstance != null)
{
((SqlConnection)e.ObjectInstance.GetType()
.GetProperty("Connection", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance )
.GetValue(e.ObjectInstance, null)
).ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
}
}
</code></pre>
<p>Note that the Connection property Microsoft generates is created as internal (on my VS 2013), so you need to give BindingFlags.NonPublic to GetProperty.</p>
<p>And of course, wire up the ObjectCreated event one way or another:</p>
<pre><code>ObjectDataSource ObjectDataSource1 = new ObjectDataSource();
...
ObjectDataSource1.ObjectCreated += OnObjectDataSourceObjectCreated;
</code></pre>
| 47,626
|
<p>I know how to connect to web server using an iPhone but now I have to connect the iPhone to a web service. I don't know how to do it and there is no demo or class available online.</p>
<p>Does anyone have any ideas?</p>
|
<p>You can use these 2 lines which return the response of your HTTP request. You don't need any configuration. This code is usefull if you try to access a PHP scritp for example. After you just have to parse your result.</p>
<pre><code>NSURL *URL=[[NSURL alloc] initWithString:stringForURL];
NSString *results = [[NSString alloc] initWithContentsOfURL :URL];
</code></pre>
|
<p>In my opinion, you have two options :</p>
<ul>
<li>Use a third party library. You can try <a href="http://code.google.com/p/wsdl2objc/" rel="nofollow noreferrer">wsdl2objc</a>. It didn't work for me, but it is under active development so it improves every day.</li>
<li>Use a raw HTTP connection and handle every request/response. This is the way I followed. It is hard, so I'd also like to know a better approach.</li>
</ul>
| 45,932
|
<p>I have a class which has the following constructor</p>
<pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject)
{
InitializeComponent();
compositeObject = CompositeObject;
}
</code></pre>
<p>along with a default constructor with no parameters.</p>
<p>Next I'm trying to create an instance, but it only works without parameters:</p>
<pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer);
</code></pre>
<p>This works just fine, but if I want to pass parameters it does not:</p>
<pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4));
</code></pre>
<p>This results in an <code>MissingMethodException</code>:</p>
<blockquote>
<p>Constructor voor type
Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesigner
was not found</p>
</blockquote>
<p>Any ideas here?</p>
<hr>
<p>The problem is I really need to pass an object during construction.</p>
<p>You see I have a designer which loads all the types that inherit from the <code>CompositeBase</code>. These are then added to a list from which the users can drag them to a designer. Upon doing so an instance of the dragged is added to the designer. Each of these classes have custom properties defined on them:</p>
<pre><code>[CompositeMetaData("Delay","Sets the delay between commands",1)]
[CompositeDesigner(typeof(DelayCompositeDesigner))]
public class DelayComposite : CompositeBase
{
}
</code></pre>
<p>When the user selects an item in the designer, it looks at these attributes in order to load up a designer for that type. For example, in the case of the <code>DelayComposite</code> it would load up a user control which has a label and a slider which allow the user to set the "Delay" property of the <code>DelayComposite</code> instance.</p>
<p>So far this works fine if I don't pass any parameters to the constructor. The designer creates an instance of the <code>DelayCompositeDesigner</code> and assigns it to the content property of a WPF <code>ContentPresenter</code>.</p>
<p>But since that designer needs to modify the properties of the selected <code>DelayComposite</code>
in the designer, I have to pass this instance to it. That is why the constructor looks lie this:</p>
<pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject)
{
InitializeComponent();
compositeObject = CompositeObject;
}
</code></pre>
<p>Suggestions are welcome</p>
<hr>
<p>@VolkerK</p>
<p>The result of your code is this:</p>
<blockquote>
<p><---- foo
Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid
.ctor()
Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid
.ctor(Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite)
param:Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite
foo ----></p>
</blockquote>
<hr>
<p>Leppie, you were correct, I had for some reason referenced the Composites assembly in my UI application... which is not something I should have done as I was loading it at runtime. The following code works:</p>
<pre><code>object composite = Activator.CreateInstance(item.CompositType,(byte)205);
var designer = Activator.CreateInstance(designerAttribute.Designer, composite);
</code></pre>
<p>As you can see the code does not have knowledge of the <code>DelayComposite</code> type.</p>
<p>This solves the current problem, but introduces many new ones for what I want to achieve,
either way thank you and thank you to everyone who has replied here.</p>
<hr>
<p>As for the following code, suggested by multiple people:</p>
<pre><code>var designer = Activator.CreateInstance(
designerAttribute.Designer,
new object[] { new DelayComposite(4) }
);
</code></pre>
<p>The <code>Activator.CreateInstance</code> has a signature that looks like this:</p>
<pre><code>Activator.CreateInstance(Type type, params object[] obj)
</code></pre>
<p>So it should accept my code, but I will try the suggested code</p>
<p><strong>UPDATE:</strong></p>
<p>I've tried this as suggested:</p>
<pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4)});
</code></pre>
<p>The result is the same.</p>
|
<p>I think you are dealing with a Type mismatch.</p>
<p>Likely the assembly is referenced in different places, or they are compiled against different versions.</p>
<p>I suggest you iterate through the ConstructorInfo's and do a <code>paramtype == typeof(DelayComposite)</code> on the appropriate parameter.</p>
|
<p>You can use the following overload on CreateInstance:</p>
<pre><code>public static Object CreateInstance(
Type type,
Object[] args
)
</code></pre>
<p>And in your case it'd be (I think):</p>
<pre><code>var designer = Activator.CreateInstance(
typeof(DelayCompositeDesigner),
new object[] { new DelayComposite(4) }
);
</code></pre>
| 25,615
|
<p>I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl_image and sdl_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls.</p>
<p>Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant.</p>
|
<p>When compiling your project, you need to make just a couple changes to your makefile.</p>
<ul>
<li>Instead of <code>sdl-config --libs</code>, use <code>sdl-config --static-libs</code></li>
<li>Surround the use of the above-mentioned <code>sdl-config --static-libs</code> with <code>-Wl,-Bstatic</code> and <code>-Wl,-Bdynamic</code>. This tells GCC to force static linking, but only for the libraries specified between them.</li>
</ul>
<p>If your makefile currently looks like:</p>
<pre><code>SDLLIBS=`sdl-config --libs`
</code></pre>
<p>Change it to:</p>
<pre><code>SDLLIBS=-Wl,-Bstatic `sdl-config --static-libs` -Wl,-Bdynamic
</code></pre>
<p>These are actually the same things you <em>should</em> do on Unix-like systems, but it usually doesn't cause as many errors on Unix-likes if you use the simpler <code>-static</code> flag to GCC, like it does on Windows.</p>
|
<p>That's because the SDL libs are under the LGPL-license.</p>
<p>If you want to static link the libs (you can do that if your recompile them. It needs some hacking into the makefiles though) you have to place your game under some compatible open source license as well.</p>
<p>The SDL-libs come as shared libraries because most programs that use them are closed source. The binary distribution comes in a form that most people need.</p>
| 14,116
|
<p>Need a function that takes a character as a parameter and returns true if it is a letter.</p>
|
<p>This was part of the code posted by <a href="https://stackoverflow.com/users/4007/rpetrich">rpetrich</a> in response to a <a href="https://stackoverflow.com/questions/61598/code-to-make-a-dhtmled-control-replace-straight-quotes-with-curly-quotes">question</a> by <a href="https://stackoverflow.com/users/4/joel-spolsky">Joel Spolsky</a>. I felt it needed a post specific to the problem it solves. It really is brilliant.</p>
<pre><code>Private Function IsLetter(ByVal character As String) As Boolean
IsLetter = UCase$(character) <> LCase$(character)
End Function
</code></pre>
<p>You may be thinking to yourself, "Will this always work?" The documentation on the UCase and LCase functions, confirms that it will:</p>
<blockquote>
<p><strong>UCase Function</strong> Only lowercase letters are converted to uppercase;
<em>all uppercase letters and nonletter characters remain unchanged</em>.</p>
<p><strong>LCase Function</strong> Only uppercase letters are converted to lowercase;
<em>all lowercase letters and nonletter characters remain unchanged</em>.</p>
</blockquote>
|
<p>It doesn't exactly document itself. And it may be slow. It's a clever hack, but that's all it is. I'd be tempted to be more obvious in my checking. Either use regex's or write a more obvious test. </p>
<pre><code>public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=new Regex("[^a-zA-Z]");
return !objAlphaPattern.IsMatch(strToCheck);
}
public bool IsCharAlpha(char chToCheck)
{
return ((chToCheck=>'a') and (chToCheck<='z')) or ((chToCheck=>'A') and (chToCheck<='Z'))
}
</code></pre>
| 11,861
|
<p>Using the Apple OS X Cocoa framework, how can I post a <em>sheet</em> (slide-down modal dialog) on the window of another process? </p>
<p><strong>Edit:</strong> Clarified a bit:</p>
<p>My application is a Finder extension to do Subversion version control (<a href="http://scplugin.tigris.org/" rel="nofollow noreferrer">http://scplugin.tigris.org/</a>). Part of my application is a plug-in (a Contextual Menu Item for Finder); the bulk of my application, however, is in a separate daemon proces. For several reasons, we've chosen to put virtually all the code into the daemon; the plug-in only defines the menu itself, and Apple-Events over to the Daemon.</p>
<p>Sometimes, the daemon needs to prompt the user for further information. It can toss a window on-screen for this, but that's disruptive (randomly positioned), and it seems to me the work flow here is legitimately modal, for example "select a file, pick 'commit' from the menu, provide commit comments, do the operation."</p>
<p>Interprocess cooperation (such as passing a reference of some kind) is acceptable: both processes are mine, but I want to avoid binding the sheet's code into the primary process.</p>
|
<p>Really, it sounds like you're trying to have your inter-process communication happen at the view level, which isn't really how Cocoa generally works. Things will be much easier if you separate your layers a bit more than that.</p>
<p>Why don't you want to put the sheet code into the other process? It's view code, and view code is inherently process-specific. The right thing to do here is probably to add somewhat generic modal-sheet support to your plugin code, and an IPC call that your daemon can make to summon that code. Trying to ship view objects over to the remote process is going to be nightmarish if you can make it work at all.</p>
<p>You're fighting the frameworks with this approach.</p>
|
<p>Please don't do this. Make the interaction nonmodal if at all possible. Especially in something like a commit, it's much nicer to be able to browse around your files while you're writing commit comments.</p>
<p>OS X does have window groups, but I don't think they can (easily) span applications.</p>
| 9,108
|
<p>I am looking for some stats on current browsers for how long it takes to render a table using plain HTML versus a hacked-up CSS puritan method that avoids using actual <code>TABLE</code>, <code>TR</code>, <code>TD</code> etc. tags.</p>
<p><strong>I am not looking for what's proper, only for what's faster</strong>, particularly on Firefox 3, although I am also interested in the stats for other browsers. Of <em>course</em> TABLE tags are designed for tables. That's not the question.</p>
|
<p>If you really have tabular data, then use tables. The idea that you should never use tables for anything was a mistaken extension of the correct concept that you should use html tags only for their intended semantic purpose. That means use CSS for layout, but use tables for tabular data. It does not mean never use tables.</p>
|
<p>Personally from what I have read, if you are actually presenting tabular data, a table is more appropriate for the task, I personally hae found that to be pretty true.</p>
<p>As for raw number of what is "faster", as mentioned by @skaffman it depends on the browsers...but to be "correct" it would make sense to use a table for tabular data.</p>
| 16,446
|
<p>I am a Java programmer and need to work on a Flex/ActionScript project right now. I got an example of using ITreeDataDesriptor from Flex 3 Cookbook, but there is one line of actionscript code that's hard for me to understand. I appreciate if someone could explain this a little further. </p>
<pre><code>public function getData(node:Object, model:Object=null):Object
{
if (node is Office) {
return {children:{label:node.name, label:node.address}};
}
}
</code></pre>
<p>The part that I didn't understand was "{children:{label:node.name, label:node.address}}". Office is simply a value object that contains two String properties: name and address.</p>
|
<p>The following return expression (modified from the question) ...</p>
<pre><code>return {children:{label:node.name, body:node.address}}
</code></pre>
<p>... is functionally equivalent to this code ...</p>
<pre><code>var obj:Object = new Object();
obj.children = new Object();
obj.children.label = node.name;
obj.children.body = node.address;
return obj;
</code></pre>
<p>The anonymous object returned in the question code complicates matters because it defines a property twice. In that case, the first declaration is used, and the subsequent one(s) are ignored. No compile-time or runtime error is thrown.</p>
|
<p>Thank you both for the quick response. So if I understand your explanations correctly, the return statement is returning an anonymous object, and this object has only one property named "children", which is again an associative array - ok, here is the part I don't quite understand still, it seems that both properties in this array are named "label", is this allowed?</p>
| 48,838
|
<p>We have an existing WCF service that makes use of wsDualHttpBinding to enable callbacks to the client. I am considering moving it to netTcpBinding for better performance, but I'm quite wary of moving away from the IIS-hosted service (a "comfort zone" we currently enjoy) into having our own Windows service to host it. I was hoping we could still host this on IIS 7 but Win2K8 won't be reality for us for some time.</p>
<p>What things should I watch out for when creating our own Windows service to host our WCF service? Things like lifetime management and request throttling are features that come free with IIS hosting so I'd also like to know how we can effectively host our service on our own without the convenience of having IIS do the hard work for us. Thanks! :)</p>
|
<p>So as you cannot host using WAS there are a couple of things to realise.</p>
<ul>
<li>If the service crashes it doesn't restart by default (although you can change this in service properties)</li>
<li>IIS will recycle the application pool if it hangs or grows too big; you must do this yourself if you want the same sort of reliability.</li>
<li>You must create an account for the service to run under, or use one of the default services. Resit the temptation to run the service as SYSTEM or under an administrator account; if you want to use a built in account use NETWORK SERVICE.</li>
<li>It becomes harder to debug in situ.</li>
<li>Consider using a error logger such as log4net</li>
</ul>
<p>Having said that I deployed a WCF/Windows service combination for a customer 9 months ago; it's heavily used and hasn't died once.</p>
<p>You can <a href="http://www.iserviceoriented.com/blog/post/Configuring+Performance+Options+-+WCF+Gotcha+3.aspx" rel="noreferrer">request throttle</a> in a Windows service, it's part of the WCF configuration. Note the defaults are very low, it is likely you will have to increase these. </p>
|
<p>Hosting in a Windows Service Application (<a href="http://msdn.microsoft.com/en-us/library/ms734781.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms734781.aspx</a>) is a good start.</p>
<p>If you can host your service on Vista, you can also benefit from Windows Process Activation Service (WAS). WAS is a generalization of the IIS process activation, which can be used to activate processes over non-HTTP endpoints (TCP, Named Pipe, MSMQ). To learn more about WCF hosted in WAS, read <a href="http://msdn.microsoft.com/en-us/library/ms733109.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms733109.aspx</a>. To learn how to install and configure WAS, read <a href="http://msdn.microsoft.com/en-us/library/ms731053.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms731053.aspx</a>.</p>
| 16,672
|
<p>I need a technique for dealing with what seems pretty simple!</p>
<p>I have a form, with some logic on the server side for validation.
if the server side code indicates that there is an issue, I want to display a modal popup to the client.</p>
<p>I am having trouble getting it to work in this way.</p>
<p>I found if I keep all the logic client side, I can use the javascript function</p>
<pre><code>window.showModalDialog("url","title", "style");
</code></pre>
<p>However the logic is currently on the server side.
this is an ASP.NET 3.5 web project - is there some way to do this using AJAX controls like the scriptmanager, an update panel etc?</p>
<p>Thank you!</p>
|
<p>I know that you do it using the ScriptManager control. Basically you just send from the server a line of JavaScript to execute immediately. In this case, the client side line you describe.</p>
<p>Sorry to be vague, but it's almost quitting time and I'll have to grep through a lot of code to find an example.</p>
<p><a href="http://codepagoda.com/2008/08/26/example-error-messages-using-a-modal-dialog-box-with-the-modalpopupextender-in-microsoft-ajax/" rel="nofollow noreferrer">Here is an example</a></p>
|
<p>You need to use an AJAX callback to perform your server side validation and return a response to the client - then decide whether to display the modal dialog... however, why do you need to validate on the server? It is usually best to try and validate in the client to save roundtrips... </p>
| 38,524
|
<p>I have a table with rowID, longitude, latitude, businessName, url, caption. This might look like:</p>
<pre><code>rowID | long | lat | businessName | url | caption
1 20 -20 Pizza Hut yum.com null
</code></pre>
<p>How do I delete all of the duplicates, but only keep the one that has a URL (first priority), or keep the one that has a caption if the other doesn't have a URL (second priority) and delete the rest?</p>
|
<p>Here's my looping technique. This will probably get voted down for not being mainstream - and I'm cool with that.</p>
<pre><code>DECLARE @LoopVar int
DECLARE
@long int,
@lat int,
@businessname varchar(30),
@winner int
SET @LoopVar = (SELECT MIN(rowID) FROM Locations)
WHILE @LoopVar is not null
BEGIN
--initialize the variables.
SELECT
@long = null,
@lat = null,
@businessname = null,
@winner = null
-- load data from the known good row.
SELECT
@long = long,
@lat = lat,
@businessname = businessname
FROM Locations
WHERE rowID = @LoopVar
--find the winning row with that data
SELECT top 1 @Winner = rowID
FROM Locations
WHERE @long = long
AND @lat = lat
AND @businessname = businessname
ORDER BY
CASE WHEN URL is not null THEN 1 ELSE 2 END,
CASE WHEN Caption is not null THEN 1 ELSE 2 END,
RowId
--delete any losers.
DELETE FROM Locations
WHERE @long = long
AND @lat = lat
AND @businessname = businessname
AND @winner != rowID
-- prep the next loop value.
SET @LoopVar = (SELECT MIN(rowID) FROM Locations WHERE @LoopVar < rowID)
END
</code></pre>
|
<p>If possible, can you homogenize, then remove duplicates?</p>
<p>Step 1:</p>
<pre><code>UPDATE BusinessLocations
SET BusinessLocations.url = LocationsWithUrl.url
FROM BusinessLocations
INNER JOIN (
SELECT long, lat, businessName, url, caption
FROM BusinessLocations
WHERE url IS NOT NULL) LocationsWithUrl
ON BusinessLocations.long = LocationsWithUrl.long
AND BusinessLocations.lat = LocationsWithUrl.lat
AND BusinessLocations.businessName = LocationsWithUrl.businessName
UPDATE BusinessLocations
SET BusinessLocations.caption = LocationsWithCaption.caption
FROM BusinessLocations
INNER JOIN (
SELECT long, lat, businessName, url, caption
FROM BusinessLocations
WHERE caption IS NOT NULL) LocationsWithCaption
ON BusinessLocations.long = LocationsWithCaption.long
AND BusinessLocations.lat = LocationsWithCaption.lat
AND BusinessLocations.businessName = LocationsWithCaption.businessName
</code></pre>
<p>Step 2:
Remove duplicates.</p>
| 18,192
|
<p>Based on what I've seen on Oslo, declarative XML will have a key role. Can I expect to be mucking around a lot of designer generated XML to create real world applications? Just know I haven't researched this. I would just appreaciate your perspective if you have examined the subject. </p>
<p><em>Some background...</em></p>
<p>Whenever I dig just under the skin of any XML backed declarative technology (such as Silverlight and WPF, ASP.NET, or MSBuild) it seems I end up editing a lot of raw XML text. The designers are seldom expressive enough for my needs. </p>
<p>One one hand I can't really see better compromise between human and machine readability, and to be fair, the XML editing experience gets better with each incarnation. </p>
<p>On the other hand I havn't found XML ideal for some of its usages. Especially when it comes to expressing logic, and for refactoring and testability. May it be the designers are too weak, or the XML too expressive, or I, too grumpy and spoiled by objects and methods.</p>
|
<p>I tend to make for a somewhat dubious champion of XML. Despite the fact that I use it daily, and that XML-based webservices have been a large part of my career (and the basis for the book I wrote), I think it is widely over-used. I tend to belong to the school-of-thought that believes you should have many tools in your toolbox, and you should use the best tool for the job. There are a lot of things for which XML is an excellent solution. But there are plenty of things for which it isn't, and some for which it's probably a terrible choice.</p>
<p>Just as some people are zealous in their criticism and avoidance of XML, some people are just as zealous (or more so) in their praise and use of it. In the cases you refer to casually above, you're talking about web-based technologies for the most part. In these cases, you generally already have an XML parser and/or DOM manipulator already available to you, so there is no harm in making use of it. You haven't added to the complexity, because it was already there. Flash & AIR make heavy use of XML for functionality, but they are targeted to an environment where parsing XML-ish markup (if not XML itself, then HTML or XHTML) is a core part of every application. For these technologies, introducing a different sort of data-expression language would be what adds complexity. Using XML makes perfect sense.</p>
<p>Here's an example... the language in question here is Perl because that's what I use primarily, but the Perl-aspect of it is not relevant to the point: I've been working on an extension of an existing module that dumps deep data structures. Useful for tons of things-- serialization, portability across platforms, etc. Also a popular tool for debugging. My reason for wanting to extend it is that truly large and complex structures (such as those produced by ORM or MOP frameworks) can get pretty hairy. So my first thought was to just make an extension that let me convert the data to HTML in a way I could exercise some control over. Then I thought that it would be nifty if I could create diagrams showing the various elements and which is linked to which, etc. <em>Then</em> it occurred to me that if I chose a reasonable neutral format, I should be able to derive both of those fairly easily.</p>
<p>That format? XML. Why would it be necessarily better than the native Perl serialization structure in this case, or better than using a different interim representation (such as YAML or JSON)? Because if I have valid, well-formed XML I can easily use XSLT to turn that into (X)HTML or SVG. I can also turn it into plain text if I want (I have XSLT stylesheets already, that choose to emit HTML fragments or cleanly-word-wrapped plain text depending on user selection).</p>
<p>There are plenty of ways to solve this particular problem, but the advantage that XML gives me <em>in this case</em> makes it the preferred choice (at least, for my preferences and my needs). XSLT is a well-defined, well-documented (OK, your opinion may vary on that with regards to the W3C documentation, but there is no shortage of books on the subject) tool for transforming XML into, well, pretty much anything. For this particular problem, the expressiveness of XML combined with the fact that my ultimate target formats (XHTML and SVG) are themselves XML, made it the clear choice. On the other hand, there have been plenty of times when I've recommended (as a consultant) to a client or (as a company employee/team member) to a boss/team that XML should <strong>not</strong> be used for some task. Sometimes the reason is clear-- using XML wouldn't improve the (re-)usability of the data, they weren't using XML on the project yet and this wasn't the sort of thing you should introduce that dependency for, etc. Sometimes the reason is more subtle; if you are trying to decide how to store/retrieve your application's configuration, does it really need to be in XML? It's highly unlikely any other application will need to read/parse this, so portability/reuse of data isn't an issue. If the data is fairly flat in nature you can probably manage with a file of key/value pairs. If the data is more complicated and/or complex, you might be fine with YAML.</p>
<p>In general, XML is the worst choice for data expression, except when it's the best choice. The same can be said for JSON and YAML, and the best way to get the most out of any of these approaches is to be familiar and comfortable with all of them and know which one is the best tool for the job you have in front of you.</p>
|
<p>I tend to make for a somewhat dubious champion of XML. Despite the fact that I use it daily, and that XML-based webservices have been a large part of my career (and the basis for the book I wrote), I think it is widely over-used. I tend to belong to the school-of-thought that believes you should have many tools in your toolbox, and you should use the best tool for the job. There are a lot of things for which XML is an excellent solution. But there are plenty of things for which it isn't, and some for which it's probably a terrible choice.</p>
<p>Just as some people are zealous in their criticism and avoidance of XML, some people are just as zealous (or more so) in their praise and use of it. In the cases you refer to casually above, you're talking about web-based technologies for the most part. In these cases, you generally already have an XML parser and/or DOM manipulator already available to you, so there is no harm in making use of it. You haven't added to the complexity, because it was already there. Flash & AIR make heavy use of XML for functionality, but they are targeted to an environment where parsing XML-ish markup (if not XML itself, then HTML or XHTML) is a core part of every application. For these technologies, introducing a different sort of data-expression language would be what adds complexity. Using XML makes perfect sense.</p>
<p>Here's an example... the language in question here is Perl because that's what I use primarily, but the Perl-aspect of it is not relevant to the point: I've been working on an extension of an existing module that dumps deep data structures. Useful for tons of things-- serialization, portability across platforms, etc. Also a popular tool for debugging. My reason for wanting to extend it is that truly large and complex structures (such as those produced by ORM or MOP frameworks) can get pretty hairy. So my first thought was to just make an extension that let me convert the data to HTML in a way I could exercise some control over. Then I thought that it would be nifty if I could create diagrams showing the various elements and which is linked to which, etc. <em>Then</em> it occurred to me that if I chose a reasonable neutral format, I should be able to derive both of those fairly easily.</p>
<p>That format? XML. Why would it be necessarily better than the native Perl serialization structure in this case, or better than using a different interim representation (such as YAML or JSON)? Because if I have valid, well-formed XML I can easily use XSLT to turn that into (X)HTML or SVG. I can also turn it into plain text if I want (I have XSLT stylesheets already, that choose to emit HTML fragments or cleanly-word-wrapped plain text depending on user selection).</p>
<p>There are plenty of ways to solve this particular problem, but the advantage that XML gives me <em>in this case</em> makes it the preferred choice (at least, for my preferences and my needs). XSLT is a well-defined, well-documented (OK, your opinion may vary on that with regards to the W3C documentation, but there is no shortage of books on the subject) tool for transforming XML into, well, pretty much anything. For this particular problem, the expressiveness of XML combined with the fact that my ultimate target formats (XHTML and SVG) are themselves XML, made it the clear choice. On the other hand, there have been plenty of times when I've recommended (as a consultant) to a client or (as a company employee/team member) to a boss/team that XML should <strong>not</strong> be used for some task. Sometimes the reason is clear-- using XML wouldn't improve the (re-)usability of the data, they weren't using XML on the project yet and this wasn't the sort of thing you should introduce that dependency for, etc. Sometimes the reason is more subtle; if you are trying to decide how to store/retrieve your application's configuration, does it really need to be in XML? It's highly unlikely any other application will need to read/parse this, so portability/reuse of data isn't an issue. If the data is fairly flat in nature you can probably manage with a file of key/value pairs. If the data is more complicated and/or complex, you might be fine with YAML.</p>
<p>In general, XML is the worst choice for data expression, except when it's the best choice. The same can be said for JSON and YAML, and the best way to get the most out of any of these approaches is to be familiar and comfortable with all of them and know which one is the best tool for the job you have in front of you.</p>
| 27,031
|
<p>What is the easiest way to do this? Is it possible with managed code?</p>
|
<pre><code>this.BackgroundImage = //Image
this.FormBorderStyle = FormBorderStyle.None;
this.Width = this.BackgroundImage.Width;
this.Height = this.BackgroundImage.Height;
this.TransparencyKey = Color.FromArgb(0, 255, 0); //Contrast Color
</code></pre>
<p>This allows you to create a form based on an image, and use transparency index to make it seem as though the form is not rectangular.</p>
|
<p>@Geoff shows the right way in winforms. </p>
<p>But If you are planning to use WPF instead of Winforms then WPF(.NET3.0+) gives very flexible ways to create anyshape custom windows. Check out this article also <a href="http://www.codeproject.com/KB/WPF/wpfpopup.aspx" rel="noreferrer">http://www.codeproject.com/KB/WPF/wpfpopup.aspx</a></p>
| 21,283
|
<p>I have a DSL Tools solution.</p>
<p>I need to add a weak-named reference to this project.
Because the DSL Tools project DLL is strong-named i cannot used the weak-named DLL.</p>
<p>I cannot make the DLL strong-named because i cannot recompile it.</p>
<p>I tried to make my DSL Tools project DLL weak-named by going to the Dsl and DslPackage project properties and unchecked the option "Sign the assembly" in the Sigining tab.</p>
<p>Then i compile it.
The error list gives the following error</p>
<pre><code>"gacutil.exe" exited with code 1
</code></pre>
<p>Looking at the VS2005 output window i see gacutil is being called </p>
<pre><code>C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\gacutil.exe -nologo -i "C:\Academy\ResearchAndDevelopment\FrontendGenerator\DslPackage\bin\Debug\vantyx.FEGenerator.DslPackage.dll"
</code></pre>
<p>After that i used the command prompt and the gacutil.exe error displays as this:</p>
<pre><code>Z:\>"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\gacutil.exe" -nologo -i "C:\Academy\ResearchAndDevelopment\FrontendGenerator\DslPackage\bin\Debug\vantyx.FEGenerator.DslPackage.dll"
Failure adding assembly to the cache: Attempt to install an assembly without a strong name
</code></pre>
<p>I don't know why and how gacutil.exe is being called.
I looked at the project and solution properties and there is no option configured to call gacutil.exe.
I even looked inside every file for "gacutil.exe" but i found nothing.</p>
<p>What i really want is to be able to use the weak-named DLL that i cannot make strong-named.
As a result of this, i've been trying to make my DSL Tools DLL weak-named but i can't.</p>
<p>Any help on how i can workaround this?</p>
<p>Many thanks in advance,
Luís Filipe </p>
|
<p>Turns out I just needed something like this:</p>
<pre><code>public TableRow DTHeader { get; set; }
protected override void OnInit(EventArgs e)
{
tblCollection.Rows.Add(DTHeader);
base.OnInit(e);
}
</code></pre>
<p>And then use this on my Page:</p>
<pre><code><ME:NewControl ID="tblCustomList" runat="server">
<DTHeader>
<asp:TableCell></asp:TableCell>
//...
</DTHeader>
</ME:NewControl>
</code></pre>
|
<p>I am not sure if I understand the question 100%.</p>
<p>However if you a custom control called Row you can add a collection to the main table user control.</p>
<p>You can do this with a generic list. This should give you the ability to add them like a normal aspx control. </p>
<p>I don't have a code sample here, but I have done it many times.</p>
| 44,364
|
<p>I am working on an MVC site that is the first my company has done, one of the things I find myself doing a lot is creating selectlists in a controller, putting them in viewdata and reading them when creating a html.DropDownList. theer are a few things that strike me as smelly about the way i do it.</p>
<ol>
<li><p>some pages can repeat lists of things (the board rate of a hotel room wheer a user can add as many rooms to a hotel as they need), currently i use the same selectlist, is this good practice or should they have one each?</p></li>
<li><p>with the previous example the "room" is an ascx rendered either by a renderpartial or an ajax call via jquery. what is the best way for the controller to pass the selectlist so the ascx can use it, currently I add to the viewdata for the page, which passes it's viewdata to the renderpartial, but then on the ajax call the action method also needs to add the selectlist to the Viewdata for the ascx, agan not sure this is the best way.</p></li>
<li><p>I have a repository that holds this "static" data and returns as a generic list, so each time the controller needs the data it hits the repository for the list (there are a few more than just board rate, things like titles for people, mr, mrs etc and others) I suspect some kind of cache would be better as the data rarely if ever changes.</p></li>
</ol>
<p>does anyone have any advice in these areas?</p>
|
<ol>
<li><p>If those SelectLists are completely equal, then I'm sure better to use one list for multiple DropDownLists.</p></li>
<li><p>Look like its common usage. I'm using the similar approach too, but thinking about to port some of the controls to Html.RenderAction, because passing through page's ViewData to control feels not good for me too. Yep, I know that it will not be pure MVC :)</p></li>
<li><p>If your ORM supports cache, of course use it.</p></li>
</ol>
<p>But also if your project is not small and you think it will continue to grow, I recommend to implement a Service Layer (PoEAA pattern) above your repositories that will contains business logic and the cache management logic too.</p>
<p>If you want to manage your cache transparently, without affecting your dal or mvc layer, I think that the best approache is to use AOP.</p>
|
<p>One way of doing this is to put the data you need for the select list in your model via a typed view. The view can iterate over the data in the model to generate any select lists it needs. You can also stuff an object directly into the ViewData collection, but I think having a typed view results in much cleaner code. </p>
| 48,092
|
<p>I was wondering if there is any good and clean object-oriented programming (OOP) implementation of Bayesian filtering for spam and text classification? This is just for learning purposes.</p>
|
<p>I definitely recommend <a href="http://www.cs.waikato.ac.nz/ml/weka/" rel="noreferrer">Weka</a> which is an <em>Open Source Data Mining Software</em> written in Java:</p>
<blockquote>
<p>Weka is a collection of machine learning algorithms for data mining tasks. The algorithms can either be applied directly to a dataset or called from your own Java code. Weka contains tools for data pre-processing, classification, regression, clustering, association rules, and visualization. It is also well-suited for developing new machine learning schemes.</p>
</blockquote>
<p>As mentioned above, it ships with a bunch of different classifiers like <a href="http://en.wikipedia.org/wiki/Support_vector_machine" rel="noreferrer">SVM</a>, <a href="http://en.wikipedia.org/wiki/Winnow_%28algorithm%29" rel="noreferrer">Winnow</a>, <a href="http://en.wikipedia.org/wiki/C4.5_algorithm" rel="noreferrer">C4.5</a>, Naive Bayes (of course) and many more (see the <a href="http://weka.sourceforge.net/doc/" rel="noreferrer">API doc</a>).
Note that a lot of classifiers are known to have <strong>much better perfomance than Naive Bayes</strong> in the field of spam detection or text classification.</p>
<p>Furthermore Weka brings you a very <a href="http://www.cs.waikato.ac.nz/~ml/weka/gui_explorer.html" rel="noreferrer">powerful GUI</a>…</p>
|
<p>In French, but you should be able to find the download link :)
<a href="http://xhtml.net/scripts/PHPNaiveBayesianFilter" rel="nofollow noreferrer">PHP Naive Bayesian Filter</a></p>
| 2,352
|
<p>I'm getting a NullPointerException in a Class from a 3rd party library. Now I'd like to debug the whole thing and I would need to know from which object the class is held. But it seems to me that I cannot set a breakpoint in a Class from a 3rd party. </p>
<p>Does anyone know a way out of my trouble? Of course I'm using Eclipse as my IDE.</p>
<p>Update: the library is open-source.</p>
|
<p>You can easily set method breakpoints in 3rd party libraries without having the source. Just open the class (you'll get the "i-have-no-source" view). Open the outline, right-click on the method you want and click on <code>Toggle Method Breakpoint</code> to create the method breakpoint.</p>
|
<p>Just attach the source (or use something that automatically attaches the source jar) and then set a breakpoint in the normal way, by double-clicking to the left of the line of interest.</p>
| 48,451
|
<p>Looking in the Cura interface, I can set any whole number 0-100 for the infill percentage. Does Cura have an algorithm to calculate a pattern for any of those possible values, or does it have a few patterns where it selects the closest one?</p>
|
<p>I fear I'm going to deny your question. The infil percentage and the infil pattern are two orthogonal properties, both of which contribute to the strength, density, mass, and print time of an object. Since there's no way for an algo to "know" what your desired outcome is, this can't be done.</p>
<p>Note - I used 'orthogonal' in the Hilbert sense, meaning neither property is a function of the other. </p>
|
<p>From what I can see, the only way to change the pattern is the manual way.
There is still an open gate to create a plugin that could select the pattern - but that is rather a complex solution - unless you will have a fully automated pipeline</p>
| 994
|
<p>I just got my azure invitation code...yay!</p>
<p>Are there any official samples for windows azure + MS asp.net MVC?</p>
<p>I still don't get the storage providers and services that come with Azure, it's a bit confusing. I don't think MS have done a very good of explaining it.</p>
|
<p>You can find more details in Jim Nakashima's blog: <a href="http://blogs.msdn.com/jnak/archive/2008/10/28/asp-net-mvc-projects-running-on-windows-azure.aspx" rel="noreferrer">ASP.Net MVC Projects running on Windows Azure</a> and <a href="http://blogs.msdn.com/jnak/archive/2008/11/10/asp-net-mvc-on-windows-azure-with-providers.aspx" rel="noreferrer">ASP.Net MVC on Windows Azure with Providers</a></p>
|
<p>Here's another full example of a Blog and a Forum, using <a href="http://www.azurebright.com" rel="nofollow noreferrer">ASP.NET MVC and Window Azure</a></p>
| 42,570
|
<p>I saw <a href="https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357">this same question for VIM</a> and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?</p>
|
<p>I use </p>
<pre><code>C-a C-SPACE C-n M-w C-y
</code></pre>
<p>which breaks down to</p>
<ul>
<li><code>C-a</code>: move cursor to start of line</li>
<li><code>C-SPACE</code>: begin a selection ("set mark")</li>
<li><code>C-n</code>: move cursor to next line</li>
<li><code>M-w</code>: copy region</li>
<li><code>C-y</code>: paste ("yank")</li>
</ul>
<p>The aforementioned</p>
<pre><code>C-a C-k C-k C-y C-y
</code></pre>
<p>amounts to the same thing (TMTOWTDI)</p>
<ul>
<li><code>C-a</code>: move cursor to start of line</li>
<li><code>C-k</code>: cut ("kill") the line</li>
<li><code>C-k</code>: cut the newline</li>
<li><code>C-y</code>: paste ("yank") (we're back at square one)</li>
<li><code>C-y</code>: paste again (now we've got two copies of the line)</li>
</ul>
<p>These are both embarrassingly verbose compared to <code>C-d</code> in your editor, but in Emacs there's always a customization. <code>C-d</code> is bound to <code>delete-char</code> by default, so how about <code>C-c C-d</code>? Just add the following to your <code>.emacs</code>:</p>
<pre><code>(global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y")
</code></pre>
<p>(@Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.)</p>
<p>Beware: some Emacs modes may reclaim <code>C-c C-d</code> to do something else.</p>
|
<p>well ive usually used:</p>
<pre>Ctl-Space (set the mark)
move to end of line
Ctl-K kill line
Ctl-Y * 2 (yank the line back)</pre>
<p>there may be a much better way though :P</p>
| 11,400
|
<p>I'm building an interface much like the built-in Weather application's flipside view, or the Alarms view of the Clock application in editing mode. The table view is always in editing mode, so the delete icon appears on the left side of each cell.</p>
<p>When the table view is in editing mode, my delegate doesn't receive <code>didSelectRowAtIndexPath</code> notifications. It receives <code>accessoryButtonTappedForRowWithIndexPath</code> notifications, but that's not what I want to do. I want my rows to stay selectable, even when the table view is in editing mode.</p>
<p>Any ideas on how I can accomplish this?</p>
<p>Thanks,</p>
<p>P.S. Hooray for the lifted NDA. =)</p>
|
<p>Set <code>table.allowsSelectionDuringEditing</code> to <code>YES</code>.</p>
|
<p>You can also set this in the attributes inspector. Make sure you select the table view, not the view controller, and select "Single Selection During Editing" in the Editing dropdown:<img src="https://i.stack.imgur.com/BcVgS.png" alt="enter image description here"></p>
| 21,002
|
<p>I want to use the MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.</p>
|
<p>I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!</p>
<p>Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.</p>
<p>Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.</p>
<p>Now create a web part, do all the usual boilerplate and then add this:</p>
<pre><code>Label l;
MultipleLookupField mlf;
protected override void CreateChildControls()
{
base.CreateChildControls();
SPList list = SPContext.Current.Web.Lists["Shared Documents"];
if (list != null && list.Items.Count > 0)
{
LiteralControl lit = new LiteralControl("Associate tasks to " +
list.Items[0].Name);
this.Controls.Add(lit);
mlf = new MultipleLookupField();
mlf.ControlMode = SPControlMode.Edit;
mlf.FieldName = "Related";
mlf.ItemId = list.Items[0].ID;
mlf.ListId = list.ID;
mlf.ID = "Related";
this.Controls.Add(mlf);
Button b = new Button();
b.Text = "Change";
b.Click += new EventHandler(bClick);
this.Controls.Add(b);
l = new Label();
this.Controls.Add(l);
}
}
void bClick(object sender, EventArgs e)
{
l.Text = "";
foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)
{
l.Text += val.LookupValue.ToString() + " ";
}
SPListItem listitem = mlf.List.Items[0];
listitem["Related"] = mlf.Value;
listitem.Update();
mlf.Value = listitem["Related"];
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
</code></pre>
<p>Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.</p>
<p>The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...</p>
|
<p>Hm. Works fine on mine, so let's see if we can work out how your setup is different...</p>
<p>It looks as though it's having trouble populating the control; my first guess would be that this is because the code makes so many assumptions about the lists it's talking to. Can you check that you've got a plain vanilla Team site, with (assume these names are case-sensitive): </p>
<ol>
<li>A list called Tasks, with several items in it</li>
<li>A library called Shared Documents with at least one document</li>
<li>A column called Related in the Shared Documents library</li>
<li>The Related column is a Lookup field into the Title column of Tasks, and allows multiple values.</li>
<li>The first document in Shared Documents has a value for Related</li>
</ol>
<p>Then add the webpart. Fingers crossed...</p>
| 6,107
|
<p>I am in the middle of reading the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a></p>
<p>One discussion is regarding passing nulls into a method.</p>
<pre><code>public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x - p1.x) * 1.5;
}
}
...
calculator.xProjection(null, new Point(12,13));
</code></pre>
<p>It represents different ways of handling this:</p>
<pre><code>public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw new IllegalArgumentException("Invalid argument for xProjection");
}
return (p2.x - p1.x) * 1.5;
}
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x - p1.x) * 1.5;
}
</code></pre>
<p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p>
<p>The book finally states:</p>
<blockquote>
<p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p>
</blockquote>
<p>It doesn't really go into how you would enforce this restriction?</p>
<p>Do any of you have strong opinions either way.</p>
|
<p>General rule is if your method doesn't expect <code>null</code> arguments then you should throw <a href="http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx" rel="nofollow noreferrer">System.ArgumentNullException</a>. Throwing proper <code>Exception</code> not only protects you from resource corruption and other bad things but serves as a guide for users of your code saving time spent debugging your code.</p>
<p>Also read an article on <a href="http://en.wikipedia.org/wiki/Defensive_programming" rel="nofollow noreferrer">Defensive programming</a></p>
|
<p>Thwrowing C# <code>ArgumentException</code>, or Java <code>IllegalArgumentException</code> right at the beginning of the method looks to me as the clearest of solutions. </p>
<p>One should always be careful with Runtime Exceptions - exceptions that are not declared on the method signature. Since the compiler doesn't enforce you to catch these it's really easy to forget about them. Make sure you have some kind of a "catch all" exception handling to prevent the software to halt abruptly. That's the most important part of your user experience.</p>
| 5,220
|
<p>Is there any way in a Win32 environment to "tune" the timeout on a socket <code>connect()</code> call? Specifically, I would like to increase the timeout length. The sockets in use are non-blocking. Thanks!</p>
|
<p>Yes, this is possible.</p>
<p>If you're in non-blocking mode after <a href="http://msdn.microsoft.com/en-us/library/ms737625(VS.85).aspx" rel="nofollow noreferrer"><code>connect()</code></a>, you normally use <a href="http://msdn.microsoft.com/en-us/library/ms740141(VS.85).aspx" rel="nofollow noreferrer"><code>select()</code></a> to wait till I/O is ready. This function has a parameter for specifying the timeout value and will return 0 in case of a timeout.</p>
|
<p>You can try to use SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations. Example:</p>
<pre><code>struct timeval timeout;
timeout.tv_sec = 10;
timeout.tv_usec = 0;
if (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
if (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,
sizeof(timeout)) < 0)
error("setsockopt failed\n");
</code></pre>
<p>You can also try alarm(). Sample:</p>
<pre><code>signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */
alarm( secs ); /* secs is your timeout in seconds */
if ( connect( fd, addr, addrlen ) < 0 )
{
if ( errno == EINTR ) /* timeout, do something below */
...
}
alarm( 0 ); /* cancel the alarm */
</code></pre>
| 36,131
|
<p>How can I go through each of the properties in my custom object? It is not a collection object, but is there something like this for non-collection objects?</p>
<pre><code>For Each entry as String in myObject
' Do stuff here...
Next
</code></pre>
<p>There are string, integer and boolean properties in my object.</p>
|
<p>By using reflection you can do that. In C# it looks like that;</p>
<pre><code>PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
</code></pre>
<hr>
<p>Added a VB.Net translation:</p>
<pre><code>Dim info() As PropertyInfo = myobject.GetType().GetProperties()
</code></pre>
|
<p>You can use reflection... With Reflection you can examine every member of a class (a Type), proeprties, methods, contructors, fields, etc.. </p>
<pre><code>using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}
</code></pre>
| 40,567
|
<p>Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing)</p>
|
<p>If you have access to the source, you can do this in the main method:</p>
<pre><code> // enable anti-aliased text:
System.setProperty("awt.useSystemAAFontSettings","on");
</code></pre>
<p>or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these options to the command line:</p>
<pre><code>-Dawt.useSystemAAFontSettings=on
</code></pre>
|
<p>thanks for the info. I was wondering about this myself.
I use SoapUI(www.eviware.com) and it does NOT, by default, use AA text. I added
-Dawt.useSystemAAFontSettings=on -Dswing.aatext=true to the batch file that launches it BUT that did NOT make a difference. Guess, I have to ask in their forum.</p>
| 21,711
|
<p>I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:</p>
<pre><code>foo = 1;
foobar = 2;
bar = 3;
</code></pre>
<p>Or this:</p>
<pre><code>if ( test_one ) return 1;
else if ( longer_test ) return 2;
else if ( shorter ) return 3;
else return 4;
</code></pre>
<p>Or this:</p>
<pre><code>thing foo_table[] =
{
{ "aaaaa", 0 },
{ "aa", 1 },
// ...
}
</code></pre>
<p>The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.</p>
<p>I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.</p>
<p>What's your view on this?</p>
|
<blockquote>
<p>I'm torn. On the one hand, lining up
like this can make repetitive code
much easier to read. On the other
hand, it does make diffs harder to
read.</p>
</blockquote>
<p>Well, since making code understandable is more important than making diffs understandable, you should not be torn.</p>
<p>IMHO lining up similar lines does greatly improve readability. Moreover, it allows easier cut-n-pasting with editors that permit vertical selection.</p>
|
<p>This is PRECISELY the reason the good Lord gave as Tabs -- adding a character in the middle of the line doesn't screw up alignment.</p>
| 12,746
|
<p>I've included a mobile web form in my asp.net project, I thought that it could/should be seen just for my mobile users but I realize that it can also be seen from any browser, I don't see problem there cause I could diff the access using HttpBrowserCapabilities.IsMobileDevice=true and transferring to the appropiate aspx page, but it results that when I access to the web form from my mobile device it is identified as IsMobileDevice = false and sends me to another page.</p>
<p>How could it be possible that?</p>
<p>The mobile device runs Pocket PC 2003.</p>
|
<p>Some are not recognized, because the UserAgent has been messed with or a new browser is being used. Such as Opera Mobile 9.5. To fix this you need to create a Browser (*.browser) file specifically for defining this. I had to do it for the new Mozilla based UserAgent that is being sent from Google.</p>
|
<p>I think you should use other DDR better than Microsoft Browser Capabilities. I´m using http://wurfl.sourceforge.net>WURFL, it is open source and maybe it is more extended and updated. There is other commercial DDRs like <a href="http://deviceatlas.com/" rel="nofollow noreferrer">DeviceAtlas</a>.</p>
<p>There is many some .net libraries but i´m using <a href="http://wurfl.marg.si/" rel="nofollow noreferrer">Marg.Wurfl</a>. It allows to rendering web mobile page using wurfl capabilities.</p>
| 3,422
|
<p>I'm using VS2008 SP1 - don't know if this would have happened before I applied SP1 as I never tried it before yesterday. I attempted to debug a fairly simple XSLT file using VS2008 SP1 and got this crash from VS2008 SP1:</p>
<hr>
<h2>Microsoft Visual Studio</h2>
<p>Unexpected error encountered. It is recommended that you restart the application as soon as possible.</p>
<p>Error: Unspecified error</p>
<p>File: vsee\pkgs\vssprovider\sccprj.cpp</p>
|
<p>We have reproduced this issue and will fix it in the next release of Visual Studio.</p>
<p>You are welcome to use <a href="http://connect.microsoft.com/" rel="nofollow noreferrer">Microsoft Connect</a> site for reporting any issues related to Visual Studio.</p>
<p>Best regards,<br/>
Anton Lapounov<br/>
Data Programmability Team @ Microsoft</p>
|
<p>The same problem, after the stylesheet finishes processing, I get Unspecified error (and eveything seems ok after closing the error message box). Selecting source control plugin to "None" in VS options gets rid of the problem. </p>
| 3,342
|
<p>I'm trying to read data from a.csv file to ouput it on a webpage as text.</p>
<p>It's the first time I'm doing this and I've run into a nasty little problem.</p>
<p>My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.</p>
<p>like this:</p>
<pre><code>$contents = file_get_contents("files/data.csv");
</code></pre>
<p>In this example file I made, there are 2 lines.</p>
<blockquote>
<p>Paul Blueberryroad
85 us Flashlight,Bag November 20,
2008, 4:39 pm</p>
<p>Hellen Blueberryroad
85 us lens13mm,Flashlight,Bag,ExtraBatteries November
20, 2008, 16:41:32</p>
</blockquote>
<p>But the string read by PHP is this:</p>
<p>Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32</p>
<p>I'm splitting this with:</p>
<pre><code>list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);
</code></pre>
<p>What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns.</p>
<p>Instead I get only Paul and the content of $orderdate[] is</p>
<blockquote>
<p>November 20, 2008, 4:39 pmHellen</p>
</blockquote>
<p>So all the rows are concatenated. Can someone show me how i can achieve what I need?</p>
<p>EDIT: solution found, just one werid thing remaining:</p>
<p>I've solved it now by using this piece of code:</p>
<pre><code>$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
</code></pre>
<p>For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.</p>
|
<p>You are better off using <a href="http://www.php.net/fgetcsv" rel="nofollow noreferrer">fgetcsv()</a> which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use <a href="http://www.php.net/manual/en/function.str-getcsv.php" rel="nofollow noreferrer">str_getcsv()</a> on the contents of the file instead.</p>
|
<p>The remark about fgetcsv is correct.</p>
<p>I will still answer your question, for educational purpose. First thing, I don't understand the difference between your data (with comas) and the "string read by PHP" (it substitutes some spaces with semi-colon, but not all?).
PS.: I looked at the source code of your message, it looks like an odd mix of TSV (tabs) and CSV (coma).</p>
<p>Beside, if you want to go this way, you need to split first the file in lines, then the lines in fields.</p>
| 40,137
|
<p>For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?</p>
<pre><code>if ($("#navbar .heading").text() > "") {
$("#navbar .heading").hide();
}
</code></pre>
<p>and </p>
<pre><code>var $heading = $("#navbar .heading");
if ($heading.text() > "") {
$heading.hide();
}
</code></pre>
<p>If the selector is more complex I can imagine it's a non-trivial hit.</p>
|
<p>jQuery doesn't, but there's the possibility of assigning to variables within your expression and then use re-using those in subsequent expressions. So, cache-ifying your example ...</p>
<pre><code>if ((cached = $("#navbar .heading")).text() > "") {
cached.hide();
}
</code></pre>
<p>Downside is it makes the code a bit fuglier and difficult to grok.</p>
|
<p>Check if this helps <a href="https://plugins.jquery.com/cache/" rel="nofollow">https://plugins.jquery.com/cache/</a></p>
<p>Came across this as part of our regular project</p>
| 37,225
|
<p>What are optimal settings for Recycling of Application Pools in IIS7 in a shared environment?</p>
<p><img src="https://i.stack.imgur.com/RNQo8.png" alt="enter image description here"></p>
|
<p>As a Hoster, you definitely want to recycle on Memory & Time, potentially Request limits and CPU. You want to be pretty aggressive about these limits, but make sure you publish them to your clients.</p>
<p><a href="https://technet.microsoft.com/en-us/library/cc725749(v=ws.10).aspx" rel="noreferrer"><strong>Memory</strong></a> - 512 for an x86 box, maybe 768. For x64, you can set this much higher depending on the number of hosts per server. You just have to be careful and watch your app pool recycle events on memory issues.</p>
<p><a href="https://technet.microsoft.com/en-us/library/cc754494(v=ws.10).aspx" rel="noreferrer"><strong>Time</strong></a> - We typically recycle at 1 am in the morning, plus or minus (first site 1:01, second 1:11, third 1:21, just so you don't have all recycling at the same time) </p>
<p><a href="https://technet.microsoft.com/en-us/library/cc770469(v=ws.10).aspx" rel="noreferrer"><strong>Request limit</strong></a> - 35,000 was the default for IIS6, but this number is quite arbitrary, and very dependant on the site in question. For small usage sites, the nightly recycle will hit long before you get 35k requests.</p>
<p><a href="http://www.iis.net/configreference/system.applicationhost/applicationpools/add/cpu" rel="noreferrer"><strong>CPU</strong></a> - 95%/1 minute limit/KillW3WP, but use this carefully. My understanding of this is that if the CPU hits 95%+ over the 1 minute limit for this worker process, the worker process gets killed and is unable to restart for the remainder of the limit when Action is set to KillW3WP. You might want to try NoAction initially and just watch your event logs carefully.</p>
<p><a href="https://technet.microsoft.com/en-us/library/cc771318(v=ws.10).aspx" rel="noreferrer"><strong>Recycle Event Logs</strong></a> - You want to make sure you are logging app pool recycles for each event threshhold that you set - i.e. if you limit based off of requests limits, make sure that Request Limit logging is enabled.</p>
<p>One thing to remember is that you <em>should</em> set <code>retail="true"</code> in the <code><deployment></code> element in your <a href="http://www.iis.net/learn/get-started/planning-your-iis-architecture/the-configuration-system-in-iis-7" rel="noreferrer">machine.config</a>:</p>
<pre class="lang-xml prettyprint-override"><code><system.web>
<!--
<deployment
retail = "false" [true|false]
/>
-->
<deployment retail="true" />
</system.web>
</code></pre>
<p>Not setting this will allow a site to turn debugging on, which allows unlimited timeouts in requests - not exactly ideal for a hoster...</p>
|
<p>you need to cater the settings to your needs, take into account the amount of memory you have and the peak times of usage for your site/web application.</p>
<p>Also take into account the memory usage of your site/web application as if there are memory leaks you might be recycling more often then you think.</p>
<p>Weigh up any leaks against the cost of recycling, as stated above you will lose state variables.</p>
| 24,197
|
<p>I just bought new TEVO Tarantula and tried to print xyz cube. I found that my cube's layer was shifted as showed in picture. How can I fix this ?</p>
<p><a href="https://i.stack.imgur.com/u53fC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/u53fC.jpg" alt="enter image description here"></a></p>
|
<p>From an electrical standpoint, a two-phase stepper motors (what most 3D printers use) works the same backwards and forwards, the phase just reverses. If you are stalling on only one direction, I would look to see if you have a mechanical bind in that direction. Generally a wiring issue will cause the motor to either not run at all or to run in the wrong direction.</p>
<p>A few things you can check:</p>
<ol>
<li>Decouple the motors from their mechanical load and confirm that they all run correctly when they aren't driving a load. If you can't do that, disconnect them all then connect a spare motor to each cable one-at-a-time.</li>
<li>Turn each of the axis with your hand and make sure it turns smoothly throughout the entire range in both directions. Note: Some times a binding issue is acceleration related - a loose frame or coupling can cause this.</li>
<li>Monitor the supply voltage to make sure that one of the motors is not pulling the supply down causing all the others to stall.</li>
</ol>
|
<p>Sounds like you are configured for NC switches but are using NO switches, causing them to invert their reported state. Issue a <strong>M119</strong> command and see if the endstop statuses are correct when none are triggered.</p>
| 773
|
<p>What are the pros and cons of using a hosting provider for a Subversion repository versus maintaining it in-house? I'm sure there are benefits in terms of ease of set up and use. And it would be nice to have somebody else make sure that our code is backed up properly. </p>
<p>However, Visual SVN Server is dirt simple to set up, and we already have a pre-established set of servers that are maintained by another department and backed up regularly. So with that said, what are the big pros and cons of using a hosted service versus maintaining it ourselves?</p>
<p>Cross links:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/99743/what-are-some-decent-isps-that-host-subversion">What Are Some Decent ISPs That Host Subversion</a></li>
<li><a href="https://stackoverflow.com/questions/140090/where-should-a-subversion-repository-be">Where Should a Subversion Repository Be</a></li>
<li><a href="https://stackoverflow.com/questions/33513/should-i-use-a-software-hosting-solution-for-my-personal-projects">Should I use software hosting solution for my personal projects</a></li>
</ul>
|
<p>If you already have the infrastructure in place and are confident in your ability to host, backup and provide accessibility to your repositories then I would say that hosting SVN yourself is the way to go. This allows you relatively unlimited growth and total control over your source.</p>
<p>If you have a primarily mobile development workforce that are small in number then the cost and limitations of using a hosted provider might make it far more convenient for you. But this applies to very few companies.</p>
|
<p>Several previous SO threads have discussed this:</p>
<p><a href="https://stackoverflow.com/questions/99743/what-are-some-decent-isps-that-host-subversion">What Are Some Decent ISPs That Host Subversion</a>
<a href="https://stackoverflow.com/questions/140090/where-should-a-subversion-repository-be">Where Should a Subversion Repository Be</a>
<a href="https://stackoverflow.com/questions/33513/should-i-use-a-software-hosting-solution-for-my-personal-projects">Should I use software hosting solution for my personal projects</a></p>
<p>I am sure I've seen couple more, but I can't find them right now.</p>
| 20,594
|
<p>I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary?</p>
<p>This will be for Ubuntu machines.</p>
|
<p>Does</p>
<pre><code>uname -a
</code></pre>
<p>give you anything you can use? I don't have a 64-bit machine to test on.</p>
<hr>
<p><strong>Note from Mike Stone:</strong> This works, though specifically</p>
<pre><code>uname -m
</code></pre>
<p>Will give "x86_64" for 64 bit, and something else for other 32 bit types (in my 32 bit VM, it's "i686").</p>
|
<p>Yes, <strong>uname -a</strong> should do the trick. see: <a href="http://www.stata.com/support/faqs/win/64bit.html" rel="nofollow noreferrer">http://www.stata.com/support/faqs/win/64bit.html</a>. </p>
| 13,187
|
<p>I've just installed CodeGear Studio 2009 and I didn`t find where I can put the Intellisense and code hints on.</p>
<p>And, by the way, in Visual Studio we can indent selected blocks of code in the same way. How can I use similar functions in CodeGear?</p>
<p>Any ideas about that?</p>
|
<p>It's called Code Insight. I don't have 2009 yet but it's probably in the same place as 2007. Have a look in <strong>Tools > Options > Editor Options > Code Insight</strong>.</p>
<p>By the way, it's no where near as good as Intellisense in VS.</p>
|
<p>The generic name is called "code completing", intellisense and insight are just catching marketing spun names companies use.</p>
| 33,955
|
<pre><code>public class MyClass
{
public int Age;
public int ID;
}
public void MyMethod()
{
MyClass m = new MyClass();
int newID;
}
</code></pre>
<p>To my understanding, the following is true:</p>
<ol>
<li>The reference m lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The value type newID lives on the stack and goes out of scope when MyMethod() exits.</li>
<li>The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. </li>
</ol>
<p>Here is my question:</p>
<ol>
<li>Do value types within objects live on the stack or the heap?</li>
<li>Is boxing/unboxing value types in an object a concern?</li>
<li>Are there any detailed, yet understandable, resources on this topic?</li>
</ol>
<p>Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.</p>
<p>Edit:</p>
<p>Suggested reading for this topic:</p>
<ol>
<li><a href="http://www.microsoft.com/MSPress/books/6522.aspx" rel="nofollow noreferrer">CLR Via C# by Jeffrey Richter</a></li>
<li><a href="http://books.google.com/books?id=Kl1DVZ8wTqcC&dq=essential+.net&pg=PP1&ots=5a-UEHSLVJ&sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPP1,M1" rel="nofollow noreferrer">Essential .NET by Don Box</a></li>
</ol>
|
<p>Value-type values for a class <em>have</em> to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack?</p>
<p>A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field.</p>
<p>Take for example, a simple class with a single field.</p>
<pre><code>public class EmbeddedValues
{
public int NumberField;
}
</code></pre>
<p>And with it, a simple testing class.</p>
<pre><code>public class EmbeddedTest
{
public void TestEmbeddedValues()
{
EmbeddedValues valueContainer = new EmbeddedValues();
valueContainer.NumberField = 20;
int publicField = valueContainer.NumberField;
}
}
</code></pre>
<p>If you use the MSIL Disassembler provided by the .NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues()</p>
<pre><code>.method public hidebysig instance void TestEmbeddedValues() cil managed
{
// Code size 23 (0x17)
.maxstack 2
.locals init ([0] class soapextensions.EmbeddedValues valueContainer,
[1] int32 publicField)
IL_0000: nop
IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.s 20
IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField
IL_000f: ldloc.0
IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField
IL_0015: stloc.1
IL_0016: ret
} // end of method EmbeddedTest::TestEmbeddedValues
</code></pre>
<p>Notice the CLR is being told to <strong>stfld</strong> the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses <strong>ldfld</strong> instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations.</p>
|
<p>A variable or other storage location of a structure type is an aggregation of that type's public and private instance fields. Given</p>
<pre><code>struct Foo {public int x,y; int z;}
</code></pre>
<p>a declaration <code>Foo bar;</code> will cause <code>bar.x</code>, <code>bar.y</code>, and <code>bar.z</code> to be stored wherever <code>bar</code> is going to be stored. Adding such a declaration of <code>bar</code> to a class will, from a storage-layout perspective, be equivalent to adding three <code>int</code> fields. Indeed, if one never did anything with <code>bar</code> except access its fields, the fields of <code>bar</code> would behave the same as would three fields <code>bar_x</code>, <code>bar_y</code>, and <code>bar_cantaccessthis_z</code> [accessing the last one would require doing things with <code>bar</code> other than accessing its fields, but it would take up space whether or not it's ever actually used for anything].</p>
<p>Recognizing structure-type storage locations as being aggregations of fields is the first step to understanding structures. Trying to view them as holding some kind of object might seem "simpler", but doesn't match how they actually work.</p>
| 4,447
|
<p>I need to pivot one column (Numbers column).
example need this data:</p>
<pre><code>a 1
a 2
b 3
b 4
c 5
d 6
d 7
d 8
d 9
e 10
e 11
e 12
e 13
e 14
</code></pre>
<p>Look like this</p>
<pre><code>a 1 2
b 3 4
c 5
d 6 7 8 9
e 10 11 12 13 14
</code></pre>
<p>any help would be greatly appreciated...</p>
|
<p>Using <code>ROW_NUMBER()</code>, <code>PIVOT</code> and some dynamic SQL (but no cursor necessary) :</p>
<pre><code>CREATE TABLE [dbo].[stackoverflow_198716](
[code] [varchar](1) NOT NULL,
[number] [int] NOT NULL
) ON [PRIMARY]
DECLARE @sql AS varchar(max)
DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique
DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique
SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'
,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']'
FROM (
SELECT DISTINCT PIVOT_CODE
FROM (
SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE
FROM stackoverflow_198716
) AS rows
) AS PIVOT_CODES
SET @sql = '
;WITH p AS (
SELECT code, number, ROW_NUMBER() OVER (PARTITION BY code ORDER BY number) AS PIVOT_CODE
FROM stackoverflow_198716
)
SELECT code, ' + @select_list + '
FROM p
PIVOT (
MIN(number)
FOR PIVOT_CODE IN (
' + @pivot_list + '
)
) AS pvt
'
PRINT @sql
EXEC (@sql)
</code></pre>
|
<p>I'm not sure that what you're doing is really possible (or at least practical) in SQL - I'm not sure, because I'm still not exactly sure what you want to do.</p>
<p>You could build that pivot table in your client application, for example with:</p>
<pre><code>select distinct Letter from MyTable
</code></pre>
<p>to get the list of letters, and then use a parameterized query inside a loop:</p>
<pre><code>select Number from MyTable where Letter=:letter
</code></pre>
<p>to get the list of numbers for each letter.</p>
| 24,217
|
<p>I am trying to get more processing power out of my grid.</p>
<p>I am using all cpus/cores, is it possible to utilize the GPU with C#.</p>
<p>Anyone know any libraries or got any sample code?</p>
|
<p>[<em>Edit OCT 2017 as even this answer gets quite old</em>]</p>
<p>Most of these answers are quite old, so I thought I'd give an updated summary of where I think each project is: </p>
<ul>
<li><p><a href="https://github.com/tidepowerd/GPU.NET-Example-Projects" rel="noreferrer">GPU.Net</a> (TidePowerd) - I tried this 6 months ago or so, and did get it working though it took a little bit of work. Converts C# kernel code to cuda at compile time. Unfortunately their website has been down and their github hasn't been updated for a couple of years, which might indicate the project is dead....</p></li>
<li><p><a href="https://cudafy.codeplex.com/" rel="noreferrer">Cudafy</a> - Open source and very easy to use. Converts C# kernel code to cuda at runtime (with ability to serialize and cache). Can easily run the same kernel code on the CPU (mostly for debugging). Supports multiple GPUs. More examples available than others here. The boilerplate code referred to by other answers is minimal, and in my case at least helped with my understanding of how the code works. Cuda/Nvidia only though. Unfortunately, it seems that they didn't update their solutions for a couple of years too (latest commit in 2015 -- support of cuda 7.0).</p></li>
<li><p><a href="http://www.altimesh.com/" rel="noreferrer">Hybridizer</a>. Commercial solution compiling C# to CUDA. Provides a free community edition on <a href="https://marketplace.visualstudio.com/items?itemName=altimesh.AltimeshHybridizerExtensionEssentials" rel="noreferrer">visual studio marketplace</a> and samples on <a href="https://github.com/altimesh/hybridizer-basic-samples" rel="noreferrer">github</a>.</p></li>
<li><p><a href="http://www.aleagpu.com/release/3_0_3/doc/" rel="noreferrer">AleaGPU</a> Commercial solution with a free community edition for consumer GPUS. See Daniel's comments for details. </p></li>
<li><p><a href="https://brahma.codeplex.com/" rel="noreferrer">Brahma</a> - runs LINQ expressions via OpenCL (so supports AMD too). Not much documentation / examples. Last update in 2011.</p></li>
<li><p><a href="https://cbucks.codeplex.com/" rel="noreferrer">C$</a> - last development was over 10 years ago...</p></li>
<li><p><a href="http://research.microsoft.com/en-us/projects/accelerator/" rel="noreferrer">Microsoft Accelerator</a> - similarly doesn't look like it is being actively developed any longer.</p></li>
<li><p>some others (<a href="http://blogs.msdn.com/b/nativeconcurrency/archive/2011/09/13/c-amp-in-a-nutshell.aspx" rel="noreferrer">C++ AMP</a>, <a href="http://www.opentk.com/" rel="noreferrer">OpenTK -- dead</a>/<a href="http://sourceforge.net/projects/cloo/" rel="noreferrer">Cloo</a>) - many of these are just bindings - ie enable you to call the GPU from C#, but your kernel code (code which is actually run on the GPU) needs to be written in C or OpenCL, meaning you must use (and learn) another language.</p></li>
</ul>
<p>As I said, I would recommend Cudafy over all the others - if it could run on OpenCL as well as Cuda it would be perfect.</p>
<p><strong>EDIT SEP 2013</strong>
Cudafy now allows you to compile for <em>both</em> CUDA and OpenCL, so will run the same C# code on on all GPUs. This sounds fantastic, though I haven't tested the OpenCL compiling yet.</p>
|
<p>WPF also uses the GPU and you can add custom shaders using HLSL.</p>
<ul>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/greg_schechter/a-series-on-gpu-based-effects-for-wpf" rel="nofollow noreferrer">A Series on GPU-based Effects for WPF</a> (Greg Schechter's Blog)</li>
</ul>
| 49,063
|
<p>My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:</p>
<ol>
<li>I put a <code>DropDownList</code> of the 4-digit year on the page.</li>
<li>I validate the expiration date in a <code>DateTime</code> field to be sure that the expiration date being passed to the CC processor isn't expired.</li>
<li>I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.</li>
</ol>
<p>Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the <code>DateTime</code> object. Or should I just keep processing it as I am?</p>
|
<p>If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:</p>
<pre><code>DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");
</code></pre>
<p>Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.</p>
|
<p>Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.</p>
| 14,068
|
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p>
<p>Can someone make it clear to me? Thanks.</p>
|
<p>As @Guillaume says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the <code>metavar</code> parameter to the <code>add_option</code> call so your preferred argument name/descriptor is output in the help message. From <a href="http://docs.python.org/library/optparse.html#generating-help" rel="noreferrer">the current module documentation</a>:</p>
<pre><code>usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--filename",
metavar="FILE", help="write output to FILE"),
</code></pre>
<p>would produce help like this:</p>
<pre><code>usage: <yourscript> [options] arg1 arg2
options:
-f FILE, --filename=FILE
</code></pre>
<p>The "FILE" after the "-f" and the "--filename" comes from the metavar.</p>
|
<p><code>metavar</code> is a variable used for print in the screen after option. Usually used for suggestion input after option are <code>FILE</code> or <code>INT</code> or <code>STRING</code> to user. Without <code>metavar</code>, <code>optparse</code> will print <code>dest</code> value after option you've been added.</p>
| 43,718
|
<p>My problem is:</p>
<p>I have a perl script which uses lot of memory (expected behaviour because of caching). But, I noticed that the more I do caching, slower it gets and the process spends most of the time in sleep mode.</p>
<p>I thought pre-allocating memory to the process might speed up the performance.</p>
<p>Does someone have any ideas here?</p>
<p><strong>Update</strong>:</p>
<p>I think I am not being very clear here. I will put question in clearer way:</p>
<p>I am not looking for the ways of pre-allocating inside the perl script. I dont think that would help me much here. What I am interested in is a way to tell OS to allocate X amount of memory for my perl script so that it does not have to compete with other processes coming in later.</p>
<p>Assume that I cant get away with the memory usage. Although, I am exploring ways of reducing that too but dont expect much improvement there.
FYI, I am working on a solaris 10 machine.</p>
|
<p>What I gathered from your posting and comments is this:</p>
<ul>
<li>Your program gets slow when memory use rises</li>
<li>Your pogram increasingly spends time sleeping, not computing.</li>
</ul>
<p>Most likely eplanation: Sleeping means waiting for a resource to become available. In this case the resource most likely is memory. Use the vmstat 1 command to verify. Have a look at the sr column. If it goes beyond ~150 consistently the system is desperate to free pages to satisfy demand. This is accompanied by high activity in the pi, po and fr columns.</p>
<p>If this is in fact the case, your best choices are:</p>
<ul>
<li>Upgrade system memory to meet demand</li>
<li>Reduce memory usage to a level appropiate for the system at hand.</li>
</ul>
<p>Preallocating memory will not help. In either case memory demand will exceed the available main memory at some point. The kernel will then have to decide which pages need to be in memory now and which pages may be cleared and reused for the more urgently needed pages. If all regularily needed pages (the working set) exceeds the size of main memory, the system is constantly moving pages from and to secondary storage (swap). The system is then said to be thrashing and spends not much time doing useful work. There is nothing you can do about this execept adding memory or using less of it.</p>
|
<p>Some questions you might ask yourself:</p>
<ul>
<li>are my data structures really useful for the task at hand?</li>
<li>do I really have to cache that much?</li>
<li>can I throw away cached data after some time? </li>
</ul>
| 15,552
|
<p>I have the following code:</p>
<pre><code>SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
</code></pre>
<p>Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?</p>
<p>(This question is related to a <a href="https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count">previous one</a>)</p>
|
<p>To say that <code>SELECT COUNT(*) vs COUNT(1)</code> results in your DBMS returning "columns" is pure bunk. That <em>may</em> have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is <strong>NO</strong> performance difference between <code>SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation')</code></p>
<p>Moreover, <code>SELECT(1) vs SELECT(*)</code> will NOT have any difference in INDEX usage -- most DBMS will actually optimize <code>SELECT( n ) into SELECT(*)</code> anyway. See the ASK TOM: Oracle has been optimizing <code>SELECT(n) into SELECT(*)</code> for the better part of a decade, if not longer:
<a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789" rel="noreferrer">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789</a></p>
<blockquote>
<p>problem is in count(col) to count(<em>)
conversion
<strong></em> **03/23/00</strong> 05:46 pm *** one workaround is to set event 10122 to
turn off count(col) ->count(<em>)
optimization. Another work around is
to change the count(col) to count(</em>),
it means the same, when the col has a
NOT NULL constraint. The bug number is
1215372.</p>
</blockquote>
<p>One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise). </p>
<p>Bottom line: if what you want is the count of rows in a table, use COUNT(*)</p>
|
<p>MySQL: According to the MySQL website, <code>COUNT(*)</code> is faster for single table queries when using MyISAM:</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count</a></p>
<p>I'm guessing with a having clause with a count in it may change things.</p>
| 8,389
|
<p>Is there anyway to get the THotkey component in delphi to support the windows key?</p>
<p>Or does anyone know of a component that can do this?</p>
<p>Thanks heaps!</p>
|
<p>IMHO it is a good thing THotKey does not support this.</p>
<p>Don't use the windows key for keyboard shortcuts in your program, the "Windows Vista User Experience Guidelines" says the following under <a href="http://msdn.microsoft.com/en-us/library/bb545460.aspx" rel="noreferrer">Guidelines - Interaction - Keyboard</a>:</p>
<blockquote>
<p>Don't use the Windows logo modifier key for program shortcut keys. Windows logo key is reserved for Windows use. Even if a Windows logo key combination isn't being used by Windows now, it may be in the future.</p>
</blockquote>
<p>Even if the shortcut isn't used by Windows, using such a keyboard shortcut would be confusing to users, as it would perform a function in your program, while other such shortcuts like Win+E or Win+R activate a system-wide function, deactivating your program in the process.</p>
<p><strong>Edit:</strong></p>
<p>THotKey is a light wrapper around a system control, supporting only the things that this system control supports. There is no documented way to set anything but the Alt, Ctrl and Shift modifiers for the shortcut.</p>
<p>You might be able to create your own control to display shortcuts using the Windows key, and set a global keyboard hook (look into the <em>SetWindowsHookEx()</em> API function).</p>
|
<p>I don't know if you can do it with the THotkey component.</p>
<p>But you can capture the left and right Windows Key in any KeyDown event using:</p>
<blockquote>
<p>if key = vk_LWin then showmessage('left');<br>
if key = vk_RWin then showmessage('right');</p>
</blockquote>
| 42,503
|
<p>Here's what I would like to do:</p>
<p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p>
<p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p>
<p>I'm looking for simplicity rather than perfection.
I'm using python.</p>
|
<h2>General idea</h2>
<p>Option 1: Load both images as arrays (<code>scipy.misc.imread</code>) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.</p>
<p>Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.</p>
<p>However, there are some decisions to make first.</p>
<h2>Questions</h2>
<p>You should answer these questions first:</p>
<ul>
<li><p>Are images of the same shape and dimension?</p>
<p>If not, you may need to resize or crop them. PIL library will help to do it in Python.</p>
<p>If they are taken with the same settings and the same device, they are probably the same.</p></li>
<li><p>Are images well-aligned?</p>
<p>If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.</p>
<p>If the camera and the scene are still, the images are likely to be well-aligned.</p></li>
<li><p>Is exposure of the images always the same? (Is lightness/contrast the same?)</p>
<p>If not, you may want <a href="http://en.wikipedia.org/wiki/Normalization_(image_processing)" rel="noreferrer">to normalize</a> images.</p>
<p>But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.</p></li>
<li><p>Is color information important?</p>
<p>If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.</p></li>
<li><p>Are there distinct edges in the image? Are they likely to move?</p>
<p>If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.</p></li>
<li><p>Is there noise in the image?</p>
<p>All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.</p></li>
<li><p>What kind of changes do you want to notice?</p>
<p>This may affect the choice of norm to use for the difference between images.</p>
<p>Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.</p></li>
</ul>
<h2>Example</h2>
<p>I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.</p>
<p>You will need these imports:</p>
<pre><code>import sys
from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average
</code></pre>
<p>Main function, read two images, convert to grayscale, compare and print results:</p>
<pre><code>def main():
file1, file2 = sys.argv[1:1+2]
# read images as 2D arrays (convert to grayscale for simplicity)
img1 = to_grayscale(imread(file1).astype(float))
img2 = to_grayscale(imread(file2).astype(float))
# compare
n_m, n_0 = compare_images(img1, img2)
print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size
print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size
</code></pre>
<p>How to compare. <code>img1</code> and <code>img2</code> are 2D SciPy arrays here:</p>
<pre><code>def compare_images(img1, img2):
# normalize to compensate for exposure difference, this may be unnecessary
# consider disabling it
img1 = normalize(img1)
img2 = normalize(img2)
# calculate the difference and its norms
diff = img1 - img2 # elementwise for scipy arrays
m_norm = sum(abs(diff)) # Manhattan norm
z_norm = norm(diff.ravel(), 0) # Zero norm
return (m_norm, z_norm)
</code></pre>
<p>If the file is a color image, <code>imread</code> returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. <code>.pgm</code>):</p>
<pre><code>def to_grayscale(arr):
"If arr is a color image (3D array), convert it to grayscale (2D array)."
if len(arr.shape) == 3:
return average(arr, -1) # average over the last axis (color channels)
else:
return arr
</code></pre>
<p>Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. <code>arr</code> is a SciPy array here, so all operations are element-wise:</p>
<pre><code>def normalize(arr):
rng = arr.max()-arr.min()
amin = arr.min()
return (arr-amin)*255/rng
</code></pre>
<p>Run the <code>main</code> function:</p>
<pre><code>if __name__ == "__main__":
main()
</code></pre>
<p>Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:</p>
<pre><code>$ python compare.py one.jpg one.jpg
Manhattan norm: 0.0 / per pixel: 0.0
Zero norm: 0 / per pixel: 0.0
</code></pre>
<p>If we blur the image and compare to the original, there is some difference:</p>
<pre><code>$ python compare.py one.jpg one-blurred.jpg
Manhattan norm: 92605183.67 / per pixel: 13.4210411116
Zero norm: 6900000 / per pixel: 1.0
</code></pre>
<p>P.S. Entire <a href="http://gist.github.com/626356" rel="noreferrer">compare.py</a> script.</p>
<h2>Update: relevant techniques</h2>
<p>As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:</p>
<ul>
<li>background subtraction and segmentation (to detect foreground objects)</li>
<li>sparse optical flow (to detect motion)</li>
<li>comparing histograms or some other statistics instead of images</li>
</ul>
<p>I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV ≥ 2.3, and its <code>cv2</code> Python module.</p>
<p>The most simple version of the background subtraction:</p>
<ul>
<li>learn the average value μ and standard deviation σ for every pixel of the background</li>
<li>compare current pixel values to the range of (μ-2σ,μ+2σ) or (μ-σ,μ+σ)</li>
</ul>
<p>More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).</p>
<p>The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use <a href="http://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_method" rel="noreferrer">Lucas-Kanade method</a> (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.</p>
<p>Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in <a href="http://www.sciencedirect.com/science/article/pii/S0967066110000808" rel="noreferrer">Courbon et al, 2010</a>:</p>
<blockquote>
<p><em>Similarity of consecutive frames.</em> The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence" rel="noreferrer">Kullback–Leibler distance</a>, or mutual entropy, on the histograms of the two frames:</p>
<p><img src="https://i.imgur.com/hdeh8ni.gif" alt="$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$"></p>
<p>where <em>p</em> and <em>q</em> are the histograms of the frames is used. The threshold is fixed on 0.2.</p>
</blockquote>
|
<p>I think you could simply compute the euclidean distance (i.e. sqrt(sum of squares of differences, pixel by pixel)) between the luminance of the two images, and consider them equal if this falls under some empirical threshold. And you would better do it wrapping a C function.</p>
| 23,047
|
<p>On a budget, I'm water-cooling a 3D printer. I'm using a 5 V aquarium pump (\$3). Originally I tried to only use about as much water in a can of chickpeas but then found out i needed a lot more. I have a deliberate need to water cool stepper motors in the first printer, so that I can print with a high temperature filament like PEI (the operating temp of a stepper is maxed at about 53 degrees celsius; PEI requires an enclosure temperature of 80 °C), but on another printer I'm having some other issues with the motors that I think could be solved by better heat dissipation.</p>
<p>What I am getting to is a device like <a href="https://rads.stackoverflow.com/amzn/click/com/B07DLQJKKC" rel="nofollow noreferrer" rel="nofollow noreferrer">this</a>: </p>
<p><a href="https://i.stack.imgur.com/DYx39.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DYx39.jpg" alt="e"></a></p>
<p>It is the perfect size for a stepper motor. My plan is to zip-tie one of these to each stepper motor and water cool it in a single path across my printer, including the hot end.</p>
<p>Can anyone think of a reason why this wouldn't work? i just haven't heard of anyone doing anything like this, but it makes sense to me as a chemistry minor. The specific heat of water is way higher than almost anything else. And it is way less noisy than fans. And it works inside an enclosure, while fans might not</p>
<p>Should I ziptie the aluminum block to the back part of the stepper where the metal is, or to one of the darker black sides?</p>
<p>Would I be able to 3D print a cooling block like this instead of paying for it? See also <a href="https://3dprinting.stackexchange.com/questions/11043/what-is-the-thermal-conductivity-of-various-3d-printing-filaments">this relevant question on thermal conductivity of various 3D printing filaments</a>. It should probably be metal to transfer heat better? </p>
|
<p>Cooling any single face of the motor is fine. The motor case conducts heat <em>very</em> well. Many 3d printers effectively cool the motors merely by having the output drive face of the motor bolted to a metal bracket which is bolted to the aluminum extrusion frame. That's it. That contact alone cools the motor, which is shown by how the motors overheat when people install vibration dampers, which puts rubber between the motor and the extrusion.</p>
<p>The only thing I would worry about is the surface area inside this particular style of block, and ensuring that you use an all-aluminum radiator since the block is aluminum.</p>
<p>There is another type of cheap 40x40 aluminum block with the nipples on the face instead of on the edge. That style has fins and a lot of surface area inside. This style with the nipples on the edge has a big S channel inside and not much surface area. It may still be more than enough. I'm just saying it's a significant difference and it might make a difference. If you find you're not cooling enough, all you may need to do is switch to that other style of block, not try to install 3 blocks per motor or any other exotic nonsense.</p>
<p>But no way do you have to worry about coooling more than one face of the motor, nor does it matter rwhich face it is, especially not with active water cooling like this, as long as the block is actually making good thermal contact with the motor (thermal tape, or thermal epoxy, or thermal pad & zip ties)</p>
|
<p>Your solution will not cool all sides effectively. Firstly don't use zip ties; get thermal tape.</p>
<p><a href="https://i.stack.imgur.com/uC6tD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uC6tD.jpg" alt="Thermal Tape"></a>
(<a href="https://rads.stackoverflow.com/amzn/click/com/B00QSHPH8E" rel="nofollow noreferrer" rel="nofollow noreferrer">https://www.amazon.com/Thermal-Interface-Products-Heat-Sink/dp/B00QSHPH8E/</a></p>
<p>Secondly, the heat will need to travel around the outside of the motor to get from the side that doesn't have the water block. Its expensive but you could use <a href="https://www.digikey.com/en/product-highlight/p/panasonic/pyrolytic-graphite-sheets" rel="nofollow noreferrer">Pyrolytic Graphite Sheets</a> to wrap around the outside of the motor, to get the heat to the water block faster.</p>
| 1,451
|
<p>I am looking for a general UI design / work-flow for changing the same property across multiple objects. </p>
<p>Suppose I have an object class called Person. The Person class has a property called City. I want to select 5 Person objects and change the City property on all 5 to "New York" in one action in the UI. </p>
<p>This is not difficult to accomplish programatically, but I am having a difficult time coming up with an intuitive UI work-flow. One thought is to use a modal like the one used in iTunes to change information about multiple selected songs. I would like to come up with another work-flow, as this idea has already gotten push-back at work.</p>
<p>Thoughts? Ideas?</p>
<p><strong>Edit:</strong> I appreciate the answers so far. There are couple of extra points I would like to call out:</p>
<ol>
<li>Should the previous City values be display in some way? If so, how? Or how should the combined property screen show that all the City values are currently the same or different with a color or other indicator?</li>
<li>How should boolean properties (Person.IsAlive for example) be displayed? Do you use a three-state toggle/check box? Us a drop-down with three values? Other ideas?</li>
</ol>
|
<p>Take the iTunes solution, ditch the modal window and display it in your application as you would otherwise display a single entry's edit view. Keep in mind that iTunes has a modal window for editing single entries as well.</p>
|
<p>One approach would be a split pane setup where all People were on one side, and all properties of people were on the other side.</p>
<p>Obviously this would work poorly for editing single people though.</p>
| 22,346
|
<p>Scott Hanselman <a href="http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx" rel="noreferrer">says yes</a>.</p>
<blockquote>
<p>Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.</p>
</blockquote>
<p>MSDN <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx" rel="noreferrer">says no</a>.</p>
<blockquote>
<p>The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.</p>
</blockquote>
<p>So what should I think?</p>
|
<p>I realize this question is old, but in the interest of helping anyone who finds this via search, its worth noting that .net v4 includes a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace:</p>
<p><a href="https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/dd997357(v=vs.110).aspx</a></p>
<p>The static reference to the default cache instance is: MemoryCache.Default</p>
|
<p>Why not avoid the question completely and use the <a href="http://msdn.microsoft.com/en-us/library/cc511588.aspx" rel="nofollow noreferrer">Caching Block of Enterprise Library</a>? You could use the System.Web.Caching, but you probably won't get Microsoft support if you run into issues and you'll raise eyebrows so it might not be worth it.</p>
| 19,196
|
<p>I am attempting to build a 3D printer using the <a href="https://github.com/gregsaun/prusa_i3_bear_upgrade" rel="nofollow noreferrer">Bear Upgrade</a> for guidance.</p>
<p>However, I want to modify some of the parts. I am basing the modified parts on the original designs.</p>
<p>I would like to understand the reason behind some design details presented on the original designs so that, if necessary, introduce them into the new designs. </p>
<p><a href="https://i.stack.imgur.com/XTG3N.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XTG3N.jpg" alt="example of design with details I don't understand the reason behind"></a></p>
<p>Item 1) The holes are not round. Why???</p>
<p>Item 2 ) There are some little squares inside the piece which i don't know if they are there for some structural reason </p>
<p>Please use <a href="https://github.com/gregsaun/prusa_i3_bear_upgrade/blob/master/full_upgrade/for_mk3/printed_parts/step/y_idler.step" rel="nofollow noreferrer">this link</a> to the piece depicted above. </p>
<p>Here is a drawing of the full assembly, showing that this piece is the y axes linear rods holder:</p>
<p><a href="https://i.stack.imgur.com/rOAzb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rOAzb.jpg" alt="enter image description here"></a></p>
|
<blockquote>
<p>Item 1) The holes are not round. Why???</p>
</blockquote>
<p>Two things about this. First, the print is upside down. The holes are not round to accommodate the fact you cannot print a round hole unsupported. If you try to print the circle unsupported, when you get to the top portion, it will sag until the print catches up to it. By that time, the circle is flat at the top and you won't be able to fit whatever you were trying to fit into it (without some post processing). Printing the V-ish looking part at the top will ensure you'll be able fit things through it you meant to fit through (sorry if that's redundant). If you'd like to know more, take a look at the following Maker's Muse video:</p>
<p><div class="youtube-embed"><div>
<iframe width="640px" height="395px" src="https://www.youtube.com/embed/j6508J94VsA?start=0"></iframe>
</div></div> </p>
<blockquote>
<p>Item 2 ) There are some little squares inside the piece which i don't know if they are there for some structural reason</p>
</blockquote>
<p>To be very honest with you, I don't know why the little squares are there either, however, I believe you can answer this part for yourself.</p>
<p>I think the answer lies in the part, meaning, if you can manipulate the 3d design in whatever you're using to design it, you can look into the part and see what's going on with it. It appears there are dashed lines in the center parts, which would make me believe these are <em>hidden lines</em>. There is a feature there which is <em>inside</em> of the part which you cannot see otherwise. By turning it, you should be able to decipher what these features are for and therefore should be able to discern what the small squares a for as well. If, after you've looked the part over completely you cannot discern a purpose for the squares, don't design them into your part. It may just be they are an artifact of the design itself and doesn't provide anything worth repeating in your own design. Bottom line, don't get hung up on the minute details which in the end don't mean a thing.</p>
|
<p>Teardrop shape
ere is a feature there which is inside of the part which you cannot see otherwise. By turning it, you should be able to decipher what these features are for and therefore should be able to</p>
| 1,533
|
<p>I am having some performance problems with my Delphi 2006 app.
Can you Suggest any profiling tools that will help me find the bottle neck </p>
<p>i.e. A tool like turbo Profiler</p>
|
<p>I asked the same <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi">question</a> not too long ago</p>
<p>I've downloaded and tried AQtime. It does seem comprehensive, but it is not an easy to use tool and is VERY expensive for an individual programmer (i.e. $600 US). I loved the fact that it was non-invasive (did not change your code), and that it could do line-by-line profiling, until I found that because it is an instrumenting profiler, it can lead to improper optimizations as in: <a href="https://stackoverflow.com/questions/332948/why-is-charinset-faster-than-case-statement">Why is CharInSet faster than Case statement?</a></p>
<p>I tried a demo of ProDelphi, much less expensive (about $80 I think), but it was much too clunky for me - I didn't like the user interface at all, and it is invasive - changing your code to add the instrumenting, which you have to be careful about.</p>
<p>I used GpProfile with Delphi 4 for many years. I loved it. It also was invasive, but it worked so well I learned to trust it and it never gave me a problem in 10 years. But when I upgraded to Delphi 2009, I didn't think it best to try using it, since it hasn't been upgraded and by GP's admission, won't work without modifications. I expect you won't be able to use it either with Delphi 2006. </p>
<p>ProDelphi and GpProfile will only profile at the procedure level. If you want to do individual lines (which I sometimes had to), you have to call PROC1, PROC2, PROC3 for each line and put the one line in each PROC. It was a bit of an annoyance to have to do that, but it gave me good results (at least I was happy with the results of GpProfile doing that).</p>
<p>The answer I accepted in my CharInSet question said that "Sampling profilers, which periodically check the location of the CPU, are usually better for measuring code time." and a later <a href="https://forums.codegear.com/thread.jspa?messageID=18506" rel="nofollow noreferrer">answer</a> gave Eric Grange's free sampling profiler for Delphi that now supports Delphi 2009. I haven't tried it yet, but I've heard good things about it, and it is the next one I'm going to try.</p>
<p>By the way, you might be best off by saving your $600 by NOT buying AQtime, and instead using that to upgrade your Delphi 2006 to Delphi 2009. The stability, speed and extra features (expecially Unicode), will be worth your while. See: <a href="https://stackoverflow.com/questions/305016/what-are-major-incentives-to-upgrade-to-d2009-unicode-excluded#307419">What are major incentives to upgrade to D2009 (Unicode excluded)?</a></p>
<p>Also AQtime does not integrate into Delphi 2009 yet.</p>
<p>One other free one, with source that I found out about, but haven't tried yet is <a href="http://www.delphiarea.com/products/delphi-components/profiler/" rel="nofollow noreferrer">TProfiler</a>. If anyone has tried that one, I'd like to know what they think.</p>
<hr>
<p>Note: The Addenum I added afterwards to <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi">question 291631</a> seems like it may be the answer. See <a href="https://stackoverflow.com/questions/291631/profiler-and-memory-analysis-tools-for-delphi/672554#672554">Andre's open source program: asmprofiler</a></p>
<hr>
<p>Feb 2010 followup. I bit the bullet and purchased AQTime. A few months ago they finally integrated it into Delphi 2009 which is what I use (but they still have to do Delphi 2010). The viewing of source lines and their individual times and counts is invaluable to me, and AQTime does a superb job of this. </p>
|
<p>Final note, www.torry.net is a great place for Delphi component/tool search</p>
| 48,170
|
<p>I am trying to get my first layer calibrating done but no matter what I do, I can not get the lines sticking to the bed.</p>
<p>My first question is the distance of the P.I.N.D.A. What I did was what Prusa recommends on <a href="https://d17kynu4zpq5hy.cloudfront.net/igi/prusa3d/KtMljQEIWfs5QXJV.medium" rel="nofollow noreferrer">this pic</a>: </p>
<p><a href="https://i.stack.imgur.com/dIH7j.jpg" rel="nofollow noreferrer" title="Annotated photo of leveling probe and printbed"><img src="https://i.stack.imgur.com/dIH7j.jpg" alt="Annotated photo of leveling probe and printbed" title="Annotated photo of leveling probe and printbed"></a></p>
<p>I am using Prusa Slic3r with PLA and all default values. I am doing the first layer calibration of the setup menu and got the lines which you can remove and the last square which the nozzle is picking up so you don't have it on the print bed. The very first line on the left corner is not really squeezed. I am looking for some greenhorn help here.</p>
|
<p>Calibrating the first layer height involves two steps:</p>
<p>The first step, as illustrated in that picture, is to adjust the PINDA probe to be roughly the right distance above the nozzle. The PINDA only has a sensing range of about a millimeter, so if it's too high, it can't detect the printbed; if it's too low, it will interfere with the printed object.</p>
<p>The second step, which you're having trouble with, is to calibrate the exact distance between the PINDA and the nozzle tip. The printer prints out a test pattern; while it's printing, you turn the the dial on the printer control panel to adjust the "live-Z" value. Typical values for a properly-assembled printer are between -0.5 and -1.0 (more-negative values are closer to the print bed). If the live-Z value is outside that range, you need to adjust the position of the PINDA probe.</p>
<p>The official Prusa procedure is good for getting a rough calibration. If you want more precision, the "<a href="https://shop.prusa3d.com/forum/assembly-and-first-prints-troubleshooting-f62/life-adjust-z-my-way-t2981.html" rel="nofollow noreferrer">Life adjust Z - my way</a>" procedure on the Prusa forums is good. Basically, you print out a large one-layer square, adjust the live-Z value halfway through, and see which half has a better first layer. Repeat until satisfied.</p>
|
<p>Your problem is that you need to define the sensor to nozzle level offset and store it in the printers memory.</p>
<p>When you have homed the printer, you should end up with the nozzle at a certain level where the sensor trigger point is now defined in relation to the bed. Next step is to relate the trigger point to the nozzle level, instruct the nozzle to go down to the build plate (placing a sheet of paper on the plate) by using the buttons of the menu to move the Z axis. When you feel friction when you pull the piece of paper, you reached the correct offset. Now store the value you read from the Z axis display as Z offset in the menu. Alternatively use G-code <code>M851 Z-x.xx</code>, where x.xx is the value you read from the display. <code>M500</code> will store it in memory.</p>
| 1,129
|
<p>At my current job, we're looking to implement our own odbc driver to allow many different applications to be able to connect to our own app as a datasource. Right now we are trying to weigh the options of developing our own driver to the implementation spec, which is massive, <em>or</em> using an SDK that allows for programmers to 'fill in' the data specific parts and allow higher levels of abstraction.</p>
<p>Has anyone else implemented a custom odbc driver? What pitfalls did you run into? What benefits did you see from doing it yourself? How many manhours would you approximate it took? Did you use an SDK, and if so, what benefits/downsides did you see from that approach?</p>
<p>Any comments and answers would be greatly appreciated. Thanks!</p>
<p><strong>EDIT:</strong> We are trying to maintain portability with our code, which is written in C.</p>
|
<p>Another option: Instead of creating a ODBC driver, implement a back end that talks the wire protocol that another database (Postgresql or MySQL for instance) uses.</p>
<p>Your users can then download and use for instance the Postgresql ODBC driver.</p>
<p>Exactly what back-end database you choose to emulate should probably depend the most on how well the wire protocol format is documented.</p>
<p>Both <a href="https://www.postgresql.org/docs/current/protocol.html" rel="noreferrer">Postgres</a> and <a href="http://dev.mysql.com/doc/internals/en/client-server-protocol.html" rel="noreferrer">MySQL</a> has decent documentation for their client-server protocols.</p>
<p>A simple Python 2.7 example of a server backend that understands parts of the Postgresql wire protocol is below. The example script creates a server that listens to port 9876. I can use the command <code>psql -h localhost -p 9876</code> to connect to the server. Any query executed will return a result set with columns abc and def and two rows, all values NULL.</p>
<p>Reading the Postgresql docs and using something like wireshark to inspect real protocol traffic would make it pretty simple to implement a Postgresql-compatible back end.</p>
<pre><code>import SocketServer
import struct
def char_to_hex(char):
retval = hex(ord(char))
if len(retval) == 4:
return retval[-2:]
else:
assert len(retval) == 3
return "0" + retval[-1]
def str_to_hex(inputstr):
return " ".join(char_to_hex(char) for char in inputstr)
class Handler(SocketServer.BaseRequestHandler):
def handle(self):
print "handle()"
self.read_SSLRequest()
self.send_to_socket("N")
self.read_StartupMessage()
self.send_AuthenticationClearText()
self.read_PasswordMessage()
self.send_AuthenticationOK()
self.send_ReadyForQuery()
self.read_Query()
self.send_queryresult()
def send_queryresult(self):
fieldnames = ['abc', 'def']
HEADERFORMAT = "!cih"
fields = ''.join(self.fieldname_msg(name) for name in fieldnames)
rdheader = struct.pack(HEADERFORMAT, 'T', struct.calcsize(HEADERFORMAT) - 1 + len(fields), len(fieldnames))
self.send_to_socket(rdheader + fields)
rows = [[1, 2], [3, 4]]
DRHEADER = "!cih"
for row in rows:
dr_data = struct.pack("!ii", -1, -1)
dr_header = struct.pack(DRHEADER, 'D', struct.calcsize(DRHEADER) - 1 + len(dr_data), 2)
self.send_to_socket(dr_header + dr_data)
self.send_CommandComplete()
self.send_ReadyForQuery()
def send_CommandComplete(self):
HFMT = "!ci"
msg = "SELECT 2\x00"
self.send_to_socket(struct.pack(HFMT, "C", struct.calcsize(HFMT) - 1 + len(msg)) + msg)
def fieldname_msg(self, name):
tableid = 0
columnid = 0
datatypeid = 23
datatypesize = 4
typemodifier = -1
format_code = 0 # 0=text 1=binary
return name + "\x00" + struct.pack("!ihihih", tableid, columnid, datatypeid, datatypesize, typemodifier, format_code)
def read_socket(self):
print "Trying recv..."
data = self.request.recv(1024)
print "Received {} bytes: {}".format(len(data), repr(data))
print "Hex: {}".format(str_to_hex(data))
return data
def send_to_socket(self, data):
print "Sending {} bytes: {}".format(len(data), repr(data))
print "Hex: {}".format(str_to_hex(data))
return self.request.sendall(data)
def read_Query(self):
data = self.read_socket()
msgident, msglen = struct.unpack("!ci", data[0:5])
assert msgident == "Q"
print data[5:]
def send_ReadyForQuery(self):
self.send_to_socket(struct.pack("!cic", 'Z', 5, 'I'))
def read_PasswordMessage(self):
data = self.read_socket()
b, msglen = struct.unpack("!ci", data[0:5])
assert b == "p"
print "Password: {}".format(data[5:])
def read_SSLRequest(self):
data = self.read_socket()
msglen, sslcode = struct.unpack("!ii", data)
assert msglen == 8
assert sslcode == 80877103
def read_StartupMessage(self):
data = self.read_socket()
msglen, protoversion = struct.unpack("!ii", data[0:8])
print "msglen: {}, protoversion: {}".format(msglen, protoversion)
assert msglen == len(data)
parameters_string = data[8:]
print parameters_string.split('\x00')
def send_AuthenticationOK(self):
self.send_to_socket(struct.pack("!cii", 'R', 8, 0))
def send_AuthenticationClearText(self):
self.send_to_socket(struct.pack("!cii", 'R', 8, 3))
if __name__ == "__main__":
server = SocketServer.TCPServer(("localhost", 9876), Handler)
try:
server.serve_forever()
except:
server.shutdown()
</code></pre>
<p>Example command line psql session:</p>
<pre><code>[~]
$ psql -h localhost -p 9876
Password:
psql (9.1.6, server 0.0.0)
WARNING: psql version 9.1, server version 0.0.
Some psql features might not work.
Type "help" for help.
codeape=> Select;
abc | def
-----+-----
|
|
(2 rows)
codeape=>
</code></pre>
<p>An ODBC driver that speaks the Postgresql protocol should work as well (but I have not tried it yet).</p>
|
<p>I have not implemented an ODBC driver, but just wanted to offer a suggestion that you can start with an open-source implementation and add your own customizations. This may get you started a lot faster.</p>
<p>There are at least two options:</p>
<ul>
<li><p><a href="http://www.unixodbc.org/" rel="nofollow noreferrer">unixODBC</a> is licensed under LGPL, which means if you modify the code you have to make your modifications open-source.</p></li>
<li><p><a href="http://www.iodbc.org/" rel="nofollow noreferrer">iODBC</a> is licensed under either LGPL or New BSD, at your choice. New BSD allows you to make modifications <em>without</em> make your modifications open-source.</p></li>
</ul>
<p>However, it's not clear if these packages run on Windows, as opposed to running on UNIX/Linux with a client API consistent with standard ODBC. You don't state which platform you're using, so I don't know if this is relevant to you.</p>
| 43,449
|
<p>I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.<br>
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx</p>
|
<pre><code>function holdit(btn, action, start, speedup) {
var t;
var repeat = function () {
action();
t = setTimeout(repeat, start);
start = start / speedup;
}
btn.mousedown = function() {
repeat();
}
btn.mouseup = function () {
clearTimeout(t);
}
};
/* to use */
holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */
</code></pre>
|
<p>something like the psuedo code below might work..</p>
<pre><code>var isClicked = false;
var clickCounter = 100;
function fnTrackClick(){
if(isClicked){
clickCounter--;
setTimeout(clickCounter * 100, fnTrackClick);
}
}
<input type="button" value="blah" onmousedown="isClicked=true;" onmouseover="fnTrackClick();" onmouseup="isClicked = false;" />
</code></pre>
| 10,522
|
<p>I have a legacy VB6 application which I've inherited. The issue I'm facing is that I'm getting the infamous</p>
<pre><code>ORA-12638: Credential retrieval failed
</code></pre>
<p>error message whenever it tries to connect to one of our Oracle databases. I can connect fine from SQLPlus and Toad, however. I've Googled around and everyone seems to say that modifying their sqlnet.ora file to</p>
<pre><code>SQLNET.AUTHENTICATION_SERVICES=(NONE)
</code></pre>
<p>did the trick. I have yet to find anyone with an alternative fix. Here is what my connection string looks like:</p>
<pre><code>"PROVIDER=OraOLEDB.Oracle;DATA SOURCE=(DESCRIPTION = " & _
"(ADDRESS = (PROTOCOL = TCP)(HOST = server1)
(PORT = 1521))" & _
"(ADDRESS = (PROTOCOL = TCP)(HOST = server2)
(PORT = 1521))" & _
"(LOAD_BALANCE = yes) " & _
"(CONNECT_DATA = " & _
"(SERVER = DEDICATED) " & _
"(SERVICE_NAME = database_name_here) " & _
") " & _
"); " & _
"User Id=username_here;Password=password_here;"
</code></pre>
<p>As for my VB code, it's quite simple.</p>
<pre><code>Private oracleDatabaseConnection As ADODB.Connection
Set oracleDatabaseConnection = New ADODB.Connection
oracleDatabaseConnection.Open oracleConnectionString
</code></pre>
<p>Anyone have any ideas?</p>
<p>Thank you. :)</p>
|
<p>I know this is a very old post but I have found a solution that has worked for me (Legacy VB6 Application):</p>
<p>Change the following entry in the sqlnet.ora file:</p>
<pre><code>Original Entry - SQLNET.AUTHENTICATION_SERVICES= (NTS)
Modified Entry - SQLNET.AUTHENTICATION_SERVICES= (NONE)
</code></pre>
<p>Here is a <a href="http://www.dba-oracle.com/t_ora_12638_credential_retrieval_failed.htm" rel="noreferrer">LINK</a> to the solution</p>
|
<p>If using IIS and for a VB app, it may help to create a new Data Source in the ODBC manager and referencing it by name (instead of by provider) in the connection string.</p>
<p>For example, if the name for the Data Source is "test_ds", I would replace</p>
<pre><code>ObjConn.open "Provider=MSDAORA;User ID=myuser;password=mypassword;Data Source=MYDATASOURCEFROMTNSNAMES;Persist Security Info=False"
</code></pre>
<p>for</p>
<pre><code>ObjConn.open "dsn=test_ds;pwd=mypassword"
</code></pre>
<p>Can't really explain the logic behind the solution, but it worked for me.</p>
| 49,671
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.