instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm just starting out with WiX as I need to be able to automate building an MSI on our CI server. Is there anyway to automatically include all the dependencies of a project?</p>
|
<p>The "proj" extension to heat.exe is getting better. <a href="http://wixtoolset.org/documentation/manual/v3/overview/heat.html" rel="nofollow noreferrer">Heat</a> isn't quite ready to be used for production in an automated fashion. It's a very reasonable way to get the initial structure put together but doesn't quite do the right thing with repeated runs (for example, Component/@Guids aren't stable, yet...).</p>
<p>When the above issues are solved in heat.exe then incorporating it into your build process will certainly save all the trouble that people mention above. It's on our list to do better after the most egregious bugs are fixed in the core toolset.</p>
|
<p>In my experience, Wix is a still a very manual process. You have to add each dependency singly - I think the idea was that you would build the Wix installer at the same time you are building your project and add each item in as you are adding it in the code. This way it seems less daunting than having to go back and do a retrospect on the project. It certainly would be a great suggestion for an enhancement though!</p>
| 38,825
|
<p>How would you use set! in a simple procedure f such that evaluating (+ (f 0) (f 1)) will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left?</p>
|
<p>Easiest approach is probably to store some external state and have the implementation of f affect it's contents.</p>
<pre><code>(define x 0)
(define (f n) (let ((tmp x)) (set! x n) tmp))
</code></pre>
<p>Thus, x is initially 0 and each call to f will return the current value of x and save the argument as the new value of x. Thus (f 0) followed by (f 1) will both return 0, leaving the final x value of 1. While evaluating (f 1) followed by (f 0) will yield 0 then 1, with a final x of 0.</p>
|
<p>With <a href="http://community.schemewiki.org/?call-with-current-continuation" rel="nofollow noreferrer">call/cc</a>.</p>
<pre><code>(define (f)
(call/cc
(lambda (c) (+ (c 0) (c 1)))))
(write (f))
</code></pre>
<p>Invoking c within either argument to <code>+</code> causes <code><em>f</em></code> to return immediately, yielding 0 or 1 depending which argument is evaluated first.</p>
<p>But I suspect it will always evaluate left-to-right and thus return 0.</p>
| 38,549
|
<p>I am kinda repeating this question bit the 1st time it was asked incorrectly.</p>
<p>I have this:</p>
<pre><code><xsd:complexType name="A">
<xsd:sequence>
<xsd:element name="options" type="options"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="B">
<xsd:complexContent>
<xsd:element name="options" type="ex_options"/>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="options">
<xsd:sequence>
...some options
</xsd:sequence>
</xsd:element>
<xsd:complexType name="ex_options">
<xsd:complexContent>
<xsd:extension base="options">
<xsd:sequence>
...some more options
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:element>
</code></pre>
<p>So basically I have class A with an inner class of options
Class B inherits from class A and I want B.options to inherit from A.options so that when we do webservices we only need to pass a and when we call getOptions it will return the right object B.options. Currently with the way the xsd stands I get an error saying multiple elements with name options with different types appear in the model group. The errors is in the B type.</p>
|
<p>Just stick with elements of type B and then use then decorate your instance document elements as described below with the appropriate <code>xsi:type</code> attribute value.</p>
<pre><code><xsd:complexType name="B">
<xsd:complexContent>
<xsd:element name="options" type="ex_options"/>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="options">
<xsd:sequence>
...some options
</xsd:sequence>
</xsd:element>
<xsd:complexType name="ex_options">
<xsd:complexContent>
<xsd:extension base="options">
<xsd:sequence>
...some more options
</xsd:sequence>
</xsd:extension>
</xsd:complexContent>
</xsd:element>
</code></pre>
<p>and then "decorate" your instance element as either</p>
<pre><code><options xsi:type="ex_options"> ... (this will work)
</code></pre>
<p>or</p>
<pre><code><options xsi:type="options"> ... (I think you can do this as long as the base xsi:type is not abstract)
</code></pre>
<p>If it turns out that you can't decorate with the base <code>xsi:type</code>,
then you can always "cheat" by creating an empty base type and then
extending by careful construction to arrive at your two desired formats.</p>
<p>See <a href="https://stackoverflow.com/questions/188389/xml-schema-for-elements-with-same-name-but-different-sub-structure-depending-on#233093">this post</a> for more elaboration & links.</p>
|
<p>You could make the <code>options</code> sequence open-ended so you can have any number of options and then validate the existing options based on an attribute value. For example, in the following schema, the <code>options</code> list has a <code>type</code> attribute of either <code>A</code> or <code>B</code>, indicating which options should actually get listed:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<xs:schema targetNamespace="http://tempuri.org/XMLSchema.xs"
elementFormDefault="qualified"
xmlns="http://tempuri.org/XMLSchema.xs"
xmlns:mstns="http://tempuri.org/XMLSchema.xs"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Elements for document structure. -->
<!-- This section is just for validating my example file to -->
<!-- demonstrate the schema. -->
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="elementA" type="A" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="elementB" type="A" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<!-- The important part of the schema. -->
<!-- Types -->
<!-- A has options of type options. -->
<xs:complexType name="A">
<xs:sequence>
<xs:element name="options" type="options"/>
</xs:sequence>
</xs:complexType>
<!-- Options specifies a options with a type attribute specifying which options will be available. -->
<xs:complexType name="options">
<xs:sequence>
<xs:element name="option" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="type" use="optional" default="A">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="A"/>
<xs:enumeration value="B"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:schema>
</code></pre>
<p>Here is an example of the XML for this schema.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://tempuri.org/XMLSchema.xs">
<elementA>
<options type="A">
<option>Test-A</option>
<option>Test2-A</option>
</options>
</elementA>
<elementB>
<options type="B">
<option>Test-B</option>
<option>Test2-B</option>
<option>Test3-B</option>
<option>Test4-B</option>
</options>
</elementB>
</root>
</code></pre>
| 25,595
|
<p>When I first started programming, I wrote everything in main. But as I learned, I tried to do as little as possible in my <code>main()</code> methods.</p>
<p>But where do you decide to give the other Class/Method the responsibility to take over the program from <code>main()</code>? How do you do it?</p>
<p>I've seen many ways of doing it, like this:</p>
<pre><code>class Main
{
public static void main(String[] args)
{
new Main();
}
}
</code></pre>
<p>and some like:</p>
<pre><code>class Main {
public static void main(String[] args) {
GetOpt.parse(args);
// Decide what to do based on the arguments passed
Database.initialize();
MyAwesomeLogicManager.initialize();
// And main waits for all others to end or shutdown signal to kill all threads.
}
}
</code></pre>
<p>What should and should not be done in <code>main()</code>? Or are there no silver bullets?</p>
<p>Thanks for the time!</p>
|
<p>In my opinion, the "main" of a sizable project should contain around 3 function calls:</p>
<ul>
<li>Calling an Initialization function that sets up all the required settings, preferences, etc. for the application.</li>
<li>Starting up the main "controller" of the application</li>
<li>Waiting for the main controller to terminate, and then calling a Termination function that cleans up anything that needs to be cleaned up in "main" (though the controller will have taken care of most of the cleanup already).</li>
</ul>
<p>Any sizable application will be divided into chunks of functionality, usually with some hierarchy. The main controller may have several child controllers for specific features.</p>
<p>Doing it this way makes it much easier to locate specific functionality, and separation-of-concerns is better.</p>
<p>Of course, as other replies have said, there really is no silver bullet in software development. For a short project I might put everything in main just to get things up-and-running quickly. I think also depends on the language - some options may be easier than others in particular languages.</p>
|
<p>I think the main method should explain, what the program does at starting up.
So it may call initialzing methods, but the logic should be extracted into methods.</p>
<p>In your example, I would not create a Main() method, but put it into the original one.</p>
| 42,145
|
<p>Backstory: I have a PKCS#12 (p12) certificate with a symmetric cipher (password) that I used OpenSSL to convert to a PEM; opening that as text I see it contains both a <code>BEGIN/END CERTIFICATE</code> section as well as <code>BEGIN/END RSA PRIVATE KEY</code>. The .NET Framework <code>X509Certificate</code> class only supports the "ASN.1 DER" format, so I used OpenSSL to convert the PEM to DER. Unfortunately it appears doing this doesn't include the private key which is what I need for making an SSL connection with <code>SslStream</code> & <code>TcpClient</code>.</p>
<pre><code>X509CertificateCollection certsFromFile = new X509CertificateCollection();
X509Certificate2 cert = new X509Certificate2("my.der.crt");
if (!cert.HasPrivateKey)
throw new Exception("No private key");
certsFromFile.Add(cert);
TcpClient tcpclient = new TcpClient(hostname, port);
SslStream sslstream = new SslStream(tcpclient.GetStream(), false,
null, null);
sslstream.AuthenticateAsClient(hostname, certsFromFile,
SslProtocols.Ssl3, false);
sslstream.Close();
tcpclient.Close();
</code></pre>
<p>How do I take this PEM file and make it into a DER while retaining the private key information so I can use it in .NET for signing?</p>
|
<p>Oops, I'm behind the times! Looks like <code>X509Certificate2</code> can read PKCS#12 files so there's no need for any conversion.</p>
|
<p>Certificates and keys are generally stored separately. Cut the PEM file into two files, one with the certificate and one with the key. You can then use the openssl toolkit to convert each file separately into a DER file.</p>
| 26,254
|
<p>I get the message that the namespace can't be found when I use the code below. Where does the AccessDeniedException live?</p>
<pre><code>try { ... }
catch (SomeKindOfException ex)
{
MessageBox.Show(ex.Message);
}
catch (AccessDeniedException ex)
{
//Do something else
}
</code></pre>
<p>Thanks</p>
|
<p>I don't think that's the exception you're looking for. The only one with this name (that I can find) is in a Sharepoint namespace. Try attaching the debugger and seeing exactly what the type of the thrown exception is.</p>
<p>The type of the exception is going to vary depending on your context. So for example, if it's an "access denied" when trying to open a file, it could be a FileLoadException, or something similar. If it's encountered because of Code Access Security, it will be SecurityException. And so on.</p>
|
<p>You may need to give the full namespace on the exception, or have a using statement at the top of your code file so .NET knows where to find the exception you're talking about. If that doesn't work, maybe you need to add the DLL that contains that exception to the "REFERENCES" list in your project.</p>
| 37,812
|
<p>I am using attribute_fu to render a nice block of rows for a particular table.</p>
<pre><code><%= f.render_associated_form(@foo.bars, :new => 5) %>
</code></pre>
<p>I would like to have the <code>bar</code> partial have some notion of a bit of state. (Because the notion is specific to the view, I do not want to externalize this to the <code>Bar</code> model itself and calculate it in the controller.) For simplicity's sake, pretend it is the index of the <code>bar</code> in the <code>@foo.bars</code> list. </p>
<p>(I am aware that if this was the case I could use the :collection => @foo.bars to enable bar_counter... this doesn't appear to function in my tests but I have seen docs for it.)</p>
<p>My question -- how do I pass a variable into the partial such that I can keep and edit the state? Naively, I assumed that doing something like </p>
<pre><code><% @tmp = {:index => 1} %>
%= f.render_associated_form(@foo.bars, :new => 5, :locals => {:tmp => @tmp}) %>
#goes in the view
<%= tmp[:index] += 1 %>
</code></pre>
<p>would work. <code>tmp</code> gets passed appropriately but calling [] throws "Uh oh, you just called a method on nil". Surprisingly to me, I can do tmp.inspect, tmp.class, etc to look at the Hash, and these have the results I would expect. But tmp[:index] or tmp[:anything_I_want] cause it to blow up. </p>
<p>Making <code>tmp</code> an array had similar results.</p>
<p>Any ideas?</p>
|
<p>I ended up solving this in a thoroughly Rails fashion -- patching :attribute_fu to meet my needs. Hopefully I'll be able to release my patches to the community fairly soon.</p>
|
<p>The behavior you describe above seems like it must be a bug in attribute_fu, since the local isn't getting properly passed along, which it definitely should. I'd be interested to know what you did to patch it.</p>
| 33,186
|
<p>I'd love to know if there is a module to parse "human formatted" dates in Perl. I mean things like "tomorrow", "Tuesday", "next week", "1 hour ago".</p>
<p>My research with CPAN suggest that there is no such module, so how would you go about creating one? NLP is way over the top for this.</p>
|
<p><a href="http://search.cpan.org/perldoc?Date::Manip" rel="noreferrer">Date::Manip</a> does exactly this.</p>
<p>Here is an example program:</p>
<pre><code>#!/usr/bin/perl
use strict;
use Date::Manip;
while (<DATA>)
{
chomp;
print UnixDate($_, "%Y-%m-%d %H:%M:%S"), " ($_)\n";
}
__DATA__
today
yesterday
tomorrow
last Tuesday
next Tuesday
1 hour ago
next week
</code></pre>
<p>Which results in the following output:</p>
<pre><code>2008-11-17 15:21:04 (today)
2008-11-16 15:21:04 (yesterday)
2008-11-18 15:21:04 (tomorrow)
2008-11-11 00:00:00 (last Tuesday)
2008-11-18 00:00:00 (next Tuesday)
2008-11-17 14:21:04 (1 hour ago)
2008-11-24 00:00:00 (next week)
</code></pre>
<p>UnixDate is one of the functions provided by <code>Date::Manip</code>, the first argument is a date/time in any format that the module supports, the second argument describes how to format the date/time. There are other functions that just parse these "human" dates, without formatting them, to be used in delta calculations, etc.</p>
|
<p>I assume you have context.
how could NLP help here ?
as a wild guess you could just find the nearest date that is an exact date(not relative to today) and use today/tommorow/yesterday to relate to that.</p>
| 37,947
|
<p>I'm wondering about MP3 decoding/encoding, and I was hoping to pull this off in Flash using AS3</p>
<p>I'm sure it'll be a right pain...</p>
<p>I have no idea where to start, can anyone offer any pointers? reference material?</p>
<p>----much later---
Thank you all very much for your input... It seems I have a long road ahead of me yet!</p>
|
<p>See <a href="http://lame.sourceforge.net/" rel="nofollow noreferrer">LAME MP3 Encoder</a>. You can checkout their source code and their <a href="http://lame.sourceforge.net/links.php" rel="nofollow noreferrer">link page</a>. <a href="http://www.mpeg.org/" rel="nofollow noreferrer">Mpeg.org</a> should have documents too.</p>
|
<p>It's going to be <strong>VERY</strong> slow doing this in AS3. You really need a C/C++ implementation if you care at all about how long it will take.</p>
| 7,684
|
<p>Right now I'm not sure...</p>
|
<p>I'd say yes. I'm using it. I know for a fact that Universal are using it on some of their (thousands of) sites. I will add some caveats, however: </p>
<ol>
<li>There are serious problems with setting it up, especially if you want to debug into the libraries. </li>
<li>The helper functions favour prototype, as opposed to the more modern jQuery. This is changing rapidly, however.</li>
<li>The documentation is a bit chaotic, again the Castle Team are working on that.</li>
</ol>
<p>I'm not guaranteeing every last "out-there" feature works, but the point of the system is actually to keep it simple.</p>
<p>Compared to vanilla ASP.NET, it's an absolute joy. I assure you that you won't miss viewstate.</p>
|
<p>We have been building a fairly large application with it for the past year and a half. Its been nice not to have to deal with the old ASP/Page based model and use the better Model/View/Controller design pattern.</p>
<p>To get the new stuff you really need to work off the trunk of development because they don't do releases very often. We have a lot of tests that get the framework involved so when an update in the framework breaks something we depend on we know about it immediately.</p>
<p>If you have to work in .NET this beats the heck out of the alternatives.</p>
| 32,975
|
<p>I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.</p>
<p>For example (where Foo is a PHP class of my making):</p>
<pre><code>$foo = new Foo();
$foo['fooKey'] = 'foo value';
echo $foo['fooKey'];
</code></pre>
<p>I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items. Python handles it by overloading __getitem__ and __setitem__.</p>
<p>Is there a way to do this in PHP? If it makes a difference, I'm running PHP 5.2.</p>
|
<p>If you extend <code>ArrayObject</code> or implement <code>ArrayAccess</code> then you can do what you want.</p>
<ul>
<li><a href="http://php.net/arrayobject" rel="noreferrer">ArrayObject</a></li>
<li><a href="http://php.net/arrayaccess" rel="noreferrer">ArrayAccess</a></li>
</ul>
|
<p>Nope, casting just results in a normal PHP array -- losing whatever functionality your ArrayObject-derived class had. Check this out:</p>
<pre><code>class CaseInsensitiveArray extends ArrayObject {
public function __construct($input = array(), $flags = 0, $iterator_class = 'ArrayIterator') {
if (isset($input) && is_array($input)) {
$tmpargs = func_get_args();
$tmpargs[0] = array_change_key_case($tmpargs[0], CASE_LOWER);
return call_user_func_array(array('parent', __FUNCTION__), $tmp args);
}
return call_user_func_array(array('parent', __FUNCTION__), func_get_args());
}
public function offsetExists($index) {
if (is_string($index)) return parent::offsetExists(strtolower($index));
return parent::offsetExists($index);
}
public function offsetGet($index) {
if (is_string($index)) return parent::offsetGet(strtolower($index));
return parent::offsetGet($index);
}
public function offsetSet($index, $value) {
if (is_string($index)) return parent::offsetSet(strtolower($index, $value));
return parent::offsetSet($index, $value);
}
public function offsetUnset($index) {
if (is_string($index)) return parent::offsetUnset(strtolower($index));
return parent::offsetUnset($index);
}
}
$blah = new CaseInsensitiveArray(array(
'A'=>'hello',
'bcD'=>'goodbye',
'efg'=>'Aloha',
));
echo "is array: ".is_array($blah)."\n";
print_r($blah);
print_r(array_keys($blah));
echo $blah['a']."\n";
echo $blah['BCD']."\n";
echo $blah['eFg']."\n";
echo $blah['A']."\n";
</code></pre>
<p>As expected, the array_keys() call fails. In addition, is_array($blah) returns false. But if you change the constructor line to:</p>
<pre><code>$blah = (array)new CaseInsensitiveArray(array(
</code></pre>
<p>then you just get a normal PHP array (is_array($blah) returns true, and array_keys($blah) works), but all of the functionality of the ArrayObject-derived subclass is lost (in this case, case-insensitive keys no longer work). Try running the above code both ways, and you'll see what I mean.</p>
<p>PHP should either provide a native array in which the keys are case-insensitive, or make ArrayObject be castable to array without losing whatever functionality the subclass implements, or just make all array functions accept ArrayObject instances.</p>
| 9,083
|
<p>I run (and am presently completely overhauling) a website that deals with theater (njtheater.com if you're interested).</p>
<p>When I query a list of plays from the database, I'd like "The Merchant of Venice" to sort under the "M"s. Of course, when I display the name of the play, I need the "The" in front.</p>
<p>What the best way of designing the database to handle this?</p>
<p>(I'm using MS-SQL 2000)</p>
|
<p>You are on the right track with two columns, but I would suggest storing the entire displayable title in one column, rather than concatenating columns. The other column is used purely for sorting. This gives you complete flexibility over sorting and display, rather than being stuck with a simple prefix.</p>
<p>This is a fairly common approach when searching (which is related to sorting). One column (with an index) is case-folded, de-punctuated, etc. In your case, you'd also apply the grammatical convention of removing leading articles to the values in this field. This column is then used as a comparison key for searching or sorting. The other column is not indexed, and preserves the original key for display.</p>
|
<p>I agree with doofledorfer, but I would recommend storing spaces entered as part of the prefix instead of assuming it's a single space. It gives your users more flexibility. You may also be able to do some concatenation in your query itself, so you don't have to merge the fields as part of your business logic. </p>
| 35,202
|
<p>I have an application that depends on gpsd and ntpd to accurately set the system time on a linux machine.</p>
<p>gpsd is fed NMEA + PPS</p>
<p>The application is punping ~25MB per second over the network and I think the loading on the system is causing jitter in the time somehow. (loaded PCI express bus causing irregular interrupt latency)</p>
<p>I have another machine that is not loaded at all that I could setup to read the GPS and act as an NTP server for the loaded machine. (the loaded machine would be getting startum 1 ???)</p>
<p><strong>How accurate can I expect the time to be from a stratum 0 NTP server on the same subnet on Ethernet?</strong></p>
<p>I hope this is not too off topic, I am sure sometime someone else will be happy the answer is documented here. ;-)</p>
|
<p>Best info I could find on <a href="https://web.archive.org/web/20100414014404/http://www.netcordia.com/community/blogs/terrys_blog/archive/2008/01/07/ntp-accuracy.aspx" rel="nofollow noreferrer">NTP accuracy</a>, seems to point at 1-2 ms in a LAN setting:</p>
<blockquote>
<p>NTP v4 with kernel mods to support it, is capable of much better than 1ms accuracy, possibly as good as 1ns. According to [Dave Mills] article, NTP v3 is accurate to 1-2ms in a LAN and 10s of ms in WAN nets. <a href="http://www.cis.udel.edu/~mills/ntp.html" rel="nofollow noreferrer">http://www.cis.udel.edu/~mills/ntp.html</a></p>
<p>Other articles suggest that with an accurate time source, such as a GPS time source, NTP is accurate to 50us, but the links on the Linux kernel support say that accuracy of a few ms are possible.
<a href="http://www.atomic-clock.galleon.eu.com/support/ntp-time-server-accuracy.html" rel="nofollow noreferrer">http://www.atomic-clock.galleon.eu.com/support/ntp-time-server-accuracy.html</a> </p>
<p>Another article says that it is dependent on the predictability of network delays (i.e. a low jitter network).
<a href="http://www.postel.org/pipermail/end2end-interest/2003-April/002925.html" rel="nofollow noreferrer">http://www.postel.org/pipermail/end2end-interest/2003-April/002925.html</a> </p>
</blockquote>
|
<p>The stratum level of the NTP server in question has no relation to the accuracy of the clock/server. It purely means the distance away from the "reference clock" you are.</p>
<p>What matters more, in regards to NTP accuracy (in regards to time, of course) is network latency between servers, type of server being used, and potentially server load. Depending on what NTP server you use, they document on how accurate their time will be. Each server software uses various algorithims to compute time based on network latency and server load, and it comes down to the accuracy of those algorithims.</p>
<p>For instance, MS NTP server states that it will be accurate within 2 seconds. OpenNTPd has stated that they won't give you the possible accuracy of the server. There are instances where stratum 3 servers can be more accurate than stratum 2 servers, etc.</p>
| 15,412
|
<p><a href="https://stackoverflow.com/questions/189925/password-encryption-in-iphone-apps">This question discusses encrypting data on the iPhone</a> using the crypt() function. As an alternative, is there a keychain on the iPhone and if so, what code would I use to access it in order to store login details and then retrieve them for us in an application?</p>
|
<p>There is a keychain you can use - for code, the best bet is to check out the GenericKeychain sample application from Apple:</p>
<p><a href="https://developer.apple.com/library/ios/DOCUMENTATION/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html" rel="nofollow noreferrer">GenericKeychain sample</a></p>
|
<p>Here is one more good wrapper class from Mr.Granoff
<a href="https://github.com/granoff/Lockbox" rel="nofollow">https://github.com/granoff/Lockbox</a>
Thanks</p>
| 23,185
|
<p>What is the difference between display:block and display:inline</p>
|
<p>Block elements will typically stack vertically whereas inline elements will line up horizontally. </p>
<p>Two Divs will stack on top of each other, but if you set them to display:inline, they will be next to each other horizontally. Vise-versa with Span tags.</p>
|
<p>Block uses the full width available, with a new line before and after. Inline uses only the width it needs without forcing new lines.</p>
| 13,069
|
<p>I am using a Cursor in my stored procedure. It works on a database that has a huge number of data. for every item in the cursor i do a update operation. This is taking a huge amount of time to complete. Almost 25min. :( .. Is there anyway i can reduce the time consumed for this?</p>
|
<p>When you need to do a more complex operation to each row than what a simple update would allow you, you can try:</p>
<ul>
<li>Write a User Defined Function and use that in the update (probably still slow)</li>
<li>Put data in a temporary table and use that in an UPDATE ... FROM:</li>
</ul>
<p>Did you know about the UPDATE ... FROM syntax? It is quite powerful when things get more complex:</p>
<pre><code>UPDATE
MyTable
SET
Col1 = CASE WHEN b.Foo = "Bar" THEN LOWER(b.Baz) ELSE "" END,
Col2 = ISNULL(c.Bling, 0) * 100 / Col3
FROM
MyTable
INNER JOIN MySecondTable AS b ON b.Id = MyTable.SecondId
LEFT JOIN ##MyTempTable AS c ON c.Id = b.ThirdId
WHERE
MyTabe.Col3 > 0
AND b.Foo NOT IS NULL
AND MyTable.TheDate > GETDATE() - 10
</code></pre>
<p>The example is completely made-up and may not make much sense, but you get the picture of how to do a more complex update without having to use a cursor. Of course, a temp table would not necessarily be required for it to work. :-)</p>
|
<p>Are you updating the same data that the cursor is operating over?</p>
<p>What type of cursor? forward only? static? keyset? dynamic?</p>
| 27,737
|
<p>Im using Prusa Slicer 2.1 for my FlyingBear Ghost 4.</p>
<p>I just changed my 0.4 mm nozzle for a 0.2 mm but it seems to jam in the heater probably due to too much filament trying to get out by the nozzle. Where is the setting to reduce the filement speed and how much I should reduce it?</p>
<p>Here are my settings:
<a href="https://drive.google.com/file/d/1j_RsFQI1EtfSzptggYjGehpdlJlX7rsK/view?usp=sharing" rel="nofollow noreferrer">Config.txt</a></p>
|
<p>0.2 mm and 0.4 mm are half the diameter, but the maximum flow is not just half: Flow scales with the area. The 0.4 mm nozzle has an area 4 times as the 0.2 mm one:</p>
<p><span class="math-container">$\frac{A_1} {A_2}=\frac {0.2^2}{0.1^2}=4$</span></p>
<p>You need to reduce <code>print speed</code> or the <code>volumetric flow</code> by this factor or make sure your printer can handle the increased flow by reducing the viscosity of the melt - for example by increasing the print temperature.</p>
<p>Also note, that a 0.2 mm nozzle can't be operated with layer heights above 0.15 mm.</p>
|
<p>The discussion about slowing the print speed is important, but in my experience it is not at the root of the problem, and slowing down printing may make it worse.</p>
<p>If ny "heater" you mean the complete hot-end, then I suspect you are jamming in the cooler part of the hot-end. This cooler part is separated from the heater itself by the heat break, which is often a thin-walled metal tube.</p>
<p>The hot side of the heat break is heated by the heater. The cooler-end, the cool side of the heat break, is cooled by two things:</p>
<ol>
<li>cold filament being moved through it and</li>
<li>airflow from the fan over the heat sink fins.</li>
</ol>
<p>It is heated by:</p>
<ol>
<li>Thermal conduction through the thin metal tube</li>
<li>Convection airflow from the hot-end vertically and over the cooler-end</li>
<li>Hot filament being pulled through the heat break during retraction.</li>
</ol>
<p>When you are printing with a smaller cross-section of extruded filament, the slicer program should adjust the flow rate and speeds based on the lesser volume of plastic extruded for a given pressure. Unfortunately, this is less plastic, so the filament cools the cooler end of the heat break less than it would if the feed rate were higher. As a result, the temperature of the cooler end goes up. If there is insufficient airflow to keep the cooler side below the softening point of filament, the filament softens and jams inside the cooler end.</p>
<p>Of course, if your jam actually is in the hot end, this discussion is not relevant.</p>
<p>But, I have found with my Prusa i3m3 that I have had problems with jamming in the cooler end, especially when I printed filament with a higher melting temperature, ABS in this case. I reduced the area of the airflow so that no air could pass through other than by passing over the heat sink fins, and the ABS printed correctly.</p>
<p>All of 3D printing is a balance of one factor against another. It is hard to lose, though, by increasing the cooler-end temperature. All will seem well until you print something with a lower flow, or a higher retraction rate, or you try using a higher temperature for the same filament. Then the jam can unexpectedly occur, or, perhaps worse, it can be an intermittent jam, or there can be a lot to sticktion, and printing becomes prone to gaps, or occasional under extrusion.</p>
| 1,743
|
<p>I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like</p>
<pre><code>StudentID StartDate EndDate Field1 Field2
1 9/3/2007 10/20/2007 3 True
1 10/21/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
</code></pre>
<p>The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like</p>
<pre><code>StudentID StartDate EndDate Field1 Field2
1 9/3/2007 6/12/2008 3 True
2 10/10/2007 3/20/2008 4 False
3 9/3/2007 11/3/2007 8 True
3 12/15/2007 6/12/2008 8 True
</code></pre>
<p>What would be the SELECT statement for this query?</p>
|
<p>The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction.</p>
<p>You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer.</p>
<pre><code>CREATE VIEW dbo.StudentStartDates
AS
SELECT
S.StudentID,
S.StartDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students PREV ON
PREV.StudentID = S.StudentID AND
PREV.Field1 = S.Field1 AND
PREV.Field2 = S.Field2 AND
PREV.EndDate = DATEADD(dy, -1, S.StartDate)
WHERE PREV.StudentID IS NULL
GO
CREATE VIEW dbo.StudentEndDates
AS
SELECT
S.StudentID,
S.EndDate,
S.Field1,
S.Field2
FROM
dbo.Students S
LEFT OUTER JOIN dbo.Students NEXT ON
NEXT.StudentID = S.StudentID AND
NEXT.Field1 = S.Field1 AND
NEXT.Field2 = S.Field2 AND
NEXT.StartDate = DATEADD(dy, 1, S.EndDate)
WHERE NEXT.StudentID IS NULL
GO
SELECT
SD.StudentID,
SD.StartDate,
ED.EndDate,
SD.Field1,
SD.Field2
FROM
dbo.StudentStartDates SD
INNER JOIN dbo.StudentEndDates ED ON
ED.StudentID = SD.StudentID AND
ED.Field1 = SD.Field1 AND
ED.Field2 = SD.Field2 AND
ED.EndDate > SD.StartDate AND
NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate)
GO
</code></pre>
|
<p>This is a classic problem in SQL (the language) e.g. covered in Joe Celko's books 'SQL for Smarties" (chapter 23, Regions, Runs, Gaps, Sequences and Series) and his latest book "Thinking in Sets" (chapter 15). </p>
<p>While it's 'fun' to fix the data at run time with a monster query, for me this is one of those situations that can be better fixed off line and procedurally (personally I'd do it with formulas in an Excel spreadsheet). </p>
<p>The important thing is to put in place effective database constraints to prevent the overlapping periods reoccurring. Again, writing sequenced constraints in SQL is a classic: see Snodgrass (<a href="http://www.cs.arizona.edu/people/rts/tdbbook.pdf" rel="nofollow noreferrer">http://www.cs.arizona.edu/people/rts/tdbbook.pdf</a>). Hint for MS Access users: you'll need to use CHECK constraints.</p>
| 16,965
|
<p>I was looking at <a href="http://tldp.org/LDP/abs/html/why-shell.html" rel="nofollow noreferrer">http://tldp.org/LDP/abs/html/why-shell.html</a> and was struck by:</p>
<blockquote>
<p>When not to use shell scripts</p>
<p>...</p>
<ul>
<li>Mission-critical applications upon which you are betting the future of the company</li>
</ul>
</blockquote>
<p>Why not?</p>
|
<p>Using shell scripts is fine when you're using their strengths. My company has some class 5 soft switches and the call processing code and the provisioning interface is written in java. Everything else is written in KSH - DB dumps for backups, pruning, log file rotation, and all the automated reporting. I would argue that all those support functions, though not directly related to call-path, are mission critical. Especially the DB interaction. If something went wrong with the DB-interaction code and dumped the call routing tables it could put us out of business.</p>
<p>But nothing ever does go wrong, because shell scripts are the perfect language for stuff like this. They're small, they're well understood, manipulating files is their strength, and they're stable. It's not like KSH09 is going to be a complete rewrite because someone thinks it should compile to byte code, so it's a stable interface. Frankly, the provisioning interface written in Java goes wonky fairly often and the shell scripts have never messed up that I can remember.</p>
|
<p>Scripts are inappropriate for implementing certain mission-critical functions, since they must have both +r and +x permissions to function. Executables need only have +x.</p>
<p>The fact that a script has +r means users might be able to make a copy of the script, edit/subvert it, and execute their edited Cuckoo's-Egg version.</p>
| 3,793
|
<p>Which is faster, python webpages or php webpages?</p>
<p>Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? </p>
<p>I know that serving a python base webpage via cgi is slower than php because of its long start up every time.</p>
<p>I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.</p>
|
<p>It sounds like you don't want to compare the two <strong>languages</strong>, but that you want to compare two <strong>web systems</strong>.</p>
<p>This is tricky, because there are many variables involved.</p>
<p>For example, Python web applications can take advantage of <a href="http://code.google.com/p/modwsgi/" rel="noreferrer">mod_wsgi</a> to talk to web servers, which is faster than any of the typical ways that PHP talks to web servers (even mod_php ends up being slower if you're using Apache, because Apache can only use the Prefork MPM with mod_php rather than multi-threaded MPM like Worker).</p>
<p>There is also the issue of code compilation. As you know, Python is compiled just-in-time to byte code (.pyc files) when a file is run each time the file changes. Therefore, after the first run of a Python file, the compilation step is skipped and the Python interpreter simply fetches the precompiled .pyc file. Because of this, one could argue that Python has a native advantage over PHP. However, optimizers and caching systems can be installed for PHP websites (my favorite is <a href="http://eaccelerator.net/" rel="noreferrer">eAccelerator</a>) to much the same effect.</p>
<p>In general, enough tools exist such that one can pretty much do everything that the other can do. Of course, as others have mentioned, there's more than just speed involved in the business case to switch languages. We have an app written in oCaml at my current employer, which turned out to be a mistake because the original author left the company and nobody else wants to touch it. Similarly, the PHP-web community is much larger than the Python-web community; Website hosting services are more likely to offer PHP support than Python support; etc.</p>
<p>But back to speed. You must recognize that the question of speed here involves many moving parts. Fortunately, many of these parts can be independently optimized, affording you various avenues to seek performance gains.</p>
|
<p>I had to come back to web development at my new job, and, if not Pylons/Python, maybe I would have chosen to live in jungle instead :) In my subjective opinion, PHP is for kindergarten, I did it in my 3rd year of uni and, I believe, many self-respecting (or over-estimating) software engineers will not want to be bothered with PHP code. </p>
<p>Why my employers agreed? We (the team) just switched to Python, and they did not have much to say. The website still is and will be PHP, but we are developing other applications, including web, in Python. Advantages of Pylons? You can integrate your python libraries into the web app, and that is, imho, a huge advantage.</p>
<p>As for performance, we are still having troubles.</p>
| 10,268
|
<p>I develop and manage about 45 WindowsCE5 devices. Updating applications on the devices is a nightmare. Is it possible/feasible to do Click-Once on the CF?</p>
<p>I take the lack of answers to be "No". :)</p>
<p><strong>EDIT</strong>: This is a duplicate of <a href="https://stackoverflow.com/questions/116713">question 116713</a></p>
|
<p>We do a lot of work with CF apps here. If your devices are wireless capable, you can build auto-update functionality into your app without a lot of trouble. Basically when the app starts up, it checks a predefined URL for a manifest file, parses it to find out what version of the .exe is sitting on the server and compares it with the version of the .exe installed on the device. When a newer version is available, it pulls it down from the server and drops it into the correct location on the device. All the user has to do at this point is restart the app to get the most recent version.</p>
<p>We based the logic on code found in this article, and revised as needed.
<a href="http://www.codeproject.com/KB/vb/Auto_Update_Revisited.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/vb/Auto_Update_Revisited.aspx</a></p>
|
<p>Not sure, if not you could always try something like <a href="http://www.modaco.com/category/332/apptodate/" rel="nofollow noreferrer">http://www.modaco.com/category/332/apptodate/</a></p>
| 26,113
|
<p>Authorize.net offers a "Silent POST" feature for their Automated Recurring Billing. It's supposed to POST data to a url of your choosing, telling you whether they were able to charge the customer, how much, etc. The problem is, it isn't very well documented.</p>
<ul>
<li>Is there any way to test a post to that URL? I've signed up for a developer account, but there's no way to specify that URL like you could in the actual system. Hence, there doesn't seem to be a way to test it out.</li>
<li>If not, is there a list of possible values it could return? It appears to send <code>x_first_name</code>, <code>x_amount</code> - I've seen code that uses those values - but since I can't actually get it to send a response, I'm not sure.</li>
<li>Is there documentation for this feature anywhere? Or even class that implements it fully?</li>
</ul>
|
<p>Better late then never: <a href="http://www.johnconde.net/blog/all-about-authorize-nets-silent-post/" rel="noreferrer">All About Authorize.Net’s Silent Post</a></p>
|
<p>You still have to call your account rep for them to activate Silent Post URL with your account because that is not something that is enabled automatically</p>
| 12,950
|
<p>I must implement a web service which expose a list of values (integers, custom classes etc).
My working solution returns a <code>List<T></code>, and according to FxCop it is better to return a <code>Collection<T></code> or <code>ReadOnlyCollection<T></code>.</p>
<p>If I choose to return a <code>ReadOnlyCollection<T></code>, the web service shows an error like:</p>
<blockquote>
<p>To be XML serializable, types which inherit from <code>ICollection</code> must have an implementation of <code>Add(System.Int32)</code> at all levels of their inheritance hierarchy.
<code>System.Collections.ObjectModel.ReadOnlyCollection</code> <code>1</code> <code>[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]</code> does not implement <code>Add(System.Int32)</code>.</p>
</blockquote>
<p>What is your favorite way to use internally a <code>List<T></code> and expose a <code>Collection<T></code> ? (using C#, and preferably framework 2.0 only)</p>
|
<p>List<T> or Collection<T> are fine in this case.</p>
<p>In terms of the original question, you can wrap a List<T> in a Collection<T> very simply:</p>
<pre><code>List<Foo> list = new List<Foo>();
// ...
Collection<Foo> col = new Collection<Foo>(list);
</code></pre>
<p>This is a true wrapper; add an item to the wrapper (col), and it gets added to the list. This can be slightly confusing, because many such constructors use the argument to do the initial population, but don't link to the original list. Collection<T> is an exception ;-p</p>
<p>Since you are on a web-service boundary, that recommendation from FxCop doesn't apply. That is useful (inline with <a href="http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx" rel="noreferrer">Eric Lippert's recent blog</a>) to prevent a caller stomping over the callee's memory - but in a web-service distributed scenario that simply doesn't apply. In fact, since web-services have a few well documented issues with certain generic scenarios, a simple array is arguably very usable and pragmatic at a web-service boundary. In the context of Eric's blog - in this case, there is no question of the caller/callee issue, since there is an enforced barrier between the two. </p>
<p>In terms of WSDL/mex, I suspect all 3 (list/collection/array) will just become a block of elements - so you may a well go with whichever is most convenient.</p>
|
<p>I usually return IList<T> from a WCF web service: FxCop is happy enough with this.
Not sure if this works with ASMX web services.</p>
| 24,039
|
<p>Are delegates the same thing as callbacks? Or are they related somehow?</p>
|
<p>A "callback" is a term that refers to a coding design pattern, available in any language that has function pointers, or an analogue to function pointers (which is kinda what a delegate is) </p>
<p>In this pattern, you pass a pointer to a function to another function, so that within the called function, it can "call back" the function you passed to it. In this way you can control a large chunk of the internal behavior of a method from outside the method, by passing pointers to different "callback" function each time you call it... An example of a callback is when you have a sorting algorithm that has to be passed a pointer to a function that will "compare" any arbitrary pair of objects in the list to be sorted, to determine which goes before the other. On one call to the sort method, you might pass a callback function that compares by object name, and another time pass a function that compares by object weight, or whatever...</p>
<p>A Delegate, otoh, is a specific .Net type that acts as a signature-specific container for a function pointer... In .Net managed code, delegates are the only way to create and use a function pointer. So in .Net to do a callback, you are in fact passing a delegate... But delegates can be used in other scenarios besides callbacks. (specifically, delegates can be also used to implement multi-threading from the .Net thread pool)</p>
<p>Callbacks are also used to implement the "observer" pattern (implemented in .Net using Events, which are themselves a special type of delegate)</p>
|
<p>The service class has a variable function called a delegate.
The calling class has a preferred function that it wants run called a callback.</p>
<p>The calling class sets the delegate to it's callback.</p>
<p>The difference between a delegate and a callback is the perspective: The service class calls the delegate that is set to the calling classes callback.</p>
| 37,084
|
<p>I need to add role based permissions to my Rails application, and am wondering what the best plugins out there are to look into. I am currently using the RESTful authentication plugin to handle user authentication. Why is the plug in you suggest better than the other ones out there?</p>
|
<p>I use, and really like, role_requirement:
<a href="http://code.google.com/p/rolerequirement/" rel="nofollow noreferrer">http://code.google.com/p/rolerequirement/</a></p>
|
<p>We've put role_requirement into <a href="http://github.com/fudgestudios/bort/tree/master" rel="nofollow noreferrer">Bort</a> too, as it's probably the best solution out there at the moment.</p>
| 10,477
|
<p>I have some code which needs to ensure some data is in a mysql enum prior to insertion in the database. The cleanest way I've found of doing this is the following code:</p>
<pre><code>sub enum_values {
my ( $self, $schema, $table, $column ) = @_;
# don't eval to let the error bubble up
my $columns = $schema->storage->dbh->selectrow_hashref(
"SHOW COLUMNS FROM `$table` like ?",
{},
$column
);
unless ($columns) {
X::Internal::Database::UnknownColumn->throw(
column => $column,
table => $table,
);
}
my $type = $columns->{Type} or X::Panic->throw(
details => "Could not determine type for $table.$column",
);
unless ( $type =~ /\Aenum\((.*)\)\z/ ) {
X::Internal::Database::IncorrectTypeForColumn->throw(
type_wanted => 'enum',
type_found => $type,
);
}
$type = $1;
require Text::CSV_XS;
my $csv = Text::CSV_XS->new;
$csv->parse($type) or X::Panic->throw(
details => "Could not parse enum CSV data: ".$csv->error_input,
);
return map { /\A'(.*)'\z/; $1 }$csv->fields;
}
</code></pre>
<p>We're using <a href="http://search.cpan.org/dist/DBIx-Class/" rel="noreferrer">DBIx::Class</a>. Surely there is a better way of accomplishing this? (Note that the $table variable is coming from our code, <em>not</em> from any external source. Thus, no security issue).</p>
|
<p>No need to be so heroic. Using a reasonably modern version of <a href="http://search.cpan.org/dist/DBD-mysql/" rel="noreferrer">DBD::mysql</a>, the hash returned by <a href="http://search.cpan.org/dist/DBI/" rel="noreferrer">DBI</a>'s <a href="http://search.cpan.org/dist/DBI/DBI.pm#column_info" rel="noreferrer">column info</a> method contains a pre-split version of the valid enum values in the key <code>mysql_values</code>:</p>
<pre><code>my $sth = $dbh->column_info(undef, undef, 'mytable', '%');
foreach my $col_info ($sth->fetchrow_hashref)
{
if($col_info->{'TYPE_NAME'} eq 'ENUM')
{
# The mysql_values key contains a reference to an array of valid enum values
print "Valid enum values for $col_info->{'COLUMN_NAME'}: ",
join(', ', @{$col_info->{'mysql_values'}}), "\n";
}
...
}
</code></pre>
|
<p>I spent part of the day asking the #dbix-class channel over on MagNet the same question and came across this lack of answer. Since I found the answer and nobody else seems to have done so yet, I'll paste the transcript below the TL;DR here:</p>
<pre><code>my $cfg = new Config::Simple( $rc_file );
my $mysql = $cfg->get_block('mysql');
my $dsn =
"DBI:mysql:database=$mysql->{database};".
"host=$mysql->{hostname};port=$mysql->{port}";
my $schema =
DTSS::CDN::Schema->connect( $dsn, $mysql->{user}, $mysql->{password} );
my $valid_enum_values =
$schema->source('Cdnurl')->column_info('scheme')->{extra}->{list};
</code></pre>
<p>And now the IRC log of me beating my head against a wall:</p>
<pre><code>14:40 < cj> is there a cross-platform way to get the valid values of an
enum?
15:11 < cj> it looks like I could add 'InflateColumn::Object::Enum' to the
__PACKAGE__->load_components(...) list for tables with enum
columns
15:12 < cj> and then call values() on the enum column
15:13 < cj> but how do I get dbic-dump to add
'InflateColumn::Object::Enum' to
__PACKAGE__->load_components(...) for only tables with enum
columns?
15:20 < cj> I guess I could just add it for all tables, since I'm doing
the same for InflateColumn::DateTime
15:39 < cj> hurm... is there a way to get a column without making a
request to the db?
15:40 < cj> I know that we store in the DTSS::CDN::Schema::Result::Cdnurl
class all of the information that I need to know about the
scheme column before any request is issued
15:42 <@ilmari> cj: for Pg and mysql Schema::Loader will add the list of
valid values to the ->{extra}->{list} column attribute
15:43 <@ilmari> cj: if you're using some other database that has enums,
patches welcome :)
15:43 <@ilmari> or even just a link to the documentation on how to extract
the values
15:43 <@ilmari> and a willingness to test if it's not a database I have
access to
15:43 < cj> thanks, but I'm using mysql. if I were using sqlite for this
project, I'd probably oblige :-)
15:44 <@ilmari> cj: to add components to only some tables, use
result_components_map
15:44 < cj> and is there a way to get at those attributes without making a
query?
15:45 < cj> can we do $schema->resultset('Cdnurl') without having it issue
a query, for instance?
15:45 <@ilmari> $result_source->column_info('colname')->{extra}->{list}
15:45 < cj> and $result_source is $schema->resultset('Cdnurl') ?
15:45 <@ilmari> dbic never issues a query until you start retrieving the
results
15:45 < cj> oh, nice.
15:46 <@ilmari> $schema->source('Cdnurl')
15:46 <@ilmari> the result source is where the result set gets the results
from when they are needed
15:47 <@ilmari> names have meanings :)
</code></pre>
| 28,372
|
<p>Excluding the Micro Framework Emulator ;)</p>
|
<p>A well known one is <a href="http://devicesolutions.net/Products/Tahoe/tabid/55/Default.aspx" rel="nofollow noreferrer">Tahoe</a>. Others are</p>
<ul>
<li><a href="http://www.sjjmicro.com/EDK.html" rel="nofollow noreferrer">http://www.sjjmicro.com/EDK.html</a></li>
<li><a href="http://www.ghielectronics.com/details.php?id=107&sid=108" rel="nofollow noreferrer">http://www.ghielectronics.com/details.php?id=107&sid=108</a></li>
</ul>
|
<p><strong><a href="http://www.tinyclr.com/hardware/1/fez-domino" rel="nofollow">Domino</a></strong> and <strong><a href="http://www.ghielectronics.com/catalog/product/135/" rel="nofollow">Panda</a></strong> with it's many Arduino compatible shields are highly affordable and well supported.</p>
| 13,591
|
<p>I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.</p>
|
<p>The following works great for printing with the win32api from C++</p>
<pre><code>char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);
</code></pre>
<p>In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/"</p>
|
<p>Unmanaged C++ doesn't exist (and managed C++ is now C++/CLI), if you are referring to C++, using unmanaged as a tag is just sad...</p>
| 13,042
|
<p>I would like to redirect <code>www.example.com</code> to <code>example.com</code>. The following htaccess code makes this happen:</p>
<pre><code>RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
</code></pre>
<p>But, is there a way to do this in a generic fashion without hardcoding the domain name?</p>
|
<pre><code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</code></pre>
<p>Same as <a href="https://stackoverflow.com/a/235064/662581">Michael's</a> except this one works :P</p>
|
<p>Hi you can use following rules on your htaccess file:</p>
<pre><code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
</code></pre>
| 29,052
|
<p>Can somebody point me at a <strong>good</strong> tutorial for py2exe? I've read over the <a href="http://www.py2exe.org/index.cgi/Tutorial" rel="nofollow noreferrer">official tutorial</a> but it is rather light on details, compared to all the options one can use when building an executable out of a python script. For the record, my python script uses Python 2.5.2, wxPython/wxWidgets 2.8 and MySQLdb 1.2.2; so if you have specific tips for py2exe with those packages that would be much appreciated (and yes, I've seen the <a href="http://www.py2exe.org/index.cgi/Py2exeAndwxPython" rel="nofollow noreferrer">Py2EXE and wxPython</a> page).</p>
|
<p>Regarding "Py2EXE and wxPython", the page mentions the import statement "from wxPython.wx import *". This is the old wxPython (several years old, I think). In my app, I just do "import wx", and I don't have any major troubles.</p>
<p>I have one tip for wxPython and py2exe: you need a manifest if you want your app to look any good on Windows XP. This email has details: <a href="http://mail.python.org/pipermail/python-list/2004-June/268126.html" rel="nofollow noreferrer">http://mail.python.org/pipermail/python-list/2004-June/268126.html</a></p>
|
<p>Don't know about a better tutorial, but there is some information to be found at the news list.</p>
<p><a href="http://news.gmane.org/gmane.comp.python.py2exe" rel="nofollow noreferrer">http://news.gmane.org/gmane.comp.python.py2exe</a></p>
| 21,242
|
<p>I have seen sample source code around that uses different ways of releasing/dealloc'ing objects, so I was wondering which way is deemed the "best" one. A few options on <code>-dealloc</code>:</p>
<p>1) Release objects</p>
<pre><code>- (void)dealloc {
[obj1 release];
[obj2 release];
[super dealloc];
}
</code></pre>
<p>2) Set objects to nil</p>
<pre><code>- (void)dealloc {
self.obj1 = nil;
self.obj2 = nil;
[super dealloc];
}
</code></pre>
<p>3) De-allocate objects directly</p>
<pre><code>- (void)dealloc {
[obj1 dealloc];
[obj2 dealloc];
[super dealloc];
}
</code></pre>
<p>Which way is the best one? Pros and cons for each?</p>
|
<p>Method 1 is the only recommended method. It's also good practice to set them to nil AFTER you've released them.</p>
<p>Method 2 only works for properties that manage their own object/value retaining, so it's not universally applicable. And if you implement your own setter method that performs other actions when the property changes, you may get undesired side effects by calling it in [dealloc].</p>
<p>Method 3 violates the reference-counting principle because it will deallocate the objects even if something else has a [retain] hold on them, so when the other objects access them next, your program will crash. You're never supposed to call [dealloc] directly -- let the runtime call it when the last owner calls [release].</p>
|
<p>If obj1 and obj2 are properties using @synthesize-d accessors, then method 1 and method 2 are equivalent. If either of those two conditions is not true then the effect is rather different. If they're not properties, then method 2 just sets the pointers to nil without doing anything that would deallocate the objects. And if they are properties but you've implemented your own setter methods, method 2 calls those methods with "nil" as the argument. Whether that's equivalent to method 1 or not depends on how you've implemented those methods. If your custom setters do anything significant when the argument is nil, method 2 would ensure that this code executed.</p>
<p>As Marco said, method 3 is just plain wrong. If you've seen sample code doing that then the author may not actually know what they're doing.</p>
| 47,505
|
<p>I have up to 4 files based on this structure (note the prefixes are dates)</p>
<ul>
<li>0830filename.txt</li>
<li>0907filename.txt</li>
<li>0914filename.txt</li>
<li>0921filename.txt</li>
</ul>
<p>I want to open the the most recent one (0921filename.txt). how can i do this in a batch file?</p>
<p>Thanks.</p>
|
<p>This method uses the actual file modification date, to figure out which one is the latest file:</p>
<pre><code>@echo off
for /F %%i in ('dir /B /O:-D *.txt') do (
call :open "%%i"
exit /B 0
)
:open
start "dummy" "%~1"
exit /B 0
</code></pre>
<p>This method, however, chooses the last file in alphabetic order (or the first one, in reverse-alphabetic order), so if the filenames are consistent - it will work:</p>
<pre><code>@echo off
for /F %%i in ('dir /B *.txt^|sort /R') do (
call :open "%%i"
exit /B 0
)
:open
start "dummy" "%~1"
exit /B 0
</code></pre>
<p>You actually have to choose which method is better for you.</p>
|
<p>Use regular expression to parse the relevant integer out and compare them.</p>
| 7,504
|
<p>In VS .NET, when you are selecting a folder for a project, a dialog that looks like an OpenFileDialog or SaveFileDialog is displayed, but is set up to accept only folders. Ever since I've seen this I've wanted to know how it's done. I am aware of the FolderBrowserDialog, but I've never really liked that dialog. It starts too small and doesn't let me take advantage of being able to type a path.</p>
<p>I'm almost certain by now there's not a way to do this from .NET, but I'm just as curious how you do it from unmanaged code as well. Short of completely reimplementing the dialog from scratch, how do you modify the dialog to have this behavior?</p>
<p>I'd also like to restate that I am aware of the FolderBrowserDialog but sometimes I don't like to use it, in addition to being genuinely curious how to configure a dialog in this manner. Telling me to just use the FolderBrowserDialog helps me maintain a consistent UI experience but doesn't satisfy my curiosity so it won't count as an answer.</p>
<p>It's not a Vista-specific thing either; I've been seeing this dialog since VS .NET 2003, so it is doable in Win2k and WinXP. This is less of a "I want to know the proper way to do this" question and more of a "I have been curious about this since I first wanted to do it in VS 2003" question. I understand that Vista's file dialog has an option to do this, but it's been working in XP so I know they did <em>something</em> to get it to work. Vista-specific answers are not answers, because Vista doesn't exist in the question context.</p>
<p><strong>Update: I'm accepting Scott Wisniewski's answer because it comes with a working sample, but I think Serge deserves credit for pointing to the dialog customization (which is admittedly nasty from .NET but it <em>does</em> work) and Mark Ransom for figuring out that MS probably rolled a custom dialog for this task.</strong></p>
|
<p>I have a dialog that I wrote called an OpenFileOrFolder dialog that allows you to open either a folder or a file.</p>
<p>If you set its AcceptFiles value to false, then it operates in only accept folder mode.</p>
<p><a href="https://github.com/scottwis/OpenFileOrFolderDialog" rel="noreferrer">You can download the source from GitHub here</a></p>
|
<p>I know the question was on configuration of <code>OpenFileDialog</code> but seeing that Google brought me here i may as well point out that if you are ONLY looking for folders you should be using a <code>FolderBrowserDialog</code> Instead as answered by another SO question below</p>
<p><a href="https://stackoverflow.com/questions/11465237/how-to-specify-path-using-open-file-dialog-in-vb-net">How to specify path using open file dialog in vb.net?</a></p>
| 5,093
|
<p>We're moving a solution with 20+ projects from .net 2.0 to 3.5 and at the same time moving from Visual Studio 2005 to 2008. We're also at the same time switching from MS Entlib 2.0 to 4.0. </p>
<ul>
<li>Is there any reasons not to let the
Visual Studio wizard convert the
solution for us?</li>
<li>Is 3.5 fully backwards compatible
with 2.0?</li>
<li>Is Entlib 4.0 fully backwards compatible
with 2.0?</li>
</ul>
<p><strong>Edit:</strong> I might been a bit confused when I wrote this, the backwards compatability is supposed to mean; is there anything that exists in a 2.0 project that will not work/compile in 3.5</p>
<p>:)</p>
<p>//W</p>
|
<p>We upgrade a rather large solution (20+ projects) from 2005 to 2008 but it was really trivial. Project upgrade only basically. The underlying framework is still the same since both 3.0/3.5 and 2.0 share the same core framework.</p>
<p>As was said above, even though you are upgrading, you don't need to change the framework reference for the projects - in fact, it defaults to leaving the framework at 2.0 instead of changing it to 3.0/3.5. This means you will not be able to take advantage of 3.0/3.5 features until you change the reference (Project Properties page, Application Table "Target Framework" field) but it also means you are that much more assured there won't be additional compatibility issues (as you will get an error adding 3.0/3.5 code until that reference is changed).</p>
<p>New features of TFS 2008 shouldn't be overlooked either though you don't need to upgrade your app to be able to use TFS 2008.</p>
<p>1.1 to 2.0 conversion was much more painful...</p>
|
<ul>
<li>Is there any reasons not to let the Visual Studio wizard convert the solution for us?</li>
</ul>
<p>No.</p>
<ul>
<li>Is 3.5 fully backwards compatible with 2.0?</li>
</ul>
<p>No. There are new features in 3.5 that wouldn't port backwards natively. And (IIRC) there are some deprecations going from 2.0 to 3.5.</p>
<ul>
<li>Is Entlib 4.0 fully backwards compatible with 2.0?</li>
</ul>
<p>I don't think so. 3.5 is listed as a requirement.</p>
<p>Make a backup, run the wizard, see what happens. It might take a while for such a chunky project but you'll be in a position where you can tell if it'll build/run-as-expected.</p>
| 19,502
|
<p>my machine did an automatic reboot, due to patch applied by my network in my company, and last error i saw reported something with the csproj.user file. Now each time i try to launch my solution, it opens and then brings the dialog to send the report to MS. If i look at the error log in event viewer it shows this</p>
<p>EventType clr20r3, P1 devenv.exe, P2 8.0.50727.762, P3 45716759, P4 system, P5 2.0.0.0, P6 4889de7a, P7 5a2, P8 0, P9 system.io.filenotfoundexception, P10 NIL.</p>
<p>EventType clr20r3, P1 devenv.exe, P2 8.0.50727.762, P3 45716759, P4 system, P5 2.0.0.0, P6 4889de7a, P7 5a2, P8 0, P9 system.io.filenotfoundexception, P10 NIL.</p>
<p>.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A2E0F92) (0)</p>
<p>any ideas?</p>
|
<p>I believe the .user file just has your personal IDE settings so they can be restored when you re-open VS. Apparently, your .user file became corrupted. It shouldn't hurt anything to delete it other than you will lose any personal settings in the IDE and have to redo them.</p>
|
<p>Hmmm, some file got deleted. I hope it was part of your project and not a .net framework file. Try and recreate your project and solution and copy your file back into it. </p>
<p>Hopefully this is not happening when you create a new solution or project. If it is you may need to reinstall Visual Studio.</p>
| 46,097
|
<p>What is the best way to find if an object is in an array?</p>
<p>This is the best way I know:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined</code></pre>
</div>
</div>
</p>
|
<p>As of ECMAScript 2016 you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer"><code>includes()</code></a></p>
<pre><code>arr.includes(obj);
</code></pre>
<p>If you want to support IE or other older browsers:</p>
<pre><code>function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
</code></pre>
<p>EDIT:
This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:</p>
<ol>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer">Mozilla's</a> (ECMA-262) version:</p>
<pre><code> if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
</code></pre>
</li>
<li><p><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144172">Daniel James</a>'s version:</p>
<pre><code> if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
</code></pre>
</li>
<li><p><a href="https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144664">roosteronacid</a>'s version:</p>
<pre><code> Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
</code></pre>
</li>
</ol>
|
<p>Here's some meta-knowledge for you - if you want to know what you can do with an Array, check the documentation - here's the Array page for Mozilla</p>
<p><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array</a></p>
<p>There you'll see reference to indexOf, added in Javascript 1.6</p>
| 17,357
|
<p>Every time that I change a value in the designer after saving it, the .designer.cs file will be deleted. </p>
<p>Can anyone tell me how can I fix this problem?</p>
|
<p>Move <code>using</code> directives in your <code>DataContext.cs</code> and <code>DataContext.designer.cs</code> files into the <code>namespace</code> scope.</p>
|
<p>Don't place your own code in the designer file, instead use a separate file leveraging the partial classes concept.</p>
| 37,323
|
<p>I create new ASP.NET web application that use SMTP to send message. The problem is the smtp was not authenticated from who send the message. </p>
<p>How can I make SMTP authenticated in my program? does C# have a class that have attribute for enter username and password?</p>
|
<pre><code>using System.Net;
using System.Net.Mail;
using(SmtpClient smtpClient = new SmtpClient())
{
var basicCredential = new NetworkCredential("username", "password");
using(MailMessage message = new MailMessage())
{
MailAddress fromAddress = new MailAddress("from@yourdomain.com");
smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
// Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>your message body</h1>";
message.To.Add("to@anydomain.com");
try
{
smtpClient.Send(message);
}
catch(Exception ex)
{
//Error, could not send the message
Response.Write(ex.Message);
}
}
}
</code></pre>
<p>You may use the above code.</p>
|
<p>In my case even after following all of the above. I had to upgrade my project from .net 3.5 to .net 4 to authorize against our internal exchange 2010 mail server.</p>
| 38,192
|
<p>In order to merge independant HTML changes, I'm looking for recomendations for a 3-way comparison / merge library for HTML. The common 3-way text merge algorithms perform poorly because they do not understand the tree like structure of HTML and XML. Of course, such a library must understand the looser syntax of HTML, i.e. tags are not always closed. My platform is .Net.</p>
|
<p>You could also just go cheep: Run the files through <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">tidy</a> and then compare. This will result in similar structures, where new / deleted children will show up with traditional diff tools. It breaks down on removal / addition of surrounding nodes - good luck on solving that one...</p>
<p>Also, the <a href="http://www.snapfiles.com/get/xmlnotepad.html" rel="nofollow noreferrer">XML Notepad</a> (sorry, couldn't find a link that works on microsoft.com) by Microsoft can compare XML files and does this in a tree based fashion.</p>
|
<p>A simple google search offered up: <a href="http://www.codeproject.com/KB/cs/differ.aspx" rel="nofollow noreferrer">Differ</a>. I've never used it so I can't vouch for the quality of that :-)</p>
| 9,120
|
<p>I'm using VSTS Database Edition GDR Version 9.1.31024.02</p>
<p>I've got a project where we will be creating multiple databases with identical schema, on the fly, as customers are added to the system. It's one DB per customer. I thought I should be able to use the deploy script to do this. Unfortunately I always get the full filenames specified on the CREATE DATABASE statement. For example:</p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [targetDBName], FILENAME = N'$(DefaultDataPath)targetDBName.mdf')
LOG ON (NAME = [targetDBName_log], FILENAME = N'$(DefaultDataPath)targetDBName_log.ldf')
GO
</code></pre>
<p>I'd expected something more like this </p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
ON
PRIMARY(NAME = [targetDBName], FILENAME = N'$(DefaultDataPath)$(DatabaseName).mdf')
LOG ON (NAME = [targetDBName_log], FILENAME = N'$(DefaultDataPath)$(DatabaseName)_log.ldf')
GO
</code></pre>
<p>Or even </p>
<pre><code>CREATE DATABASE [$(DatabaseName)]
</code></pre>
<p>I'm not going to be running this on an on-going basis so I'd like to make it as simple as possible, for the next guy. There are a bunch of options for deployment in the project properties, but I can't get this to work the way I'd like.</p>
<p>Any one know how to set this up?</p>
|
<p>Better late than never, I know how to get the <code>$(DefaultDataPath)$(DatabaseName)</code> file names from your second example. </p>
<p>The SQL you're showing in your first code snippet suggests that you don't have scripts for creating the database files in your VSTS:DB project, perhaps by deliberately excluded them from any schema comparisons you've done. I found it a little counter-intuitive, but the solution is to let VSTS:DB script the MDF and LDF in you development environment, then edit those scripts to use the SQLCMD variables. </p>
<p>In your database project, go to the folder <em>Schema Objects > Database Level Objects > Storage > Files</em>. In there, add these two files:</p>
<p><strong>Database.sqlfile.sql</strong></p>
<pre><code>ALTER DATABASE [$(DatabaseName)]
ADD FILE (NAME = [$(DatabaseName)],
FILENAME = '$(DefaultDataPath)$(DatabaseName).mdf',
SIZE = 2304 KB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024 KB)
TO FILEGROUP [PRIMARY];
</code></pre>
<p><strong>Database_log.sqlfile.sql</strong></p>
<pre><code>ALTER DATABASE [$(DatabaseName)]
ADD LOG FILE (NAME = [$(DatabaseName)_log],
FILENAME = '$(DefaultDataPath)$(DatabaseName)_log.ldf',
SIZE = 1024 KB, MAXSIZE = 2097152 MB, FILEGROWTH = 10 %);
</code></pre>
<p>The full database creation script that VSTS:DB, or for that matter VSDBCMD.exe, generates will now use the SQLCMD variables for naming the MDF and LDF files, allowing you to specify them on the command line, or in MSBuild. </p>
|
<p>Hmm, well it seems that the best answer so far (given the over whelming response) is to edit the file after the fact... Still looking</p>
| 43,588
|
<p>I have a requirement on my current project (a Flex app which will be run in Flash player) to display an arbitrary subset of the components on a form while hiding all the other components based on certain aspects of the application state. There are about a dozen different text boxes and drop downs, but some become irrelevant based on previously entered user data and we don't want to display those when we get to this particular form. Every time this form is displayed I could need to show any one of the many permutations of these components.</p>
<p>I'm trying to decide what the best way to approach this problem is. Should I create a Canvas (or other container) with all of the needed controls on it and then just set visible = false on the ones I don't need? The problem then becomes making sure the layout looks decent. I don't want there to be gaps where the hidden controls would have been.</p>
<p>The other option I've thought about is just having a mechanism that could dynamically instantiate the TextInput or CheckBox etc. component and then call container.addChild(control) in order to build up the components and not have to worry about the gap issue.</p>
<p>This seems like a problem that has an idiomatic solution in flex, but I don't know what it is. Neither of these ideas seem great so I'm wondering if anyone else has a better idea.</p>
|
<p>I don't know if this is a good solution or not, but when I was in exactly the same situation, I did basically your first method. Set <code>visible = false</code> and also set <code>includeInLayout = false</code> to prevent those "gaps" you were talking about. It's a very simple solution, very easy and quick to implement... perhaps someone else knows of something more idiomatic though.</p>
|
<p>If states won't do, check out articles that explain the components life cycle.</p>
<p>If you create a class that extends a flex component like Canvas, you will define all components in a function that override createChildren. You will revisit the layout in another function that override updateDisplayList</p>
<ul>
<li><a href="https://web.archive.org/web/20080911223134/http://flexcomps.wordpress.com/2008/05/09/flex-component-life-cycle/" rel="nofollow noreferrer">Flex Component Life Cycle</a> @flexcomps</li>
<li><a href="https://web.archive.org/web/20090308034358/http://weblogs.macromedia.com:80/pent/archives/2007/10/component_class_2.html" rel="nofollow noreferrer">Component Class - Part Three</a> @PeterEnt</li>
<li><a href="http://guavus.wordpress.com/2008/09/15/flex-component-lifecycle/" rel="nofollow noreferrer">Flex component lifecyle</a> @guavus</li>
<li><a href="http://www.billdwhite.com/wordpress/?p=21" rel="nofollow noreferrer">Understanding Custom Flex Component Development</a> @billWhite</li>
</ul>
| 25,780
|
<p>What is the resolution of the image for the tab bar item?</p>
<p>And also, please provide some other useful information regarding that tab item image.</p>
<p>Thanks in advance.</p>
|
<p>The documentation says that the tab bar image is usually 30x30, but I've found that the best size to setup the images is 48x32 pixels. This size still renders and gives you a bit more space.</p>
<p>The image is a PNG with transparency, only the mask is used. The UI renders the mask gray when unselected or blue/chrome when selected. </p>
|
<p>Check the "UITabBarItem Class Reference" in the <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UITabBarItem_Class/Reference/Reference.html" rel="nofollow noreferrer">SDK documentation</a></p>
| 18,286
|
<p>Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob?
(I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)</p>
|
<p>If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field.</p>
<p>Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the ability to use SQL to do any useful manipulation on that data. Although without knowing what you're actually doing, I can't really make a moral call on it.</p>
|
<p>See this solution at SourceForge:</p>
<p>y_serial.py module :: warehouse Python objects with SQLite</p>
<p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p>
<p><a href="http://yserial.sourceforge.net" rel="nofollow noreferrer">http://yserial.sourceforge.net</a></p>
| 24,212
|
<p>Does anybody knows why this snippet returns <code>false</code> even if the passed string is "Active"?</p>
<pre><code>if ($('status_'+id).getText()=="Active")
</code></pre>
<p>I've also tried changing the code to</p>
<pre><code>if ($('status_'+id).getText()==String("Active"))
</code></pre>
<p>and</p>
<pre><code>if (String($('status_'+id).getText())=="Active")
</code></pre>
<p>and still no luck.</p>
<p>I've also checked <code>$('status_'+id).getText()</code> through <code>console.log</code> to verify if it really returns "Active"</p>
<p>i wonder why it doesnt work?
any ideas?</p>
|
<p>A key difference between C++ and .NET/Java is the automatic reclaiming of memory that is no longer required. This is known as <strong>garbage collection</strong>. For this property, they are known as <strong>managed</strong> platforms.</p>
<p>Both Java/.NET delay the compilation of bytecode into native code until the last minute. For this property they are known as <strong>JIT-compiled</strong> (Just In Time).</p>
<p>The C#/Java/C++ languages are known as <strong>imperative, object-oriented</strong> languages.</p>
<p>The type system in both .NET and Java only allows verifiable invocation of methods. For this property they are known as <strong>statically typed</strong>. </p>
<p>C#/Java/C++ are <strong>Turing complete</strong>, meaning that, in practice, they can produce any calculation.</p>
|
<p>It depends, if you are talking about the fact they run on a virtual machine then they are regarded as JIT-compiled (Just-In-Time) or bytecode (logically 1/2 compiled and 1/2 interpreted).</p>
<p>If you are talking about the garbage collection then they are simply referred to as garbage collected.</p>
<p>The key point here is the two attributes are separate, a garbage collected language does not have to have a virtual machine and a virtual machine based language does not have to be garbage collected.</p>
<p>As an example Python is an interpreted language which has garbage collection, but it is interpreted as opposed to running on a virtual machine.</p>
| 24,430
|
<p>Here's some code I saw once. Can you see what's wrong with it?</p>
<p>[updated]</p>
<pre><code>public class ResourceManager1
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
public class ResourceManager2
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
</code></pre>
|
<p>Never synchronize on strings, particularly string literals which are interned. You've basically just got a single lock.</p>
<p>In general, never synchronize on any reference that might be visible outside your class (including "this") <em>unless</em> the purpose of the external visibility is precisely for locking purposes. I usually use a <code>private final</code> variable created solely for the purpose of locking.</p>
|
<p>mutex is not final and resource is not private.</p>
<p>Besides, you need a getResource method that returns resource, but I suppose this is just a typo.</p>
| 44,669
|
<p>Like the title says, how can I remove GAC assembly file using vbscript?</p>
|
<p>You can run this to uninstall it from GAC:</p>
<pre><code>gacutil /u YourAssembly
</code></pre>
|
<p>As I remember gacutil in a .NET enabled shell. </p>
<pre><code>C:\>gacutil
Microsoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Usage: Gacutil <command> [ <options> ]
Commands:
/i <assembly_path> [ /r <...> ] [ /f ]
Installs an assembly to the global assembly cache.
/il <assembly_path_list_file> [ /r <...> ] [ /f ]
Installs one or more assemblies to the global assembly cache.
/u <assembly_display_name> [ /r <...> ]
Uninstalls an assembly from the global assembly cache.
/ul <assembly_display_name_list_file> [ /r <...> ]
Uninstalls one or more assemblies from the global assembly cache.
/l [ <assembly_name> ]
List the global assembly cache filtered by <assembly_name>
/lr [ <assembly_name> ]
List the global assembly cache with all traced references.
/cdl
Deletes the contents of the download cache
/ldl
Lists the contents of the download cache
/?
Displays a detailed help screen
Options:
/r <reference_scheme> <reference_id> <description>
Specifies a traced reference to install (/i, /il) or uninstall (/u, /ul).
/f
Forces reinstall of an assembly.
/nologo
Suppresses display of the logo banner
/silent
Suppresses display of all output
</code></pre>
| 36,486
|
<p>I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings?</p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/7c5fyk1k.aspx" rel="noreferrer"><code>HttpUtility.HtmlDecode</code></a></p>
<p>If you are using .NET 4.0+ you can also use <a href="http://msdn.microsoft.com/en-us/library/ee388354.aspx" rel="noreferrer"><code>WebUtility.HtmlDecode</code></a> which does not require an extra assembly reference as it is available in the <code>System.Net</code> namespace.</p>
|
<p>Write static a method into some utility class, which accept string as parameter and return the decoded html string.</p>
<p>Include the <code>using System.Web.HttpUtility</code> into your class</p>
<pre><code>public static string HtmlEncode(string text)
{
if(text.length > 0){
return HttpUtility.HtmlDecode(text);
}else{
return text;
}
}
</code></pre>
| 14,918
|
<p>I'm using the Accessibility API to detect when a certain application opens windows, closes windows, when the windows are moved or resized, or made main and/or focused. However the client app seems to move a window to front without an Accessibility API notification being
fired.</p>
<p>How can my application detect when another application brings a window to front, without making it key?</p>
<p>I'm hoping to find a solution that works on OS X 10.4 and 10.5</p>
<p>More info:
I'm using these statements at the moment. They work fine when the user manually selects a window to bring it to front. But it doens't work when the app itself is bringing the window to the front.</p>
<pre><code>AXObserverAddNotification(observer, element, kAXMainWindowChangedNotification, 0);
AXObserverAddNotification(observer, element, kAXFocusedWindowChangedNotification, 0);
</code></pre>
|
<p>I've been unable to subscribe to current window changes, but you can ask the accessibility API for the current application, and the current applications most foreground window. </p>
<p>Imagine you have a class called CurrentAppData, with the following data:</p>
<pre><code>@interface CurrentAppData : NSObject {
NSString* _title;
AXUIElementRef _systemWide;
AXUIElementRef _app;
AXUIElementRef _window;
}
</code></pre>
<p>The code to find the current application looks something like this:</p>
<pre><code>-(void) updateCurrentApplication {
// get the currently active application
_app = (AXUIElementRef)[CurrentAppData
valueOfExistingAttribute:kAXFocusedApplicationAttribute
ofUIElement:_systemWide];
// Get the window that has focus for this application
_window = (AXUIElementRef)[CurrentAppData
valueOfExistingAttribute:kAXFocusedWindowAttribute
ofUIElement:_app];
NSString* appName = [CurrentAppData descriptionOfValue:_window
beingVerbose:TRUE];
[self setTitle:appName];
}
</code></pre>
<p>In this example the _systemWide variable is initialized in the classes init function as:
_system = AXUIElementCreateSystemWide();</p>
<p>The class function valueOfExistingAttribute looks like this:</p>
<pre><code>// -------------------------------------------------------------------------------
// valueOfExistingAttribute:attribute:element
//
// Given a uiElement and its attribute, return the value of an accessibility
// object's attribute.
// -------------------------------------------------------------------------------
+ (id)valueOfExistingAttribute:(CFStringRef)attribute ofUIElement:(AXUIElementRef)element
{
id result = nil;
NSArray *attrNames;
if (AXUIElementCopyAttributeNames(element, (CFArrayRef *)&attrNames) == kAXErrorSuccess)
{
if ( [attrNames indexOfObject:(NSString *)attribute] != NSNotFound
&&
AXUIElementCopyAttributeValue(element, attribute, (CFTypeRef *)&result) == kAXErrorSuccess
)
{
[result autorelease];
}
[attrNames release];
}
return result;
}
</code></pre>
<p>The previous function was taken from the Apple <a href="http://developer.apple.com/samplecode/UIElementInspector/index.html" rel="noreferrer">UIElementInspector</a> example, which is also a great resource for learning about the Accessibility API.</p>
|
<p>What about <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSAccessibility_Protocol/Reference/Reference.html#//apple_ref/doc/uid/20000945-DontLinkElementID_287" rel="nofollow noreferrer">NSAccessibilityFocusedUIElementChangedNotification</a>?</p>
| 45,201
|
<p>Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?</p>
|
<p>I prefer the <a href="http://www.php.net/gd" rel="nofollow noreferrer">GD library</a> - check out <a href="http://www.php.net/manual/en/image.examples.php" rel="nofollow noreferrer">the Examples</a>, and this example:</p>
<pre><code><?php
header ("Content-type: image/png");
$im = @imagecreatetruecolor(120, 20)
or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>
</code></pre>
<p>Outputs:</p>
<p><a href="https://i.stack.imgur.com/kBN75.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kBN75.png" alt="imagecreatetrucolor example"></a><br>
<sub>(source: <a href="http://uk2.php.net/manual/en/figures/image.imagecreatetruecolor.png" rel="nofollow noreferrer">php.net</a>)</sub> </p>
<p>See <a href="http://www.php.net/manual/en/function.imagecreatetruecolor.php" rel="nofollow noreferrer">imagecreatetruecolor</a>.</p>
|
<p>MagickWand is pretty good for that as well, and pretty powerful.</p>
<p><a href="http://www.bitweaver.org/doc/magickwand/index.html" rel="nofollow noreferrer">http://www.bitweaver.org/doc/magickwand/index.html</a></p>
<p>This snippet will take an image, wrie the 'rose' in Vera, or whatever fonts are available, and flush the image to the browser.</p>
<pre><code>$drawing_wand=NewDrawingWand();
DrawSetFont($drawing_wand,"/usr/share/fonts/bitstream-vera/Vera.ttf");
DrawSetFontSize($drawing_wand,20);
DrawSetGravity($drawing_wand,MW_CenterGravity);
$pixel_wand=NewPixelWand();
PixelSetColor($pixel_wand,"white");
DrawSetFillColor($drawing_wand,$pixel_wand);
if (MagickAnnotateImage($magick_wand,$drawing_wand,0,0,0,"Rose") != 0) {
header("Content-type: image/jpeg");
MagickEchoImageBlob( $magick_wand );
} else {
echo MagickGetExceptionString($magick_wand);
}
</code></pre>
| 4,473
|
<p>We attempt to do agile development at my current job and we succeed for the most part. The main problem seems to be that the developers on the project are always waiting for requirements at the beginning of the sprint and rushing to get get things down by the end. The business analysts who are delivering the requirements are always working non-stop to get the requirements done.</p>
<p><strong>EDIT: Additional Information:</strong>
We are customizing a COTS application for our internal use. Our 'user stories' just consist of what part of the application we will be customizing in the specific sprint and also what systems we will integrate with internally. The integration with different systems normally works pretty well because we can start working on that right away. The 'customize x screen' are the main problems areas because the developers can't do anything from that. We have to wait until we get the requirements from the BAs before we can really do anything.</p>
<p><strong>EDIT: More insight/confusion perhaps:</strong>
I wonder if part of the problem is that the screen that are being customized are already there as this is a COTS product that is being heavily customized. People suggest that the user stories should be along the lines of 'make a screen that does X'. That's already done. Maybe there isn't a good way to do user stories for these requirements... maybe this need to be a whole new question.</p>
|
<p>Don't wait. Build a prototype based on whatever minimal requirements you do have and get feedback ASAP from the product owner. More often than not they don't know what they want anyway - if you can show them something tangible as a starting point you're more likely to get useful feedback. Also, once you have a better idea of the real requirements you will probably have already gained a lot of insight from developing your prototype.</p>
|
<p>I see a few ways to handle this: </p>
<p>Option 1, Under SCRUM, you should have a Product Owner who is managing your product backlog, which is supposed to contain requests for features of the software. If the feature consists of something vague like 'Customize screen X' and you decide to add that to your sprint, then the sprint tasks should be concrete, decomposed tasks, and I would say one of those tasks has to be 'Define requirements for screen X'. </p>
<p>During the daily SCRUM, when you're asking your three questions of each team member, the developer who has that screen mod task will say "I'm blocked waiting for requirements from the BA.", and your scrum master does what they can to get that moving along. </p>
<p>option 2, in my opinion, is that items do not go into your product backlog until they're defined well enough to do at least some productive work on. We all know requirements change, but the point is that you're supposed to have enough to start with. </p>
| 14,982
|
<p>What is the regular expression for a decimal with a precision of 2?</p>
<p><em>Valid examples</em>:</p>
<pre><code>123.12
2
56754
92929292929292.12
0.21
3.1
</code></pre>
<p><em>Invalid examples:</em></p>
<pre><code>12.1232
2.23332
e666.76
</code></pre>
<p>The decimal point may be optional, and integers may also be included.</p>
|
<p>Valid regex tokens vary by implementation. A generic form is:</p>
<pre><code>[0-9]+(\.[0-9][0-9]?)?
</code></pre>
<p>More compact:</p>
<pre><code>\d+(\.\d{1,2})?
</code></pre>
<p>Both assume that both have at least one digit before and one after the decimal place.</p>
<p>To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):</p>
<pre><code>^\d+(\.\d{1,2})?$
</code></pre>
<p>To match numbers without a leading digit before the decimal (<code>.12</code>) and whole numbers having a trailing period (<code>12.</code>) while excluding input of a single period (<code>.</code>), try the following:</p>
<pre><code>^(\d+(\.\d{0,2})?|\.?\d{1,2})$
</code></pre>
<hr>
<h2>Added</h2>
<p>Wrapped the fractional portion in <code>()?</code> to make it optional. Be aware that this excludes forms such as <code>12.</code> Including that would be more like <code>^\d+\\.?\d{0,2}$</code>.</p>
<h2>Added</h2>
<p>Use <code>^\d{1,6}(\.\d{1,2})?$</code> to stop repetition and give a restriction to whole part of the decimal value.</p>
|
<pre><code> function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
</code></pre>
<p>function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.</p>
<p>Thanks... :)</p>
| 39,677
|
<p>Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.</p>
<p>I've been working on so many complete rewrites of a custom template engine in php for so long and so many times that i thought i'd ask for opinions.</p>
<p>In short, this is the most important part i have implemented so far:</p>
<ol>
<li>Any http request is routed to handler.php</li>
<li>based on the requested URL a controller is instantiated and a method on that controller is called.</li>
<li>The controller method must return an <code>IView</code> compatible class instance ( <code>IView</code> defines a <code>Render()</code> method)
<ol>
<li>The template engine does some xpath for every namespace that ends in 'serverside' <code>sprintf('//%s:*[@runat="server"]', $namespaceprefix )</code></li>
<li>For every found tag, it looks up the php class identified by <code>$tag.localName</code> and instantiates one and attaches it to the original template.</li>
<li>Once attached, the original template node is fed to the 'ServerTag' so it can initialize properly</li>
<li>the fully complete IView compatible instance is assigned to a temporary variable in the controller method. </li>
</ol></li>
<li>The controller asks pushes data from a Model class to the view which does some nifty xpath DOM replacement.</li>
<li>The controller returns the completely filled view to <code>main()</code>the handler, which renders it.</li>
</ol>
<p>I am basing my template on xml. a simple template currently looks like:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml"
xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title will be filed by the View depending on the Controller</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/" />
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo" />
</div>
<h1>www.theredhead.nl :: Test Template</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br />
<red:UserProfileLink runat="server" Username="kris" />
</div>
</body>
</html>
</code></pre>
<p>At current, this outputs (including the broken indentation):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Welcome to my site</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Custom/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Profile/"/>
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo"/>
</div>
<h1>www.theredhead.nl :: ModelViewController</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br/>
<div><div xmlns:profile="http://www.theredhead.nl/profile" class="ProfileBadge" style="font-size : .8em;">
<a style="text-decoration : none; border: none;" href="/Profile/View/kris">
<img style="float : left;" src="http://www.gravatar.com/avatar/5beeab66d6fe021cbd4daa041330cc86?d=identicon&amp;s=32&amp;r=pg" alt="Gravatar"/>
&#xA0;Kris
</a>
<br/>
<small>
&#xA0;Rep:&#xA0;1
</small>
</div></div>
</div>
</body>
</html>
</code></pre>
<ul>
<li>I've only touched on the tip of the iceberg here and yes, I will be stripping unused xmlns attributes from the output once I'm happy with the functionality</li>
<li>there are currently just over 200 classes in my mvc and core frameworks</li>
<li>I am aware there are existing solutions that can do similar things, but I want to build my own.</li>
</ul>
<p>So the big question is: <strong>Do you have any input on must-have functionality?</strong></p>
<p>P.S. if anyone is interested in the complete source-code, please leave a comment, I will be providing it on my site when I reach reasonable developer usability levels.</p>
|
<p>Why not just use PHP as your templating system. PHP <em>IS</em> the template system.</p>
<p>What is wrong with just dumping <code><?php=$variable;?></code> in an HTML template? You can use foreach loops, etc.
Just make sure that you run it from within a scope that cannot access any variables you do not want.</p>
<p>I have a really deep founded hate for overcomplicated template systems like this since my Java/Struts nightmares. You have to dive into namespaces, xpath, custom namespaces and all that stuff before you can change just the one thing you need. </p>
|
<p>Here's an article on templating engines: <a href="http://massassi.com/php/articles/template_engines/" rel="nofollow noreferrer">http://massassi.com/php/articles/template_engines/</a></p>
<p>You're doing it wrong.</p>
| 23,850
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/61320/svn-plugins-for-eclipse-subclipse-vs-subversive">SVN plugins for Eclipse - Subclipse vs. Subversive</a> </p>
</blockquote>
<p>I've been using Subclipse (an SVN plugin for Eclipse), for quite a while, but have become increasingly unhappy with it. I notice that Tortoise SVN is available as an Eclipse plugin and am considering using that instead within Eclipse (I already use it when accessing SVN outside Eclipse).</p>
<p>Before I make the switch, does anyone have any experience with using the Tortoise SVN Eclipse plugin, or are there any other Eclipse SVN plugins (other than Subclipse) that are recommended?</p>
|
<p><a href="https://stackoverflow.com/questions/61320/svn-plugins-for-eclipse-subclipse-vs-subversive#61328"><strong>SVN plugins for Eclipse - Subclipse vs. Subversive</strong></a></p>
|
<p>I use tortiseSVN and have had nothing but a positive experience. </p>
| 24,082
|
<p>I need to find a good Lua to JavaScript converter; lua2js on luaforge.org is out of date (3 or so years old and looks like it doesn't work on Lua 5.1) and I haven't yet found anything on Google.</p>
<p>Does anyone have any experience with any other converters out there? It should work on Lua 5.1 and preferably be .NET based, but .NET is not a requirement. A javascript lua interpreter would work as well.</p>
|
<p>This is a recurrent question on the Lua list, i guess because of the superficial similarity of the two languages.</p>
<p>Unfortunately, there are many important differences that are not so obvious. Making it work need either a full-blown compiler targeting JS instead of Lua's bytecode, or rewriting the Lua VM in JavaScript.</p>
<p>I don't know the original goals of Lua2js; but if it was simply a limited 'translator', then writing Lua code intended to be translated would deny most (all?) of the nice things about Lua. For instance, i don't think you could use a function as a table key, since in JavaScript the keys are only strings (and numbers? i'm not sure).</p>
<p>The .NET choice is more reasonable, it could be done changing the existing compiler to emit CLR bytecode instead of standard Lua bytecode. Even if CLR is designed and optimised for other kind of languages, it's definitely generic enough to run very well. The main hurdle would be the availability of libraries.</p>
<p>Another option I just found is <a href="http://www.lua.inf.puc-rio.br/luanet/lua2il_jucs.pdf" rel="noreferrer">this paper</a> by Roberto Ierusalmschy and Fabio Mascarenhas, where they explore translating LuaVM bytecode into CLR bytecode.</p>
<p>As is usual on academic papers, there's no indication about the date when it was written, so i have no idea if it's new and revolutionary or old and forgotten.</p>
|
<p>Translation to javascript is interesting to allow for a javascript replacement on the browser-side. We could take a little type safety on the browser too. Targeting javascript as a platform is targeting one of the most pervasive platform, the browsers of the planet. GWT does java2js but I am not sure if I want to introduce GWT for only a few pages in an application. I have to think about it. For your function as a key in a table, there must be some magic to be done. Maybe just assign a unique name to each function at compilation and use that for your key. You can also add a prefix to all your keys for type checking and that is a nice start. </p>
| 21,229
|
<p>This only happens with IE (all versions), on line 1120 in
jquery-1.2.6.js I get the following error:</p>
<pre><code>Line 1120:
Invalid Property Value
</code></pre>
<p>The line in the js file is the following:</p>
<pre><code>elem[name] = value;
</code></pre>
<p>It is inside attr: <code>function( elem, name, value )</code></p>
<p>Does anybody have a problem similar to this? </p>
|
<p>If <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/3ef3a830916b2fbb" rel="nofollow noreferrer">this</a> is also you, it sounds like you're trying to change the CSS of the element rather than give it an attribute.</p>
<p>If that is the case then try this instead;</p>
<pre><code>jQuery.css('color', 'inherit');
</code></pre>
|
<p>This error can also occur if you call jQuery.css with an invalid attribute value, such as: </p>
<pre><code>$('div.foo').css('padding-left', 'NaNpx');
</code></pre>
| 41,595
|
<p>I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients. </p>
<p>The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:</p>
<blockquote>
<p>The process cannot access the file because it is being used by another process.</p>
</blockquote>
<p>The solutions that I have tried to implement in C# and failed are as below.</p>
<ol>
<li>Implemented singleton class that contains code that writes to a file.</li>
<li>Used lock statement to wrap the code that writes to the file. </li>
<li>I have also tried to use open source logger log4net but it also is not a perfect solution. </li>
<li>I know about logging to system event logger, but I do not have that choice.</li>
</ol>
<p>I want to know if there exists a perfect and complete solution to such a problem? </p>
|
<p>The locking is probably failing because your webservice is being run by more than one worker process.
You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using <code>lock(someobject) {...}</code>:</p>
<pre><code>Mutex lock = new Mutex("mymutex", false);
lock.WaitOne();
// access file
lock.ReleaseMutex();
</code></pre>
|
<p>Maybe write a "queue line" of sorts for writing to the file, so when you try to write to the file it keeps checking to see if the file is locked, if it is - it keeps waiting, if it isn't locked - then write to it.</p>
| 14,536
|
<p>I've seen (and used) on various projects this layout, with a group of fields followed by a group of properties:</p>
<pre><code>private int MyIntField;
private string MyStringField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
</code></pre>
<p>And I've also encountered this layout with fields next to their property:</p>
<pre><code>private int MyIntField;
public int MyInt {
get { return MyIntField; }
set { MyIntField = value; }
}
private string MyStringField;
public string MyString {
get { return MyStringField; }
set { MyStringField = value; }
}
</code></pre>
<p>Is there a reason to consider one better than the other? I think most coding standards recommend Option #1, but sometimes it's handy having the field next to the property that operates on it.</p>
<p><em>Note: I'm assuming non-trivial properties that can't use auto-implemented properties.</em></p>
|
<p>I think it is whatever the team feels comfortable with. Settle on a standard for the project/company/language and stick to it. I prefer the private variables all together, the methods/interfaces together, the private members....I think you get the point.</p>
|
<p>To reiterate what Kenny said above, it's really all about the coding standards of your organization. It's hard to objectively classify one style over the other, although everyone seems to have their own opinion.</p>
<p>I generally tend to prefer having data and methods groups by access modifier, and so in this case would prefer Option #1. This is to emphasize the interface, not the design. That is, I could transparently change the implementation of the MyInt modifier in the future (maybe I don't really need to store a backing variable).</p>
| 34,616
|
<p>I began build LCD printer and I want make some modifications.</p>
<p>What if I will place LCD below VAT<a href="https://i.stack.imgur.com/Tznt5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tznt5.jpg" alt="enter image description here"></a>? Will the display break when printing? what are the risks?
I seen a lot of printers and all of them use PP material for VAT bottom and attach with a lot of screws. I want make more simple VAT-LCD constructions and I think this construction transmis UV light better</p>
|
<p>Your calculations about the theoretical extruder resolution are spot on. I did a similar calculation to evaluate which extruder to use with different hot ends, I paste the results. The dark cells are the input cells, the rest is calculated. You can see that for some lines I entered directly the mm/microstep value, since I wanted not a theoretical but practical result for my printer (3 mm filament) or for known extruders (BMG).</p>
<p><a href="https://i.stack.imgur.com/3mQeA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3mQeA.png" alt="enter image description here" /></a></p>
<p>Concerning the question, the resolution of the extruder matters, but it's a bit complicated to estimate exactly how much.</p>
<p>In general, this are the factors I can think about.</p>
<p>A poor resolution may not impact straight lines much, since the rotation of the extruder is continuous and the extruder is unlikely to snap exactly to the desired microstep position as soon as you ask for it: it's likely a bit behind all the time, that's how torque is obtained (more or less).</p>
<p>The issue may become smaller with drivers which interpolate microsteps up to 256x.</p>
<p>However, whenever there is a change of flow rate, poor resolution implies that you cannot control the exact location/moment where/when the flow changes. This matters mostly at the end and at the beginning or retractions/re-retractions. Maybe you get more ooze?</p>
<p>However, the extruder resolution is not, in practice, as good as you calculated. In fact, as we know, microsteps reduce the incremental torque to very low values. The extruder is a motor which requires quite a lot of torque, since pushing the filament is quite hard, and it is unlikely that you can achieve all the time the 16x microstep accuracy you assumed. For example, due to friction in Bowden, hot end, ... the filament (= the motor shaft) may at a certain point stay "back" more than average. This would cause an increase of effective torque, pushing the filament a bit faster, which would it bring to in sync or so with the desired position, but at that point it would slow down, and so on. Depending on the average speed, this oscillation may be dampened (and then no rippling is visible) or may oscillate constantly, and you see ripples also along straight lines.</p>
<p>This is why I placed the usteps column in my calculations: it is meant to calculate a more realistic resolution assuming that no accurate microstepping is achieved. I assumed higher achievable microsteps the lower the load on the motor is (this means gears, or thinner filament).</p>
<p>Having a high resolution to begin with clearly helps to reduce this issue. You can try to increase the current to the max your drivers and motor and cooling allow, and see if the ripples change. I think it will be reduced.</p>
<p>You may also try to build the <a href="https://www.thingiverse.com/thing:4223085" rel="noreferrer">Orbiter extruder</a> (linked also in the table) and see how it goes.</p>
|
<h2>Short answer</h2>
<p><em>Usually</em> no.</p>
<h2>Long answer</h2>
<p>There are several big factors that limit how small things you can print. The bigger ones are pretty much:</p>
<ul>
<li>Positional accuracy and settings (limited by steps/mm in X, Y, Z)</li>
<li>Nozzle diameter</li>
</ul>
<p>Now, why don't you need to care about steps/mm on the extruder that muchin the grand scale compared to the positional accuracy? Well, we have 1.8° per step, from which, with the diameter of the gear, 11mm, we get 0,1778 mm of filament extrusion or 0.428 mm³ of extruded plastic per full 1.8° step - which clearly is unsuitable to printing at all. But with the 16 micro-steps the shorter movements are possible and a single micro-step extrusion is in the area you calculated - I got to 0,0267 mm³, possibly the result of different rounding between us. With an assumed effective gear diameter of 11mm (usually the effective gear diameter is a little smaller, thus the 93 steps) we come to about 89.9 steps per mm of filament, which corresponds to about 2.4 mm³ of extruded plastic, or about 30 mm of line (with your given parameters), bringing us to about 3 microsteps per millimeter of line on the tray. So far, your math checks out. But that usually shouldn't be too much a limiting factor. We know from your given settings, that the <em>Configuration.h</em> will look like this, putting the microsteps into the steps/mm:</p>
<pre><code>/**
* Default Axis Steps Per Unit (steps/mm)
* Override with M92
* X, Y, Z, E0 [, E1[, E2[, E3[, E4]]]]
*/
#define DEFAULT_AXIS_STEPS_PER_UNIT { 80, 80, 400, 93 }
</code></pre>
<p>As you don't have a micro-stepping driver, this part in <em>Configuration_adv.h</em> is non-functional:</p>
<pre><code>// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU.
#define MICROSTEP_MODES {16,16,16,16,16} // [1,2,4,8,16]
</code></pre>
<p>With the proposed 0.4 mm/0.2 mm line, we are still somewhat on the good side, allowing us about 1/3rd of a millimeter as the shortest line printable as a single step extrusion. That's a consistent with printing a simple, circular dot being printable with these settings - 0.4 > 1/3.</p>
<p>But once you get to smaller nozzle diameters, the limitation gets more noticeable: at a 0.2 mm nozzle and 0.22 mm line at 0.1 mm height, that's a 0.022 mm² crosssection, so the 1-step extrusion is equivalent to a full millimeter of line! That's much more bothersome in theory.</p>
<p>However, I haven't been able to witness the inability of showing that limit of lacking extrusion yet on my TronXY-X1 with a 0.2 mm nozzle - the steps/mm in it are also about 90-100 last I set them. The TronXY uses a very similar (virtually identical) extruder setup as the Ender 3, and it achieved printed lines of about 0.3 mm length at 0.1 mm layer height somewhat reliable, but the retraction made huge issues, which might also mask the problem.</p>
<p>I believe that it needs these smaller nozzles to amplify the problems to make them noticeable. It also should become more noticeable if you'd use 2.85 mm or 3 mm filament.</p>
<h2>Ways to improve resolution</h2>
<p>However, if printing with smaller nozzles, it might be a good idea to think about how one could improve the accuracy of the extruder system.</p>
<p>The most-easy way would be to alter the extruder and swap the gear to one of a <em>smaller</em> effective diameter - That way a single step accounts to <em>less</em> extrusion, which means, in turn, a higher number of steps/mm, and thus allowing for shorter extrusions that can be still achieved.</p>
<p>Next one might think about getting a different motor/driver setup that might have either more microsteps or generally a smaller step size.</p>
<p>Quadrupling the effective (micros)steps/mm would allow us to print about a 0.25 mm line on the 0.22 mm nozzle I proposed, being pretty much a spot - if it wouldn't be partially masked in other issues as I experience.</p>
| 1,603
|
<p>I have made some prints with the Ultimaker 2+ and Ultimaker 2 Extended+. The prints are in PLA. For slicing, I use Cura and I check the support checkbox (haven't gone to advanced settings to adjust support yet). I can clearly see that there is a little space between the support and the print. The supports often look like long pillars and such. </p>
<p>My question then is: "What is the best technique for removing the support?". Is it to use a knife, pliers or perhaps PLA-water? Is it possible to use PLA-water to remove support when printed with Ulitmaker 2+ or is that just the Ultimaker 3? What type of technique would give a good looking print?</p>
<p>Ultimaker 3 has <a href="https://ultimaker.com/materials/pva" rel="nofollow noreferrer">support filament that's water-soluble</a>. Is there something similar for Ultimaker 2+? </p>
|
<p>The Ultimaker 2+ is a single extruder 3D printer. Without changing the PLA spool and PVA spool continuously during the print you practically cannot make water soluble supports on the Ultimaker 2+ which can be done on the Ultimaker 3. Note that PVA (from experience) is strange material to print, the filament is very hygroscopic and will form bubbles during printing when moist. Also, PVA is prone to clog the nozzle (it cooks easily) it therefore has its own printer core (nozzle assembly) on the Ultimaker 3 (still it clogs easily). Furthermore, it takes a while to dissolve in water.</p>
<p>If you have a single extruder and nozzle, your best option is to use the same material for support, but modify the support settings as such that it can be easily removed. E.g. on thin layer heights (0.1 mm) I usually increase the gap between support and product over the default value, see <a href="https://3dprinting.stackexchange.com/a/7991">this answer</a>.</p>
<p>On dual extruder printers, e.g. on the Ultimaker 3 and S5, my colleagues have better experience using <a href="https://ultimaker.com/en/products/materials/breakaway" rel="nofollow noreferrer">Ultimaker Breakaway</a> filament rather than using PVA. As with the PLA supports, you need to "break them away" from the actual product; I use a Leatherman Charge or FREE P4 as these tools have fine pointed pliers. Note that there are removal tools available that are best described as soldering irons that can aid in the removal of support structures:</p>
<p><a href="https://i.stack.imgur.com/81q27.png" rel="nofollow noreferrer" title="Modifi3d support removal tool"><img src="https://i.stack.imgur.com/81q27.png" alt="Modifi3d support removal tool" title="Modifi3d support removal tool"></a></p>
<p>Note that I have mixed feelings about this product; it is hard to neatly remove supports using these small soldering irons, but it sometimes works.</p>
|
<p>PLA and ABS are hard plastics. They are not water-soluble. If you print with these materials, just snap printed support materials off and clean the interface layer with a knife and sanding.</p>
<p>To remove the support, it is best to use strong tweezers or a pair of pliers to grip and then apply some force. Generally, I use needle pliers, but occasionally I also use snippets to cut up the support towers into more manageable chunks and keep the printed part safer. It can help to remove it in pieces and score the breaking lines.</p>
<p>As PLA is brittle, I prefer to break away from the object and not pull.</p>
| 1,491
|
<p>Do you guys keep track of stored procedures and database schema in your source control system of choice?</p>
<p>When you make a change (add a table, update an stored proc, how do you get the changes into source control? </p>
<p>We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools.</p>
<p><em>Edit:</em> Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!</p>
|
<p>We choose to script everything, and that includes all stored procedures and schema changes. No wysiwyg tools, and no fancy 'sync' programs are necessary.</p>
<p>Schema changes are easy, all you need to do is create and maintain a single file for that version, including all schema and data changes. This becomes your conversion script from version x to x+1. You can then run it against a production backup and integrate that into your 'daily build' to verify that it works without errors. Note it's important not to change or delete already written schema / data loading sql as you can end up breaking any sql written later.</p>
<pre><code>-- change #1234
ALTER TABLE asdf ADD COLUMN MyNewID INT
GO
-- change #5678
ALTER TABLE asdf DROP COLUMN SomeOtherID
GO
</code></pre>
<p>For stored procedures, we elect for a single file per sproc, and it uses the drop/create form. All stored procedures are recreated at deployment. The downside is that if a change was done outside source control, the change is lost. At the same time, that's true for any code, but your DBA'a need to be aware of this. This really stops people outside the team mucking with your stored procedures, as their changes are lost in an upgrade. </p>
<p>Using Sql Server, the syntax looks like this:</p>
<pre><code>if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_MyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [usp_MyProc]
GO
CREATE PROCEDURE [usp_MyProc]
(
@UserID INT
)
AS
SET NOCOUNT ON
-- stored procedure logic.
SET NOCOUNT OFF
GO
</code></pre>
<p>The only thing left to do is write a utility program that collates all the individual files and creates a new file with the entire set of updates (as a single script). Do this by first adding the schema changes then recursing the directory structure and including all the stored procedure files.</p>
<p>As an upside to scripting everything, you'll become much better at reading and writing SQL. You can also make this entire process more elaborate, but this is the basic format of how to source-control all sql without any special software.</p>
<p>addendum: Rick is correct that you will lose permissions on stored procedures with DROP/CREATE, so you may need to write another script will re-enable specific permissions. This permission script would be the last to run. Our experience found more issues with ALTER verses DROP/CREATE semantics. YMMV</p>
|
<p>If you're looking for an easy, ready-made solution, our <a href="http://tessik.com/sqlhistorian" rel="nofollow">Sql Historian</a> system uses a background process to automatically synchronizes DDL changes to TFS or SVN, transparent to anyone making changes on the database. In my experience, the big problem is maintaining the code in source control with what was changed on your server--and that's because usually you have to rely on people (developers, even!) to change their workflow and remember to check in their changes after they've already made it on the server. Putting that burden on a machine makes everyone's life easier. </p>
| 10,276
|
<p>I need to edit (using javascript) an SVG document embedded in an html page.</p>
<p>When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.</p>
<p>To access the SVG dom, I use this code:</p>
<pre><code>var svg = document.getElementById("chart").getSVGDocument();
</code></pre>
<p>where "chart" is the id of the embed element.</p>
<p>If I try to access the SVG when the html document is ready, in this way:</p>
<pre><code>jQuery(document).ready( function() {
var svg = document.getElementById("chart").getSVGDocument();
...
</code></pre>
<p>svg is always null. I just need to know when it is not null, so I can start manipulate it.
Do you know if there is a way to do it?</p>
|
<p>On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an <code>onload</code> attribute which calls your function, or add the event listener in script, e.g <code>embeddingElm.addEventListener('load', callbackFunction, false)</code>. Another option might be to listen for <code>DOMContentLoaded</code>, depends on what you want it for.</p>
<p>You can also add a load listener on the main document. <code>jQuery(document).ready</code> doesn't mean that all resources are loaded, just that the document itself has a DOM that is ready for action. However note that if you listen for load on the entire document your callback function won't be called until all resources in that document are loaded, css, javascript etc.</p>
<p>If you use inline svg, then <code>jQuery(document).ready</code> will work just fine however.</p>
<p>On a further note you might want to consider using <code>embeddingElm.contentDocument</code> (if available) instead of <code>embeddingElm.getSVGDocument()</code>.</p>
|
<p>You can assign an onload event handler to an element within your SVG document and have it call a javascript function in the html page. onload maps to SVGLoad.</p>
<p><a href="http://www.w3.org/TR/SVG11/interact.html#LoadEvent" rel="nofollow noreferrer">http://www.w3.org/TR/SVG11/interact.html#LoadEvent</a></p>
<blockquote>
<p>The event is triggered at the point at which the user agent has fully parsed the element and its descendants and is ready to act appropriately upon that element</p>
</blockquote>
| 43,763
|
<p>Brand new to Slic3r, I've been using Cura for a while, so not sure is happening. I tried to load <a href="https://www.shapeways.com/product/YDCPJF8KV/knight" rel="nofollow noreferrer">this Knight model</a> into Slic3er (v1.2.9 running on OS X), and it's reporting "Manifold: auto-repaired (11430 errors)", and the model looks incomplete. Hovering the model with the mouse shows more details:</p>
<p><a href="https://i.stack.imgur.com/hb2DY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hb2DY.png" alt="Slic3r Screenshot"></a></p>
<p>Preview mode shows supports holding up the head, so I don't think it's just a screen rendering issue. But I loaded this same model into Cura earlier today, and it worked just fine; I've printed the resulting GCode. So I believe the model is fine. I wanted to print using Slic3r and compare the results. </p>
<p>Is this a known issue with certain types of models? Not sure what to try next.</p>
|
<p>Dimensional accuracy is not as important as dimensional uniformity. I can print with undersized (or oversized) filament, adjusting the flow appropriately, provided the filament has a consistent diameter. When creating filament in-house, without expensive equipment, it is difficult to maintain the same diameter throughout the entire extrusion. It is likely this extrusion diameter (when creating filament, rather than the output of the actual print head) to which Barafu is referring when he mentions his tolerances: +/- 0.05 mm <em>in diameter</em>. Which is reasonable.</p>
<p>The "miniature printing" comment likely refers to printing miniature models for tabletop gaming.</p>
<p>If the source filament becomes wider than expected, the output will have overflow, or more material than desired will be deposited, and this will certainly affect the quality of the piece.</p>
|
<p>Put it simply: they say 1.75 mm with a ± error of 0.05 mm. Which means your flow may vary ±2.9 % while you are printing creating blobs and such. </p>
<p>The smaller the filament tolerance, the more expensive the production costs.</p>
| 501
|
<p>Will learning C++ help me build native applications with good speed? Will it help me as a programmer, and what are the other benefits?</p>
<p>The reason why I want to learn C++ is because I'm disappointed with the UI performances of applications built on top of JVM and .NET. They feel slow, and start slow too. Of course, a really bad programmer can create a slower and sluggish application using C++ too, but I'm not considering that case.</p>
<p>One of my favorite Windows utility application is <a href="http://launchy.net/" rel="noreferrer">Launchy</a>. And in the Readme.pdf file, the author of the program wrote this:</p>
<blockquote>
<p>0.6 This is the first C++ release. As I became frustrated with C#’s large
.NET framework requirements and users
lack of desire to install it, I
decided to switch back to the faster
language.</p>
</blockquote>
<p>I totally agree with the author of Launchy about the .NET framework requirement or even a JRE requirement for desktop applications. Let alone the specific version of them. And some of the best and my favorite desktop applications don't need .NET or Java to run. They just run after installing. Are they mostly built using C++? Is C++ the only option for good and fast GUI based applications?</p>
<p>And, I'm also very interested in hearing the other benefits of learning C++.</p>
|
<p>If you want to build Windows applications that will run without frameworks such as .NET or virtual machines/interpreters, then your only really viable choices are going to be Visual Basic or C/C++</p>
<p>I've written some small Windows apps before in C++ code, and there is definitely a benefit in terms of speed and ease of deployment, at the expense of difficulty going up for development. C++ can be very fast, natively compiles, has many modern language features, and wide support. The trade off is that it's likely that you'll need to write more code in certain situations, or seek out libraries like <a href="http://www.boost.org/" rel="nofollow noreferrer">Boost</a> that provide the functionality you're after.</p>
<p>As a programmer, working in C++ and especially in C is good experience for helping you understand something just a tad closer to the machine than say, .NET, Java or a scripting language like VBScript, Python, Perl etc. It won't necessarily make you a better programmer, but if you are open to learning new lessons from it you may find that it helps you gain a new perspective on software. After all, most of the frameworks and systems you depend on are written in pure C, so it will never hurt you to understand the foundations. C++ is a different animal from straight C, but if you develop in C++ for Windows you'll likely find yourself working in a mix of C and C++ to work with Windows APIs, so it will have a trickle-down effect.</p>
|
<p>C++ will indeed potentially get you a leaner, meaner and faster application (if you do it right). </p>
<p>However, the .NET framework is built for comfort from a developer point of view; a vast improvement over Win32 API or MFC, which may seem like hard work in comparison, So consider how you will implement the aspects for which your application depends on .NET (there are other frameworks available that may be easier than MFC or Win32 API), and also consider the costs and license issues of using such frameworks; for example the free VC++ Express Edition for example does not include MFC support.</p>
<p>If you know where you application is sluggish, C++/CLI may be a solution; allowing you to mix managed and native code to accelerate the parts that need it. However if it is the GUI that is intrinsically slow rather than the application processing; this may not be a useful path.</p>
| 20,322
|
<p>You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.</p>
<p>So an example Perl problem:</p>
<p>A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.</p>
<p>The question, for Perl developers: What is your best way to accomplish this?</p>
|
<p>This sounds like a job for <a href="http://search.cpan.org/perldoc?File::Find::Rule" rel="nofollow noreferrer">File::Find::Rule</a>:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use autodie; # Causes built-ins like open to succeed or die.
# You can 'use Fatal qw(open)' if autodie is not installed.
use File::Find::Rule;
use Getopt::Std;
use constant SECONDS_IN_DAY => 24 * 60 * 60;
our %option = (
m => 1, # -m switch: days ago modified, defaults to 1
o => undef, # -o switch: output file, defaults to STDOUT
);
getopts('m:o:', \%option);
# If we haven't been given directories to search, default to the
# current working directory.
if (not @ARGV) {
@ARGV = ( '.' );
}
print STDERR "Finding files changed in the last $option{m} day(s)\n";
# Convert our time in days into a timestamp in seconds from the epoch.
my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};
# Now find all the regular files, which have been modified in the last
# $option{m} days, looking in all the locations specified in
# @ARGV (our remaining command line arguments).
my @files = File::Find::Rule->file()
->mtime(">= $last_modified_timestamp")
->in(@ARGV);
# $out_fh will store the filehandle where we send the file list.
# It defaults to STDOUT.
my $out_fh = \*STDOUT;
if ($option{o}) {
open($out_fh, '>', $option{o});
}
# Print our results.
print {$out_fh} join("\n", @files), "\n";
</code></pre>
|
<p>I write a subroutine that reads a directory with <code>readdir</code>, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use <code>utime</code> or <code>stat</code>). By time the recursion is done, every file should have been examined.</p>
<p>I think all the functions you'd need for this script are described briefly here:
<a href="http://www.cs.cf.ac.uk/Dave/PERL/node70.html" rel="nofollow noreferrer">http://www.cs.cf.ac.uk/Dave/PERL/node70.html</a></p>
<p>The semantics of input and output are a fairly trivial exercise which I'll leave to you.</p>
| 19,548
|
<p>For example, if I have a network spec like 172.20.10.0/24, "24" is the bitcount. What's the best way to convert that to a netmask like 0xffffff00 ?</p>
|
<p>Assuming 32-bit mask and 32-bit int.</p>
<pre><code>int keepBits = 24; /* actually get it from somewhere else? */
int mask = (0xffffffff >> (32 - keepBits )) << (32 - keepBits);
</code></pre>
<p>Note: this isn't necessarily the answer to the question "What's the best way to get the network mask for an interface?"</p>
|
<p>You could try something simple, like taking the bitcount and dividing by 4. That'd give you the leading F's in the mask. And then take the remainder and have a switch from 0 bits to 3 bits.</p>
| 26,896
|
<p>I'd like to print a cylinder, 50 mm diameter, 200 mm long, with 1.5 mm diameter holes tightly fit like this:</p>
<p><a href="https://i.stack.imgur.com/i11dN.png" rel="nofollow noreferrer" title="3D rendering of a cylinder with holes"><img src="https://i.stack.imgur.com/i11dN.png" alt="3D rendering of a cylinder with holes" title="3D rendering of a cylinder with holes" /></a></p>
<p>The holes go all the way through from top to bottom.</p>
<p>I am using a Prusa i3 MK3S. With 0.1 mm detail and 20 % infill, printing one cylinder is going to take 5 days and 5 hours. I need at least five cylinders.</p>
<ul>
<li>Is the above setting appropriate for this job?</li>
<li>Is there any way I can reduce the printing time?</li>
</ul>
|
<h1>That's a hell of a print!</h1>
<p>You are printing a model that has a highly complex structure there, with about 650ish holes, assuming there is space for about 2 perimeters between each hole.</p>
<p><a href="https://i.stack.imgur.com/gcrSm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gcrSm.png" alt="imitated design of a cylinder with ca 650 thin holes" /></a></p>
<p>Taking my standard 0.3 mm layer height and 0.4 mm nozzle using a 0.45 mm wide line, I sliced a 10mm high slice of the model for a first estimate of the expected print time - and came out with 2:21 hours. That means the expected print time with 0.3 mm layer height is in the area of 47 hours - or just about 2 days.</p>
<p>As a result, 5 days and 5 hours are in the order I'd expect from a 0.1 mm layer height print for the same nozzle, in fact, your settings seem to have a faster print speed than I do work with.</p>
<p>In general, don't think this model is good for FDM Printing at all, due to many non-fully formed lines inside the model (yellow) and the red perimeters being a very dense pattern.</p>
<p><a href="https://i.stack.imgur.com/l0oH6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l0oH6.png" alt="Sliced crossection: in yellow: many extra thin lines!" /></a></p>
<h2>Solutions?</h2>
<h3>print faster</h3>
<p>You might get a faster speed with a high flow solution, for example, using a long melt zone (volcano-style) or an even higher flow core-heating 3DSolex nozzle. The latter originally only comes in 0.6 mm and up, also mandating fewer holes, but in late 2021 CHT Nozles in 0.4 mm came to the market. This could drop print time some, but it'd still be a several days print job.</p>
<h3>reduced pattern</h3>
<p>Besides increasing layer height to drop printing time by the same factor, reducing the number of holes and as a result, spacing them further apart not only can increase the print speed but also make the print form more reliable.</p>
<p>Another alternative would be to alter the pattern from a circle to a hexagonal pattern: by using hexagons, the resulting pattern does not contain thin walls and might print much faster - depending on hole size, you might experience a drop by a factor of 2!</p>
<p><a href="https://i.stack.imgur.com/Bk583.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bk583.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/Jjr3P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jjr3P.png" alt="enter image description here" /></a></p>
<h3>Printed differently</h3>
<p>Going from FDM printing to a system such as SLS might be faster and more reliable while SLA/DLP would make this print not only fast and reliable but also trivial - if one can get a 200 mm high SLA/DLP printer, all three models should be able to be printed in one go at the same time!</p>
|
<p>Holes, circles, and curves are slow to print, and get slower as the number of wall segments increase.</p>
<p>Ideally you'd use square holes, but hexagonal-sided ones would be a fair compromise too.</p>
<p>Your slicer should be able to give a breakdown on the times for each kind of line in the part. Check and see how much of the time is spent on "moves".</p>
<p>Is there a reason for using all these little holes? Fewer, larger holes will provide better airflow and require less printing, up to the ultimate of one single large hole, where you're essentially printing a pipe/tube.</p>
<p>Do you need the holes to go right-through? Printing a big "cup" with holes across the floor, and separately a "lid" then gluing them together would be quicker and you have one large hole in the middle. If this idea works, you might prefer to just buy plastic pipe of a suitable size, and print only endcaps.</p>
<p>Additionally, if you're printing 5 cylinders because you need a metre total length, then printing two endcaps for a 1 metre piece of plastic PVC pipe should take a couple of hours at most. And it will save you a lot of filament.</p>
| 2,077
|
<p>Why is it that they decided to make <code>String</code> immutable in Java and .NET (and some other languages)? Why didn't they make it mutable?</p>
|
<p>According to <a href="http://www.oracle.com/technetwork/java/effectivejava-136174.html" rel="noreferrer">Effective Java</a>, chapter 4, page 73, 2nd edition:</p>
<blockquote>
<p>"There are many good reasons for this: Immutable classes are easier to
design, implement, and use than mutable classes. They are less prone
to error and are more secure.</p>
<p>[...]</p>
<p>"<strong>Immutable objects are simple.</strong> An immutable object can be in
exactly one state, the state in which it was created. If you make sure
that all constructors establish class invariants, then it is
guaranteed that these invariants will remain true for all time, with
no effort on your part.</p>
<p>[...]</p>
<p><strong>Immutable objects are inherently thread-safe; they require no synchronization.</strong> They cannot be corrupted by multiple threads
accessing them concurrently. This is far and away the easiest approach
to achieving thread safety. In fact, no thread can ever observe any
effect of another thread on an immutable object. Therefore,
<strong>immutable objects can be shared freely</strong></p>
<p>[...]</p>
</blockquote>
<p>Other small points from the same chapter:</p>
<blockquote>
<p>Not only can you share immutable objects, but you can share their internals.</p>
<p>[...]</p>
<p>Immutable objects make great building blocks for other objects, whether mutable or immutable.</p>
<p>[...]</p>
<p>The only real disadvantage of immutable classes is that they require a separate object for each distinct value.</p>
</blockquote>
|
<p>It's largely for security reasons. It's much harder to secure a system if you can't trust that your <code>String</code>s are tamperproof.</p>
| 11,858
|
<p>When you're using Tiles with Struts and do...</p>
<pre><code>request.getRequestURL()
</code></pre>
<p>...you get the URL to e.g. <code>/WEB-INF/jsp/layout/newLayout.jsp</code> instead of the real URL that was entered/clicked by the user, something like <code>/context/action.do</code>.</p>
<p>In newer Struts versions, 1.3.x and after, you can use the <a href="http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=58&t=012300" rel="nofollow noreferrer">solution mentioned on javaranch</a> and get the real URL using the request attribute <a href="http://struts.apache.org/1.x/apidocs/org/apache/struts/Globals.html#ORIGINAL_URI_KEY" rel="nofollow noreferrer"><code>ORIGINAL_URI_KEY</code></a>.</p>
<p>But how to do this in Struts 1.2.x?</p>
|
<p>I use this, which also works on Spring:</p>
<pre><code><% out.println(request.getAttribute("javax.servlet.forward.request_uri")); %>
</code></pre>
<p>If you also need the query string (contributed by <a href="https://stackoverflow.com/users/638649/matchew">matchew</a>):</p>
<pre><code><% out.println(request.getAttribute("javax.servlet.forward.query_string")); %>
</code></pre>
|
<p>You just need to do this in your action:</p>
<pre><code> request.getAttribute("javax.servlet.forward.request_uri")
</code></pre>
| 16,018
|
<p>I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as </p>
<blockquote>
<p>[A-Za-z]</p>
</blockquote>
<p>would lock down to just Alpha characters. </p>
<pre><code>protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
base.OnKeyPress(e);
return;
}
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
base.OnKeyPress(e);
}
else
{
bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
if (isValidChar)
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
}
</code></pre>
<p>I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.</p>
<p>As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.</p>
<p>What is the best way to handle this situation?</p>
|
<p>What if you put the validation in OnTextChanged instead of OnKeyPress, but each time it passes validation you save the value to a variable? Then you can revert if the user pastes or types an incorrect string, as well as give some other UI hint that something was invalid (e.g. set a Label's text).</p>
|
<p>The solution that I have come up with is to check the keys in the OnKeyDown event and then setting a flag if the keypress should be handled, which is then check in the OnKeyPress event.</p>
<pre><code>protected override void OnKeyDown(KeyEventArgs e)
{
Keys keyCode = (Keys)e.KeyValue;
base.OnKeyDown(e);
if ((e.Modifiers == Keys.Control) ||
(e.Modifiers == Keys.Control) ||
(keyCode == Keys.Back) ||
(keyCode == Keys.Delete))
{
this._handleKey = true;
}
else
{
// check if the key is valid and set the flag
this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (this._handleKey)
{
base.OnKeyPress(e);
this._handleKey = false;
}
else
{
e.Handled = true;
}
}
</code></pre>
| 31,471
|
<p>I've a web service running on server which return data either in XML format or JSON format.
I wanted to request a JSON format but using HTTP Post method.</p>
|
<p>This is the code which work for JSON post request,
TouchJSON Framework is used for parsing the JSON, thanks 'schwa'.</p>
<pre><code>NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil];
NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil];
NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
NSLog(@"%@", theBodyString);
NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
// NSLog(@"%@", theBodyData);
[theRequest setHTTPBody:theBodyData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(theResponseString);
NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];
NSLog(@"%@", theResponseDictionary);
NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"];
[self setValue:theGreeting forKey:@"greeting"];
</code></pre>
|
<p>Sorry for errors and memory leaks, but how about something like:</p>
<pre><code>CFURLRef url = CFURLCreateWithString(NULL, CFSTR("http://example.com/post"), NULL);
CFHTTPMessageRef msg = CFHTTPMessageCreateRequest(
NULL,
CFSTR("POST"),
url,
kCFHTTPVersion1_1);
const char *body = "key=value&id=30293";
CFDataRef bodyData = CFDataCreate(NULL, body, strlen(body));
CFHTTPMessageSetBody(msg, bodyData);
CFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(NULL, myRequest);
CFReadStreamOpen(myReadStream);
CFHTTPMessageRef myResponse = CFReadStreamCopyProperty(
myReadStream,
kCFStreamPropertyHTTPResponseHeader);
//
// Handle myResponse
//
CFReadStreamClose(myReadStream);
CFRelease(myReadStream);
CFRelease(bodyData);
CFRelease(msg);
CFRelease(url);
</code></pre>
| 33,079
|
<p>I'm looking for a syntax highlighter cum code formatter for my blog on BlogSpot. I've tried several today, but the all want to include <code><style></code> tags, or reference a stylesheet. I'm looking for one that is ideal for segments of code, and includes styling inline. Any suggestions?</p>
|
<p>You can always copy the extra few bytes of styling for, say, a <a href="http://pygments.org/" rel="nofollow noreferrer">Pygments</a> highlighter (which really is quite excellent) into the <code><head></code> of your blog. You don't even need to install any software; just copy the HTML from the online service.</p>
|
<p>I had this exact problem.</p>
<p>I wrote an image formatter for <a href="http://pygments.org" rel="nofollow noreferrer">Pygments</a> (included in the core distribution).</p>
<p>Please don't hate me for such an abomination, but yes, it renders the highlighted code as a png or jpg or whatever you want. So it has no external dependencies etc.</p>
<pre><code>pygmentize -f png -o mysource.png mysource.cs
</code></pre>
<p>I try to make sure that I always link a plain text version of the source for people copy-pasting.</p>
| 41,960
|
<p>Besides open-sourcing your project and legislation, are there ways to prevent, or at least minimize the damages of code leaking outside your company/group?</p>
<p>We obviously can't block Internet access (to prevent emailing the code) because programmer's need their references. We also can't block peripheral devices (USB, Firewire, etc.)</p>
<p>The code matters most when it has some proprietary algorithms and in-house developed knowledge (as opposed to regular routine code to draw GUIs, connect to databases, etc.), but some applications (like accounting software and CRMs) are just that: complex collections of routine code that are simple to develop in principle, but will take years to write from scratch. This is where leaked code will come in handy to competitors.</p>
<p>As far as I see it, preventing leakage relies almost entirely on human process. What do you think? What precautions and measures are you taking? And has code leakage affected you before?</p>
|
<p>You can't stop it getting out. So two solutions - stop people wanting to hurt you, and have legal precautions. To stop people hating you treat them right (saying more is probably off topic for stack overflow).</p>
<p>I'm not a lawyer, but to give yourself legal protection, if you believe in it, patent the ideas, put a copyright notice in the code, and make sure the contracts for your programmers specify carefully intellectual property rights.</p>
<p>But at the end of the day, the answer is run quicker than the competition.</p>
|
<p>The best step starts from reruting guys with strong ethical behaviour.
Various other steps can be taken like all communication being scanned. There are places where email and all information going out is scanned. The desktop/laptop does not have hard-disk or the access is restricted and all work is on network folders, even when working from home, one has to get connected to internet. The offline work gets synchronized. The USB and drives are disconnected.</p>
<p>The other policies are to provide access only on need basis.
These will only slow down and hinder to some extent, but is one is very determined then he would find ways to get around this.
The other way is if the code is really very important, then have the idea copywrite protected legaly.</p>
| 20,955
|
<p>What SQL Server Alerts do you always setup for every database? What do you always monitor regardless of the database?</p>
|
<p>You should monitor and be alerted for severity levels 17 to 25. <br></p>
<p>Severity levels from 17 through 19 will require intervention from a DBA, they're not as serious as 20-25 but the DBA needs to be alerted.<br>
17 Insufficient Resources<br>
18 Nonfatal Internal Error Detected<br>
19 Error in Resource<br>
<br>
<br>
These are serious errors that will mean SQL Server is no longer working<br>
20 SQL Error in Current Process <br>
21 SQL Fatal Error in Database dbid Processes<br>
22 SQL Fatal Error Table Integrity Suspect<br>
23 SQL Fatal Error: Database Integrity Suspect<br>
24,25 Hardware Error<br></p>
<p>for more information on the severity levels see <a href="http://msdn.microsoft.com/en-us/library/aa937483(SQL.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa937483(SQL.80).aspx</a></p>
|
<blockquote>
<p>What do you always monitor regardless of the database? </p>
</blockquote>
<p>We always turn on hardware alerts for all of our servers, in addition to log alerts. Hardware errors, such as inode errors, can take down servers just as fast as 5xx errors, for example. We've seen customers' PDF export capabilities fail when code on a server failed to delete old exports, filling up the disk space until exports failed altogether. Regular log alerts won't warn you of these things until it's too late. But monitoring the disk space would have.</p>
<p>Unfortunately, log management solutions don't set these alerts up for you automatically, so sometimes you find out you needed the alerts the hard way: when you've already got a problem.</p>
<p>We wrote a blog post about why it's important to pair hardware metric alerting with standard log alerts: <a href="https://blog.bluematador.com/posts/how-essential-alerts-could-have-saved-the-millennium-falcon/?utm_source=stackoverflow" rel="nofollow noreferrer">https://blog.bluematador.com/posts/how-essential-alerts-could-have-saved-the-millennium-falcon/</a></p>
| 43,390
|
<p>I'm wondering how to make a release build that includes all necessary dll files into the .exe so the program can be run on a non-development machine without it having to install the microsoft redistributable on the target machine.</p>
<p>Without doing this you get the error message that the application configuration is not correct and to reinstall.</p>
|
<ol>
<li>Choose Project -> Properties</li>
<li>Select Configuration -> General</li>
<li>In the box for how you should link MFC, choose to statically link it.</li>
<li>Choose Linker -> Input. Under <strong>Additional Dependencies</strong>, add any libraries you need your app to statically link in.</li>
</ol>
|
<p>You'd be looking to static link (as opposed to dynamically link)</p>
<p>I'm not sure how many of the MS redistributables statically link in.</p>
| 2,540
|
<p>Not wanting to re-invent the wheel or anything, I was wondering if there's a plugin out there a field or form validation plugin that works with Prototype that you can recommend from your own experience and why?</p>
|
<p>I like Ben Keen's Really Simple Validation component. </p>
<p>Features I like:</p>
<p>All the validation rules can be kept within javascript so you're not adding class="required" to your HTML code.</p>
<p>You can display error messages in a javascript alert box or with HTML text.</p>
<p>Adding your own extensions is easy.</p>
<p><a href="http://www.benjaminkeen.com/software/rsv/" rel="nofollow noreferrer">http://www.benjaminkeen.com/software/rsv/</a></p>
<p>Note that I've only used the jQuery version, but a Prototype version is also available.</p>
|
<p>I like <a href="http://www.formassembly.com/wForms/" rel="nofollow noreferrer">wforms</a>. Example:</p>
<pre><code><input type="text" name="myDate" class="validate-date"/>
</code></pre>
| 33,287
|
<p>If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?</p>
<p>I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.</p>
<p>I know I could do something like this: </p>
<pre><code>int baseCase = 5;
bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5;
</code></pre>
<p>I'm curious to see if I could do something more like this:</p>
<pre><code>int baseCase = 5;
bool testResult = baseCase == (3 | 7 | 12 | 5);
</code></pre>
<p>Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.</p>
<p><strong>UPDATE:</strong><br>
I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.</p>
<p>Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of: </p>
<pre><code>new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5);
</code></pre>
|
<pre><code> bool b = new int[] { 3,7,12,5 }.Contains(5);
</code></pre>
|
<p>Since you did not specify what type of data you have as input I'm going to assume you can partition your input into powers of 2 -> 2,4,8,16... This will allow you to use the bits to determine if your test value is one of the bits in the input.</p>
<p>4 => 0000100<br>
16 => 0010000<br>
64 => 1000000</p>
<p>using some binary math... </p>
<p>testList = 4 + 16 + 64 => 1010100<br>
testValue = 16<br>
testResult = testList & testValue</p>
| 3,897
|
<p>What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding?</p>
<p>In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1.</p>
<p>Plus if the solution is elegant for Java.
I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.)</p>
|
<p>Perhaps you could deserialise the byte array using a known encoding and ensure that (a) it doesn't throw any exceptions, and (b) deserialises to the original string. It seems that from your description of the scenario, you may not have the original string readily available. Might there be a way to create it?</p>
|
<p>That's good.
You're right, I don't have the original string, since I'm testing a module that creates an XML document as a byte array. I didn't think about deserializing to a String with an expected encoding. That will do the trick.</p>
| 2,928
|
<p>I've got a somewhat dated Java EE application running on Sun Application Server 8.1 (aka SJSAS, precursor to Glassfish). With 500+ simultaneous users the application becomes unacceptably slow and I'm trying to assist in identifying where most of the execution time is spent and what can be done to speed it up. So far, we've been experimenting and measuring with LoadRunner, the app server logs, Oracle statpack, snoop, adjusting the app server acceptor and session (worker) threads, adjusting Hibernate batch size and join fetch use, etc but after some initial gains we're struggling to improve matters more.</p>
<p>Ok, with that introduction to the problem, here's the real question: If you had a slow Java EE application running on a box whose CPU and memory use never went above 20% and while running with 500+ users you showed two things: 1) that requesting even static files within the same app server JVM process was exceedingly slow, and 2) that requesting a static file outside of the app server JVM process but on the same box was fast, what would you investigate?</p>
<p>My thoughts initially jumped to the application server threads, both acceptor and session threads, thinking that even requests for static files were being queued, waiting for an available thread, and if the CPU/memory weren't really taxed then more threads were in order. But then we upped both the acceptor and session threads substantially and there was no improvement. </p>
<p>Clarification Edits: </p>
<p>1) Static files should be served by a web server rather than an app server. I am using the fact that in our case this (unfortunately) is not the configuration so that I can see the app server performance for files that it doesn't execute -- therefore excluding any database performance costs, etc. </p>
<p>2) I don't think there is a proxy between the requesters and the app server but even if there was it doesn't seem to be overloaded because static files requested from the same application server machine but outside of the application's JVM instance return immediately.</p>
<p>3) The JVM heap size (Xmx) is set to 1GB.</p>
<p>Thanks for any help!</p>
|
<p>There is a number of ways to do this. </p>
<p>On jquery.com it is part of background image applied the body tag. </p>
<p>You can have a header section which has background aligned to the bottom as an image and bottom padding that prevents text/content from overlaying that part. Finally you could use thick border if you want to just have plain color. I am sure there are numerous other ways to do this as well. </p>
|
<p>Its a <a href="http://static.jquery.com/files/rocker/images/bg_home_tile_sml.jpg" rel="nofollow noreferrer">BG image</a> that's applied to the body tag.</p>
<pre><code>body {
background: #2a3139 url(../images/bg_home_tile_sml.jpg) repeat-x 50% 0;
}
</code></pre>
<p>IMO it's the best way to achieve this effect.</p>
| 37,014
|
<p>In a JSF dataTable I want to display the row index next to the rows... like:</p>
<pre><code>Column A Column B
1 xxx
2 yyy
</code></pre>
<p>I thought that I could use an implicit el variable like #{rowIndex} but this is not working.</p>
<p>A solution I found is to create a binding for the data table and use the binding like:</p>
<pre><code><h:dataTable var="item" value="#{controller.items}" binding="#{controller.dataTable}">
<h:column>#{controller.dataTable.rowIndex}</h:column>
<h:column>value</h:column>
</h:dataTable>
</code></pre>
<p>but this solution is complex and doesn't work well when I have many nested dataTables in a page.</p>
<p>Any ideas on how to solve this in a better way?</p>
|
<p>The existing solution does not strike me as a bad one. The rowIndex should work in nested tables so long as you're referencing the model of the nested table.</p>
<pre><code> <h:dataTable border="1" value="#{nestedDataModel}" var="nested">
<h:column>
<h:dataTable border="1" value="#{nested}" var="item">
<h:column>
<h:outputText value="#{nested.rowIndex}" />
</h:column>
<h:column>
<h:outputText value="#{item}" />
</h:column>
</h:dataTable>
</h:column>
</h:dataTable>
</code></pre>
<p>Sample model:</p>
<pre><code>public class NestedDataModel extends DataModel implements Serializable {
private List<List<String>> nestedDataModel = populateModel();
private int index;
private List<List<String>> populateModel() {
List<List<String>> list = new ArrayList<List<String>>();
for(int x=0; x<3; x++) {
List<String> nestedTableData = new ArrayList<String>();
for(int y=0; y<3; y++) {
nestedTableData.add("Foo x="+x+" y="+y);
}
list.add(nestedTableData);
}
return list;
}
@Override
public int getRowCount() {
return nestedDataModel.size();
}
@Override
public Object getRowData() {
List<String> list = nestedDataModel.get(index);
return new ListDataModel(list);
}
@Override
public int getRowIndex() {
return index;
}
@Override
public Object getWrappedData() {
return nestedDataModel;
}
@Override
public boolean isRowAvailable() {
return index >= 0 && index < nestedDataModel.size();
}
@Override
public void setRowIndex(int arg0) {
index = arg0;
}
@Override
public void setWrappedData(Object arg0) {
throw new UnsupportedOperationException();
}
}
</code></pre>
<p>Nesting dataTables should generally be avoided - if you're not careful (e.g. make them children of a form), this can lead to a O(N^2) pass over the table children for each phase of the lifecycle on a submit (and there are 6 phases in the lifecycle).</p>
<hr>
<p>For something that is external to the model, you could use a simple counter in a managed bean:</p>
<pre><code>public class RowCounter implements Serializable {
private transient int row = 0;
public int getRow() {
return ++row;
}
}
</code></pre>
<p>Config:</p>
<pre><code><managed-bean>
<managed-bean-name>rowCounter</managed-bean-name>
<managed-bean-class>tablerows.RowCounter</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</code></pre>
<p>View:</p>
<pre><code><f:view>
<h:dataTable border="1" value="#{tableDataBean.tableDataModel}"
var="rowBean">
<h:column>
<h:outputText value="#{rowCounter.row}" />
</h:column>
<h:column>
<h:outputText value="#{rowBean}" />
</h:column>
</h:dataTable>
</f:view>
</code></pre>
<p>This works because the bean is request-scope and bound to a read-only control outside a form. It would not work in a nested dataTable unless you wanted the row counter to be global to the view. But then, I'm not convinced that the row index should be a function of the view.</p>
<p>For a nested dataTable, you would be better off providing the row index from the row bean. It gives you more control if you decide to do things like pagination over data sets too.</p>
|
<p>Since JSF 2.0 (introduced in 2009) the current <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/faces/component/uicomponent" rel="nofollow noreferrer"><code>UIComponent</code></a> instance in the view is available via implicit EL variable <code>#{component}</code>. See also <a href="https://stackoverflow.com/questions/29035760/what-exactly-is-component-in-el">What exactly is #{component} in EL?</a></p>
<p>The <code><h:dataTable></code> tag is backed by the <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/faces/component/uidata" rel="nofollow noreferrer"><code>UIData</code></a> component which implements <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/faces/component/namingcontainer" rel="nofollow noreferrer"><code>NamingContainer</code></a>. So, using <code>#{component.namingContainer}</code> anywhere within the context of the <code><h:dataTable></code> will give you the concrete <code>UIData</code> instance, usually in flavor of <code>HtmlDataTable</code> class.</p>
<pre class="lang-html prettyprint-override"><code><h:dataTable value="#{['one', 'two', 'three']}" var="item">
<h:column>This is the `UIData` component: #{component.namingContainer}</h:column>
</h:dataTable>
</code></pre>
<blockquote>
<p>jakarta.faces.component.html.HtmlDataTable@cafebabe<br />
jakarta.faces.component.html.HtmlDataTable@cafebabe<br />
jakarta.faces.component.html.HtmlDataTable@cafebabe</p>
</blockquote>
<p>The <code>UIData</code> class has in turn the <a href="https://jakarta.ee/specifications/platform/9/apidocs/jakarta/faces/component/uidata#getRowIndex--" rel="nofollow noreferrer"><code>getRowIndex()</code></a> method, so this should suffice:</p>
<pre class="lang-html prettyprint-override"><code><h:dataTable value="#{['one', 'two', 'three']}" var="item">
<h:column>Row index: #{component.namingContainer.rowIndex + 1}</h:column>
</h:dataTable>
</code></pre>
<blockquote>
<p>1<br />
2<br />
3</p>
</blockquote>
<p>Do note that it is zero based, hence the <code>+ 1</code>.</p>
<p>No need for <code>binding</code> or 3rd party tags or any custom backing bean logic.</p>
| 38,152
|
<p>I began printing the parts for the Ultrascope DIY telescope designed by the Open Space Agency. See <a href="http://www.openspaceagency.com/ultrascope" rel="noreferrer">http://www.openspaceagency.com/ultrascope</a>.</p>
<p>All of the STL files for the 3D printable parts are canted 45 degrees. Brackets, tubes, everything I have seen so far. Is there a reason for this? I printed one part last night and simply rotated the part so it would lay flat because I didn't want to deal with supports. I am relatively new to 3D printing -- Am I missing something I should know? Is this a thing?</p>
|
<p>The orientation of the part in the STL file depends on the Software that creates the file. I had a software that would export the parts standing upright instead of laying flat. Depending on the CAD software it can be beneficial for the creator of the model to create in in a different orientation as the one you want to use for printing. Also not all CAD Engineers know (or care) about the best orientation for printing a part.</p>
<p>So my guess is that this is an issue of file export/ STL file creation.</p>
<p>It is totally normal to rotate the parts into a position that is best for printing.</p>
|
<p>Layer lines are failure lines.</p>
<p>Sometimes I choose to print a part in a weird or sub-optimal orientation just to minimise the load across layer lines when in use.</p>
<p>That may mean more support material and longer print time, but a completed part that fails is no use at all.</p>
| 244
|
<p>What mysql functions are there (if any) to trim leading zeros from an alphanumeric text field? </p>
<p>Field with value "00345ABC" would need to return "345ABC".</p>
|
<p>You are looking for the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim" rel="noreferrer">trim() function</a>.</p>
<p>Alright, here is your example</p>
<pre><code>SELECT TRIM(LEADING '0' FROM myfield) FROM table
</code></pre>
|
<p>simply perfect:</p>
<pre><code>SELECT TRIM(LEADING '0' FROM myfield) FROM table
</code></pre>
| 12,245
|
<p>I have a header file like this:</p>
<pre><code>#ifndef __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__
#define __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__
#ifdef _DEBUG
// macros for turning a number into a string
#define STRING2(x) #x
#define STRING(x) STRING2(x)
#ifdef TRIAGE_MESG_AS_WARNING
#define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE TO-DO: " STRING(description) ))
#define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : warning : TRIAGE FIXTHIS: " STRING(description) ))
#else
#define TRIAGE_TODO_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE TO-DO: " STRING(description) ))
#define TRIAGE_FIXTHIS_TAG(description) __pragma(message(__FILE__"("STRING(__LINE__)") : message : TRIAGE FIXTHIS: " STRING(description) ))
#endif
#else
#define TRIAGE_TODO_TAG(description)
#define TRIAGE_FIXTHIS_TAG(description)
#endif
#endif // __GEN_NOTE_MARKERS_TO_DEVELOPERS_HPP__
</code></pre>
<p>Which outputs notes to the output pane in Visual Studio 2005. When 'TRIAGE_MESG_AS_WARNING' is defined, Visual Studio will harvest these messages and list them as warnings in the Error List. It does this because the text format matches a warning. However, I don't want them to show up as warnings all the time, I would rather they show up in the Messages pane of the Error List.</p>
<blockquote>
<p>How do you format lines you put in the
"Output Window" so that Visual Studio
will auto-magically show them in the
"Messages" tab of the "Error List"
window?</p>
</blockquote>
<p>The format I have setup for messages in the above code looks like a message from other output, but does not get harvested in the same way.</p>
<p>A co-worker suggested to me that I might need to write a 'custom automation object' to write to the Messages pane. That seems like a pain, especially since it is trivial to end-up with entries in the Error pane and Warning pane simply by proper formating. Is this a possible avenue?</p>
<p>We're using unmanaged C++, so we can't rely on managed (.NET) only tooling. We do not want to extend VS with hooks.</p>
|
<p>I believe they just <strong><em>forgot</em></strong> about adding additional category: info.
At least it is not specified in output format for external tools.</p>
<p>Citation: "Category must be either '<em>error</em>' or '<em>warning</em>'. Case does not matter. Like origin, category must not be localized."</p>
<p>Link: <a href="http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx" rel="noreferrer">http://blogs.msdn.com/msbuild/archive/2006/11/03/msbuild-visual-studio-aware-error-messages-and-message-formats.aspx</a></p>
|
<p>Could you not use "Trace" command within your code? This will just place whatever text that you tell it within the Output window. So for placing of error messages you'll need to format them first probably.</p>
| 26,115
|
<p>I have an application that displays an image inside of a Windows Forms <code>PictureBox</code> control. The <code>SizeMode</code> of the control is set to <code>Zoom</code> so that the image contained in the <code>PictureBox</code> will be displayed in an aspect-correct way regardless of the dimensions of the <code>PictureBox</code>.</p>
<p>This is great for the visual appearance of the application because you can size the window however you want and the image will always be displayed using its best fit. Unfortunately, I also need to handle mouse click events on the picture box and need to be able to translate from screen-space coordinates to image-space coordinates.</p>
<p>It looks like it's easy to translate from screen space to control space, but I don't see any obvious way to translate from control space to image space (i.e. the pixel coordinate in the source image that has been scaled in the picture box).</p>
<p>Is there an easy way to do this, or should I just duplicate the scaling math that they're using internally to position the image and do the translation myself?</p>
|
<p>Depending on the scaling, the relative image pixel could be anywhere in a number of pixels. For example, if the image is scaled down significantly, pixel 2, 10 could represent 2, 10 all the way up to 20, 100), so you'll have to do the math yourself and take full responsibility for any inaccuracies! :-)</p>
|
<p>Depending on the scaling, the relative image pixel could be anywhere in a number of pixels. For example, if the image is scaled down significantly, pixel 2, 10 could represent 2, 10 all the way up to 20, 100), so you'll have to do the math yourself and take full responsibility for any inaccuracies! :-)</p>
| 2,494
|
<p>I have the following scenario:
1. .NET UI side uses Logging App Block to write to a flat file
2. Unmanaged Windows Service uses a proprietary logger to write to the same file as 1.</p>
<p>Question: Is there a way to enable FlatFile TraceListener to close it's file handle once the entry is logged so that the Windows Service could also write to the file?</p>
<p>Thanks!</p>
<p>Update:
I included Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Writer.Dispose();
and this closes the stream, so this would do the trick -- just curious if there is another way to do this.</p>
<p><strong>Update2: Final Notes</strong></p>
<p>P&P proposes to write to a single MSMQ from multiple applications. This way you won't need to call Dispose(), etc.</p>
|
<p>I've had to deal with this using log4net. I wasn't able to make use of the logging framework's file logging support at all, and had to roll my own log appender that catches sharing violations. At that point, your choices are either to buffer events in memory and write them out later or to block until you can get access to the file.</p>
|
<p>I think that your choice is the best way to take care of it - just dispose the writer after you're done, which should finalize and release all of the resources that the writer still holds.</p>
<p>Also, I'd be worried about both processing trying to write at the same time and it causing an exception, but perhaps the App Block has some workaround code for that built in.</p>
| 48,351
|
<p>I need to make an AJAX request from a website to a REST web service hosted in another domain.</p>
<p>Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.</p>
<p>The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.</p>
<p>Here is the JavaScript code that makes the asynchronous call:</p>
<pre><code>var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
</code></pre>
<p>How can I have this work in other browsers beside Internet Explorer? </p>
|
<p>maybe <a href="http://en.wikipedia.org/wiki/JSONP" rel="noreferrer">JSONP</a> can help.</p>
<p>NB youll have to change your messages to use json instead of xml</p>
<p>Edit</p>
<p>Major sites such as flickr and <a href="http://apiwiki.twitter.com/Search+API+Documentation" rel="noreferrer">twitter</a> support jsonp with callbacks etc </p>
|
<p>This can also be done using a webserver setup localy that calls curl with the correct arguments and returns the curl output.</p>
<p>app.rb</p>
<pre><code>require 'sinatra'
require 'curb'
set :views,lambda {"views/"+self.name.to_s.downcase.sub("controller","")}
set :haml, :layout => :'../layout', :format => :html5, :escape_html=>true
disable :raise_errors
get '/data/:brand' do
data_link = "https://externalsite.com/#{params[:brand]}"
c = Curl::Easy.perform(data_link)
c.body_str
end
</code></pre>
<p>Sending an ajax request to localhost:4567/data/something will return the result from externalsite.com/something.</p>
| 43,234
|
<p>Suppose you have an XElement or an XmlElment or even a string containing xml that you want to send via WCF. Are there any special precautions you have to take? The question just came up, what happens when, within the xml message, you transmit an xml document declaration (<?xml version=’1.0’ ?>), which may happen if serializing an XmlDocument...</p>
|
<p>I hade no problem sending XML as a string with WCF. If your XML exceed a few Kb, you must make changes in client&server to allow larger data amounts.</p>
|
<p>Just thought I'd add that in most cases these will be configuration changes, unless you're doing all your binding setup through code. </p>
<p>Specifically, you'll probably need to adjust the MaxReceivedMessageSize property of the binding and the reader quotas on the receiving side.</p>
<p>This is not related specifically to sending XML, by the way, it just comes up whenever you're sending largish messages because the default quotas are very conservative (64kb max message size, for example).</p>
| 17,147
|
<p><code>NSInteger</code>/<code>NSUInteger</code> are Cocoa-defined replacements for the regular built-in types.</p>
<p>Is there any benefit to using the NS* types over the built-ins? Which do you prefer and why? Are <code>NSInteger</code> and <code>int</code> the same width on 32-bit / 64-bit platforms?</p>
|
<p>The way I understand it is that NSInteger et al. are architecture safe versions of the corresponding C types. Basically their size vary depending on the architecture, but NSInteger, for example, is guaranteed to hold any valid pointer for the current architecture.</p>
<p>Apple recommends that you use these to work with OS X 10.5 and onwards, and Apple's API:s will use them, so it's definitely a good idea to get into the habit of using them. They require a little more typing, but apart from that it doesn't seem to be any reason not to use them.</p>
|
<p>I prefer the standard c style declarations but only because I switch between several languages and I don't have to think too much about it but sounds like I should start looking at nsinteger</p>
| 3,466
|
<p>At a new job I started, we have both a Java application that handles most of the heavy lifting in the core business logic, and we also have a Rails application that of course handles the web interface to this server. Both of these access the same database.</p>
<p>Up until now, most of the focus has been on the Java application, and as such, there are no migrations in the Rails project. The sql to update the shared database is managed in a file like changes.sql.</p>
<p>As you can imagine, this makes it somewhat difficult to develop.</p>
<p>My initial thought was to combine the codebases for the Java project and the Rails application, because there is a dependency there, and to manage that SQL file in the source. However, I thought I'd ask here to see if anyone else had tackled this issue with some degree of success.</p>
|
<p>One approach is to use the rails migration tools, generate the DDL files for the database and use Hibernate to update the Java objects that relate to specific database entities. You don't really say how you manage database changes on the Java side or whether you use an ORM, but you can certainly synchronize the two with a little work.</p>
<p>Or you can go the other way around and let the Java definitions control changes on the Rails side.</p>
<p>I think the key to doing this successfully is to select one of the two platforms as your "primary database modeller" and develop the process to migrate that model to the other platform. Attempting to allow changes from both will only cause headaches.</p>
|
<p>Thanks Steve</p>
<p>On the Java side, they are using Hibernate, but with a manual SQL updating process. </p>
<p>I agree, that it should be one or the other. The more I think about it, adding yet another application / module / codebase to manage just the database is definitely the wrong idea.</p>
<p>Thanks</p>
| 26,878
|
<p>Out of order execution in CPUs means that a CPU can reorder instructions to gain better performance and it means the CPU is having to do some very nifty bookkeeping and such. There are other processor approaches too, such as hyper-threading.</p>
<p>Some fancy compilers understand the (un)interrelatedness of instructions to a limited extent, and will automatically interleave instruction flows (probably over a longer window than the CPU sees) to better utilise the processor. Deliberate compile-time interleaving of floating and integer instructions is another example of this.</p>
<p>Now I have highly-parallel task. And I typically have an ageing single-core x86 processor without hyper-threading.</p>
<p>Is there a straight-forward way to get my the body of my 'for' loop for this highly-parallel task to be interleaved so that two (or more) iterations are being done together? (This is slightly different from 'loop unwinding' as I understand it.)</p>
<p>My task is a 'virtual machine' running through a set of instructions, which I'll really simplify for illustration as:</p>
<pre>void run(int num) {
for(int n=0; n<num; n++) {
vm_t data(n);
for(int i=0; i<data.len(); i++) {
data.insn(i).parse();
data.insn(i).eval();
}
}
}</pre>
<p>So the execution trail might look like this:</p>
<pre>data(1) insn(0) parse
data(1) insn(0) eval
data(1) insn(1) parse
...
data(2) insn(1) eval
data(2) insn(2) parse
data(2) insn(2) eval</pre>
<p>Now, what I'd like is to be able to do two (or more) iterations explicitly in parallel:</p>
<pre>data(1) insn(0) parse
data(2) insn(0) parse \ processor can do OOO as these two flow in
data(1) insn(0) eval /
data(2) insn(0) eval \ OOO opportunity here too
data(1) insn(1) parse /
data(2) insn(1) parse</pre>
<p>I know, from profiling, (e.g. using Callgrind with --simulate-cache=yes), that parsing is about random memory accesses (cache missing) and eval is about doing ops in registers and then writing results back. Each step is several thousand instructions long. So if I can intermingle the two steps for two iterations at once, the processor will hopefully have something to do whilst the cache misses of the parse step are occurring...</p>
<p>Is there some c++ template madness to get this kind of explicit parallelism generated?</p>
<p>Of course I can do the interleaving - and even staggering - myself in code, but it makes for much less readable code. And if I really want unreadable, I can go so far as assembler! But surely there is some pattern for this kind of thing?</p>
|
<p>Given optimizing compilers and pipelined processors, I would suggest you just write clear, readable code.</p>
|
<p>Take a look at <a href="http://supertech.csail.mit.edu/cilk/" rel="nofollow noreferrer">cilk</a>. It's an extension to ANSI C that has some nice constructs for writing parallelized code in C. However, since it's an extension of C, it has very limited compiler support, and can be tricky to work with.</p>
| 17,196
|
<p>How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?</p>
|
<p>There is a trimWhiteSpaces directive that should accomplish this,</p>
<p>In your JSP:</p>
<pre><code><%@ page trimDirectiveWhitespaces="true" %>
</code></pre>
<p>Or in the jsp-config section your web.xml (Note that this works starting from servlet specification 2.5.):</p>
<pre><code><jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
</code></pre>
<p>Unfortunately if you have a required space it might also need strip that, so you may need a non-breaking space in some locations.</p>
|
<p>Add/edit your tomcat <code>catalina.properties</code> file with </p>
<pre><code>org.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false
</code></pre>
<p>See also: <a href="https://confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7" rel="nofollow">https://confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7</a></p>
| 25,611
|
<p>I want to programmatically disable the notification I get when I connect to a wireless network. I know there is a way to disable ALL notifications (see <a href="http://www.howtogeek.com/howto/windows/disable-notification-balloons-in-xp/" rel="nofollow noreferrer">here</a>) but is there a way to only disable the one issued by Windows wireless Manager (i.e. wlanapi.dll).</p>
<p>Many thanks!</p>
|
<p>I don't think this is possible, except in Windows 7 when it's available. (It apparently includes a much more configurable tray-program manager).</p>
|
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
New \ DWORD
EnableBalloonTips
Hexadecimal
0
</code></pre>
| 35,699
|
<p>I need to search a string in the string array. I dont want to use any for looping in it</p>
<pre><code>string [] arr = {"One","Two","Three"};
string theString = "One"
</code></pre>
<p>I need to check whether theString variable is present in arr.</p>
|
<p>Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:</p>
<pre><code>bool has = arr.Contains(var); // .NET 3.5
</code></pre>
<p>or</p>
<pre><code>bool has = Array.IndexOf(arr, var) >= 0;
</code></pre>
<p>For info: <strong>avoid names like var</strong> - this is a keyword in C# 3.0.</p>
|
<p>it is old one ,but this is the way i do it ,</p>
<p><code>enter code here</code>var result = Array.Find(names, element => element == "One");</p>
| 33,201
|
<p>I have 3 projects in my solution that I want to deploy. Is there a nice and quick way of using Visual Studio's setup projects to deploy all three apps using one MSI and letting the user decide which apps he wants to install during the install process? </p>
<p>I have setup projects for the 3 individual apps, I also have an overarching setup project that has the output of those other three projects. Am I on the right track or is there a better way?</p>
|
<p>I think you probably want merge modules. Accrding to MSDN:</p>
<blockquote>
<p>A merge module is a standard feature of Microsoft Windows Installer that packages components together with any related files, resources, registry entries, and setup logic. You can use merge modules to install components that multiple applications share. You cannot install merge modules directly. You must merge them into deployment projects.</p>
</blockquote>
<p><a href="http://support.microsoft.com/kb/827025" rel="nofollow noreferrer">http://support.microsoft.com/kb/827025</a></p>
<p>In your case, each application would be a merge module and you would need to provide some UI to select which applications you would like to install. You could modify one of the default page templates to do that.</p>
|
<p>I also have a similar requirement, however i used merge modules but cant seem to find a way of selecting which specific msm to install and which not to. As i understand there is a no condition property which can be set on msm's while integrating them with msi's. Please let me know if there is some alternate way of doin so..</p>
<p>Thanks,
Apn</p>
| 37,705
|
<p>I have a very simple question. I want to test whether a particular port is currently under use or not. For this, I want to bind a TCP socket to the port, if the connection is refused means the port is in use and if not that mean the port is free.</p>
<p>Can someone please tell me how can I write the TCP socket code in C? I am on a solaris platform.</p>
<p>I know its very basic. But I appreciate your help. Thanks in advance.</p>
|
<p>The call to bind function will return -1 if there is an error. This includes the case where the address is already in use.</p>
<pre><code>#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 12345
int main()
{
struct sockaddr_in addr;
int fd;
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("Error opening socket\n");
return -1;
}
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = AF_INET;
if(bind(fd, (struct sockaddr *)&addr,sizeof(struct sockaddr_in) ) == -1)
{
printf("Error binding socket\n");
return -1;
}
printf("Successfully bound to port %u\n", PORT);
}
</code></pre>
|
<p>You might want to look at the source code of netstat. I believe there is a netstat in Solaris as well.</p>
| 24,977
|
<blockquote>
<p>char *strtok(char *s1, const char *s2)</p>
<p>repeated calls to this function break string s1 into "tokens"--that is
the string is broken into substrings,
each terminating with a '\0', where
the '\0' replaces any characters
contained in string s2. The first call
uses the string to be tokenized as s1;
subsequent calls use NULL as the first
argument. A pointer to the beginning
of the current token is returned; NULL
is returned if there are no more
tokens.</p>
</blockquote>
<p>Hi, </p>
<p>I have been trying to use <code>strtok</code> just now and found out that if I pass in a <code>char*</code> into <code>s1</code>, I get a segmentation fault. If I pass in a <code>char[]</code>, <code>strtok</code> works fine. </p>
<p>Why is this?</p>
<p>I googled around and the reason seems to be something about how <code>char*</code> is read only and <code>char[]</code> is writeable. A more thorough explanation would be much appreciated.</p>
|
<p>What did you initialize the <code>char *</code> to?</p>
<p>If something like</p>
<pre><code>char *text = "foobar";
</code></pre>
<p>then you have a pointer to some read-only characters</p>
<p>For </p>
<pre><code>char text[7] = "foobar";
</code></pre>
<p>then you have a seven element array of characters that you can do what you like with.</p>
<p><code>strtok</code> writes into the string you give it - overwriting the separator character with <code>null</code> and keeping a pointer to the rest of the string.</p>
<p>Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.</p>
<p>Also, becasue <code>strtok</code> keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here: <a href="http://www.rt.com/man/strsep.3.html" rel="nofollow noreferrer">http://www.rt.com/man/strsep.3.html</a> (although that still writes into the string so has the same read-only/segfault issue)</p>
|
<p>In brief:</p>
<pre><code>char *s = "HAPPY DAY";
printf("\n %s ", s);
s = "NEW YEAR"; /* Valid */
printf("\n %s ", s);
s[0] = 'c'; /* Invalid */
</code></pre>
| 34,362
|
<p>Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following.</p>
<pre><code>Action1 VIEW
Action1 EDIT
Action2 VIEW
Action3 VIEW
Action3 EDIT
</code></pre>
<p>I would like to use PIVOT (if even possible) to make the results like so:</p>
<pre><code>Action1 VIEW EDIT
Action2 VIEW NULL
Action3 VIEW EDIT
</code></pre>
<p>Is this even possible with the PIVOT functionality?</p>
|
<p>Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once.</p>
<pre><code>SELECT Action,
MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol,
MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol
FROM t
GROUP BY Action
</code></pre>
|
<p>I had a situation where I was parsing strings and the first two positions of the string in question would be the field names of a healthcare claims coding standard. So I would strip out the strings and get values for F4, UR and UQ or whatnot. This was great on one record or a few records for one user. But when I wanted to see hundreds of records and the values for all usersz it needed to be a PIVOT. This was wonderful especially for exporting lots of records to excel. The specific reporting request I had received was "every time someone submitted a claim for Benadryl, what value did they submit in fields F4, UR, and UQ. I had an OUTER APPLY that created the ColTitle and the value fields below</p>
<pre><code>PIVOT(
min(value)
FOR ColTitle in([F4], [UR], [UQ])
)
</code></pre>
| 4,408
|
<p>I would like to upload a file asynchronously with jQuery. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/></code></pre>
</div>
</div>
</p>
<p>Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?</p>
|
<p>With <a href="http://en.wikipedia.org/wiki/HTML5" rel="noreferrer">HTML5</a> you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> nor Iframes or plugins and after some research I came up with the solution.</p>
<p>The HTML:</p>
<pre><code><form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
</code></pre>
<p>First, you can do some validation if you want. For example, in the <code>.on('change')</code> event of the file:</p>
<pre><code>$(':file').on('change', function () {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k');
}
// Also see .name, .type
});
</code></pre>
<p>Now the <code>$.ajax()</code> submit with the button's click:</p>
<pre><code>$(':button').on('click', function () {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
}, false);
}
return myXhr;
}
});
});
</code></pre>
<p>As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with <a href="http://en.wikipedia.org/wiki/Google_Chrome" rel="noreferrer">Google Chrome</a> as some of the HTML5 components of the examples aren't available in every browser.</p>
|
<p>You can use the following code.</p>
<pre><code>async: false(true)
</code></pre>
| 20,075
|
<p>When using <code>G1</code> command in G-code, what is the difference between <code>Z</code>- axis and <code>E</code>- axis?</p>
<p>I see all <code>E</code>, <code>F</code> and <code>Z</code> in</p>
<pre><code>G1 Z0.350 F7800.000
G1 E-2.00000 F2400.00000
G92 E0
G1 X96.753 Y95.367 F7800.000
G1 E2.00000 F2400.00000
</code></pre>
|
<p>G-CODE can be confusing as historically it was <a href="http://ws680.nist.gov/publication/get_pdf.cfm?pub_id=823374" rel="noreferrer">developed for machining tools</a> rather than FDM printers, and thus:</p>
<ul>
<li>not all available commands make sense for a 3D printer</li>
<li>some of the command do slightly different things than those one may intuitively think they do.</li>
</ul>
<p>Typically, Cartesian printers use 4 "axis": <code>X</code>, <code>Y</code> and <code>Z</code> for moving the printhead in space and <code>E</code> for "extruder". The "extruder axis" is not in fact at all an axis in the geometrical sense of the word: it refers to the amount of filament to be moved into (extruded) or out of (retracted) the printing head. The reason why it is considered an "axis" is that it is used in conjunction with the codes <code>G0</code> and <code>G1</code> which are for movement.</p>
<p>Confusingly, the letter <code>E</code> is <a href="https://en.wikipedia.org/wiki/G-code#Letter_addresses" rel="noreferrer">used for the precision feedrate of lathes</a> but in the 3D printing world we rather use <code>F</code> to that purpose. As a non-native English speaker, I was further confused, because for the longest time I thought "feedrate" was referring to the amount of filament <em>fed</em> to the printing head, while in fact it is the speed at which the printing head moves (in mm/minute).</p>
<p>So to summarise, your example code "translated" would look like this:</p>
<pre><code>G1 Z0.350 F7800.000 ; move up 350 microns at 7.8 m/min
G1 E-2.00000 F2400.00000 ; retract 2mm of filament at 2.4 m/min
G92 E0 ; reset the extruder position
G1 X96.753 Y95.367 F7800.000 ; move to X,Y (without changing Z) at 7.8 m/min
</code></pre>
<p>Should you wish to dig deeper into the topic, the <a href="http://reprap.org/wiki/G-code" rel="noreferrer">RepRap wiki page on gcode</a> is rather comprehensive. Mind that several manufacturers add their own "special codes" to the common ones....</p>
|
<p>z-axis refers typically to vertical movement</p>
<p>F references are feed rates/movement rates</p>
<p>E references are for the extruder, referencing the amount and speed to eject filament, negative e-values are retraction commands</p>
| 816
|
<p>How can I search for specific value in the registry keys?</p>
<p>For example I want to search for XXX in </p>
<pre><code>HKEY_CLASSES_ROOT\Installer\Products
</code></pre>
<p>any code sample in C# will be appreciated,</p>
<p>thanks</p>
|
<p>Help <a href="http://bytes.com/forum/thread279622.html" rel="nofollow noreferrer">here</a>...</p>
<p>Microsoft has a great (but not well known) tool for this - called <a href="https://www.microsoft.com/en-us/download/details.aspx?id=24659" rel="nofollow noreferrer">LogParser</a></p>
<p>It uses a SQL engine to query all kind of text based data like the Registry,
the Filesystem, the eventlog, AD etc...
To be usable from C#, you need to build an Interop Assembly from the
Logparser.dll COM server using following (adjust LogParser.dll path)
command.</p>
<pre><code>tlbimp "C:\Program Files\Log Parser 2.2\LogParser.dll"
/out:Interop.MSUtil.dll
</code></pre>
<p>Following is a small sample, that illustrates how to query for the Value
'VisualStudio' in the \HKLM\SOFTWARE\Microsoft tree.</p>
<pre><code>using System;
using System.Runtime.InteropServices;
using LogQuery = Interop.MSUtil.LogQueryClass;
using RegistryInputFormat = Interop.MSUtil.COMRegistryInputContextClass;
using RegRecordSet = Interop.MSUtil.ILogRecordset;
class Program
{
public static void Main()
{
RegRecordSet rs = null;
try
{
LogQuery qry = new LogQuery();
RegistryInputFormat registryFormat = new RegistryInputFormat();
string query = @"SELECT Path from \HKLM\SOFTWARE\Microsoft where
Value='VisualStudio'";
rs = qry.Execute(query, registryFormat);
for(; !rs.atEnd(); rs.moveNext())
Console.WriteLine(rs.getRecord().toNativeString(","));
}
finally
{
rs.close();
}
}
}
</code></pre>
|
<p>@Caltor your solution gave me the answer I was looking for. I welcome improvements or a completely different solution that does not involve the registry. I am working with enterprise applications on Windows 10 with devices joined to Azure AD. I want/need to use Windows Hello for devices and for HoloLens 2 in a UWP app. My problem has been getting the AAD userPrincipal name from Windows 10. After a couple days searching and trying lots of code I searched the Windows Registry for my AAD account in the Current User key and found it. With some research it appears that this information is in a specific key. Because you can be joined to multiple directories there may be more than one entry. I was not trying to solve that issue, that is done with the AAD tenant Id. I just needed the AAD userPrincipal name.
My solution de-dups the return list so that I have a list of unique userPrincipal names. App users may have to select an account, this is tolerable for even HoloLens.</p>
<pre><code>using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
namespace WinReg
{
public class WinRegistryUserFind
{
// Windows 10 apparently places Office/Azure AAD in the registry at this location
// each login gets a unique key in the registry that ends with the aadrm.com and the values
// are held in a key named Identities and the value we want is the Email data item.
const string regKeyPath = "SOFTWARE\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC";
const string matchOnEnd = "aadrm.com";
const string matchKey = "Identities";
const string matchData = "Email";
public static List<string> GetAADuserFromRegistry()
{
var usersFound = new List<string>();
RegistryKey regKey = Registry.CurrentUser.OpenSubKey(regKeyPath);
var programs = regKey.GetSubKeyNames();
foreach (var program in programs)
{
RegistryKey subkey = regKey.OpenSubKey(program);
if(subkey.Name.EndsWith(matchOnEnd))
{
var value = (subkey.OpenSubKey(matchKey) != null)? (string)subkey.OpenSubKey(matchKey).GetValue(matchData): string.Empty;
if (string.IsNullOrEmpty(value)) continue;
if((from user in usersFound where user == value select user).FirstOrDefault() == null)
usersFound.Add(value) ;
}
}
return usersFound;
}
}
}
</code></pre>
| 37,725
|
<p>Good morning,</p>
<p>Apologies for the newbie question. I'm just getting started with ASP.NET internationalization settings.</p>
<p>Background info:</p>
<p>I have a website which displays a <code><table></code> HTML object. In that <code><table></code> HTML object, I have a column which displays dates. My server being in the US, those dates show up as <code>MM/DD/YYYY</code>. Many of my users plug into this webpage through Excel, via the Data --> Import External Data --> Import Web Query interface. My users, for the most part, are in the US, so those dates show up correctly in their Excel screens.</p>
<p>Now I need to make the webpage work for UK users. As is, they are downloading the dates as <code>MM/DD/YYYY</code>, which makes their spreadsheets unusable since their regional settings are set to <code>DD/MM/YYYY</code>.</p>
<p>My question is:</p>
<p>How do I make it so the web server realizes that the incoming request has a <code>en-GB</code> culture setting? I could engineer my own little custom workaround, but I'm sure I'm not the first programmer to come across this. How do the pro's handle this? I'm looking for a solution that would be relatively simple and quick to put up, but I don't want to just put some crappy buggy piece of my own logic togethe that I'm going to dread 6 months from now.</p>
<p>Thanks a lot in advance,
-Alan.</p>
|
<p>A couple of points:</p>
<ul>
<li><p>The <globalization> element also needs the attribute culture="auto". The uiCulture attribute affects the language used to retrieve resources. The culture attribute affects the culture used for formatting numbers an dates.</p></li>
<li><p>As noted in <a href="http://msdn.microsoft.com/en-us/library/bz9tc508.aspx" rel="nofollow noreferrer">this MSDN article</a>, it is not a best practice to rely exclusively on browser settings to determine the UI culture for a page. Users frequently use browsers that are not set to their preferences (for example, in an Internet cafe). You should provide a method for users to explicitly choose a language or language and culture (CultureInfo name) for the page. </p></li>
</ul>
|
<p>You could also accept a query string parameter for overriding the culture settings.</p>
<p>Culture initialization should go in the Page.InitializeCulture method.</p>
<pre><code>protected override void InitializeCulture ( )
{
Thread.CurrentThread.CurrentCulture
= Thread.CurrentThread.CurrentUICulture
= Request.QueryString [ "culture" ] != null ? new CultureInfo ( Request.QueryString [ "culture" ] ) : CultureInfo.InvariantCulture;
//base.InitializeCulture ( );
}
</code></pre>
<p>Usage: <a href="http://tempuri.org/page.aspx?culture=en-GB" rel="nofollow noreferrer">http://tempuri.org/page.aspx?culture=en-GB</a></p>
| 38,790
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.