instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm trying to create a very simple form in an Access database. Whenever I drag a textbox on the form, a label gets created with it. I want to be able to move the label without moving the textbox,but whenever I try to do that, the textbox moves with it. Its like they're linked with each other.
Is there a way to separate them from each other so that they can be moved separately?</p>
|
<p>Yes, but you are better off looking for the small square black box that appears on the top left corner of each control when you click the textbox or label. This box will allow you to drag each control independently. Don't forget Format->Align (Left,Right,Top,Bottom) it is probably more useful for tidying up controls than anything else. </p>
<p>You can separate the label from its parent control by deleting the label, clicking the detail section to ensure that no controls are selected, and pasting, but I would advise against it. You can do a number of useful things with labels that are related to controls and one of them is move the two together - this is useful when you have the form tidied. Another is to find the parent of the control, which is useful when using VBA to change controls.</p>
|
<p>You can also use Group/Ungroup menu commands to establish/remove the connection. Grouping the label and control causes them to move together in design view.</p>
| 39,720
|
<p>I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at? </p>
<p>Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation? </p>
<p>Any insight into methods or best practises would be great, thanks!</p>
|
<p>Header files should contain class and function declarations.</p>
<p>Source files contain class and function definitions.</p>
<p>It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.</p>
<h3>Example: Class Menu</h3>
<pre><code>Menu.h: Contains the Menu declaration.
Menu.cpp: Contains the Menu definition.
</code></pre>
<p>The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.</p>
<p>Consider it this way:<br>
If you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.</p>
|
<p>Suggestion:
1. Have a design ready for your application now.
2. Based on the design, create necessary objects that interact with each other.
3. Refactor or completely change the existing code to suit the newly created design.</p>
<p>Header files provide an interface to the other classes that might use it's functionality.</p>
| 35,398
|
<p>I'm setting the below variables in my vimrc to control how windows get split when I bring up the file explorer plugin for vim. But it appears these variables are not being read because they have no effect on how the file explorer window is displayed. I'm new to vim. I know the vimrc file is being read because I can make other setting changes and they get picked up but these don't work. What am I missing?</p>
<p><code>let g:explWinSize=10</code></p>
<p><code>let g:explSplitBelow=1</code></p>
<p><code>let g:explDetailedHelp=0</code></p>
|
<p>Wherever you got those settings from is outdated. They were valid in vim 6.x, but not 7.x.</p>
<p>For 7.x, use the following settings instead:</p>
<pre><code>let g:netrw_winsize=10
let g:netrw_alto=1
</code></pre>
<p>There is no option for disabling "detailed help" that I can find, but the help provided by netrw in v6 vs v7 is quite different anyway. Read :h netrw for additional info.</p>
|
<p>Create a gvimrc right beside your vimrc file and add those settings in there.</p>
| 33,461
|
<p>In C++ often do something like this:</p>
<pre><code>typedef map<int, vector<int> > MyIndexType;
</code></pre>
<p>Where I then use it like this:</p>
<pre><code>MyIndexType myIndex;
for( ... some loop ...)
{
myIndex[someId].push_back(someVal);
}
</code></pre>
<p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p>
<p>In Python it would look like this:</p>
<pre><code>myIndex = {}
for (someId,someVal) in collection:
try:
myIndex[someId].append(someVal)
except KeyError:
myIndex[someId] = [someVal]
</code></pre>
<p>The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?</p>
|
<p>You want to use:</p>
<pre><code>from collections import defaultdict
myIndex = defaultdict(list)
myIndex[someId].append(someVal)
</code></pre>
<p>Standard Library <a href="http://docs.python.org/library/collections.html#id3" rel="nofollow noreferrer"><code>defaultdict</code> objects</a>.</p>
<p>Example usage from the Python documentation:</p>
<pre><code>>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
</code></pre>
|
<p>How about this? It may not be performance-optimal, but I think it's the "simplest thing that could possibly work".</p>
<pre><code>myIndex = {}
for (someId,someVal) in collection:
if someId not in myIndex:
myIndex[someId] = []
myIndex[someId].append(someVal)
</code></pre>
| 42,040
|
<p>What is the best way to convert between HTML, XML, and XSL-FO in C#?</p>
<p>I already have the HTML (piped in from FCKEditor) and I'd like to print a PDF (I have an XSL->PDF converter). I just can't seem to find a library that will convert from HTML into anything XSL friendly.</p>
|
<p>A year or two back, I had to generate pdfs from a C++/C# program. In the end I settled on launching Apache's Java <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">FOP</a> as a separate process to do the conversion. The experience with xsl-fo was not a pleasant one. At the time, there didn't appear to be a single tool that had implemented xsl-fo completely. Tools tended to pick a subset of the specification and hack away at that. Given the sprawling complexity of xsl-fo, I'm starting to wonder if there will ever be a full implementation.</p>
<p>FOP tended to be buggy and considerable time was spent working around issues. XSLT and XPaths were difficult to learn. It took a few weeks before I was seeing past the verbosity and could quickly get things done. I don't think I ever quite got my head around xsl-fo though. It makes the html and css model look like a child's toy. Luckily, the pdfs generate, and don't have too many problems. :-)</p>
<p>Anyway, the task at hand: generating pdfs from xhtml output from FCKEditor.</p>
<blockquote>
<p>I just can't seem to find a library that will convert from HTML into anything XSL friendly.</p>
</blockquote>
<p>Heh. Yeah, that's 'cos there isn't one, and probably won't be an html to xsl-fo converter that's any good. Such a converter has a few things against it: complexity of browsers and complexity of xsl-fo. For such a converter to deal with an average html document, it needs the guts of a web browser: the layout, css support probably even JavaScript. Then it has to take the rendered page, and figure out what xsl-fo is needed to get something which looks similar, and fits within the paged constraints of xsl-fo.</p>
<p>It's like the problem with making a word viewer: without reimplementing a lot of word, it sucks most of the time because it doesn't look the same.</p>
<p>So... what can you do? Well, having a small subset of html to work with is a good start. Hopefully the output from FCKEditor is xhtml, as getting html into xml is a world of pain in itself (which <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">tidy</a> can be useful for). Next, unless some poor soul has already made an FCKEditor xhtml -> xsl-fo xslt for your xsl-fo implementation, you'll have to make one. That involves learning xsl-fo, xslt and xpath. In my experience it'll take a few weeks and will be a cobbled together solution.</p>
<p>To get started with xsl-fo I found the following links useful:</p>
<ul>
<li><a href="http://www.ecrion.com/Support/Resources/XSL-FOTutorial/toc.xml.html" rel="nofollow noreferrer">XSL-FOTutorial</a></li>
<li><a href="http://www.w3.org/TR/xsl/" rel="nofollow noreferrer">XSL Standard</a></li>
<li><a href="http://xmlgraphics.apache.org/fop/compliance.html" rel="nofollow noreferrer">Apache FOP Compliance Page</a></li>
<li><a href="http://gilbane.com/gilbane_report.pl/94/XSLFO_Ready_for_Prime_Time.html" rel="nofollow noreferrer">XSL-FO: Ready for Prime Time?</a> outlines the problem xsl-fo tries to solve</li>
<li>For three quick intros see <a href="http://www.xml.com/pub/a/2001/01/17/xsl-fo/index.html" rel="nofollow noreferrer">a</a>, <a href="http://www.xml.com/pub/a/2001/01/24/xsl-fo/" rel="nofollow noreferrer">b</a> and <a href="http://www.xml.com/pub/a/2002/03/20/xsl-fo.html" rel="nofollow noreferrer">c</a></li>
</ul>
<p>So what's all this xsl-fo, xslt stuff and all the other things? The <a href="http://gilbane.com/gilbane_report.pl/94/XSLFO_Ready_for_Prime_Time.html" rel="nofollow noreferrer">XSL-FO: Ready for Prime Time?</a> lays it out as:</p>
<blockquote>
<p>The Extensible Stylesheet Language Family (XSL) XSL is a family of recommendations for defining XML document transformation and presentation. It consists of three parts:</p>
<ul>
<li>XSL Transformations (XSLT), a language for transforming XML</li>
<li>The XML Path Language (XPath), an expression language used by XSLT to access or refer to parts of an XML document. (XPath is also used by the XML Linking specification)</li>
<li>XSL Formatting Objects (XSL-FO), an XML vocabulary for specifying formatting semantics</li>
</ul>
</blockquote>
<p>My advice? Run. Find another away. Find another solution. Generate LaTeX files, and convert them into pdfs. Generate something else. Make word documents and print them using <a href="http://sourceforge.net/projects/pdfcreator/" rel="nofollow noreferrer">PDFCreator</a>. Generate images. Control Firefox to print pages as pdfs. Find away to avoid needing pdfs at all. Anything, as long as it isn't fighting html, xsl-fo, FOP, xslt and xpath.</p>
<p>PS: Let me know if you need any help. :-)</p>
|
<p>Very informative exchange here. I have created a web application using ASP.NET and C#.NET for my IT contract business. One of the major goals of the web app is to generate customized resumes in various formats. I store my resume content in a SQL Server database and build the XML mostly raw in a C# method. I used XSLT to convert to HTML and with a little akwardness have finally got a basic presentable resume. My next goal is to get a printable version of the resume. I got a book on XML from the library and touched up the XSLT a little. Then I came to the XSL-FO chapter. That's when the iceberg hit. I wanted to take on the challenge of having a PDF option that would be a menu choice and do a tranform to XSLT to XSL-FO to PDF. Thing is all the book recommendations had references to commercial products. It is just not worth the money as PDF is not neccessary. I looked at Altova XMLSpy on a 30 day trail basis but as soon as I tried my first transform of a XSL-FO example file I got a message stating that I needed to download more software. That download was taking forever from their site so I gave up and removed the software. Free versions of the commmercial software from other vendors do not have the transform option. After reading the notes here I have decided to avoid the XSL-FO myself. I am going to try getting an MS Word version now and if my clients want to convert it to PDF they can pay for the PDF create version from Adobe.</p>
| 25,799
|
<p>In Firefox I can get the stack trace of an exception by using <code>exception.stack</code>.</p>
<p>Is there a way to get that in other browsers, too?</p>
<p><b>Edit:</b> I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).</p>
|
<p>Place this line where you want to print the stack trace:</p>
<pre><code>console.log(new Error().stack);
</code></pre>
<p><strong>Note:</strong> tested by me on <strong>Chrome 24</strong> and <strong>Firefox 18</strong></p>
<p>May be worth taking a look at <a href="https://github.com/ebobby/tracing.js" rel="noreferrer">this tool</a> as well.</p>
|
<p>Not really, at least not easily.</p>
<p>In IE, you can debug the browser process with MS Script Debugger (which for some reason is an Office component) or Visual Studio, and then you can see the stack on breakpoints.</p>
| 17,807
|
<p>I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not?</p>
<p>Is there anything more to be added to the code that goes into a real world application?</p>
<p>What all steps are to be taken to make the application more robust and secure?</p>
<p>Here is a sample source code I got from the web:</p>
<pre><code>function getChats() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
return;
}
var url="getchat.php?latest="+latest;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
} catch (e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</code></pre>
|
<p>The code you posted is missing one important ingredient: the function stateChanged.</p>
<p>If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function "stateChanged" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with "gets" then I'm pretty sure the response is something you're going to be interested in. </p>
<p>That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single "xmlHttp" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time.</p>
<p>Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user.</p>
<p>If you just want to use AJAX functionality on your website then I'd point you in the direction of <a href="http://www.jquery.com" rel="nofollow noreferrer">jQuery</a> or a <a href="http://www.prototypejs.org" rel="nofollow noreferrer">similar</a> <a href="http://www.mootools.net" rel="nofollow noreferrer">framework</a>.</p>
<p>BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes.</p>
|
<p>I would use a framework like <a href="http://www.domassistant.com/" rel="nofollow noreferrer">DOMAssistant</a> which has already done the hard work for you and will be more robust as well as adding extra useful features.</p>
<p>Apart from that, you code looks like it would do the job.</p>
| 6,510
|
<p>I'm setting up a server to offer JIRA and SVN. I figure, I'll use LDAP to keep the identity management simple. </p>
<p>So, before I write one.... is there a good app out there to let users change their ldap password? I want something that lets a user authenticate with ldap and update their password. A form with username, old password, new password and verification would be enough. </p>
<p>I can write my own, but it seems silly to do so if there's already a good app out there that handles this....</p>
<p>Thanks for the help.</p>
|
<p>This should do it:</p>
<pre><code>private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
if (align == Alignment.LEFT)
{
//Process it...
}
}
</code></pre>
|
<p>Sure, you could use an enum. Would something like the following work?</p>
<pre><code>enum Alignment {
LEFT,
RIGHT
}
</code></pre>
<p>private static String drawCellValue(int maxCellLength, String cellValue, Alignment alignment) { }</p>
<p>If you wanted to use a boolean, you could rename the align parameter to something like alignLeft. I agree that this implementation is not as clean, but if you don't anticipate a lot of changes and this is not a public interface, it might be a good choice.</p>
| 17,215
|
<p>While checking out the generic collection in .net i found about KeyedByTypeCollection. Although I worked with it and got to know how to use it, I did not get in which scenario it will be useful.</p>
<p>I read through <a href="https://stackoverflow.com/questions/178255/serviceprovider-cache-etc-done-with-generics-without-cast">ServiceProvider, cache etc. done with generics without cast</a>, but could not get much.</p>
<p>I think, there must have a reason as to why it has been included in the .Net framework. Any body who have used the KeyedByTypeCollection can explain me why they used it or any body, if they know in which scenario potentially it can be used, can explain it to me. </p>
<p>As more of a curiosity does any other languages support this type of collection ? </p>
|
<p>AFAIK, this generic collection serves just as a simple wrapper for <code>KeyedCollection<KEY,VALUE></code> when <code>KEY</code> is the Type of the <code>VALUE</code> to store.</p>
<p>For example, it is very convinient to use this collection if you want to implement a factory returning singletons:</p>
<pre><code>public class Factory<T>
{
private readonly KeyedByTypeCollection<T> _singletons = new KeyedByTypeCollection<T>();
public V GetSingleton<V>() where V : T, new()
{
if (!_singletons.Contains(typeof(V)))
{
_singletons.Add(new V());
}
return (V)_singletons[typeof(V)];
}
}
</code></pre>
<p>The use of this simple factory would be something like the following:</p>
<pre><code> [Test]
public void Returns_Singletons()
{
Factory<ICar> factory = new Factory<ICar>();
Opel opel1 = factory.GetSingleton<Opel>();
Opel opel2 = factory.GetSingleton<Opel>();
Assert.IsNotNull(opel1);
Assert.IsNotNull(opel2);
Assert.AreEqual(opel1, opel2);
}
</code></pre>
<p>Another usage for <code>KeyedByTypeCollection<T></code> would be inside a service locator...</p>
|
<p>In analyzing this class, my take is that it is totally irrelevant. Use the base class <code>KeyedCollection</code> and write the <code>GetKeyForItem</code> method to return the Type of the Item parameter.</p>
<p>There are four methods defined on the <code>KeyedByTypeCollection</code> that are irrelevant (<code>Find</code>, <code>FindAll</code>, <code>Remove</code>, and <code>RemoveAll</code>). <em>Find, FindAll, and RemoveAll</em> have no base <code>KeyedCollection</code> implementations. <em>Remove</em> does exist in the base class.</p>
<p>The first problem with all four of these methods in the <code>KeyedByTypeCollection</code> is that they perform a serial search of the base Collection to find the item(s). Why not just use the indexer from <code>KeyedCollection</code> to retrieve the appropriate item?</p>
<p>Second, <code>FindAll</code> and <code>RemoveAll</code> will only ever find 1 item (if one exists in the Collection) - because BY DEFINITION, only one item of the specified Type will exist in the Collection (oh, and <code>FindAll</code> will serially read through all the elements in the Collection, even if it finds the matching element at the beginning). So, <code>FindAll</code> and <code>RemoveAll</code> will read ALL the items in the Collection before either Finding/Removing 0 or 1 item(s). Again, why not use the indexer or the base version of Remove to perform the required process?</p>
<p>The second problem with the class is that it is not designed to be a base class (in other words, don't inherit from it unless you know how the internals of the methods are written). There are no calls to the <code>GetKeyForItem</code> method in places where it should be used, so, if you override the <code>GetKeyForItem</code> method, you must also override several other methods to properly get the key for the Collection.</p>
| 42,798
|
<p>As per RFC1035, dns names may contain \ddd \x and quote symbol. Please explain with examples about those.</p>
|
<p><a href="http://www.ietf.org/rfc/rfc1035.txt" rel="nofollow noreferrer">RFC1035</a> doesn't say that DNS <strong>names</strong> can contain those characters. In section 5 (MASTER FILES) it says that the <strong>file</strong> that contains the RR information can contain those characters. Specifically: "Because these files are text files several special encodings are
necessary to allow arbitrary data to be loaded." There's text other than domains that can go into zone files. For instance, the entry in a TXT record is free text, so you might want to put a binary character in it, represented with a \ddd string, etc. You are also allowed to make comments, so you might use these "special encodings" in your comments.</p>
<p>There is support for internationalized domain names, but RFC1035 is from 1987, it wasn't talking about i18n domain names at that time.</p>
<p>EDIT: I just reread it and I think I'm wrong. The stuff above is technically about the file format. However, this is also in the RFC in section 3.1:</p>
<blockquote>
<pre><code>Although labels can contain any 8 bit values in octets that make up a
label, it is strongly recommended that labels follow the preferred
syntax described elsewhere in this memo, which is compatible with
existing host naming conventions. Name servers and resolvers must
compare labels in a case-insensitive manner (i.e., A=a), assuming ASCII
with zero parity. Non-alphabetic codes must match exactly.
</code></pre>
</blockquote>
<p>So, that says that any 8-bit char can be part of a label (where a label is that part of the domain name between dots). This doc is describing the technical capability of the DNS protocol, though. Common usage is a different thing. In fact, in section "2.3.1. Preferred name syntax":</p>
<pre><code>The following syntax will result in
fewer problems with many applications
that use domain names (e.g., mail,
TELNET).
<domain> ::= <subdomain> | " "
<subdomain> ::= <label> | <subdomain>
"." <label>
<label> ::= <letter> [ [ <ldh-str> ]
<let-dig> ]
<ldh-str> ::= <let-dig-hyp> |
<let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52
alphabetic characters A through Z in
upper case and a through z in lower
case
<digit> ::= any one of the ten digits
0 through 9
</code></pre>
<p>In other words, the DNS protocol was defined from the beginning to work with 8-bit ascii. However, if you actually wanted your programs to be able to use the domains in the DNS, you should stick with [a-z-].</p>
<p>As for an example, I think this just meant you could have a DNS entry like this:</p>
<pre><code>IHaveAn\020EmbeddedTab IN A 172.24.3.1
</code></pre>
|
<p>The recommended reading is <a href="http://www.ietf.org/rfc/rfc2181.txt" rel="nofollow noreferrer">RFC 2181</a>, whose section 11 explains well the issue.</p>
<p>Otherwise, for an example, see <code>maps-to-nonascii.rfc-test.net</code>. This name is an alias for a name with non-ASCII characters.</p>
| 28,931
|
<p>I'm trying to create web applications that use JavaScript. I'd like to be able to use animation in these applications. I've tried to use basic JavaScript, but I've decided that the best thing to do is to use a library (such as <a href="http://en.wikipedia.org/wiki/Yahoo!_UI_Library" rel="nofollow noreferrer">YUI</a> or jQuery).</p>
<p>I'm running into a problem. On Safari, when I run animation scripts, the animation is very chunky, very blocky. This happens with YUI as well as basic JavaScript. Why does this happen? Are there any good libraries that don't create this problem in Safari, but are also good for Internet Explorer and Firefox (and, hopefully, Opera)?</p>
|
<p>I have found <a href="http://en.wikipedia.org/wiki/MooTools" rel="nofollow noreferrer">MooTools</a> to be pretty slick for animations, just a little smoother than jQuery. </p>
<p>I generally prefer jQuery, which I find to be a little more intuitive (in my head anyway), but I would use MooTools if slick animation is the most important requirement. </p>
|
<p>JQuery has animation, but I don't know what it is like on a Mac (I don't have a mac). If things are going slow, then you are probably making the animations too complicated. Remember, JavaScript is a slow language, and DOM is not designed for animation, so try to limit yourself with respect to the number of animations at the same time. Always ask if the animation is really necessary. </p>
| 5,120
|
<p>What is the default capacity of a <code>StringBuilder</code>?</p>
<p>And when should (or shouldn't) the default be used?</p>
|
<p>The default capacity of StringBuilder is 16 characters (I used .NET Reflector to find out).</p>
|
<p>[edit: at the time, the question asked about <code>StringList</code>]</p>
<p>Do you mean <code>StringCollection</code>? This uses an empty <code>ArrayList</code> initially, so the answer is 0. And you have no option to change it. When you first add an item, the capacity jumps to 4, then uses a doubling strategy when it fills.</p>
<p>If you mean <code>List<string></code>, then it is similar (an empty <code>T[]</code>, not an <code>ArrayList</code>), but you can initialize a known size if you need (i.e. you know how much data you expect). Again, the first time you <code>Add</code> to a <code>List<T></code> the size jumps to 4, then doubles every time it fills up.</p>
| 30,550
|
<p>I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report</p>
<p>eg</p>
<pre><code>ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc);
</code></pre>
<p>My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above).</p>
<p>Does anyone have a way of achieving this?</p>
<p>Thanks</p>
|
<p>regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number.</p>
<p>This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch.</p>
<pre><code>let rec visitor lst tree =
match tree with
| Branch(n, sub) -> List.collect (visitor (n::lst)) sub
| Leaf(n) -> [List.rev (n::lst)]
// For example...
> let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;
> visitor [] tr;;
val it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]
</code></pre>
<p>In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning).
In the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map_concat' to turn them into a single list that contains all posble paths from the current branch.</p>
<p>Now, you can rewrite this to return a list of integers:</p>
<pre><code>let rec visitor2 lst tree =
match tree with
| Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub
| Leaf(n) -> [lst * 10 + n]
// For example...
> visitor2 0 tr;;
val it : int list = [13; 124; 125]
</code></pre>
<p>Instead of concatenating lists, we now calculate the number.</p>
|
<p>Regarding laziness -
You can make this lazy by using F# "seq" type instead of "list" type. Here is an example:</p>
<pre><code>let rec visitor2 lst tree =
match tree with
| Branch(n, sub) -> Seq.map_concat (visitor2 (lst * 10 + n)) sub
| Leaf(n) ->
seq { do printfn "--yielding: %d" (lst * 10 + n)
yield lst * 10 + n };;
</code></pre>
<p>The "seq" thing is a sequence expression, which represents a lazy stream of values. I added "printfn" to the code, so we can track how things are executing:</p>
<pre><code>> visitor2 0 tr |> Seq.take 2;;
--yielding: 13
--yielding: 124
val it : seq<int> = seq [13; 124]
</code></pre>
<p>You can probably use something like Seq.first to find the first value which represents the result.</p>
| 35,959
|
<p><strong>SpousesTable</strong>
<em>SpouseID</em></p>
<p><strong>SpousePreviousAddressesTable</strong>
<em>PreviousAddressID</em>, <em>SpouseID</em>, FromDate, AddressTypeID</p>
<p>What I have now is updating the most recent for the whole table and assigning the most recent regardless of SpouseID the AddressTypeID = 1</p>
<p>I want to assign the most recent SpousePreviousAddress.AddressTypeID = 1
for each unique SpouseID in the SpousePreviousAddresses table.</p>
<pre><code>UPDATE spa
SET spa.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa INNER JOIN Spouses ON spa.SpouseID = Spouses.SpouseID,
(SELECT TOP 1 SpousePreviousAddresses.* FROM SpousePreviousAddresses
INNER JOIN Spouses AS s ON SpousePreviousAddresses.SpouseID = s.SpouseID
WHERE SpousePreviousAddresses.CountryID = 181 ORDER BY SpousePreviousAddresses.FromDate DESC) as us
WHERE spa.PreviousAddressID = us.PreviousAddressID
</code></pre>
<p>I think I need a group by but my sql isn't all that hot. Thanks.</p>
<p><strong>Update that is Working</strong></p>
<p>I was wrong about having found a solution to this earlier. Below is the solution I am going with</p>
<pre><code>WITH result AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) AS rowNumber, *
FROM SpousePreviousAddresses
WHERE CountryID = 181
)
UPDATE result
SET AddressTypeID = 1
FROM result WHERE rowNumber = 1
</code></pre>
|
<p>Presuming you are using SQLServer 2005 (based on the error message you got from the previous attempt) probably the most straightforward way to do this would be to use the ROW_NUMBER() Function couple with a Common Table Expression, I think this might do what you are looking for:</p>
<pre><code>WITH result AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,
*
FROM
SpousePreviousAddresses
)
UPDATE SpousePreviousAddresses
SET
AddressTypeID = 2
FROM
SpousePreviousAddresses spa
INNER JOIN result r ON spa.SpouseId = r.SpouseId
WHERE r.rowNumber = 1
AND spa.PreviousAddressID = r.PreviousAddressID
AND spa.CountryID = 181
</code></pre>
<p>In SQLServer2005 the ROW_NUMBER() function is one of the most powerful around. It is very usefull in lots of situations. The time spent learning about it will be re-paid many times over.</p>
<p>The CTE is used to simplyfy the code abit, as it removes the need for a temporary table of some kind to store the itermediate result.</p>
<p>The resulting query should be fast and efficient. I know the select in the CTE uses *, which is a bit of overkill as we dont need all the columns, but it may help to show what is happening if anyone want to see what is happening inside the query.</p>
|
<pre><code>UPDATE spa SET spa.AddressTypeID = 1
WHERE spa.SpouseID IN (
SELECT DISTINCT s1.SpouseID FROM Spa S1, SpousePreviousAddresses S2
WHERE s1.SpouseID = s2.SpouseID
AND s2.CountryID = 181
AND s1.PreviousAddressId = s2.PreviousAddressId
ORDER BY S2.FromDate DESC)
</code></pre>
<p>Just a guess.</p>
| 37,156
|
<p>I'm not talking about algorithmic stuff (eg use quicksort instead of bubblesort), and I'm not talking about simple things like loop unrolling.</p>
<p>I'm talking about the <em>hardcore</em> stuff. Like <a href="http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html" rel="noreferrer">Tiny Teensy ELF</a>, <a href="http://catb.org/jargon/html/story-of-mel.html" rel="noreferrer">The Story of Mel</a>; practically everything in the demoscene, and so on.</p>
|
<p>I once wrote a brute force RC5 key search that processed two keys at a time, the first key used the integer pipeline, the second key used the SSE pipelines and the two were interleaved at the instruction level. This was then coupled with a supervisor program that ran an instance of the code on each core in the system. In total, the code ran about 25 times faster than a naive C version.</p>
|
<p>The <a href="http://en.wikipedia.org/wiki/EFF_DES_cracker" rel="nofollow noreferrer">EFF DES cracker</a>, which used custom-built hardware to generate candidate keys (the hardware they made could prove a key isn't the solution, but could not prove a key was the solution) which were then tested with a more conventional code.</p>
| 27,973
|
<p>How do you check that monkey patching has been done to a specific class in Ruby? If that is possible, is it also possible to get the previous implementation(s) of the attribute that's been patched?</p>
|
<p>There are the hooks <code>method_added</code> and <code>method_undefined</code>. Garry Dolley has written an I<a href="http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby" rel="noreferrer">mmutable module</a> that prevents monkey patching.</p>
|
<p>There are the hooks <code>method_added</code> and <code>method_undefined</code>. Garry Dolley has written an I<a href="http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby" rel="noreferrer">mmutable module</a> that prevents monkey patching.</p>
| 43,522
|
<p>Our company has a point of sale system with many extras, such as ordering and receiving functionality, sales and order history etc. Our main issue is that the system was not designed properly from the ground up, so it takes too long to make fixes and handle requests from our customers. Also, the current technology we are using (Progress database, Progress 4GL for the language) incurs quite a bit of licensing expenses on our customers due to mutli-user license fees for database connections etc.</p>
<p>After a lot of discussion it is looking like we will probably start over from scratch (while maintaining the current product at least for the time being). We are looking for a couple of things:</p>
<ol>
<li><p>Create the system with a nice GUI front end (it is currently CHUI and the application was not built in a way that allows us to redesign the front end... no layering or separation of business logic and gui...shudder).</p></li>
<li><p>Create the system with the ability to modularize different functionality so the product doesn't have to include all features. This would keep the cost down for our current customers that want basic functionality and a lower price tag. The bells and whistles would be available for those that would want them.</p></li>
<li><p>Use proper design patterns to make the product easy to add or change any part at any time (i.e. change the database or change the front end without needing to rewrite the application or most of it). This is a problem today because the Progress 4GL code is directly compiled against the database. Small changes in the database requires lots of code recompiling.</p></li>
</ol>
<p>Our new system will be Linux based, with a possibility of a client application providing functionality from one or more windows boxes.</p>
<p>So what I'm looking for is any suggestions on which database and/or framework or programming language(s) someone might recommend for this sort of product. Anyone that has experience in this field might be able to point us in the right direction or even have some ideas of what to avoid. We have considered .NET and SQL Express (we don't need an enterprise level DB), but that would limit us to windows (as far as I know anyway). I have heard of Mono for writing .NET code in a Linux environment, but I don't know much about it yet. We've also considered a Java and MySql based implementation.</p>
<p>To summarize we are looking to do the following:</p>
<ol>
<li><p>Keep licensing costs down on the technology we will use to develop the product (Oracle, yikes! MySQL, nice.)</p></li>
<li><p>Deliver a solution that is easily maintainable and supportable.</p></li>
<li><p>A solution that has a component capable of running on "old" hardware through a CHUI front end. (some of our customers have 40+ terminals which would be a ton of cash in order to convert over to a PC).</p></li>
</ol>
<p>Suggestions would be appreciated.</p>
<p>Thanks</p>
<p>[UPDATE]
I should note that we are currently performing a total cost analysis. This question is intended to give us a couple of "educated" options to look into to include in or analysis. Anyone who could share experiences/suggestions about client/server setups would be appreciated (not just those who have experience with point of sale systems... that would just be a bonus).</p>
<p><strong>[UPDATE]</strong></p>
<p>For anyone who is interested, we ended up going with Microsoft Dynamics NAV, LS Retail (a plugin for the point of sale and various other things) and then did some (and are currently working on) customization work on top of that. This setup gave us the added benefit of having a fully integrated g/l system, which our current system lacked.</p>
|
<p>Java for language (or Scala if you want to be "bleeding edge", depending on how you plan to support it and what your developers are like it might be better, but also worse)</p>
<p>H2 for database</p>
<p>Swing for GUI</p>
<p>Reason: Free, portable and pretty standard.</p>
<p>Update: Missed the part where the system should be a client-server setup. My assumption was that the database and client should run on the same machine.</p>
|
<p>I suggest you use browser for the UI. </p>
<p>Organize your application as a web application. </p>
<p>There are tons of options for the back-end. You can use Java + MySQL. Java backend will save you from windows/linux debate as it will run on both platforms. You won't have any licensing cost for both Java and MySQL. (Edit: Definitely there are a lot of others languages that have run-times for both linux & windows including PHP, Ruby, Python etc)</p>
<p>If you go this route, you may also want to consider Google Web Toolkit (GWT) for creating the browser based front-end in a modular fashion. </p>
<p>One word of caution though. Browsers can be pesky when it comes to memory management. In our experience, this was the most significant challenge in doing browser based POS You may want to checkout Adobe Flex that runs in browser but might be more civil in its memory management.</p>
| 23,317
|
<p>I'd like to check a few queries generated by ActiveRecord, but I don't need to actually run them. Is there a way to get at the query before it returns its result?</p>
|
<p>Both of these articles should help you do what you want.</p>
<p><a href="http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing" rel="nofollow noreferrer">http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing</a></p>
<p><a href="http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord" rel="nofollow noreferrer">http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord</a></p>
|
<p>Jamis' article is outdated, or at least doesn't work my Rails app (possibly due to some other reason with a 3 year old 30,000 line app). However this works in a console any time:</p>
<pre><code>ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT)
</code></pre>
| 30,190
|
<p>I'm looking for a web based upload manager, with good support for images. It should be as easy as possible for novice users to "add images to a website". I could use such a thing for two use cases:</p>
<ul>
<li>A CMS for external use, needs proper image support (1-file upload doesn't quite cut it).</li>
<li>A Wiki for internal use, to get popular it will need the ability to put in screenshots easily without bothering with "save screenshot to file - upload file - put complicated markup on page to display image".</li>
</ul>
<p>Ideally, the thing I'm looking for shows galleries of uploaded images and allows the user to add/remove/replace images. </p>
<p>I know there are probably a lot of server-side PHP scripts that can do things like this, in a pop-up window, or with AJAX, but where they're all lacking is in copy/paste support. Especially for the internal support site, a printscreen + paste would be an ideal solution, but I'm unable to find a package that supports this.</p>
<p>I'm guessing this should be possible using Flash; unless there's no way to paste image data into a Flash file. I don't know much about that though. I could probably develop something myself, but I really don't want to have to learn Flash, and I don't have the $$ to pay for the Flash development tools.</p>
<p>So tell me, is it even possible to copy/paste bitmap data into a Flash movie? And has someone perhaps already written an elegant image/upload manager that makes use of it?</p>
|
<p>I found this explanation: <code>http://www.astahost.com/info.php/max_allowed_packet-mysql_t2725.html</code></p>
<blockquote>
<p>It's safe to increase the value of
this variable because the extra memory
is allocated only when needed. For
example, mysqld allocates more memory
only when you issue a long query or
when mysqld must return a large result
row. The small default value of the
variable is a precaution to catch
incorrect packets between the client
and server and also to ensure that you
don't run out of memory by using large
packets accidentally.</p>
</blockquote>
<p>Also note that I read you have to change the value for both the mysql client and the mysql server.</p>
|
<p>I suggest not touching this variable, instead adjusting your storage implementation to handle any size files using the default settings.</p>
<p>Can you see <a href="http://www.dreamwerx.net/phpforum/?id=1" rel="nofollow noreferrer">here</a> for an example.</p>
| 37,769
|
<p>I notice that modern C and C++ code seems to use <code>size_t</code> instead of <code>int</code>/<code>unsigned int</code> pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.</p>
|
<p>The <code>size_t</code> type is the unsigned integer type that is the result of the <code>sizeof</code> operator (and the <code>offsetof</code> operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).</p>
<p>The <code>size_t</code> type may be bigger than, equal to, or smaller than an <code>unsigned int</code>, and your compiler might make assumptions about it for optimization.</p>
<p>You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="noreferrer">pdf</a> format, or in the C11 standard, section 7.19, also available as a <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf" rel="noreferrer">pdf draft</a>.</p>
|
<p>size_t is the size of a pointer. </p>
<p>So in 32 bits or the common ILP32 (integer, long, pointer) model size_t is 32 bits.
and in 64 bits or the common LP64 (long, pointer) model size_t is 64 bits (integers are still 32 bits).</p>
<p>There are other models but these are the ones that g++ use (at least by default)</p>
| 15,987
|
<p>I would like to intercept any URL which the user enters in their browser and perform some tasks before allowing the navigation to continue (any way could be good - i.e. via plug in, via proxy or any other creative suggestion).
To clarify - I am not referring to a specific application that needs to catch this, but rather - any navigation that the user does on his browser needs to be caught (i.e. the user is not opening my application, it should be running in the background or something like that...)
Thanks in advance...</p>
|
<p>I do not think you can "intercept" what the user enters via javascript. It smells like a big security exploit. You can detect when the user leaves the page, but you cannot detect where he is going next.</p>
<ul>
<li><p>A proxy is a good choice if you just need the URL string to be processed. But anything more complex will be complicated to implement in a proxy.</p></li>
<li><p>A plugin however, depends on which browser you are targetting, you can't make a single plugin that targets all browser and control user navigation at the same time. But if you get to selects which browser your user uses, then maybe.</p></li>
<li><p>How about rolling your own browser (using IE's ActiveX control) or using one of the open source alternatives and use that?</p></li>
</ul>
<p>What exact processing is it that you wish to do?</p>
|
<p>If you're using Javascript, there's an event which fires when the user exists a page called <code>onunload</code>.</p>
<pre><code>window.onunload = function() {
alert("You're leaving this page.");
};
</code></pre>
| 34,972
|
<p>My Virtual Machine's clock drifts pretty significantly. There's documentation out there about dealing with this, but nothing seems to be working very well.</p>
<p>Anyone have any suggestions, things that worked well for them, ...</p>
<p>Supposedly updating regularly via ntp is not a good solution.</p>
|
<p>vmware have <a href="http://www.vmware.com/files/pdf/Timekeeping-In-VirtualMachines.pdf" rel="nofollow noreferrer">a really good PDF doc</a> on this problem.</p>
<p>Basically, the host will slew the ticks delivered to your guests as it can.
<strong>Don't</strong> run NTP or timed or junk like that. Just install vmware-guestd and let the host slew your ticks. If you still lose ticks, then any other solution will have major drift too.</p>
<p>If you can, use a guest OS that has a low frequency tick rate. Newer versions of Linux come with 1000Hz ticks, but it used only to be 100Hz. That seems easier for the host to deliver. A kernel rebuild is usually needed to change the HZ value.</p>
|
<p>You can use the cmd and </p>
<pre><code>net time \\computer_name /set
</code></pre>
<p>to set the clock remotly (or in a script for example)</p>
| 14,301
|
<p>I'm probably going to be using Tomcat and the Apache Axis webapp plugin, but I'm curious as to any other potential lightweight solutions.</p>
<p>The main goal of this is to connect to MySQL database for doing some demos.</p>
<p>Thanks,
Todd</p>
|
<p>Define lightweight? (What DOES that mean anyway nowadays??)</p>
<p>With JAX-WS/Metro you need to simply make a boiler plate change to the web.xml, and then annotate a POJO with @WebService, and, tada, instant web service.</p>
<p>The distribution has several jars in it (around a dozen I think, but they're all in the install -- you don't have to go crawling the web for them), however, but the implementation is top notch and the "simple" stuff simply works.</p>
<p>Edit: JAX-WS can be readily deployed in Tomcat and Jetty, and comes "for free" in Glassfish and Glassfish V3 Prelude.</p>
|
<p>Check out <a href="http://xfire.codehaus.org/" rel="nofollow noreferrer">XFire</a>, which apparently has morphed into <a href="http://cxf.apache.org/" rel="nofollow noreferrer">CXF</a>.</p>
<p>They have a <a href="http://cwiki.apache.org/CXF20DOC/index.html" rel="nofollow noreferrer">user guide</a> to get you started.</p>
| 35,721
|
<p>I have plenty of experience with NUnit and MBUnit, but I'm new to .NET Compact Framework development and I'd like to get off on the right foot.</p>
<p>Is there a prevailing unit testing framework for the .NET Compact Framework, and if so, what is it?</p>
|
<p>Check out NUnitLite: <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=NUnitLite" rel="nofollow noreferrer">http://www.codeplex.com/Wiki/View.aspx?ProjectName=NUnitLite</a></p>
|
<p>For an embedded project running on Portable.NET, we ended up writing our own minimal version of NUnit, since we couldn't get the NUnit code to compile and run on that runtime. It wasn't really all that hard to do, actually.</p>
| 38,419
|
<p>I like Steve Yegge's <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html" rel="noreferrer">Prototype Pattern example</a> and decided to whip up a quick proof of concept example.</p>
<p>However, I didn't really think things through. While it is great for dynamically specifying the behaviour of objects and is an easy solution to Steve's <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">opinionated elf</a> example, I'm still trying to work out the best way to handle instance variables.</p>
<p>For instance, let's say I have an AwesomeDragon object. I then want to make an AwesomeDragonImmuneToFire object so I make a new child of the AwesomeDragon (AwesomeDragonImmuneToFire inherits properties from AwesomeDragon) and 'put' "ImmuneToFire" as a property with a value of 'true'. So far so good. Now let's say I want to send my AwesomeDragon object on a tour of nearby peasant villages. This will involve updating the 'position' property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well.</p>
<p>Is the best solution to override instance values upon object creation e.g. immediately 'put' the 'position' value on AwesomeDragonImmuneToFire to the current 'get' value of 'position'?</p>
|
<p>Doesn't it depend how you actually implement the inheritance in your system?</p>
<p>For example, in a JavaScript version of what you describe, the <code>prototype</code> for <code>AwesomeDragonImmuneToFire</code> would normally be an <em>instance</em> of an <code>AwesomeDragon</code>, and since you'd always be working with instances, it wouldn't matter what you do to any particular <code>AwesomeDragon</code>:</p>
<pre><code>function Dragon()
{
this.position = "starting point";
}
function AwesomeDragon()
{
this.awesome = true;
}
AwesomeDragon.prototype = new Dragon();
function AwesomeDragonImmuneToFire()
{
this.immuneToFire = true;
}
AwesomeDragonImmuneToFire.prototype = new AwesomeDragon();
>>> var awesome = new AwesomeDragon();
>>> var immune = new AwesomeDragonImmuneToFire();
>>> awesome.position = "flying above village";
>>> immune.position;
"starting point"
>>> immune.awesome
true
</code></pre>
<p>In this example, there are no classes and all instances are just instances of <code>Object</code> which happen to know which function was used to construct them. <code>new</code> is just <a href="http://javascript.crockford.com/prototypal.html" rel="noreferrer">a bit of syntactic sugar</a> and using StudlyCaps for constructor functions is just a convention for functions which are intended to be used with <code>new</code>.</p>
<p>The key thing is that each object has a chain of prototype objects, which is examined if you try to access an attribute which the object itself doesn't hold, as per Yegge's description of what the "Properties Pattern" is.</p>
<p><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model" rel="noreferrer">https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model</a></p>
|
<blockquote>
<p>This will involve updating the 'position' property of AwesomeDragon. However, the moment I do this AwesomeDragonImmuneToFire will take off as well.</p>
</blockquote>
<p>Maybe I misunderstand but I am not sure why you think the AwesomeDragonImmuneToFire will take off as well. If they are two distinct objects and position is a property of the objects then each instance (dragon) will have their own position. Changing the position of one dragon should not affect the position of the other.</p>
| 28,234
|
<p>I'm trying to refactor a large, old project and one thing I've noticed is a range of different Iterator implementations:</p>
<pre><code>while($iterator->moveNext()) {
$item = $iterator->current();
// do something with $item;
}
for($iterator = getIterator(), $iterator->HasNext()) {
$item = $iterator->Next();
// do something with $item
}
while($item = $iterator->fetch()) {
// do something with item
}
</code></pre>
<p>or even the <a href="http://www.php.net/~helly/php/ext/spl/" rel="nofollow noreferrer">StandardPHPLibrary (SPL)</a> iterator which allows</p>
<pre><code>foreach($iterator as $item) {
// do something with $item
}
</code></pre>
<p>Having so many different Iterators (with different methods for looping over collections) seems like a strong code smell, and I'm inclined to refactor everything to SPL.
Is there a compelling advantage to any of these implementations of Iterator, or is it purely a matter of personal taste? </p>
|
<p>The SPL version is definitely the way to go. Not only is it the easiest to read, but it's a part of PHP now, so will be familiar to many more people.</p>
<p>There's nothing "wrong" with the others, but as you stated, having all these different versions in one project isn't helping anyone.</p>
|
<p>Imo, simply utilising one or more of the SPL libraries as an interface tends to be less ugly in use at the front end. However, the backing behind the implementation can get a bit ugly. </p>
<p>For instance, I wrote an iterator that efficiently iterated a database result set, so that results that were never requested were never fetched from the request pointer, and if items were prematurely fetched ( IE: $obj[ 5 ] ) , it would seek all the required results into an internal buffer. </p>
<p>Worked wonderfully, you just pray that code that makes the magic behind the scenes never fails because it confuses people when they see you use something that looks like an array, and it does "magic" which can fail :)</p>
<p>Magic got people burnt at the stake. So use it carefully and wisely, possibly make it obvious how it works. </p>
<p>My personal preference is for the </p>
<pre><code>for( $object as $i => $v )
</code></pre>
<p>notation for it is generally more consistent and predictable. </p>
<pre><code>for( $dbresult->iterator() as $i => $v ){
}
</code></pre>
<p>style notation is functionally identical, but at least you have less guesswork how it works on the surface. </p>
| 46,833
|
<p>Is it possible to to change a <code><span></code> tag (or <code><div></code>) to preformat its contents like a <code><pre></code> tag would using only CSS?</p>
|
<p>Look at the <a href="https://www.w3.org/TR/CSS21/sample.html" rel="noreferrer">W3C CSS2.1 Default Style Sheet</a> or the <a href="https://www.w3.org/TR/CSS22/sample.html" rel="noreferrer">CSS2.2 Working Draft</a>. Copy all the settings for PRE and put them into your own class.</p>
<pre class="lang-css prettyprint-override"><code>pre {
display: block;
unicode-bidi: embed;
font-family: monospace;
white-space: pre;
}
</code></pre>
|
<p>Why not just use the <pre> tag, instead of the span tag? Both are inline, so both should behave in the way you would like. If you have a problem overriding the entire definition of <pre>, just give it a class/id.</p>
| 26,978
|
<p>Hi I'm doing the Collatz sequence problem in project Euler (problem 14). My code works with numbers below 100000 but with numbers bigger I get stack over-flow error. </p>
<p>Is there a way I can re-factor the code to use tail recursion, or prevent the stack overflow. The code is below:</p>
<pre><code>import java.util.*;
public class v4
{
// use a HashMap to store computed number, and chain size
static HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
public static void main(String[] args)
{
hm.put(1, 1);
final int CEILING_MAX=Integer.parseInt(args[0]);
int len=1;
int max_count=1;
int max_seed=1;
for(int i=2; i<CEILING_MAX; i++)
{
len = seqCount(i);
if(len > max_count)
{
max_count = len;
max_seed = i;
}
}
System.out.println(max_seed+"\t"+max_count);
}
// find the size of the hailstone sequence for N
public static int seqCount(int n)
{
if(hm.get(n) != null)
{
return hm.get(n);
}
if(n ==1)
{
return 1;
}
else
{
int length = 1 + seqCount(nextSeq(n));
hm.put(n, length);
return length;
}
}
// Find the next element in the sequence
public static int nextSeq(int n)
{
if(n%2 == 0)
{
return n/2;
}
else
{
return n*3+1;
}
}
}
</code></pre>
|
<p>Your problem is not with the size of the stack (you're already memoizing the values), but with </p>
<ol>
<li>the size of some of the numbers in the sequences, and </li>
<li>the upper limits of a 32-bit integer. </li>
</ol>
<p>Hint:</p>
<pre><code>public static int seqCount(int n)
{
if(hm.get(n) != null) {
return hm.get(n);
}
if (n < 1) {
// this should never happen, right? ;)
} ...
...
</code></pre>
<p>That should hopefully be enough :)</p>
<p>P.S. you'll run into a need for BigNums in a lot of project euler problems...</p>
|
<pre><code>import java .util.*;
public class file
{
public static void main(String [] args)
{
long largest=0;
long number=0;
for( long i=106239;i<1000000;i=i+2)
{
long k=1;
long z=i;
while(z!=1)
{
if(z%2==0)
{
k++;
z=z/2;
} else{
k++;
z=3*z+1;
}
}
if(k>largest)
{
number=i;
largest=k;
System.out.println(number+" "+largest);
}
}//for loop
}//main
}
</code></pre>
| 49,261
|
<p>I know that there is no way to fully protect our code.
I also know that if a user wants to crack our app, then he or she is not a user that would buy our app.
I also know that it is better to improve our app.. instead of being afraid of anticracking techniques.
I also know that there is no commercial tool that can protec our app....
I also know that....</p>
<p>Ok. Enough. I've heard everything.
I really think that adding a little protection won't hurt.</p>
<p>So.... have you ever used code virtulizer from oreans or vmprotect?
I've heard that they are sometimes detected as virus by some antivirus.</p>
<p>Any experiences that I should be aware of before buying it.
I know it creates some virtual machines and obfuscates a little the code to make it harder to find the weaknesses of our registration routines.</p>
<p>Is there any warning I should know?</p>
<p>Thanks.
Any advice would be appreciated.</p>
<p>Jag</p>
|
<p>Unfortunately, VM-protected software is more likely to get affected by false positives than conventional packing software. The reason for that is that since AV protection is so complicated, AV software are often unable to analyze the protected code, and may rely on either pattern libraries or may issue generic warnings for any files protected by a system it can't analyze. If your priority is to eliminate false positives, I suggest picking a widely-used protection solution, e.g. AsProtect (although Oreans' products are becoming quite popular as well).</p>
|
<p>Software VM protection is quite popular today, especially as it's now available at an accessible price for small companies and independent software developers. It also takes a considerable amount of effort to crack in comparison to non-VM techniques - the wrappers usually have the standard anti-debugging tricks that other protections have, as well as the VM protection. Since the virtual machine is generated randomly on each build, the crackers will need to analyze the VM instruction set and reverse engineer the protected code back to machine code.</p>
<p>The main disadvantage of VM protection is that if it's overused (used to protect excessive parts of the code), it can slow down your application considerably - so you'll need to protect just the critical parts (registration checks, etc). It also doesn't apply to certain application types - it likely won't work on DLLs that are used for injection, as well as device drivers.</p>
<p>I've also heard that StrongBit EXECryptor is a decent protection package at a decent price. (I'm not affiliated with said company nor guarantee any quality what-so-ever, it's just word of mouth and worth checking out IMO).</p>
| 46,207
|
<p>I'm interested in writing eclipse plugins where do I start? </p>
<p>What resources have helped you?</p>
<p>I'm looking for:<br>
1. Tutorials<br>
2. Sites devoted to plugin development<br>
3. Books </p>
|
<p>You can find a good step by step detailed tutorial here:</p>
<p><a href="http://www.eclipsepluginsite.com/" rel="nofollow noreferrer">http://www.eclipsepluginsite.com/</a></p>
<p>Other tutorials:</p>
<p><a href="http://www.ibm.com/developerworks/opensource/library/os-eclipse-snippet/index.html?ca=dgr-lnxw16RichEclipse" rel="nofollow noreferrer">http://www.ibm.com/developerworks/opensource/library/os-eclipse-snippet/index.html?ca=dgr-lnxw16RichEclipse</a></p>
<p><a href="http://www.vogella.de/articles/EclipsePlugIn/article.html" rel="nofollow noreferrer">http://www.vogella.de/articles/EclipsePlugIn/article.html</a></p>
<p>A decent book, that I've used is "<a href="https://rads.stackoverflow.com/amzn/click/com/0321228472" rel="nofollow noreferrer" rel="nofollow noreferrer">Eclipse: Building Commercial-Quality Plug-Ins</a>".</p>
|
<p>Here's all the books available for developing Eclipse Plugins:
<a href="http://www.eclipseplugincentral.com/books-index-req-view_subcat-sid-4.html" rel="nofollow noreferrer">http://www.eclipseplugincentral.com/books-index-req-view_subcat-sid-4.html</a></p>
| 7,083
|
<p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p>
<p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p>
|
<p>Use the <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html" rel="noreferrer">javap</a> tool that comes with the JDK. The <code>-verbose</code> option will print the version number of the class file.</p>
<pre><code>> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
</code></pre>
<p>To only show the version:</p>
<pre><code>WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
</code></pre>
|
<p>The simplest way is to scan a class file using many of the answers here which read the class file magic bytes.</p>
<p>However some code is packaged in jars or other archive formats like WAR and EAR, some of which contain other archives or class files, plus you now have multi-release JAR files - see <a href="https://openjdk.java.net/jeps/238" rel="nofollow noreferrer">JEP-238</a> which use different JDK compilers per JAR.</p>
<p>This program scans classes from a list of files + folders and prints summary of java class file versions for each component including each JAR within WAR/EARs:</p>
<pre><code>public static void main(String[] args) throws IOException {
var files = Arrays.stream(args).map(Path::of).collect(Collectors.toList());
ShowClassVersions v = new ShowClassVersions();
for (var f : files) {
v.scan(f);
}
v.print();
}
</code></pre>
<p>Example output from a scan:</p>
<pre><code>Version: 49.0 ~ JDK-5
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 50.0 ~ JDK-6
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 52.0 ~ JDK-8
C:\java\apache-tomcat-10.0.12\lib\catalina.jar
C:\jars\junit-platform-console-standalone-1.7.1.jar
Version: 53.0 ~ JDK-9
C:\java\apache-tomcat-10.0.12\lib\catalina.jar
C:\jars\junit-platform-console-standalone-1.7.1.jar
</code></pre>
<p>The scanner:</p>
<pre><code>public class ShowClassVersions {
private TreeMap<String, ArrayList<String>> vers = new TreeMap<>();
private static final byte[] CLASS_MAGIC = new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe };
private final byte[] bytes = new byte[8];
private String versionOfClass(InputStream in) throws IOException {
int c = in.readNBytes(bytes, 0, bytes.length);
if (c == bytes.length && Arrays.mismatch(bytes, CLASS_MAGIC) == CLASS_MAGIC.length) {
int minorVersion = (bytes[4] << 8) + (bytes[4] << 0);
int majorVersion = (bytes[6] << 8) + (bytes[7] << 0);
return ""+ majorVersion + "." + minorVersion;
}
return "Unknown";
}
private Matcher classes = Pattern.compile("\\.(class|ear|war|jar)$").matcher("");
// This code scans any path (dir or file):
public void scan(Path f) throws IOException {
try (var stream = Files.find(f, Integer.MAX_VALUE,
(p, a) -> a.isRegularFile() && classes.reset(p.toString()).find())) {
stream.forEach(this::scanFile);
}
}
private void scanFile(Path f) {
String fn = f.getFileName().toString();
try {
if (fn.endsWith(".ear") || fn.endsWith(".war") || fn.endsWith(".jar"))
scanArchive(f);
else if (fn.endsWith(".class"))
store(f.toAbsolutePath().toString(), versionOfClass(f));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void scanArchive(Path p) throws IOException {
try (InputStream in = Files.newInputStream(p)) {
scanArchive(p.toAbsolutePath().toString(), Files.newInputStream(p));
}
}
private void scanArchive(String desc, InputStream in) throws IOException {
HashSet<String> versions = new HashSet<>();
ZipInputStream zip = new ZipInputStream(in);
for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {
String name = entry.getName();
// There could be different compiler versions per class in one jar
if (name.endsWith(".class")) {
versions.add(versionOfClass(zip));
} else if (name.endsWith(".jar") || name.endsWith(".war")) {
scanArchive(desc + " => " + name, zip);
}
}
if (versions.size() > 1)
System.out.println("Warn: "+desc+" contains multiple versions: "+versions);
for (String version : versions)
store(desc, version);
}
private String versionOfClass(Path p) throws IOException {
try (InputStream in = Files.newInputStream(p)) {
return versionOfClass(in);
}
}
private void store(String path, String jdkVer) {
vers.computeIfAbsent(jdkVer, k -> new ArrayList<>()).add(path);
}
// Could add a mapping table for JDK names, this guesses based on (JDK17 = 61.0)
public void print() {
for (var ver : vers.keySet()) {
System.out.println("Version: " + ver + " ~ " +jdkOf(ver));
for (var p : vers.get(ver)) {
System.out.println(" " + p);
}
}
}
private static String jdkOf(String ver) {
try {
return "JDK-"+((int)Float.parseFloat(ver)-44);
}
catch(NumberFormatException nfe)
{
return "JDK-??";
}
}
}
</code></pre>
| 4,671
|
<p>I have a couple CSS files with overlapping CSS selectors that I'd like to programmatically merge (as in not just appending one file to the end of the other). Is there any tool to do this online? or a Firefox extension perhaps?</p>
|
<p>I found <a href="http://zamez.org/factorcss" rel="noreferrer">Factor CSS</a> - complete with source code, but I think it does way more than I'd need. I really just want to combine CSS blocks that have the same selectors. I'll check out the source code and see if it can be converted to something usable as a TextMate bundle. That is, unless someone else manages to get to it before me.</p>
<p>EDIT: Even better - here's <a href="http://sixrevisions.com/css/css_code_optimization_formatting_validation/" rel="noreferrer">a list of web-based tools for checking/formatting/optimizing css</a>.</p>
|
<p>I wrote a Perl utility to do this several years ago.</p>
<p>As well as merging one or more stylesheets into a single coherent sorted output (complete with comments to show which file(s) each property appeared in, and warnings when a property has conflicting values), you can also <em>selectively</em> search or merge based on the selector, the property or both. </p>
<p>These are handled intelligently so that, for example, if you search for the property <code>font</code> you also get <code>font-size</code>, <code>font-weight</code> etc (still presented inside CSS blocks with the relevant selectors that they were taken from). Likewise, selector searching tries to Do The Right (ie generally most useful) Thing. If you search for, say, the element <code>a</code>, it will match any block whose selector is <code>a</code>, <code>a:hover</code>, <code>a.extlink</code>, <code>a#mylink</code>, <code>.foo a</code>, <code>#bar a</code>, <code>p a</code>, <code>pre > a</code>, <code>a + p</code>, <code>a img</code>... (the last two don't <em>directly</em> affect the styling of the <code>a</code> itself but of an adjacent or descendent element, which it is often useful to know about in such a search), without matching <code>#a</code>, <code>.a</code>, etc. Of course this behaviour is optional, you can also search for an exact selector. Or a regex. </p>
<p>Apart from perl itself the only dependency is <a href="http://search.cpan.org/search?query=css%3A%3Atiny&mode=module" rel="nofollow">CSS::Tiny</a></p>
<p>It's free software, and you can get it here: <a href="http://src.qolc.net/cat/software/cssmerge" rel="nofollow">cssmerge</a> </p>
| 3,744
|
<p>In bash shell with emacs key-binding, you can use key combination like M-f, M-b to move one word forward or backward on the shell prompt respectively. Usually, the meta key is mapped to Alt key on Windows and Linux. However, in iTerm, I could not find a way to map this meta key to either Option or Command key on my MacBook Pro.</p>
<p>It seems that in OS X, the meta key is by default mapped to ESC key. So you can use ESC-f, ESC-b on iTerm. However, ESC key is apparently not practical to use. In addition, iTerm does have option that allow you to modifier mapping for the meta key (Bookmarks > Profiles > Keyboard Profiles > Global > Option Key as...), this setting does not seem to work at all.</p>
<p>Therefore, if anyone know what is the solution to this problem, please let me know. </p>
<p>I have upgraded to the latest release, 0.9.6.1012, and this behavior is still persist.</p>
<p><strong>Edit:</strong> Some clarification to my question. The key-binding I'm talking about is for bash shell, not in emacs. It just happens that, by default, bash shell also use the same key-binding as emacs.</p>
|
<ol>
<li>Open "Preferences" (<kbd>⌘</kbd><kbd>,</kbd>) -> <code>Profiles</code> -> <code>Keys</code> -> <code>General</code> tab.</li>
<li>Set <code>Left Option key:</code> to act as <code>Esc+</code>.</li>
</ol>
<p>Works for me in Emacs, though I'm not sure if it will have any other undesirable effects.</p>
|
<p>Try "export LANG=C". I'm not emacs expert, but I found this enables emacs on OS X to recognize the Option key as the Meta key in iTerm,</p>
| 23,855
|
<p>How do I call an external command within Python as if I'd typed it in a shell or command prompt?</p>
|
<p>Use the <a href="https://docs.python.org/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> module in the standard library:</p>
<pre class="lang-py prettyprint-override"><code>import subprocess
subprocess.run(["ls", "-l"])
</code></pre>
<p>The advantage of <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a> over <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer"><code>os.system</code></a> is that it is more flexible (you can get the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout" rel="noreferrer"><code>stdout</code></a>, <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr" rel="noreferrer"><code>stderr</code></a>, the <a href="https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode" rel="noreferrer">"real" status code</a>, better <a href="https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError" rel="noreferrer">error handling</a>, etc...).</p>
<p>Even <a href="https://docs.python.org/library/os.html#os.system" rel="noreferrer">the documentation for <code>os.system</code></a> recommends using <code>subprocess</code> instead:</p>
<blockquote>
<p>The <code>subprocess</code> module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the <a href="https://docs.python.org/library/subprocess.html#subprocess-replacements" rel="noreferrer">Replacing Older Functions with the subprocess Module</a> section in the <a href="https://docs.python.org/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> documentation for some helpful recipes.</p>
</blockquote>
<p>On Python 3.4 and earlier, use <code>subprocess.call</code> instead of <code>.run</code>:</p>
<pre class="lang-py prettyprint-override"><code>subprocess.call(["ls", "-l"])
</code></pre>
|
<p>I use this for Python 3.6+:</p>
<pre><code>import subprocess
def execute(cmd):
"""
Purpose : To execute a command and return exit status
Argument : cmd - command to execute
Return : result, exit_code
"""
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(result, error) = process.communicate()
rc = process.wait()
if rc != 0:
print ("Error: failed to execute command: ", cmd)
print (error.rstrip().decode("utf-8"))
return result.rstrip().decode("utf-8"), serror.rstrip().decode("utf-8")
# def
</code></pre>
| 11,480
|
<p>My question is about one particular usage of static keyword. It is possible to use <code>static</code> keyword to cover a code block within a class which does not belong to any function. For example following code compiles:</p>
<pre><code>public class Test {
private static final int a;
static {
a = 5;
doSomething(a);
}
private static int doSomething(int x) {
return (x+5);
}
}
</code></pre>
<p>If you remove the <code>static</code> keyword it complains because the variable <code>a</code> is <code>final</code>. However it is possible to remove both <code>final</code> and <code>static</code> keywords and make it compile. </p>
<p>It is confusing for me in both ways. How am I supposed to have a code section that does not belong to any method? How is it possible to invoke it? In general, what is the purpose of this usage? Or better, where can I find documentation about this?</p>
|
<p>The code block with the static modifier signifies a <em>class</em> initializer; without the static modifier the code block is an <em>instance</em> initializer. </p>
<p>Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).</p>
<p>Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.</p>
<p>If you remove <code>static</code> from <code>int a</code>, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".</p>
<p>If you also remove <code>static</code> from the initializer block, it then becomes an instance initializer and so <code>int a</code> is initialized at construction.</p>
|
<p>The <em>static initializer blocks</em> are invoked (in the order they were defined in) when the JVM loads the class into memory, and before the main method. It's used to conditionally initialize static variables.</p>
<p>Similarly we have the <em>instance initializer blocks</em> (aka IIBs) which are invoked upon object instantiation, and they're generally used to de-duplicate constructor logic.</p>
<p>The order in which initializers and constructors are executed is:</p>
<ol>
<li>Static initializer blocks;</li>
<li>Object initializer blocks;</li>
<li>Constructors;</li>
</ol>
| 43,488
|
<p>I didn't know I would be getting too many replies so fast. I can provide more details. It is definitely for use within the company. I was looking for some info on whether I should be more careful or anything to watch out for...</p>
<p>My boss is asking me to put some tracking info on what users do with their application. It is not about collecting sensitive data but there might be some screenshots involved and I am not sure if this is a breach of privacy.</p>
<p>Would love to hear any thoughts on this or if you handled something similar.</p>
|
<p>At work, there is no privacy. Think of it this way, if you work for a financial institution, or a government one, monitoring users may be the difference between keeping sensitive information secret and not. (I want my personal information kept private). They are paid to do work at work. If they are afraid about what they are doing is wrong, then they shouldn't be doing it. </p>
<p>A comment brought up a good point. If you are selling the product and spying on end users, that is totally different. That is highly unethical to take screen shots and report them back to the company. Actually where I work, we'd have you arrested for it if we found out. (yes, you'd be violating a federal law, and I guarantee we'd go after everyone and sort out the mistakes later.) That is a very slippery slope.</p>
|
<p>If the client is external, this should be disclosed to the client. Actually, if the client is internal OR external, if you do not disclose it, it is totally unethical.</p>
<p>An employment agreement that states that there can be no expectation of privacy constitutes disclosure.</p>
| 16,554
|
<p>I'm trying to find some references in regards to x86 Assembly languages. Tutorials/Examples to help my understanding.
-Thanks</p>
|
<ul>
<li><a href="http://download.savannah.gnu.org/releases/pgubook/ProgrammingGroundUp-1-0-booksize.pdf" rel="noreferrer">Programming from the Ground Up</a> (free book, highly recommended)</li>
<li><a href="http://en.wikibooks.org/wiki/X86_Assembly" rel="noreferrer">x86 Assembly</a> (wikibooks.org)</li>
<li><a href="http://learn86.awardspace.co.uk/" rel="noreferrer">Essential Resources for x86 Programmers</a></li>
</ul>
|
<p>The best, most comprehensive source of Assembly I've seen is the "<a href="http://www.plantation-productions.com/Webster/www.artofasm.com/Windows/index.html" rel="nofollow noreferrer">Art of Assembly Language</a>" book. It's a free download, in several versions.</p>
| 26,395
|
<p>I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <a href="http://www.caliban.org/ruby/ruby-aws/" rel="nofollow noreferrer">http://www.caliban.org/ruby/ruby-aws/</a>. This defines a class Amazon::AWS:Error:</p>
<pre><code>module Amazon
module AWS
# All dynamically generated exceptions occur within this namespace.
#
module Error
# An exception generator class.
#
class AWSError
attr_reader :exception
def initialize(xml)
err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
err_msg = xml.elements['Message'].text
unless Amazon::AWS::Error.const_defined?( err_class )
Amazon::AWS::Error.const_set( err_class,
Class.new( StandardError ) )
end
ex_class = Amazon::AWS::Error.const_get( err_class )
@exception = ex_class.new( err_msg )
end
end
end
end
end
</code></pre>
<p>This means that if you get an errorcode like <code>AWS.InvalidParameterValue</code>, this will produce (in its exception variable) a new class <code>Amazon::AWS::Error::InvalidParameterValue</code> which is a subclass of <code>StandardError</code>.</p>
<p>Now here's where it gets weird. I have some code that looks like this:</p>
<pre><code>begin
do_aws_stuff
rescue Amazon::AWS::Error => error
puts "Got an AWS error"
end
</code></pre>
<p>Now, if <code>do_aws_stuff</code> throws a <code>NameError</code>, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:</p>
<pre><code>irb(main):007:0> NameError.new.kind_of?(Amazon::AWS::Error)
=> true
</code></pre>
<p>It says <code>true</code>, which I find confusing, especially given this:</p>
<pre><code>irb(main):009:0> NameError.new.kind_of?(Amazon::AWS)
=> false
</code></pre>
<p>What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:</p>
<pre><code>begin
do_aws_stuff
rescue => error
if error.class.to_s =~ /^Amazon::AWS::Error/
puts "Got an AWS error"
else
raise error
end
end
</code></pre>
<p>That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:</p>
<pre><code>error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
</code></pre>
<p>So the exceptions I'm looking to <code>rescue</code> from are the generated exception types that only inherit from StandardError.</p>
<p>To clarify, I have two questions:</p>
<ol>
<li><p>Why is NameError, a Ruby built in exception, a <code>kind_of?(Amazon::AWS::Error)</code>, which is a module?<br>
<strong>Answer:</strong> I had said <code>include Amazon::AWS::Error</code> at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in <code>Amazon::AWS::Error</code> (present and future) to the implicit Kernel class, which is an ancestor of every class. This means <strong>anything</strong> would pass <code>kind_of?(Amazon::AWS::Error)</code>.</p></li>
<li><p>How can I best distinguish the dynamically-created exceptions in <code>Amazon::AWS::Error</code> from random other exceptions from elsewhere?</p></li>
</ol>
|
<p>Ok, I'll try to help here : </p>
<p>First a module is not a class, it allows you to mix behaviour in a class. second see the following example : </p>
<pre><code>module A
module B
module Error
def foobar
puts "foo"
end
end
end
end
class StandardError
include A::B::Error
end
StandardError.new.kind_of?(A::B::Error)
StandardError.new.kind_of?(A::B)
StandardError.included_modules #=> [A::B::Error,Kernel]
</code></pre>
<p>kind_of? tells you that yes, Error does possess All of A::B::Error behaviour (which is normal since it includes A::B::Error) however it does not include all the behaviour from A::B and therefore is not of the A::B kind. (duck typing)</p>
<p>Now there is a very good chance that ruby-aws reopens one of the superclass of NameError and includes Amazon::AWS:Error in there. (monkey patching)</p>
<p>You can find out programatically where the module is included in the hierarchy with the following :</p>
<pre><code>class Class
def has_module?(module_ref)
if self.included_modules.include?(module_ref) and not self.superclass.included_modules.include?(module_ref)
puts self.name+" has module "+ module_ref.name
else
self.superclass.nil? ? false : self.superclass.has_module?(module_ref)
end
end
end
StandardError.has_module?(A::B::Error)
NameError.has_module?(A::B::Error)
</code></pre>
<p>Regarding your second question I can't see anything better than </p>
<pre><code>begin
#do AWS error prone stuff
rescue Exception => e
if Amazon::AWS::Error.constants.include?(e.class.name)
#awsError
else
whatever
end
end
</code></pre>
<p>(edit -- above code doesn't work as is : name includes module prefix which is not the case of the constants arrays. You should definitely contact the lib maintainer the AWSError class looks more like a factory class to me :/ )</p>
<p>I don't have ruby-aws here and the caliban site is blocked by the company's firewall so I can't test much further. </p>
<p>Regarding the include : that might be the thing doing the monkey patching on the StandardError hierarchy. I am not sure anymore but most likely doing it at the root of a file outside every context is including the module on Object or on the Object metaclass. (this is what would happen in IRB, where the default context is Object, not sure about in a file)</p>
<p>from the <a href="http://www.rubycentral.com/pickaxe/tut_modules.html" rel="nofollow noreferrer">pickaxe on modules</a> :</p>
<p><code>A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include.</code></p>
<p>(edit -- I can't seem to be able to comment using this browser :/ yay for locked in platforms) </p>
|
<p>One issue you're running into is that <code>Amazon::AWS::Error::AWSError</code> is not actually an exception. When <code>raise</code> is called, it looks to see if the first parameter responds to the <code>exception</code> method and will use the result of that instead. Anything that is a subclass of <code>Exception</code> will return itself when <code>exception</code> is called so you can do things like <code>raise Exception.new("Something is wrong")</code>.</p>
<p>In this case, <code>AWSError</code> has <code>exception</code> set up as an attribute reader which it defines the value to on initialization to something like <code>Amazon::AWS::Error::SOME_ERROR</code>. This means that when you call <code>raise Amazon::AWS::Error::AWSError.new(SOME_XML)</code> Ruby ends up calling <code>Amazon::AWS::Error::AWSError.new(SOME_XML).exception</code> which will returns an instance of <code>Amazon::AWS::Error::SOME_ERROR</code>. As was pointed out by one of the other responders, this class is a direct subclass of <code>StandardError</code> instead of being a subclass of a common Amazon error. Until this is rectified, Jean's solution is probably your best bet.</p>
<p>I hope that helped explain more of what's actually going on behind the scenes.</p>
| 9,547
|
<p>I am trying to link the as3corelib library to use their JSON functionality following <a href="http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscript-3/" rel="nofollow noreferrer">this tutorial</a>. But am having trouble compiling it. My command looks like:</p>
<pre>
mxmlc --strict=true -library-path+=as3corelib.swc --file-specs myapp.mxml
</pre>
<p>But I am getting this error:</p>
<pre>
_divided_mx_managers_SystemManager.as(13): col: 14 Error: Interface method getVisibleApplicationRect in namespace mx.managers:ISystemManager not implemented by
class _divided_mx_managers_SystemManager.
public class _divided_mx_managers_SystemManager
</pre>
<p>What is the problem?</p>
<p><em>Update: Is this because I am using Flex 3? The tutorial seems to be for Flex 2. If so, what do I need to do for Flex 3?</em></p>
|
<p>I found an older version of the library bundled with some tutorial which worked. Submitted a bug report to as3corelib, of course I am not entirely sure how valid the bug is.</p>
|
<p>Are you using the flex Gubmo sdk?
Looks like the method it's complaining about is in an interface that's part of Gumbo.
If so, then as3corelib probably won't work with it.</p>
| 36,723
|
<p>I'm working with an older MakerBot Replicator clone, actually a Flashforge Creator 1, with original Creator firmware.</p>
<ul>
<li>I'm able to design objects, using Solidworks, and exporting the file as xxx.stl (ascii)</li>
<li>Then I use Slic3r to generate tool paths with output as xxx.gcode</li>
<li>finally, I use <a href="https://markwal.github.io/GpxUi/" rel="nofollow noreferrer">GPX UI</a> to generate a xxx.x3g file.</li>
</ul>
<p>I don't understand where on the build plate the print starts. Is that controlled by the 3d printer's firmware values, or something else in the chain from .stl --> .gcode --> x3g ?? Right now my prints start in the corner nearest 0,0.0, instead of in the middle of the build plate.</p>
<p>How do I control where to place the 3d print on the build plate?</p>
<p>edit: Apologies for the delay. As a result of the answers posted here, I did a whole bunch more testing. The initial response from @mick, seems to indicate that what you see in the Slicer preview is what you'll see on the print bed. That makes sense, but <strong>that is definitely not what I'm seeing</strong>. I definitely don't see anywhere anything that remotely looks like a check the box [] center. Here's what I do see:</p>
<p>When I drop the object into Slic3r, it goes to middle of build plate.</p>
<p><a href="https://i.stack.imgur.com/kNiWQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kNiWQ.jpg" alt="Slicer Preview" /></a></p>
<p><a href="https://i.stack.imgur.com/JFgvU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFgvU.jpg" alt="Slic3r Settings" /></a></p>
<p><a href="https://i.stack.imgur.com/LLqrd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LLqrd.jpg" alt="GPX UI" /></a></p>
<p>Unfortunately here's what gets printed.</p>
<h1>Attempt #1, off in space</h1>
<p><a href="https://i.stack.imgur.com/IkzsV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IkzsV.jpg" alt="print fail #1" /></a></p>
<h1>Attempt #2, Right Hand Margin</h1>
<p><a href="https://i.stack.imgur.com/mJATD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mJATD.jpg" alt="print fail #2" /></a></p>
<h1>Attempt #3, Near the front.</h1>
<p><a href="https://i.stack.imgur.com/v3aLM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v3aLM.jpg" alt="print #3" /></a></p>
<p>I tried moving the print head to center of build plate, thinking that might be a logical start point. No go. Print start moves head to home (rear right corner of print bed) then after elements heat up to temp, it seems to select a random spot on the build plate to start. I never touched the .x3g file between these attempts. So I'm right back to where I started, per the title of this posting "What determines print start location on the build plate?"</p>
|
<p>So it turns out there are elements from each of the previous answers that make sense here, but its not a clear picture. I've spent a whole lot of time trying to make sense of this. I also upgraded my firmware to <a href="https://www.thingiverse.com/thing:32084" rel="nofollow noreferrer">Sailfish.</a> </p>
<p>For the MakerBot Replicator (or FastForge Creator) family of 3d printers, the origin of the build plate is NOT at any of the corners, its right in the center of the build plate. Reference <a href="https://www.sailfishfirmware.com/doc/parameters-home-offsets.html#x20-630004.1" rel="nofollow noreferrer">here.</a> </p>
<blockquote>
<p>4.1 Home Offsets:<br>
By convention, <strong>the center of the build platform</strong> is assumed to be the point (0,0,0) in XYZ space. The X, Y, and Z <strong>home offsets</strong> tell the printer the location of the X, Y, and Z <strong>endstops</strong> in relation to the build platform’s center.</p>
</blockquote>
<p>Looks like this:</p>
<p><a href="https://i.stack.imgur.com/c2YlJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c2YlJ.png" alt="Center of build plate is origin"></a></p>
<p>And it would appear that most other 3D printers are not using this convention. Sigh. From my testing, the main control of print location is within the G-Code generated by the slicer. The tool I was using, Slic3r does give one a chance to correct that
adjustment. You have to go to top menu <code>Settings --> Printer Settings --> Size and Coordinates (Bed Shape) --> Set</code> to get a nice popup visual tool. See below.</p>
<p>Unfortunately the default setting is accurate for the overall bed size, but is a fail for the origin location on the bed. The default origin is set at 0,0, in the corner. Ouch. Big ouch. The origin needs to be located right in the center of the build plate (to be consistent with the firmware controlling the print for this family of printers). It <strong>should</strong> look like this:</p>
<p><a href="https://i.stack.imgur.com/iXV61.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iXV61.png" alt="print bed origin setup"></a></p>
<p>Note, when you tell the printer to go to 'home' it doesn't go to origin (0,0,0) it goes to the endstops. </p>
<pre><code> G68 X0 Y0 F500 ; Perform Homing Routine
</code></pre>
<p>So as long as you understand the quirks of these printers things will work out. You have to ensure offsets are set accurately in firmware config files. (Replicator / Sailfish) And you have to indicate the correct center location to the slicer program. I will say the advice given here was of some help in understanding this. Many thanks. I'm posting here in case others using the Replicator or FastForge Creator series of printers is having troubles centering their prints on the build plate. </p>
<p>Additional info for anybody using a MakerBot Replicator or Flashforge Creator series printer with Slic3r. I wanted to add my custom G-code stuff. The default Slic3r stuff definitely did not work. </p>
<p>Printer Settings --> Custom G-Code --> Start G-Code</p>
<pre><code>M103 ; Turn all extruders off, Extruder Retraction
G21 ; set units to mm
G90 ; Use absolute coordinates
(**** begin homing ****)
G162 X Y F2500 ; home XY axes to maximum stops
G161 Z F1100 ; home Z axis to minimum stop
G92 Z-5 ; Set Position Z =-5mm
G1 Z0.0 ; move Z to "0"
G161 Z F100 ; home Z axis to minimum stop slowly
M132 X Y Z A B ; Recall stored home offsets for XYZAB axis
; Loads the axis offset of the current home position from the EEPROM and waits for the buffer to empty.
G90 ; Use absolute coordinates
G1 X0 Y0 Z50 F3300.0 ; move to waiting position near center of build plate
</code></pre>
<p>Printer Settings --> Custom G-Code --> End G-Code</p>
<pre><code>M109 S0 T0 ; Cool down the build platform
M104 S0 T0 ; Cool down the Right Extruder
M104 S0 T1 ; Cool down the Left Extruder
M73 P100 ; End build progress
G0 Z150 ; Send Z axis to bottom of machine
M18 ; Disable steppers
G162 X Y F2500 ; Home XY endstops
M18 ; Disable stepper motors
M70 P30 ; We <3 Making Things! Yipee, you made it...
; display message above for 30 seconds
M72 P1 ; Play Ta-Da song
</code></pre>
<p>One other thing I do with Slic3r. I print a single loop of print on the periphery of a phantom skirt. I do this as a printer head clean extrude exercise. </p>
<p>Print Settings --> Skirt and Brim --> Skirt --> Loops (minimum): 1, Distance from object: 6mm, Skirt height: 1 This works well. I do this in lieu of the G-code startup used in ReplicatorG software (which went to the lower left hand corner, and did this odd 4mm extrude exercise, with odd timing...) The skirt thing works just fine. </p>
|
<p>It sounds like you have "Origin at center" checked in your slicer's printer definition. That is generally only used with delta printers. Most Cartesian printers have the origin at the front-left corner of the build plate. Uncheck "Origin at center" and re-slice.</p>
<p>Providing that you have set up your slicer with the build plate dimensions and origin correctly defined, your models will be printed where the slicer shows them in the preview. You can rearrange the models before you slice, of course.</p>
| 1,495
|
<p>I would like to create an application wide keyboard shortcut for a Java Swing application.
Looping over all components and adding the shortcut on each, has focus related side effects, and seems like a brute force solution.</p>
<p>Anyone has a cleaner solution?</p>
|
<p>Install a custom KeyEventDispatcher. The KeyboardFocusManager class is also a good place for this functionality.</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/awt/KeyEventDispatcher.html" rel="noreferrer">KeyEventDispatcher</a></p>
|
<p>Use the following piece of code</p>
<pre><code>ActionListener a=new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
// your code
}
};
getRootPane().registerKeyboardAction(a,KeyStroke.getKeyStroke("ctrl D"),JComponent.WHEN_IN_FOCUSED_WINDOW);
</code></pre>
<p>Replace "ctrl D" with the shortcut you want.</p>
| 12,534
|
<p>I am using Apache <a href="http://hc.apache.org/httpclient-3.x/" rel="noreferrer">HttpClient</a> and would like to communicate HTTP errors (400 Bad Request, 404 Not Found, 500 Server Error, etc.) via the Java exception mechanism to the calling code. Is there an exception in the Java standard library or in a widely used library that would be appropriate to use or to subclass for this purpose?</p>
<p>The alternative is to check status return codes. This appears to be the HttpClient design philosophy, but since these errors are truly exceptional in my app, I would like to have the stack trace and other nice exception things set up for me when they happen.</p>
|
<p>If it's not an Exception in HttpClient design philosophy, but an Exception in your code, then create your own Exception classes. ( As a subclass of org.apache.commons.httpclient.HttpException )</p>
|
<p>There is <a href="http://hc.apache.org/httpclient-3.x/tutorial.html" rel="nofollow noreferrer">org.apache.commons.httpclient.HttpException</a> if you want a library exception. We have also sometimes created our own for specific purposes, both creating an exception for specific HTTP status codes and a generic one for and unexpected status code.</p>
| 26,087
|
<p>Given a select with multiple option's in jQuery. </p>
<pre><code>$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
.append("<option>John</option>") //Key = 32
.append("<option>Paul</option>") //Key = 423
</code></pre>
<p>How should the key be stored and retrieved?</p>
<p>The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).</p>
<p>Thanks</p>
<p>and in the spirit of TMTOWTDI.</p>
<pre><code>$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
$(this).append($("<option/>").val(value).text(text));
};
$select.append($option.val(1).text("Jason").clone())
.append("<option value=32>John</option>")
.append($("<option/>").val(423).text("Paul"))
.addOption("321","Lenny");
</code></pre>
|
<p>Like lucas said the value attribute is what you need. Using your code it would look something like this ( I added an id attribute to the select to make it fit ):</p>
<pre><code>$select = $('<select id="mySelect"></select>');
$select.append('<option value="1">Jason</option>') //Key = 1
.append('<option value="32">John</option>') //Key = 32
.append('<option value="423">Paul</option>') //Key = 423
</code></pre>
<p>jQuery lets you get the value using the val() method. Using it on the select tag you get the current selected option's value.</p>
<pre><code>$( '#mySelect' ).val(); //Gets the value for the current selected option
$( '#mySelect > option' ).each( function( index, option ) {
option.val(); //The value for each individual option
} );
</code></pre>
<p>Just in case, the .each method loops throught every element the query matched.</p>
|
<p>If you are using HTML5, you can use a <a href="http://ejohn.org/blog/html-5-data-attributes/" rel="nofollow noreferrer">custom data attribute</a>. It would look like this:</p>
<pre><code>$select = $("<select></select>");
$select.append("<option data-key=\"1\">Jason</option>") //Key = 1
.append("<option data-key=\"32\">John</option>") //Key = 32
.append("<option data-key=\"423\">Paul</option>") //Key = 423
</code></pre>
<p>Then to get the selected key you could do:</p>
<pre><code>var key = $('select option:selected').attr('data-key');
</code></pre>
<p>Or if you are using XHTML, then you can create a custom namespace.</p>
<p>Since you say the keys can repeat, using the value attribute is probably not an option since then you wouldn't be able to tell which of the different options with the same value was selected on the form post.</p>
| 4,683
|
<p>I have created a Dynamic Web Project in my Eclipse workspace. It is also a Maven project, and under SVN control. But in "Open Resource" (Ctrl+Alt+R) no file from this project appears, unless I check from the window's options (top right drop-down) "Show Derived Resources".</p>
<p>I have checked on some of the project's folders and they are not marked as "Derived".</p>
<p>I have two more (plain Java) projects in the workspace, and all the files from them are visible in "Open Resource".</p>
<p>Do you know what might be wrong with either Eclipse, the Maven plugin or Subclipse (the SVN plugin)?</p>
|
<p>I experienced a similar issue in Eclipse (Ganymede), when using the Maven and Subclipse plugins. I have not determined which plugin caused this problem, but I suspect that it is related to my pom.xml containing nested modules (ie. a <code><modules><module>main-module</module><module>integration-test</module></code>). These appear in Eclipse as nested folders with their own pom.xml files (I did not use the Multiple Projects plugin although I have installed it).</p>
<p>I assume that one of the plug-ins has incorrectly set the derived flag on these folders when I checked out the project by SVN and then updated the MVN dependencies and project settings.</p>
<p>When I right click->properties on the top-level nested module directories I can see the Derived flag is checked. By unchecking the derive flag on the module directories (and checking the derive flag on the target directories within each sub-module instead), it fixed the Open Resource functionality.</p>
<p>As the derived flag is inherited from directories, you may need to check all of your directories in the hierarchy to find the 'culprit'.</p>
<p>If it helps the plug-in authors, my top level module directories contain a hyphen '-' in their names. Maybe that is throwing out one of the plugins.</p>
|
<p>In fact, I think that somehow this is eclipse in its own right, as I don't have m2eclipse or using maven for this.</p>
<p>By default, eclipse uses /bin as the target directory. My situation is similar to having maven in the project in that the target directory was changed to lib/classes to accommodate an existing project. </p>
<p>I started seeing issues similar to what is reported here, and while searching for the problem, came across this solution. Eclipse somehow didn't "uncheck" the bin directory as no longer derived, so I ran into the same issues. I tried replicating it, but I couldn't.</p>
| 21,954
|
<p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives? </p>
|
<p>If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:</p>
<pre><code>{% for field in form.fields %}
<div class="form-field">{{ field }}</div>
{% endfor %}
</code></pre>
<p>This also affords you the ability to do conditional checks using {% if %} blocks inside the loop should you want to exclude certain fields.</p>
|
<p>If your problem is just to serialze a ModelForm to json, just write your own simplejson serializer subclass.</p>
| 48,221
|
<p>This is along similar lines as these recent questions:</p>
<p><a href="https://stackoverflow.com/questions/93290/best-java-obfuscation-application-for-size-reduction">Best Java Obfuscation Application For Size Reduction</a>
<a href="https://stackoverflow.com/questions/149937/creating-non-reverse-engineerable-java-programs">Creating non-reverse-engineerable Java programs</a></p>
<p>However, one ends up recommending yGuard and the other ProGuard but neither mention both. I wonder if we could get a comparison of each one and hear peoples experiences from both sides of the fence. Looking at this <a href="http://proguard.sourceforge.net/alternatives.html" rel="nofollow noreferrer">comparison chart</a> on the ProGuard website its clearly angled towards ProGuard. But what about real-world experience of each - which one produces smaller output? which one is harder to decompile from? what Java versions are supported by each?</p>
<p>Personally I'm particularly interested from a J2ME point of view but please don't limit the discussion to that.</p>
|
<p>Proguard is a better product; especially if you take the time to go through the settings for J2ME. </p>
<p>Specifically for J2ME there is a far better (commercial) product called <a href="http://www.innaworks.com/mBooster.html" rel="noreferrer">mBooster</a></p>
<p>I've been getting around 25% improvement in size on my application <em>after</em> its been through Proguard. This is mainly to do with the better Zip compression on the Jar file and comprehensive support for class merging and preverification.</p>
|
<p>My opinion is - ProGuard is better. Output is smaller a bit. Optimizing is better and much faster. </p>
<p>Decompiling is simple in both cases. Well, i mean, if u know Java well and really <em>know</em> business-logic of what you're decompiling, there is no problem to get it back to sources from obfuscated classes.</p>
<p>So, my opinion is ProGuard is better.</p>
| 18,162
|
<p>I have a very complicated .NET application that contains cut/copy/paste functionality. I want to enable/disable cut/copy/paste buttons depending on the selected control/content. The app has many user controls. What is the best way to achieve this?</p>
<p>Thanks</p>
|
<p>Are you talking about catching the focus of the control or about a design pattern in which to do this?</p>
<p>I would probably register each control that is to be enabled/disabled with the control that it's dependent on. Then when the dependent control gets selected/focused, spin through the controls and enable/disable each one. This is pretty much the <a href="http://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">observer pattern</a>.</p>
<p>For example:</p>
<p>In OnInit:</p>
<pre><code>selectedControl1.AddObserver(button1);
selectedControl1.AddObserver(button2);
selectedControl1.AddObserver(textBox1);
selectedControl2.AddObserver(button1);
selectedControl2.AddObserver(textbox3);
</code></pre>
<p>In OnFocused:</p>
<pre><code>foreach(Control ctl in selectedControl1.Observers)
{
ctl.Enabled = true;
}
</code></pre>
<p>Something like that...</p>
|
<p>One approach:</p>
<p>Add a delegate to the appropriate event for each control you wish to monitor. </p>
<p>e.g. :
<code>textBox.GotFocus += myFunctionalityEnabler;</code></p>
| 44,501
|
<p>I've developed an application at working using MySQL 5, that uses Views to access the major pieces of data. It turns out that our production server uses MySQL 4, which does not have Views included.</p>
<p>Does anybody have a quick and dirty way to deal with this that doesn't involve rewriting all my code? </p>
|
<p>This certainly points out the importance of using the same technology in your development and production environments!</p>
<p>Workarounds involving triggers or stored procedures won't work, because these are also not supported on MySQL 4.x.</p>
<p>Your options at this point:</p>
<ul>
<li><p>Rewrite application code to duplicate data in denormalized tables, designed to match your views.</p></li>
<li><p>Upgrade your production database to MySQL 5.0. If you're talking about a hosting provider, then contact that provider and ask if they have an option for MySQL 5.0, otherwise you need to relocate to a provider who does.</p></li>
</ul>
<p>I'd recommend the latter path, it'll be far less work than writing code to manage duplicate data.</p>
<p>Note that MySQL 4.1 was released as production software over four years ago. Active support for this release ended in 2006. Extended support for MySQL 4.1 ends 2009-12-31. See <a href="http://www.mysql.com/about/legal/lifecycle/" rel="nofollow noreferrer">http://www.mysql.com/about/legal/lifecycle/</a></p>
|
<p>Unfortunately, without upgrading to MySQL 5, probably not.</p>
| 43,050
|
<p>Is there a way to temporary swap Flex's main application to another then switch back.
Scenario : Main app started, display login box - then go on with main app. Login box is an application as well. </p>
<p>Application.application is a read only property, that attempt failed.</p>
|
<p>I've had great success with a modular application whereby the main application basically consists of a module loader, that initially loads a logon module.</p>
<p>Once the logon module has done it's stuff (in my case validated inputs, called the logon service and retrieved a token), it dispatches an event (imaginatively called "LogonEvent") that contains details required by the main application. I should point out that the logon module itself is just a wrapper for a logon component that does all the real work (so the logon component can be used in a module or ViewStack etc). Having a LogonEvent makes all the difference.</p>
<p>The wrapper application processes the logon event by unloading the logon module, loading the main module that contains the guts of the application, and then sets the required logon details on the loaded module.</p>
<p>The log off button is in the wrapper application so that it can unload the main module and reload the logon module ready for logging in again.</p>
<p>The benefit of this kind of layout is that the relatively small logon module loads pretty quickly. And while the user is logging on, the main module is already getting pre-loaded, so there is generally no wait for the main module to load after log on. If you have one large monolithic application the initial load time could be off putting.</p>
<p>Some bits of code that may help...</p>
<pre><code>private var mainModuleLogOnEventDispatcher:*;
[Bindable]
private var _logOnDetails:LogOnDetails = new LogOnDetails();
private function onCreationComplete(event:Event):void
{
// Load log on module.
loadMainModule("LogOnModule.swf");
// Pre-load main module while user is logging on.
var mm:IModuleInfo = ModuleManager.getModule("MainModule.swf");
mm.load();
}
[Bindable]
private function set logOnDetails(value:LogOnDetails):void
{
_logOnDetails = value;
}
private function get logOnDetails():LogOnDetails
{
return _logOnDetails;
}
private function loadMainModule(moduleName:String):void
{
// Unload anything already loaded.
if (mainModule.url.length > 0)
{
mainModule.unloadModule();
mainModule.url = "";
}
mainModule.addEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);
mainModule.url = moduleName;
}
private function handleMainModuleReadyEvent(event:ModuleEvent):void
{
// Remove listener, we've caught the event now.
mainModule.removeEventListener(ModuleEvent.READY, handleMainModuleReadyEvent);
// Add listeners to other events or apply data.
if (mainModule.url == "LogOnModule.swf")
{
mainModuleLogOnEventDispatcher = mainModule.child;
if (mainModule.child != null) {
mainModuleLogOnEventDispatcher.addEventListener("logOnEvent", handleLogOnEvent);
}
}
if (mainModule.url == "MainModule.swf")
{
var mm:* = mainModule.child;
if (mainModule.child != null)
{
mm.logOnDetails = logOnDetails;
}
}
}
private function handleLogOnEvent(logOnEvent:LogOnEvent):void
{
mainModuleLogOnEventDispatcher.removeEventListener("logOnEvent", handleLogOnEvent);
logOnDetails = logOnEvent.logOnDetails;
// Now get person's details and swap in main module if successful.
var parameters:Object = new Object();
parameters.cmd = "viewPerson";
parameters.token = logOnDetails.logOnToken;
viewPersonRequest.send(parameters);
}
private function handleViewPersonRequestResult(event:ResultEvent):void
{
//*** Loads of setting logonDetails and error handling removed!!! ***//
loadMainModule("MainModule.swf");
currentState = "LoggedOn";
return;
}
private function onLogOff(event:MouseEvent):void
{
// Make sure we don't auto-logon when we log off.
var logOnPrefs:SharedObject = SharedObject.getLocal("LogOn", "/");
logOnPrefs.data.loggedOff = true;
var parameters:Object = new Object();
parameters.cmd = "logoff";
parameters.token = logOnDetails.logOnToken;
logoffRequest.send(parameters);
loadMainModule("LogOnModule.swf");
currentState = "";
}
<!-- *** Loads of view state related mxml removed *** -->
<mx:VBox width="100%" height="100%" horizontalAlign="center" verticalAlign="middle" id="mainModuleVBox">
<basic:IJModuleLoader id="mainModule" url="" width="100%" height="100%" horizontalAlign="center" verticalAlign="middle"/>
</mx:VBox>
</code></pre>
<p>I should also note that this wrapper application isn't actually an application! This is actually a module itself, which is loaded by either a Flex or AIR application. This way I can have separate Flex and AIR projects that reference a core library project that holds the application module, logon module, main (post logon) module and basically all other components and classes used by the application.</p>
|
<p>That's funny, this is exactly what I am attempting to figure out the best way to do at the moment. I had thought of using a ViewStack, but as I already have a lot of other nested ViewStacks being used, I was also looking into the State tag. If anyone knows "the right thing" to do I'll be very interested too!</p>
| 26,908
|
<p>I need to keep a couple of <a href="http://jena.sf.net" rel="nofollow noreferrer">Jena</a> Models (OntModels, specifically) synchronized across a socket, and I'd like to do this one change at a time (for various reasons -- one being that each Statement added or removed from the OntModels is also adapting a JESS rule base.). I am able to listen to the add/remove events on the OntModels and then create simple event instances that wrap the added / removed Statements along with a ChangeType that indicates that the Statement was added or removed, but serializing the Statement has proven to be a problem.</p>
<p>Unfortunately, all of the JENA serialization documentation that I've found relates to serializing an entire model to xml / rdf / n3 / etc. Since statements are simply triples of Strings (at one level, anyway) it seems like it should be trivial to serialize the data at the Statement level. However, <a href="http://jena.sf.net" rel="nofollow noreferrer">Jena</a> doesn't seem to provide an API for creating Statements with plain strings that "does the right thing". Problems arise with typed literals. eg:</p>
<p>I can create the statement:</p>
<pre><code><http://someuri/myont#foo> <http://someuri/myont#weight> "50.7"^^www.w3.org/2001/XMLSchema#double
</code></pre>
<p>but the string version that I can get out looks like this:</p>
<pre><code>"http://someuri/myont#foo" "http://someuri/myont#weight" "50.7^^www.w3.org/2001/XMLSchema#double"
</code></pre>
<p>(note the absence of a " before the ^^)</p>
<p>This wouldn't be that much of a problem, since the literal can still be parsed out with a regex, but I've been unable to create a Statement with the proper literal. The obvious approach (ModelCon.createStatement(Resource, Property, String)) generates an untyped string literal with the full value of the String passed in.</p>
<p>Does anyone know how I can reliably serialize (and deserialize, of course) individual Jena Statements?</p>
|
<p>I would serialize the changes out in N-TRIPLES format. Jena has built-in N-TRIPLES serializer and parser, but the N-TRIPLES syntax is (deliberately) very simple so it would be easy to generate manually in your code. </p>
<p>However, it might be even easier to keep a plain mem model around to hold the changes, have the event handlers write changes into that model, then serialize that model over the wire according to your synchronization schedule. Likewise, at the far end I would read the updates from the sync channel into a temporary mem model, then <code>yourOntModel.add( changesModel )</code> should add in the updates very straightforwardly.</p>
<p>Ian</p>
|
<p>Maybe you should try to replace the String parameter of createStatement by Model.createLiteral(String)... </p>
| 49,161
|
<p>Why is the following C# code not allowed:</p>
<pre><code>public abstract class BaseClass
{
public abstract int Bar { get;}
}
public class ConcreteClass : BaseClass
{
public override int Bar
{
get { return 0; }
set {}
}
}
</code></pre>
<blockquote>
<p>CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Bar' does not have an overridable set accessor</p>
</blockquote>
|
<p>I think the main reason is simply that the syntax is too explicit for this to work any other way. This code:</p>
<pre><code>public override int MyProperty { get { ... } set { ... } }
</code></pre>
<p>is quite explicit that both the <code>get</code> and the <code>set</code> are overrides. There is no <code>set</code> in the base class, so the compiler complains. Just like you can't override a method that's not defined in the base class, you can't override a setter either.</p>
<p>You might say that the compiler should guess your intention and only apply the override to the method that can be overridden (i.e. the getter in this case), but this goes against one of the C# design principles - that the compiler must not guess your intentions, because it may guess wrong without you knowing.</p>
<p>I think the following syntax might do nicely, but as Eric Lippert keeps saying, implementing even a minor feature like this is still a major amount of effort...</p>
<pre><code>public int MyProperty
{
override get { ... } // not valid C#
set { ... }
}
</code></pre>
<p>or, for autoimplemented properties,</p>
<pre><code>public int MyProperty { override get; set; } // not valid C#
</code></pre>
|
<p>Because at the IL level, a read/write property translates into two (getter and setter) methods.</p>
<p>When overriding, you have to keep supporting the underlying interface. If you could add a setter, you would effectively be adding a new method, which would remain invisible to the outside world, as far as your classes' interface was concerned.</p>
<p>True, adding a new method would not be breaking compatibility per se, but since it would remain hidden, decision to disallow this makes perfect sense.</p>
| 10,818
|
<p>I thought this was pretty straight forward but I don't get the same results as the tutorials I read. I have a button on an html page that calls a function in script tags. I also have a reference to the prototype.js file which I haven't even begun to implement yet. If I leave that reference in the page, my function call does not work from the button's onclick event. Below is what is called from the button onclick event.</p>
<p> </p>
<p></p>
<pre><code>callIt = function(){
alert('It worked!');
}
</script>
</code></pre>
|
<p>A couple of things: first, make sure your HTML is valid. Run it through the validator at <a href="http://validator.wc.org" rel="nofollow noreferrer">http://validator.wc.org</a>.</p>
<p>Next, once you're sure that your page is valid, add the prototype.js library as the first script reference on the page:</p>
<pre><code><script type="text/javascript" src="prototype.js"></script>
</code></pre>
<p>Notice that I didn't close it like this <code><script ... /></code> Script blocks need to have an explicit closing tag (at least in XHTML 1.0 Transitional)</p>
<p>Now, to answer your question, I'm really not sure what you're asking, but if you wanted to attach the callIt method to the onclick handler of your button using Prototype, then do this:</p>
<pre><code>Event.observe(window, 'load', function() {
Event.observe('button_id', 'click', callIt);
});
</code></pre>
<p>Put this in script tags in the element of the page, below the prototype script reference. This will execute when the DOM is loaded & the button exists on the page.</p>
<p>Hope this helps.</p>
|
<p>That worked. I'm just puzzled why none of the examples I have been working from have done this. </p>
<p>Thanks!</p>
| 48,241
|
<p>I made some 3D printed supports for tools, using screws to fix it to the wall, some of them broken because of the screw forces. Is there a way to reinforce only the screw holes where it will have more stress/compress? I am using PLA, Fusion 360 and Ultimaker Cura.</p>
|
<p>You can test different print settings. Trying to visualize, but I believe you can increase the <strong>perimeter lines</strong>, since there is a hole, this will increase the resistance in that area. Or try to change the <strong>orientation</strong> with which the part will be printed</p>
|
<p>You can use a washer between the screw head and the plastic material to distribute the load</p>
<p>In my designs I also put in a depression to fit the washer so that it sits flush with the resultant surface. </p>
<p><a href="https://i.stack.imgur.com/2Mh31.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Mh31.png" alt="Cad design with recessed washer holes"></a></p>
| 1,198
|
<p>Anyone know of an opensource PHP Load Testing Framework similar to the Grinder " "<a href="http://grinder.sourceforge.net/" rel="nofollow noreferrer">http://grinder.sourceforge.net/</a>". </p>
|
<p>I haven't used the grinder, but It sounds similar to <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">JMeter</a>. Also at times I have used plain old <a href="http://selenium-rc.openqa.org/" rel="nofollow noreferrer">Selenium</a> for load testing.</p>
|
<p>RedLine has a <a href="http://www.redline13.com" rel="nofollow">Cloud Load Testing</a> tool in PHP on Amazon AWS now. it is free for the service, but you have to pay for the Spot Instances on your account (for example 50,000 user test on 200 m1.small is about $2/hour).</p>
| 31,228
|
<p>My colleagues and I have tried to build a project containing several thousand classes , but we're getting a LNK1102 error ( Linker out of memory ) . I've seen several tips on the internet , such as increasing the virtual memory . We tried but this didn't help . We've also seen some as enabling different warning levels when compiling the code . A guy suggested enabling level 4 for warnings .
How could that be done ? Are there other suggestions ?</p>
|
<p>Project (right click) → Properties → Configuration Properties → Linker → Optimization → References → change to <strong>Keep Unreferenced Data</strong></p>
<p>Worked on my machine!</p>
|
<p>Run the 64 bits version of the Linker? Downside: you'll get a amd64 executable.
(Unlike the 32->64 crosscompilation toolset, there is no 64->32 bit toolset)</p>
| 20,970
|
<p>I have a syntax highlighting function in vb.net. I use regular expressions to match "!IF" for instance and then color it blue. This works perfect until I tried to figure out how to do comments. </p>
<p>The language I'm writing this for a comment can either be if the line starts with a single quote ' OR if anywhere in the line there is two single quotes</p>
<pre><code>'this line is a comment
!if StackOverflow = "AWESOME" ''this is also a comment
</code></pre>
<p>Now i know how to see if it starts with a single line ^' but i need to to return the string all the way to the end of the line so i can color the entire comment green and not just the single quotes.</p>
<p>You shouldn't need the code but here is a snippet just in case it helps. </p>
<pre><code> For Each pass In frmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)
rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))
Next
PassNumber += 1
Next
</code></pre>
|
<p>Something along the lines of:</p>
<pre><code>^(\'[^\r\n]+)$|(''[^\r\n]+)$
</code></pre>
<p>should give you the commented line (of part of the line) in group n° 1</p>
<p>Actually, you do not even need group</p>
<pre><code>^\'[^\r\n]+$|''[^\r\n]+$
</code></pre>
<p>If it finds something, it is a comment.</p>
<pre><code>"(^'|'').*$"
</code></pre>
<p>mentioned by Boaz would work if applied only line by line (which may be your case).<br>
For multi-line detection, you must be sure to avoid the 'Dotall' mode, where '.' stands also for \r and \n characters. Otherwise that pattern would match both your lines entirely.</p>
<p>That is why I generally prefer <code>[^\r\n]</code> to '.': it avoids any dependency to the mode of the pattern. Even in 'Dotall' mode, it still works and avoids trying any match on the next line.</p>
|
<p>Using the regex pattern: REM((\t| ).*$|$)|^\'[^\r\n]+$|''[^\r\n]+$</p>
<p>see more <a href="https://code.msdn.microsoft.com/How-to-find-code-comments-9d1f7a29/" rel="nofollow">https://code.msdn.microsoft.com/How-to-find-code-comments-9d1f7a29/</a></p>
| 40,194
|
<p>I want to create an MSI in WiX such that it can take a command line parameter to indicate whether it is a per-machine or per-user installation and consequently whether to raise a UAC dialog.</p>
<p>What is the best way to accomplish this?</p>
|
<p>This is the link for per-machine/per-user from <a href="http://msdn.microsoft.com/en-us/library/aa371865(VS.85).aspx" rel="nofollow noreferrer">MSDN</a>.</p>
<p>so to change the values from the command line parameter, you'll need something like so:</p>
<p>msiexec /i myinstaller.msi ALLUSERS=[1|2]</p>
<p>Also, have a look at this <a href="http://www.mail-archive.com/wix-users@lists.sourceforge.net/msg07066.html" rel="nofollow noreferrer">link</a> from wix-users</p>
|
<p>The UAC dialog is controlled by a bit in the SummaryInformation stream. That, unfortunately, means it cannot be controlled at "run time" (install/repair/uninstall). You have to build different MSI files to truly change the UAC prompt.</p>
| 40,620
|
<p>I'm looking for publications about the history of the internet browsers. Papers, articles, blog posts whatever. Cannot find anything on ACM IEEE etc. and my blog search also didn't reveal anything remarkable.</p>
|
<p>Did you take a look at the entries in Wikipedia? It's a useful starting point.</p>
<p>Here are a few to start you off:</p>
<p><a href="http://en.wikipedia.org/wiki/Web_browser" rel="nofollow noreferrer">Wikipedia - Web browser</a></p>
<p><a href="http://en.wikipedia.org/wiki/Timeline_of_web_browsers" rel="nofollow noreferrer">Wikipedia - Timeline of web browsers</a></p>
<p><a href="http://en.wikipedia.org/wiki/Browser_war" rel="nofollow noreferrer">Wikipedia - Browser Wars</a></p>
|
<p>I would start with Wikipedia as Eward mentioned.</p>
<p>But after you read wikipedia, check the bottom of the articles for the sources used. Then read those sources. If this is for a school paper I doubt you'll get full points for using wikipedia.</p>
| 13,883
|
<p>How do I discover how many bytes have been sent to a TCP socket but have not yet been put on the wire?</p>
<p>Looking at the diagram here:
<a href="https://i.stack.imgur.com/pHB5a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pHB5a.png" alt="http://www.tcpipguide.com/free/diagrams/tcpswpointers.png"></a></p>
<p>I would like to know the total of Categories 2, 3, and 4 or the total of 3 and 4. This is in C(++) and on both Windows and Linux. Ideally there is a ioctl that I could use, but there doesn't seem to be any. </p>
|
<p>Under Linux, see the man page for tcp(7).</p>
<p>It appears that you can get the number of untransmitted bytes by ioctl(sock,SIOCINQ ...</p>
<p>Other stats might be available from members of the structure given back by the TCP_INFO getsockopt() call.</p>
|
<p>Some Unix flavors may have an API way to do this, but there is no way to do it that is portable across different variants.</p>
| 13,119
|
<p>I have a helper method has been created which allows a MovieClip-based class in code and have the constructor called. Unfortunately the solution is not complete because the MovieClip callback <b>onLoad()</b> is never called. </p>
<p>(Link to the <a href="http://www.flashdevelop.org/community/viewtopic.php?f=13&t=458" rel="nofollow noreferrer">Flashdevelop thread</a> which created the method .)</p>
<p>How can the following function be modified so both the <b>constructor</b> and <b>onLoad()</b> is properly called.</p>
<pre><code> //------------------------------------------------------------------------
// - Helper to create a strongly typed class that subclasses MovieClip.
// - You do not use "new" when calling as it is done internally.
// - The syntax requires the caller to cast to the specific type since
// the return type is an object. (See example below).
//
// classRef, Class to create
// id, Instance name
// ..., (optional) Arguments to pass to MovieClip constructor
// RETURNS Reference to the created object
//
// e.g., var f:Foo = Foo( newClassMC(Foo, "foo1") );
//
public function newClassMC( classRef:Function, id:String ):Object
{
var mc:MovieClip = this.createEmptyMovieClip(id, this.getNextHighestDepth());
mc.__proto__ = classRef.prototype;
if (arguments.length > 2)
{
// Duplicate only the arguments to be passed to the constructor of
// the movie clip we are constructing.
var a:Array = new Array(arguments.length - 2);
for (var i:Number = 2; i < arguments.length; i++)
a[Number(i) - 2] = arguments[Number(i)];
classRef.apply(mc, a);
}
else
{
classRef.apply(mc);
}
return mc;
}
</code></pre>
<p>An example of a class that I may want to create:</p>
<pre><code>class Foo extends MovieClip
</code></pre>
<p>And some examples of how I would currently create the class in code:</p>
<pre><code>// The way I most commonly create one:
var f:Foo = Foo( newClassMC(Foo, "foo1") );
// Another example...
var obj:Object = newClassMC(Foo, "foo2") );
var myFoo:Foo = Foo( obj );
</code></pre>
|
<p>Do I understand correctly that you want to create an instance of an empty movie clip with class behavior attached and without having to define an empty clip symbol in the library?</p>
<p>If that's the case you need to use the packages trick. This is my base class (called View) that I've been using over the years and on hundreds of projects:</p>
<pre><code>import mx.events.EventDispatcher;
class com.tequila.common.View extends MovieClip
{
private static var _symbolClass : Function = View;
private static var _symbolPackage : String = "__Packages.com.tequila.common.View";
public var dispatchEvent : Function;
public var addEventListener : Function;
public var removeEventListener : Function;
private function View()
{
super();
EventDispatcher.initialize( this );
onEnterFrame = __$_init;
}
private function onInitialize() : Void
{
// called on the first frame. Event dispatchers are
// ready and initialized at this point.
}
private function __$_init() : Void
{
delete onEnterFrame;
onInitialize();
}
private static function createInstance(symbolClass, parent : View, instance : String, depth : Number, init : Object) : MovieClip
{
if( symbolClass._symbolPackage.indexOf("__Packages") >= 0 )
{
Object.registerClass(symbolClass._symbolPackage, symbolClass);
}
if( depth == undefined )
{
depth = parent.getNextHighestDepth();
}
if( instance == undefined )
{
instance = "__$_" + depth;
}
return( parent.attachMovie(symbolClass._symbolPackage, instance, depth, init) );
}
public static function create(parent : View, instance : String, depth : Number, init : Object) : View
{
return( View( createInstance(_symbolClass, parent, instance, depth, init) ) );
}
}
</code></pre>
<p>So, all you have to do to use this class is to subclass it:</p>
<pre><code>class Foo extends View
{
private static var _symbolClass : Function = Foo;
private static var _symbolPackage : String = "__Packages.Foo";
private function Foo()
{
// constructor private
}
private function onInitialize() : Void
{
// implement this to add listeners etc.
}
public static function create(parent : View, instance : String, depth : Number, init : Object) : Foo
{
return( Foo( createInstance(_symbolClass, parent, instance, depth, init) ) );
}
}
</code></pre>
<p>You can now create an instance of Foo like this;</p>
<pre><code>var foo : Foo = Foo.create( this );
</code></pre>
<p>Assuming that 'this' is some type of MovieClip or View.</p>
<p>If you need to use this with a library symbol then just leave out the __Packages prefix on the _symbolPackage member.</p>
<p>Hope this helps...</p>
|
<p>Do I understand correctly that you want to create an instance of an empty movie clip with class behavior attached and without having to define an empty clip symbol in the library?</p>
<p>If that's the case you need to use the packages trick. This is my base class (called View) that I've been using over the years and on hundreds of projects:</p>
<pre><code>import mx.events.EventDispatcher;
class com.tequila.common.View extends MovieClip
{
private static var _symbolClass : Function = View;
private static var _symbolPackage : String = "__Packages.com.tequila.common.View";
public var dispatchEvent : Function;
public var addEventListener : Function;
public var removeEventListener : Function;
private function View()
{
super();
EventDispatcher.initialize( this );
onEnterFrame = __$_init;
}
private function onInitialize() : Void
{
// called on the first frame. Event dispatchers are
// ready and initialized at this point.
}
private function __$_init() : Void
{
delete onEnterFrame;
onInitialize();
}
private static function createInstance(symbolClass, parent : View, instance : String, depth : Number, init : Object) : MovieClip
{
if( symbolClass._symbolPackage.indexOf("__Packages") >= 0 )
{
Object.registerClass(symbolClass._symbolPackage, symbolClass);
}
if( depth == undefined )
{
depth = parent.getNextHighestDepth();
}
if( instance == undefined )
{
instance = "__$_" + depth;
}
return( parent.attachMovie(symbolClass._symbolPackage, instance, depth, init) );
}
public static function create(parent : View, instance : String, depth : Number, init : Object) : View
{
return( View( createInstance(_symbolClass, parent, instance, depth, init) ) );
}
}
</code></pre>
<p>So, all you have to do to use this class is to subclass it:</p>
<pre><code>class Foo extends View
{
private static var _symbolClass : Function = Foo;
private static var _symbolPackage : String = "__Packages.Foo";
private function Foo()
{
// constructor private
}
private function onInitialize() : Void
{
// implement this to add listeners etc.
}
public static function create(parent : View, instance : String, depth : Number, init : Object) : Foo
{
return( Foo( createInstance(_symbolClass, parent, instance, depth, init) ) );
}
}
</code></pre>
<p>You can now create an instance of Foo like this;</p>
<pre><code>var foo : Foo = Foo.create( this );
</code></pre>
<p>Assuming that 'this' is some type of MovieClip or View.</p>
<p>If you need to use this with a library symbol then just leave out the __Packages prefix on the _symbolPackage member.</p>
<p>Hope this helps...</p>
| 19,063
|
<p>Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?</p>
<pre><code><Image Height="60" HorizontalAlignment="Right"
Margin="0,122,11,0" VerticalAlignment="Top" Width="60"
Source="Images/Fish128x128.png" Stretch="Fill"
RenderTransformOrigin="0.5,0.5" x:Name="fishImage">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform ScaleX="1" ScaleY="1"/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
</code></pre>
<p>I want to bind the ScaleX and ScaleY of the ScaleTransform element.</p>
<p>I'm getting a runtime error when I try to bind against a double property on my data context: </p>
<pre><code>Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]"
</code></pre>
<p>My binding looks like this:</p>
<pre><code><ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}"
ScaleY="{Binding Path=SelectedDive.Visibility}"/>
</code></pre>
<p>I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...</p>
<p>Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against...</p>
|
<p>ScaleTransform doesn't have a data context so most likely the binding is looking for SelectedDive.Visibility off it's self and not finding it. There is much in Silverlight xaml and databinding that is different from WPF... </p>
<p>Anyway to solve this you will want to set up the binding in code**, or manually listen for the PropertyChanged event of your data object and set the Scale in code behind.</p>
<p>I would choose the latter if you wanted to do an animation/storyboard for the scale change.</p>
<p>** i need to check but you may not be able to bind to it. as i recall if the RenderTransform is not part of an animation it gets turned into a matrix transform and all bets are off. </p>
|
<p>Ah I think I see your problem. You're attempting to bind a property of type Visibility (SelectedDive.Visibility) to a property of type Double (ScaleTransform.ScaleX). WPF/Silverlight can't convert between those two types.</p>
<p>What are you trying to accomplish? Maybe I can help you with the XAML. What is "SelectedDive" and what do you want to happen when its Visibility changes?</p>
| 4,697
|
<p>I have several small open-source projects that I wrote. All my attempts to find collaborators (looked on sourceforge.net and codeplex) failed miserably - I either couldn't find anyone, or I found people who either weren't interested or didn't contribute anything. Thus comes the question: how and where can I find people to work with (on open source stuff)?</p>
|
<p>The short answer is: Be awesome.</p>
<p>If your software really addresses a pain point and addresses it well, people will come to it on their own (assuming a reasonable amount of promotion on your part) via SourceForge/GitHub/etc., Google, and word of mouth. If you attract a critical mass of people who need what your software does and need it to have new features, collaborators will come.</p>
<p>Also: Stay active. If you haven't updated your code in 6 months, or if your page on SourceForge says your software has been in Alpha for a year, a lot of people are going to ignore it and move on to the next search result. Get the software to where it's ready for others to use, and maintain it.</p>
<p>The thing about Open Source is that it really has to grow organically - nobody's getting paid, nobody's under the threat of being fired - people have to <em>care about your software</em> for it to grow beyond what you can do. You're never going to get collaborators (or anyway, good ones) by soliciting for them - only by making something that a good programmer would find interesting to work with. </p>
|
<p><a href="http://www.builditwith.me" rel="nofollow">http://www.builditwith.me</a> also is an option if you're looking for designers and/or developers</p>
| 46,160
|
<p>During a discussion about security, a developer on my team asked if there was a way to tell if viewstate has been tampered with. I'm embarrassed to say that I didnt know the answer. I told him I would find out, but thought I would give someone on here a chance to answer first. I know there is some automatic validation, but is there a way to do it manually if event validation is not enabled?</p>
|
<p>EnableViewStateMac page directive</p>
|
<p>You might be able to do it manually, but you'd just be implementing the same algorithm that's already there for you. It's generally a bad idea to disable the ViewState validation on a page.</p>
| 9,431
|
<p>I want to embed a swf over a html page, like a floating video watching panel. I already have a swf file which will automatically adjust its size according to the browser size, and the swf file is partially transparent. I thought I can just add a div tag, make the position absolute and change z-index bigger, but that doesn't work because the swf just replaced everything that's on the page. </p>
<p>Here's what I did</p>
<pre><code><script>
swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0");
</script>
<body bgcolor="#000000">
<div id="header"></div>
<div id="shell">
things in my html
</div>
</body>
#header {
position:absolute;
z-index:100;
}
</code></pre>
<p>Any idea? Thanks.</p>
|
<p>Once you get your sizing to work properly you will need to set the <em>wmode</em> to <em>transparent</em> to be able to see what's behind the flash, if you don't it's background will be opaque.</p>
<p>This is a quick copypaste from the <a href="http://code.google.com/p/swfobject/wiki/documentation" rel="noreferrer">swfobject docs</a>, but it should get the point across:</p>
<pre><code><script type="text/javascript">
var flashvars = {};
var params = {wmode : "transparent"};
var attributes = {};
swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0","expressInstall.swf", flashvars, params, attributes);
</script>
</code></pre>
|
<p>I believe the problem with this is that the CSS doesn't work well with <code><object /></code> tags. The <code>swfobject.embedSWF</code> turns the <code><div id="header"></div></code> into an <code><object /></code> tag with a bunch of attributes that might be effecting the CSS. If you create a wrapper DIV around the header DIV and apply the CSS to the wrapper DIV, everything works better. You also need to add 100% width and height in the CSS. Here's the revised source:</p>
<pre><code><script>
swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0");
</script>
<body bgcolor="#000000">
<div id="wrapper">
<div id="header"></div>
</div>
<div id="shell">
things in my html
</div>
</body>
#wrapper {
position:absolute;
z-index:100;
width:100%;
height:100%;
}
</code></pre>
| 38,474
|
<p>I know about this question: <a href="https://stackoverflow.com/questions/100548/which-third-party-debug-visualizers-for-visual-studio-20052008-do-you-use">Which (third-party) debug visualizers for Visual Studio 2005/2008 do you use?</a></p>
<p>But I don't want to know what debug visualizers you use, I want to know which debug visualizers are <em>out</em> there.</p>
<p>I have only found Mole (<a href="http://www.codeproject.com/KB/macros/MoleForVisualStudioEdit.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/macros/MoleForVisualStudioEdit.aspx</a>), which is great. But there has to be plenty more out there?</p>
<p>Enlighten me.</p>
|
<p>From a quick web search...</p>
<p>There is the one referenced in the blog post from the related question:</p>
<ul>
<li><a href="http://blogs.msdn.com/dparys/archive/2007/10/23/das-debugger-visualizer-item-template.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/dparys/archive/2007/10/23/das-debugger-visualizer-item-template.aspx</a></li>
<li><a href="https://weblogs.asp.net/scottgu/linq-to-sql-debug-visualizer" rel="nofollow noreferrer">LINQ to SQL Debug Visualizer</a></li>
<li><a href="https://www.codeproject.com/Articles/24211/Graphics-Debugger-Visualizer" rel="nofollow noreferrer">Graphics Debug Visualizer</a></li>
<li><a href="https://web.archive.org/web/20200725224405/http://geekswithblogs.net/khanna/archive/2006/01/05/64903.aspx" rel="nofollow noreferrer">Windows Identity Debug Visualizer</a></li>
<li><a href="https://web.archive.org/web/20090813175627/http://blogs.conchango.com:80/howardvanrooijen/archive/2005/11/24/2424.aspx" rel="nofollow noreferrer">Conchango XML Debug Visualizer</a></li>
<li><a href="https://track.vcdc.com/proceed.php?domain=subsonicproject.com&hash=fff186fca48a5e41a363c0d2382a6966&u=eyJkb21haW4iOiJzdWJzb25pY3Byb2plY3QuY29tIiwiZG9tYWluX2lkIjoiNTY1MDg5OSIsImZvbGRlcl9pZCI6bnVsbCwibWlkIjoiMTUxIiwiZmlsdGVyX2lkIjpudWxsLCJhZHZlcnRpc2VyX2lkIjoiMTI4IiwidGFyZ2V0IjoiaHR0cDpcL1wveG1sLXY0LnB4ZmluZG9uZS5jb21cL2NsaWNrP2k9MFBHTmdQeXNqRDhfMCIsImlwX2FkZHJlc3MiOiIxNDMuMTc3LjE4Ni4xMTQiLCJ0eXBlIjoiamF2YV9yZWRpcmVjdCIsImJpZCI6IjAuMDIxNyJ9" rel="nofollow noreferrer">SubSonic Collections Debug Visualizer</a></li>
<li><a href="https://web.archive.org/web/20100130144420/http://www.codeplex.com:80/PoSHDebugVisualizer" rel="nofollow noreferrer">PowerShell Debug Visualizer</a></li>
<li><a href="https://web.archive.org/web/20100213062526/http://www.codeplex.com:80/XmlVisualizer" rel="nofollow noreferrer">Xml Visualizer v.2</a></li>
<li><a href="https://web.archive.org/web/20100125224103/http://www.codeplex.com:80/WCFVisualizer" rel="nofollow noreferrer">WCF Visualizers Tool</a></li>
<li><a href="https://web.archive.org/web/20100131044056/http://www.codeplex.com:80/dathanliblikdepo" rel="nofollow noreferrer">WPF Dependency Object Visualizer</a></li>
<li><a href="https://web.archive.org/web/20100324013610/http://www.codeplex.com:80/dbvisualizer" rel="nofollow noreferrer">DB Connection Visualizer</a></li>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/gzunino/" rel="nofollow noreferrer">Debugger Visualizer for BizTalk 2006: MessageContext</a></li>
<li><a href="https://web.archive.org/web/20140430153156/http://cs.rthand.com:80/blogs/blog_with_righthand/pages/Righthand-Dataset-Debugger-Visualizer.aspx" rel="nofollow noreferrer">DataSet Debug Visualizer</a></li>
<li><a href="https://devmatter.blogspot.com/2006/04/guid-debugger-visualizer-for-visual.html" rel="nofollow noreferrer">GUID Debug Visualizer</a></li>
<li><a href="https://web.archive.org/web/20090122050040/http://visualstudiogallery.com:80/ExtensionDetails.aspx?ExtensionID=f52d4c99-a49f-4d5e-9251-97669a15038d" rel="nofollow noreferrer">Debug Inspector</a></li>
<li><a href="https://web.archive.org/web/20171222180002/http://brushvisualizer.codeplex.com/" rel="nofollow noreferrer">WPF Brush Visualizer</a></li>
<li><a href="https://github.com/zspitz/ExpressionTreeVisualizer" rel="nofollow noreferrer">Expression Tree Visualizer</a></li>
<li><a href="https://github.com/zspitz/ANTLR4ParseTreeVisualizer" rel="nofollow noreferrer">ANTLR4 Parse Tree Visualizer</a></li>
<li><a href="https://github.com/zspitz/DateTimeVisualizer" rel="nofollow noreferrer">DateTime Visualizer</a></li>
</ul>
|
<p>There's also <a href="http://osherove.com/blog/2005/11/26/announcing-regex-kit-regular-expression-visualizers-for-vs-2.html" rel="nofollow">Regex Kit</a>, a regular expression debugger visualizer.</p>
| 33,787
|
<p>I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:</p>
<pre><code> for (int month = 0; month < 13; month++) {
GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
</code></pre>
|
<p>Based on <a href="https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437">marked23's</a> suggestion:</p>
<pre><code>public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
</code></pre>
|
<pre><code>public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1);
cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);
return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;
}
</code></pre>
| 10,183
|
<p>I am getting the following error when running a reporting services report.</p>
<pre><code>Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: XmlException
Exception message: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method.
</code></pre>
<p>I select a report, enter the parameters(the parameters look messed up) and then press view report. Then at the bottom the message "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings ..." shows up.</p>
<p>How do I fix this?</p>
|
<p>Check to see if your reporting server website has the correct local path folder. You might need to do an iisreset if it is not correct. </p>
|
<p>I have noticed this when using SSRS 2005 and running large reports containing XML data.</p>
<p>It would work when running say a monthly report, but give me this error when I ran a quarterly report.</p>
<p>Upgrading to SQL/SSRS 2008 fixed the issue for me!</p>
| 12,360
|
<p>Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.</p>
<pre><code>
private TreeNode AddNodeForCore(TreeNode root, Core c) {
string key = GetImageKey(c);
TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key);
t.Tag = c;
return t;
}
</code></pre>
<p>Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.</p>
<p>Edit:<br>
My google-fu is weak. Can't believe I didn't find that answer myself.</p>
|
<p>The helpful bit of the googled posts above is in fact:</p>
<p>"This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Program.cs avoids this. Thanks for posting back!"</p>
<p>So basically, guarantee that Application.EnableVisualStyles() is called before you initialise your imagelist.</p>
|
<p>The solution posted by Yossarian nor the popular "Call Application.DoEvents() between Application.EnableVisualStyles() and Application.Run()" worked for me.</p>
<p>After much flailing, gnashing of teeth, and Googling, the solution posted by <a href="http://blogs.msdn.com/asanto/archive/2004/08/18/216825.aspx" rel="nofollow noreferrer">Addy Santo</a> did the trick.</p>
| 15,306
|
<p>Let's just assume for now that you have narrowed down where the typical bottlenecks in your app are. For all you know, it might be the batch process you run to reindex your tables; it could be the SQL queries that runs over your effective-dated trees; it could be the XML marshalling of a few hundred composite objects. In other words, you might have something like this:</p>
<pre><code>public Result takeAnAnnoyingLongTime(Input in) {
// impl of above
}
</code></pre>
<p>Unfortunately, even after you've identified your bottleneck, all you can do is chip away at it. No simple solution is available.</p>
<p>How do you measure the performance of your bottleneck so that you know your fixes are headed in the right direction?</p>
|
<p>Two points:</p>
<ol>
<li><p>Beware of the infamous "optimizing the idle loop" problem. (E.g. see the <a href="http://c2.com/cgi/wiki/wiki?OptimizationStories" rel="noreferrer">optimization story</a> under the heading "Porsche-in-the-parking-lot".) That is, just because a routine is taking a significant amount of time (as shown by your profiling), don't assume that it's responsible for slow performance as perceived by the user.</p></li>
<li><p>The biggest performance gains often come not from that clever tweak or optimization to the implementation of the algorithm, but from realising that there's a better algorithm altogether. Some improvements are relatively obvious, while others require more detailed analysis of the algorithms, and possibly a major change to the data structures involved. This may include trading off processor time for I/O time, in which case you need to make sure that you're not optimizing only one of those measures.</p></li>
</ol>
<p>Bringing it back to the question asked, make sure that whatever you're measuring represents what the user actually experiences, otherwise your efforts could be a complete waste of time. </p>
|
<p>It's an interesting question. I don't think anyone knows the answer. I believe that significant part of the problem is that for more complicated programs, no one can predict their complexity. Therefore, even if you have profiler results, it's very complicated to interpret it in terms of changes that should be made to the program, because you have no theoretical basis for what the optimal solution is.</p>
<p>I think this is a reason why we have so bloated software. We optimize only so that quite simple cases would work on our fast machines. But once you put such pieces together into a large system, or you use order of magnitude larger input, wrong algorithms used (which were until then invisible both theoretically and practically) will start showing their true complexity.</p>
<p>Example: You create a string class, which handles Unicode. You use it somewhere like computer-generated XML processing where it really doesn't matter. But Unicode processing is in there, taking part of the resources. By itself, the string class can be very fast, but call it million times, and the program will be slow. </p>
<p>I believe that most of the current software bloat is of this nature. There is a way to reduce it, but it contradicts OOP. There is an interesting book <a href="http://www.cix.co.uk/~smallmemory/book.html" rel="nofollow noreferrer">There is an interesting book</a> about various techniques, it's memory oriented but most of them could be reverted to get more speed.</p>
| 20,017
|
<p>I was wondering if something exists (in Java world) able to take an snapshot of the JVM current state with the following features:</p>
<ul>
<li>Do it while an exception is being thrown.</li>
<li>Capture local variables, method's arguments, etc.</li>
<li>Put it in a handy file which can be used to extract or reproduce in a IDE the situation in your source code.</li>
</ul>
<p>The two first features are required (third would be awesome). And it must be suitable for production use (so, there is no way about debuggers).</p>
<p>Before asking this I've searched through the WWW (as long as possible) and I found some pointers:</p>
<ul>
<li><a href="http://www.cajoon.com" rel="nofollow noreferrer">Cajoon Interceptor</a>: As said in <a href="http://www.dzone.com/links/java_production_errors_rapid_resolution.html" rel="nofollow noreferrer">Dzone post</a>, it's a passive JVM agent which fulfill the three requirements! But, it has two downsides: you must pay for it and the site is down (maybe there is no chance to pay anything).</li>
<li><a href="http://www.avicode.com/" rel="nofollow noreferrer">AviCode Intercept Studio</a>: Cajoon's .NET equivalent. Just to give some insight about.</li>
<li><a href="http://twitter.com/thobe/status/1012650896" rel="nofollow noreferrer">JavaFrame</a>: Ok, it's a tweet, but it points to a available SVN repo which have the source code (under MIT license) of a JVM agent which looks fine (I'm going to give a try to it).</li>
</ul>
<p>So, maybe I'm looking for a non existent solution? It's not urgent, but I had this idea for a project and it would be great to explore this "unknown" (?) path and get something real.</p>
<p>It seems to be clear that it would be a JVM agent (exception event from JVMTI, for <a href="http://java.sun.com/developer/technicalArticles/Programming/jvmti/" rel="nofollow noreferrer">example</a>).</p>
<p>At last, I would highlight the followin paragraph from <a href="http://en.wikipedia.org/wiki/Exception_handling" rel="nofollow noreferrer">Wikipedia's Exception Handling article</a>:</p>
<blockquote>
<p>In runtime engine environments such as
Java or .NET, there exist tools that
attach to the runtime engine and every
time that an exception of interest
occurs, they record debugging
information that existed in memory at
the time the exception was thrown
(call stack and heap values). These
tools are called Automated Exception
Handling or Error Interception tools
and provide 'root-cause' information
for exceptions.</p>
</blockquote>
<p>That's the idea. I hope somebody can give me some insight or maybe, in the future, somebody get inspired by this humble post :)</p>
<p>Thanks!</p>
|
<p>I give a look to <a href="http://kenai.com/projects/jvm-frame-introspect" rel="nofollow noreferrer">JavaFrame</a> and it seems a good starting point. Just install Apache Ant, do <code>ant</code> in the javaframe directory and launch the test suite (inside test directory) with:</p>
<pre><code>LD_LIBRARY_PATH=../build/native/ java -agentlib:frameintrospect -classpath ../build/classes/:. org.thobe.frame.Test
</code></pre>
<p>It does not get any local variable but it tries. So, as I said, it can be an starting point. I hope to get further about its usage, but no time and no documentation (there are lots of projects named JavaFrame) are bad circumstances.</p>
<p>Maybe some day it can be done again. Yes, again. There was Cajoon, it looked promising and shiny but its website is down and there is no trace of any downloadable jar to try.</p>
<p>Thanks to everybody!</p>
<p>PD.: Just for reference, some links I found while researching:</p>
<ul>
<li><a href="http://blogs.oracle.com/kto/entry/using_vm_agents" rel="nofollow noreferrer">How VM Agents Work</a></li>
<li><a href="http://blogs.oracle.com/watt/resource/jvm-options-list.html" rel="nofollow noreferrer">JVM options</a></li>
</ul>
|
<p>Not sure if this is viable in a production environment, but there's the Omniscient debugger:</p>
<blockquote>
<p>What if your debugger could go "go backwards in time?" Would that make debugging easier? By simply recording all variable assignments, it is possible to do essentially this. This is the underlying idea for omniscient debugging. The amazing part is that significantly large programs can be debugged in this fashion -- Ant, JUnit, the debugger itself. </p>
</blockquote>
<p><a href="http://www.lambdacs.com/debugger/" rel="nofollow noreferrer">http://www.lambdacs.com/debugger/</a></p>
| 48,704
|
<p>For various reasons calling <code>System.exit</code> is frowned upon when writing <strong>Java Applications</strong>, so how can I notify the calling process that not everything is going according to plan?</p>
<p><strong>Edit:</strong> The 1 is a <code>standin</code> for any non-zero exit code.</p>
|
<p>The use of <code>System.exit</code> is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the <code>System.exit</code> could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.</p>
<p>If the java application is really meant to be run as a standalone application, there is nothing wrong with using <code>System.exit</code>. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.</p>
|
<p>It's frowned upon for <em>normal</em> exits. If "not everything is going according to plan", then System.exit is fine.</p>
<p>Update: I should add that I assume your '1' has meaning that is documented somewhere.</p>
| 5,279
|
<p><a href="http://oreilly.com/catalog/9780596515829/" rel="nofollow noreferrer">Python for Unix and Linux System Administration</a> is aimed at sysadmins.
Any other favorites besides this.</p>
|
<p>Mark Pilgrim's <a href="http://www.diveintopython.net/" rel="nofollow noreferrer">http://www.diveintopython.net/</a> is very good and clear.</p>
|
<p>I started with Mark Lutz's Programming Python (O'Reilly).</p>
| 20,717
|
<p>Yet again, my teacher was unable to answer my question. I knew who may be able to...</p>
<p>So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put </p>
<pre><code>setbuf( stdout , NULL );
</code></pre>
<p>at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.</p>
<p>My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? </p>
<p>Thanks in advance!</p>
|
<p>By default, iostreams and stdio are synchronised. <a href="http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio" rel="nofollow noreferrer">Reference.</a></p>
<p>This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise <code>std::endl</code> or <code>std::flush</code> (from <code><ostream></code>), which may help you. e.g.,</p>
<pre><code>std::cout << "Hello, world!" << std::endl;
</code></pre>
<p>or</p>
<pre><code>std::cout << "Hello, world!\n" << std::flush;
</code></pre>
<p>Both of these do the same thing. (<a href="http://en.cppreference.com/w/cpp/io/manip/endl" rel="nofollow noreferrer"><code>std::endl</code></a> = print endline, then flush.)</p>
|
<p>Usually, when it's important to see the output immediately, we're talking about complex highly-reliable financial routine that must log a transaction all the way to hard drive before actually sending it to counterparty. Or, (much more common case) we want to see debug messages even when the program is crashing.</p>
<p>Since you're studying, I'll assume you're dealing with the second case. In that case, my advice would be to use stderr rather than stdout. It is unbuffered by default, and you can redirect it separately from stdout, putting your output in one place and your logging in another.</p>
| 18,901
|
<p>I know Microsoft has made efforts in the direction of semantic and cross-browser compliant XHTML and CSS, but it still seems like a PitA to pull off elegant markup. I've downloaded and tweaked the CSS Friendly Adapters and all that. But I still find myself frustrated with bloated and unattractive code.</p>
<p>Is elegant, semantic CSS with ASP.Net still a pipe dream? Or is it finally possible, I just need more practice?</p>
|
<p>The easiest way to generate elegant HTML and CSS is to use MVC framework, where you have much more control over HTML generation than with Web Forms.</p>
|
<p>As long as you use the Visual Studio designer, it's probably a pipe dream. I write all of my ASP.NET code (all markup, and CSS) by hand, simply to avoid the designer. Later versions of Visual Studio have gotten much better at not mangling your .aspx/.ascx files, but they're still far from perfect.</p>
| 5,323
|
<p>How does the HttpBrowserCapabilities.Crawler property (<a href="http://msdn.microsoft.com/en-us/library/aa332775(VS.71).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa332775(VS.71).aspx</a>) work? I need to detect a partner's custom crawler and this property is returning false. </p>
<p>Where/How can I add his user agent so that this property will return true? Any other way outside of creating my own user agent detecting mechanism?</p>
|
<p>This is all driven by the default browsercaps declarations that are part of the .NET framework.</p>
<p>To setup this specific crawler, you would need to add a custom browserCaps section to your web.config to identify it as a crawler.</p>
<p>The MSDN documentation on how to go about this is pretty well documented, <a href="http://msdn.microsoft.com/en-us/library/sk9az15a.aspx" rel="noreferrer">here is a link.</a></p>
|
<p>HttpBrowserCapabilities is populated from a set of *.browser files in C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers. You can add your own file in ~/App_Browsers/ with the details of your custom crawler. The schema is <a href="http://msdn.microsoft.com/en-us/library/ms228122.aspx" rel="nofollow noreferrer">here</a>. Basically it contains a regular expression to match against the User-Agent header and a collection of property values.</p>
| 27,461
|
<p>I've been doing some performance testing around the use of System.Diagnostics.Debug, and it seems that all code related to the static class Debug gets completely removed when the Release configuration is built. I was wondering how the compiler knows that. Maybe there is some class or configuration attribute that allows to specify exactly that behavior.</p>
<p>I am trying to create some debugging code that I want completely removed from the Release configuration, and I was wondering if I could do it just like the Debug class where simply changing the configuration parameters removes the code.</p>
|
<p>You can apply the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=netframework-4.8" rel="nofollow noreferrer">ConditionalAttribute</a> attribute, with the string "DEBUG" to any method and calls to that item will only be present in DEBUG builds.</p>
<p>This differs from using the #ifdef approach as this allows you to release methods for use by other people in their DEBUG configurations (like the Debug class methods in the .NET framework).</p>
|
<p>Have a look at <a href="http://www.csharphelp.com/archives/archive36.html" rel="nofollow noreferrer">preprocessor directives</a>...</p>
<pre><code>#if DEBUG
//code
#endif
</code></pre>
| 43,785
|
<p>Any ideas on how to disable, but not uninstall Resharper 4.x or above?</p>
|
<p>You can disable ReSharper 4 and lower using the Visual Studio Add-In Manager (remove the check from check box on the left).</p>
<p>In ReSharper 5 and above (tested up to version 7.0.1), <a href="https://stackoverflow.com/questions/253063/disable-but-not-uninstall-resharper-4-x/1900927#1900927">this is how you can suspend</a> ReSharper from the Tools > Options > Resharper
<img src="https://i.stack.imgur.com/eT81q.png" alt="alt text"></p>
|
<p>You can also press Ctrl+8.</p>
| 31,542
|
<p>I'm trying to compile a project and I'm getting this error.</p>
<p>The error occurs in a RemObjects source file, but I think it doesn't have anything to do with RemObjects.</p>
<p>Anyway this error is too generic, and I don't quite get why it happens, so how can I solve it?</p>
|
<p>The problem was that we translated the unit SysConsts and the Interface changed, removing that unit solved the problem.</p>
|
<p>This error occurs if you mix libraries. You are probably using a (third-party) library that is compiled with a different version. Try to get the latest version, or recompile if you have the source.</p>
<p>If the problem persists, try to get a minimal subset of the project to find the offending unit / dcu file.</p>
| 33,709
|
<p>I'm working on a page has an ol with nested p's, div's, and li's. Internet Explorer 6 and 7 both render the numbers for the ol tag after the p element at the end (at the very, very bottom of the li tag) rather than at the top of the outermost li as expected. I'm working on a PowerPC Mac and can't do any testing. Is there some simple CSS hack to make this render the same as it does in Firefox?</p>
<p>You can view the live page <a href="http://www.taxminimiser.com/beta/whats_included.php" rel="nofollow noreferrer">here</a>. I know, I'm working on positioning the sidebar. Ignore that for now.</p>
<p>Markup is as follows:</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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/global.css" />
<link rel="stylesheet" type="text/css" href="css/whats_included.css" />
<script type="text/javascript" src="script/compliant_target_blank.js"></script>
<!--[if lte IE 5]>
<script type="text/javascript" src="script/ie_5_unsupported_warning.js"></script>
<![endif]-->
<!--[if gt IE 5]>
<link rel="stylesheet" type="text/css" href="css/ie_hacks/global.css" />
<![endif]-->
<title>
The Daily Plan-It, LLC - Home of the Tax MiniMiser
</title>
</head>
<body>
<?php include("includes/nav_bar.php") ?>
<div id="content">
<img src="images/title.png" alt="Tax MiniMiser Financial Tracking System" />
<div id="bordered_wrapper">
<h1>Here's What You Get With The Tax MiniMiser!</h1>
<h2>24 Envelopes, 7-hole punched to fit one-at-a-time in your binder</h2>
<ol>
<li class="main_item">
Business Income &amp; Expense Record
<div class="preview_image">
<a href="previews/large/bier/front.html" rel="external">
<img src="images/small_previews/large/bier_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes with all the income &amp; expense columns you need to transform your planner or binder into a daily tax journal!</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the &quot;20 Column Heading Guidelines&quot;, <a href="files/downloads/20_column_heading_guidelines.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Vehicle Mileage &amp; Expense Record
<div class="preview_image">
<a href="previews/large/vme/front.html" rel="external">
<img src="images/small_previews/large/mileage_preview.jpg" alt=""/><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>12 receipt envelopes to track your daily mileage and vehicle expenses. Keep one envelope in each vehicle used for your business(es).</li>
<li>Store daily receipts in the convenient pocket envelopes.</li>
</ul>
</div>
<p>To get a free copy of the &quot;Instructions for Vehicle Mileage &amp; Expense Record&quot;, <a href="files/downloads/vehicle_record_instructions.pdf">click here</a> or call our Fax-on-Demand line at 888-829-8237.</p>
</li>
<li class="main_item">
Annual Business Summary of Income and Expense
<div class="preview_image">
<a href="previews/large/cover/inside.html" rel="external">
<img src="images/small_previews/large/cover_inside_preview.jpg" alt="" /><br/>
Click to Preview!
</a>
</div>
<div class="details">
<ul>
<li>Enter the subtotals from all the envelopes throughout the year. Then you and your tax pro can figure out profitability and taxes to maximize your deductions and legally minimize your taxes.</li>
</ul>
</div>
</li>
</ol>
<p class="end">To see previews of the small (6&quot; x 8&frac12;&quot;) Tax MiniMisers, visit their respective pages <a href="products.php">here.</a></p>
</div>
</div>
<?php include("includes/footer.php") ?>
</body>
</html>
</code></pre>
<p>And the CSS:</p>
<pre><code>#content {
background-color: white;
}
#bordered_wrapper {
margin-left: 26px;
background: top left no-repeat url(../images/borders/yellow-box-top.gif);
}
#bordered_wrapper h1, #bordered_wrapper h2 {
margin-left: 20px;
}
#bordered_wrapper h1 {
padding-top: 15px;
margin-bottom: 0;
}
#bordered_wrapper h2 {
margin-top: 0;
font-size: 1.3em;
}
ol {
font-size: 1.1em;
}
ul {
list-style-type: disc;
}
li.main_item {
width: 700px;
clear: right;
}
li p {
clear: both;
margin-bottom: 20px;
}
.preview_image {
width: 200px;
float: right;
text-align: center;
margin-bottom: 10px;
}
.preview_image a {
text-decoration: none;
}
.preview_image img {
border-style: none;
}
.end {
clear: right;
padding-bottom: 25px;
padding-left: 20px;
background: bottom left no-repeat url(../images/borders/yellow-box-bottom.gif);
}
</code></pre>
|
<p>Congratulations, you are the victim of IE's <a href="http://msdn.microsoft.com/en-us/library/ms533776.aspx" rel="noreferrer">hasLayout</a> property.</p>
<p>Short version: You've got it easy this time. Changes these rules:</p>
<pre><code>...
ol {
font-size: 1.1em;
}
...
li.main_item {
width: 700px;
clear: right;
}
...
</code></pre>
<p>To this:</p>
<pre><code>...
ol {
font-size: 1.1em;
width: 700px;
}
...
li.main_item {
clear: right;
}
...
</code></pre>
<p>And it's all good.</p>
<p>Longer version: When you apply certain CSS rules to certain elements, IE 5.5+ gives those elements a property called "hasLayout" that changes how that element is rendered. Since hasLayout was a read-only property with no apparent purpose, it took quite a while before web designers caught on to the issue. Older sites (even Quirksmode.org!) still has pages that suggest twiddling padding, margins, or even using Javascript to fix these issues. If you can at all help it, don't do these things. Instead, see if you can find out what element is incorrectly being given hasLayout, and change the offending CSS so that the element no longer gets hasLayout. If that totally borks your page, use <a href="http://www.quirksmode.org/css/condcom.html" rel="noreferrer">conditional comments</a> to fix it just for IE. Here are some CSS rules that add "hasLayout" to an element that doesn't already have it:</p>
<ul>
<li>position: absolute</li>
<li>float: left|right</li>
<li>display: inline-block</li>
<li>height: any value other than 'auto'</li>
<li>zoom: any value other than 'normal' (MS proprietary)</li>
<li>writing-mode: tb-rl (MS proprietary)</li>
</ul>
<p>As of IE7, overflow became a trigger for hasLayout.</p>
<ul>
<li>overflow: hidden|scroll|auto</li>
</ul>
<p>Longest version: read the following articles.</p>
<ol>
<li>Here's all the neat things Microsoft would like you do <a href="http://msdn.microsoft.com/en-us/library/bb250481.aspx" rel="noreferrer">by triggering "hasLayout"</a>. </li>
<li>Here's the clean-language version of <a href="http://www.satzansatz.de/cssd/onhavinglayout" rel="noreferrer">what web designers thought about hasLayout</a> when they found out what was going on. Some of the same content, but includes CSS hacks and stuff.</li>
</ol>
|
<p>I just tested your example html in firefox 3/webkit nightly/internet explorer 7 and all of them rendered exactly the same with the number at the top where it should be.</p>
<p>The problem is probably in your CSS, can you show us the actual page that is broken?</p>
| 13,552
|
<p>Let's say we have these tables;</p>
<p>table user:<br>
- id<br>
- username<br>
- email</p>
<p>table user2group:<br>
- userid<br>
- groupid</p>
<p>table group:<br>
- id<br>
- groupname</p>
<p>How do I make one query that returns all users, and the groups they belong to (as an array in the resultset or something..)</p>
|
<pre><code>select u.id, u.username, u.email, g.groupid, g.groupname
from user u
join user2group ug on u.userid=ug.userid
join group g on g.groupid=ug.groupid
order by u.userid
</code></pre>
<p>As you are looping through the result set, each time you see a new userid make a new user object (or whatever) and add the groups to it.</p>
|
<p>Both of the above are more or less correct (deepends if each user has a group or not). But they will also both give a result set with several entries for each user.</p>
<p>There are ways of concatenating every group member into one comma separated string, I'd suggest you read about it here:
<a href="http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/" rel="nofollow noreferrer">http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/</a></p>
<p>Another method I personally like is to use bit values instead of the relational table user2group</p>
<p>table user then gets a int (or bigint) field group, and each group ID is assigned one bit value (ie: 1,2,4,8,16 and so on) The value of the user table's group field is then the sum of the groupID it's assigned to. To query if its got a group you do:
where (group AND groupID = groupID)</p>
| 36,172
|
<p>Is it possible to make FlexBuilder show all compile errors in all files? FlexBuilder does not show errors in Action Script files, that are not referenced. Also very often I fix a problem just to see new problems pop up after compiling the whole project although these errors existed long before.</p>
<p>IntelliJ is showing all compile errors it can find and I would like to have FlexBuilder behaving the same way since IntelliJ is not mature enough to handle our complex set up. Is there a compiler switch to enable this?</p>
|
<p>The compiler can (and will) show errors only in code that you tell it to compile, and like you said, whatever is not referenced in the code you compile, will not be compiled, and thus, checked by the compiler.</p>
<p>So if you want to have the compiler check some part of your code, you need to tell it to compile it. I'm not sure how your projects are set up, but I'm assuming that you're compiling a bunch of smaller projects that are all using different parts of a shared codebase (or something similar.) In this case, you could either:</p>
<ul>
<li>set up some sort of "master" project that references all of your code, compiling which would then check for errors everywhere (maybe you have this already, in which case the solution is simply to compile this regularly)</li>
<li>set up a job/target for compiling the AsDoc documentation for all of your code -- you could then run this regularly and at the same time you'd be keeping your API docs up to date</li>
</ul>
|
<p>The following MXMLC compiler arguments might be useful:</p>
<p><strong>-includes <em>className</em> [...]</strong></p>
<p>Links one or more classes into the output SWF, regardless of whether they are required at compile time.</p>
<p><strong>-include-libraries <em>swcPath</em> [...]</strong></p>
<p>Links the entire contents of one or more SWC libraries into the output SWF, regardless of whether its classes are required at compile time.</p>
| 46,403
|
<p>How can I change the width of a textarea form element if I used ModelForm to create it?</p>
<p>Here is my product class:</p>
<pre><code>class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
</code></pre>
<p>And the template code...</p>
<pre><code>{% for f in form %}
{{ f.name }}:{{ f }}
{% endfor %}
</code></pre>
<p><code>f</code> is the actual form element...</p>
|
<p><strong>The easiest way for your use case is to use CSS</strong>. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.</p>
<p>Example for <code>long_desc</code> field in your ProductForm (when your form does not have a custom prefix):</p>
<pre><code>#id_long_desc {
width: 300px;
height: 200px;
}
</code></pre>
<p><strong>Second approach</strong> is to pass the <code>attrs</code> keyword to your widget constructor.</p>
<pre><code>class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
</code></pre>
<p>It's <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs" rel="noreferrer">described in Django documentation</a>.</p>
<p><strong>Third approach</strong> is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.</p>
<pre><code>class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
# Edit by bryan
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
self.fields['long_desc'].widget.attrs['cols'] = 10
self.fields['long_desc'].widget.attrs['rows'] = 20
</code></pre>
<p>This approach has the following advantages:</p>
<ul>
<li>You can define widget attributes for fields that are generated automatically from your model without redefining whole fields.</li>
<li>It doesn't depend on the prefix of your form.</li>
</ul>
|
<p>Set row and your css class in your admin model view:</p>
<pre><code>'explicacion': AutosizedTextarea(attrs={'rows': 5, 'class': 'input-xxlarge', 'style': 'width: 99% !important; resize: vertical !important;'}),
</code></pre>
| 13,563
|
<p>Is it valid to have a 'choice' of 'group' elements when defining an XML Schema (XSD)</p>
<p>i.e. is the following valid</p>
<pre><code><xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" />
<xs:choice minOccurs="1" maxOccurs="1">
<xs:group ref="ReservationGroup" />
<xs:group ref="CancellationGroup"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</code></pre>
<p>Where an XML message can represent, for example, either a new reservation or a cancellation of an existing reservation.</p>
<p>If the message is for a reservation, then it must include all the elements defined in the ReservationGroup group.</p>
<p>If it is a cancellation, then it must include all the elements defined in the CancellationGroup group.</p>
<p>For some reason, my XML editor (Eclipse) does not like this, but does not indicate why. It shows there being an error on the line <xs:complexType name="HeaderType"> but does not say what the error is</p>
|
<p>I'm no XML expert, although I use it quite a lot. This isn't the way I'd generally do this sort of structure. I would prefer a separate complex types rather than a choice of two groups (see the very end of this answer).</p>
<p>I suspect that the problem is that ReservationGroup and CancellationGroup start with the same element, in which case you will violate the Schema Component Constraint: Unique Particle Attribution (below).</p>
<p><a href="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig" rel="noreferrer" title="http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig">http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/#cos-nonambig</a></p>
<blockquote>
<p><strong>Schema Component Constraint: Unique
Particle Attribution</strong> </p>
<p>A content model
must be formed such that during
·validation· of an element information
item sequence, the particle component
contained directly, indirectly or
·implicitly· therein with which to
attempt to ·validate· each item in the
sequence in turn can be uniquely
determined without examining the
content or attributes of that item,
and without any information about the
items in the remainder of the
sequence.</p>
<p><strong>Note:</strong> This constraint
reconstructs for XML Schema the
equivalent constraints of [XML 1.0
(Second Edition)] and SGML. Given the
presence of element substitution
groups and wildcards, the concise
expression of this constraint is
difficult, see Analysis of the Unique
Particle Attribution Constraint
(non-normative) (§H) for further
discussion.</p>
</blockquote>
<p>For example, the two groups below are illegal in the same choice, because each of their first element is "name" which means that you cannot identify which group you are looking at. However is the first element of ReservationGroup is different from Cancellation group
(resDate and cancDate maybe), then the that is valid.</p>
<p><strong>Edit:</strong> I'd never come across this sort of problem before, and I think its fascinating that the definitions of the groups are totally legal, but if you put them together in a choice, that choice becomes illegal because of the definition of each group.</p>
<p><strong>Groups that cannot form a legal choice</strong></p>
<pre><code><xs:group name="ReservationGroup">
<xs:sequence>
<xs:element name="date"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
<xs:group name="CancellationGroup">
<xs:sequence>
<xs:element name="date"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
</code></pre>
<p><strong>Groups that can form a legal choice</strong></p>
<pre><code><xs:group name="ReservationGroup">
<xs:sequence>
<xs:element name="resDate"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
<xs:group name="CancellationGroup">
<xs:sequence>
<xs:element name="cancDate"/>
<xs:element name="name"/>
<xs:element name="address"/>
</xs:sequence>
</xs:group>
</code></pre>
<p>As I mentioned above, I'd do this sort of thing with complex types. Yes, it adds another element, but it seems the obvious way and I like obviousness.</p>
<pre><code><xs:complexType name="HeaderType">
<xs:sequence>
<xs:element name="reservation-number" type="ReservationNumberType" minOccurs="1" maxOccurs="1" nillable="false" />
<xs:choice minOccurs="1" maxOccurs="1">
<xs:element name="reservation" type="ReservationType" />
<xs:element name="cancellation" type="CancellationType" />
</xs:choice>
</xs:sequence>
</xs:complexType>
</code></pre>
|
<p>Whether this is valid depends on the content of the groups: if they're 'sequence' or 'choice' model groups, it's perfectly legal; 'all' model groups are more problematic and generally not allowed in this case.</p>
| 12,681
|
<p>I have a form that I would like to style. specifcally I would like to chnage the background color of the form item's label. (the backgorundColor attribute changes both the label and the inputs background color)</p>
<p>i.e.</p>
<pre>
<code>
<mx:Form>
<mx:FormItem label="username:">
<mx:TextInput />
</mx:FormItem>
</mx:Form>
</code>
</pre>
<p>I would like to make the label with 'username:' have a different background color, but have the text input still be the default background color. </p>
<p>is this possible with a FormItem ?</p>
|
<p>A formitem has an object it uses to display the label called the FormItemLabel, this objects purpose is so you can style the label of a form item.</p>
<p>In flex 2 to change the style you can try:</p>
<pre><code>FormItemLabel {
}
</code></pre>
<p>However I looked over the flex 2 lang ref and it doesn't seem like you can change the background color of the label. <a href="http://livedocs.adobe.com/flex/2/langref/mx/controls/FormItemLabel.html#styleSummary" rel="nofollow noreferrer">Click here for lang ref link</a></p>
<p>If you are using flex 3 the desired way to change the label of the FormItem is through the formitems labelStyleName</p>
<pre><code>FormItem {
labelStyleName: newStyle;
}
</code></pre>
<p>However once again I don't believe they added the ability to change the background color of the label itself. <a href="http://livedocs.adobe.com/flex/3/langref/mx/controls/FormItemLabel.html" rel="nofollow noreferrer">Click here for lang ref link</a></p>
<p>Best choice of action if this is required would be to extend the formitem class, unless anyone else has any ideas.</p>
<p>Hope this helps...</p>
|
<p>Try using the flex style explorers to create your desired style:</p>
<ul>
<li><p><a href="http://examples.adobe.com/flex3/consulting/styleexplorer/Flex3StyleExplorer.html" rel="nofollow noreferrer">Flex 3 Style Explorer</a></p></li>
<li><p><a href="http://examples.adobe.com/flex2/consulting/styleexplorer/Flex2StyleExplorer.html" rel="nofollow noreferrer">Flex 2 Style Explorer</a></p></li>
</ul>
<p>I used the TextArea in the style explorer and formatted the background color which gave the following css output:</p>
<pre><code>TextArea {
backgroundColor: #0000ff;
}
</code></pre>
<p>You can change this to the following to include in you stylesheet:</p>
<pre><code>.formLabel {
backgroundColor: #0000ff;
}
</code></pre>
<p>Then in the FormItem tag:</p>
<pre><code><FormItem label="Label" styleName="formLabel" />
</code></pre>
<p>More info on Flex Style Sheets:
<a href="http://www.adobe.com/devnet/flex/quickstart/styling_components/" rel="nofollow noreferrer">Flex Style Sheets</a></p>
<p>These examples will show that you can declare styles within the mxml Style tags rather than an external style sheet if you would like.</p>
| 21,066
|
<p>I want to find out if length property for Java arrays is an int/long or something else.</p>
|
<p>It is an int. See the <a href="http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7" rel="noreferrer">Java Language Specification</a>, section 10.7.</p>
|
<p>In JavaCard array indexes are shorts, but JavaCard is odd like that. Everywhere else, int like everyone else says.</p>
| 25,959
|
<p>In the documentation of hardware that allows us to control it via UDP/IP,
I found the following fragment:</p>
<blockquote>
<p>In this communication protocol, DWORD is a 4 bytes data, WORD is a 2 bytes data,
BYTE is a single byte data. The storage format is little endian, namely 4 bytes (32bits) data is stored as: d7-d0, d15-d8, d23-d16, d31-d24; double bytes (16bits) data is stored as: d7-d0 , d15-d8.</p>
</blockquote>
<p>I am wondering how this translates to C#?
Do I have to convert stuff before sending it over?
For example, if I want to send over a 32 bit integer, or a 4 character string?</p>
|
<p>C# itself doesn't define the endianness. Whenever you convert to bytes, however, you're making a choice. The <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx" rel="noreferrer">BitConverter</a> class has an <a href="http://msdn.microsoft.com/en-us/library/system.bitconverter.islittleendian.aspx" rel="noreferrer">IsLittleEndian</a> field to tell you how it will behave, but it doesn't give the choice. The same goes for BinaryReader/BinaryWriter.</p>
<p>My <a href="http://pobox.com/~skeet/csharp/miscutil" rel="noreferrer">MiscUtil</a> library has an EndianBitConverter class which allows you to define the endianness; there are similar equivalents for BinaryReader/Writer. No online usage guide I'm afraid, but they're trivial :)</p>
<p>(EndianBitConverter also has a piece of functionality which isn't present in the normal BitConverter, which is to do conversions in-place in a byte array.)</p>
|
<p>If you're parsing and performance is not critical, consider this very simple code:</p>
<pre><code>private static byte[] NetworkToHostOrder (byte[] array, int offset, int length)
{
return array.Skip (offset).Take (length).Reverse ().ToArray ();
}
int foo = BitConverter.ToInt64 (NetworkToHostOrder (queue, 14, 8), 0);
</code></pre>
| 26,808
|
<p>Java is one of my programming languages of choice. I always run into the problem though of distributing my application to end-users.</p>
<p>Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server.</p>
<p>What's the best way to distribute a Java application? What if the Java application needs to install artifacts to the user's computer? Are there any good Java installation/packaging systems out there?</p>
|
<p>There are a variety of solutions, depending on your distribution requirements.</p>
<ol>
<li><p>Just use a jar. This assumes that the user has the the correct java version installed, otherwise the user will get "class-file format version" exceptions. This is fine for internal distribution inside a company.</p></li>
<li><p>Use launch4j and an installer like NSIS. This gives you a lot more control, although the user can still do stupid stuff like un-installing the java runtime. This is probably the most popular approach, and what I currently use.</p></li>
<li><p>Use Webstart. This also assumes that the user has the correct java version installed, but it's a lot easier to get going. My experience is that this is fine for tightly controlled intranet environments, but becomes a pain with larger deployments because it has some many weird failures. It may get better with the new plug-in technology in Java 1.7.</p></li>
<li><p>Use a native-code compiler like Excelsior JET and distribute as a executable, or wrap it up in an installer. Expensive, and it generally ties you to a slightly older version of java, and there is some pain with dynamic class-loading, but its very effective for large-scale deployment where you need to minimise your support hassles.</p></li>
</ol>
|
<p>I would zip the jar file along with other dependent jars, configuration files and documentation along with a run.bat/run.sh. End user should be able unzip it to any location and edit the run.bat if required (It should run without editing in most of the cases).
An installer may be useful if you want to create entries in start menu, desktop, system tray etc.</p>
<p>As a user I prefer unzip and run kind of installation (no start menu entries please). However People outside IT industry may have different preferences. So if the application is largely targeted for developers zip-run.bat route and applications for general public may be installed using a installer.</p>
| 10,554
|
<p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p>
|
<p>This appears to work.</p>
<pre><code>public string RenderControlToHtml(Control ControlToRender)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
return sb.ToString();
}
</code></pre>
|
<p>If your control is a web user control, this is how you can get to the HTML it emits from another page or handler:</p>
<pre><code>public void GetHtmlFromMySweetControl(HttpContext context)
{
HttpRequest httpRequest = context.Request;
HttpResponse httpResponse = context.Response;
string foo = httpRequest["foo"];
Page pageHolder = new Page();
string path = "~/usercontrols/MySweetControl.ascx";
MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path);
ctrl.BindProducts(foo);
pageHolder.Controls.Add(ctrl);
StringWriter sw = new StringWriter();
context.Server.Execute(pageHolder, sw, false);
httpResponse.Write(sw.ToString());
}
</code></pre>
| 8,337
|
<p>We need to implement a large-scale key-value store (let's say up to 500GB) and BerkeleyDB seemed like it might be a decent option, but we would really like it to be network accessible. This led me to look at memcachedb. I haven't found much on the web where people talk about actual experiences with memcachedb, so my questions are, if you've used memcachedb:</p>
<ul>
<li>would you recommend using it for a large k-v store?</li>
<li>if not, why not?</li>
</ul>
<p>Thanks in advance!</p>
<p>Francis</p>
|
<p>When I was trying to use BerkeleyDB (Which memcachedb apparrently uses as a backend), I found the insert speed to be atrociously slow. It really was unusable in that respect. My insert pattern and configuration was fairly standard, so I have no idea if it's just a general weakness of BDB, or something strange with my test setup.</p>
<p>One option to look into would be <a href="http://incubator.apache.org/couchdb/" rel="nofollow noreferrer">CouchDB</a>. If you need to scale <em>really</em> big, there's always HBase or Hypertable, which are both Bigtable clones.</p>
|
<p>I have used memcached a little bit in one of my projects. I think it's a very efficient and scalable caching platform. By changing small configurations, you're able to replicate the cached objects in more than one server. Facebook uses memacached for their in-memory storage and it's a large scale entity on the web. This gives a thumb up for memcahced.</p>
<p>The only problem I faced in implementation is that doesn't automatically accept objects to store. You will need to serialize the objects before storing which may be a little bit confusing at the beginning.</p>
<p>FYI, there is a nother caching platform produced by Microsoft called: Velocity. You may need to take a look on it:
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyId=B24C3708-EEFF-4055-A867-19B5851E7CD2&displaylang=en</a></p>
| 26,460
|
<p>How can I open multiple Eclipse workspaces at the same time on the Mac?</p>
<p>On other platforms, I can just launch extra Eclipse instances, but the Mac will not let me open the same application twice. Is there a better way than keeping two copies of Eclipse?</p>
|
<p><strong>EDIT:</strong> <a href="https://stackoverflow.com/a/386470/16562">Milhous's answer</a> seems to be the officially supported way to do this as of 10.5. Earlier version of OS X and even 10.5 and up should still work using the following instructions though.</p>
<hr>
<ol>
<li><p>Open the <strong>command line</strong> (Terminal)</p></li>
<li><p>Navigate to your Eclipse installation folder, for instance: </p>
<ul>
<li><code>cd /Applications/eclipse/</code></li>
<li><code>cd /Developer/Eclipse/Eclipse.app/Contents/MacOS/eclipse</code></li>
<li><code>cd /Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse</code></li>
<li><code>cd /Users/<usernamehere>/eclipse/jee-neon/Eclipse.app/Contents/MacOS</code></li>
</ul></li>
<li><p>Launch Eclipse: <code>./eclipse &</code></p></li>
</ol>
<p>This last command will launch eclipse and immediately background the process.</p>
<p>Rinse and repeat to open as many unique instances of Eclipse as you want.</p>
<hr>
<h3>Warning</h3>
<p>You might have to <strong>change the Tomcat</strong> server ports in order to run your project in <strong>different/multiple Tomcat instances</strong>, see <a href="https://stackoverflow.com/a/34259707/759452">Tomcat Server Error - Port 8080 already in use</a> </p>
|
<pre><code>Window -> New Window
</code></pre>
<p>This opens a new window and you can then open another project in it. You can use this as a workaround hopefully. </p>
<p>It actually allows you to work in same workspace. </p>
| 14,392
|
<p>In a nutshell, the hashCode contract, according to Java's object.hashCode():</p>
<ol>
<li>The hash code shouldn't change unless something affecting equals() changes</li>
<li>equals() implies hash codes are ==</li>
</ol>
<p>Let's assume interest primarily in immutable data objects - their information never changes after they're constructed, so #1 is assumed to hold. That leaves #2: the problem is simply one of confirming that equals implies hash code ==.</p>
<p>Obviously, we can't test every conceivable data object unless that set is trivially small. So, what is the best way to write a unit test that is likely to catch the common cases?</p>
<p>Since the instances of this class are immutable, there are limited ways to construct such an object; this unit test should cover all of them if possible. Off the top of my head, the entry points are the constructors, deserialization, and constructors of subclasses (which should be reducible to the constructor call problem).</p>
<p>[I'm going to try to answer my own question via research. Input from other StackOverflowers is a welcome safety mechanism to this process.]</p>
<p>[This could be applicable to other OO languages, so I'm adding that tag.]</p>
|
<p><a href="http://www.jqno.nl/equalsverifier/" rel="noreferrer">EqualsVerifier</a> is a relatively new open source project and it does a very good job at testing the equals contract. It doesn't have the <a href="https://stackoverflow.com/questions/188311#188681">issues</a> the EqualsTester from GSBase has. I would definitely recommend it. </p>
|
<p>If I have a class <code>Thing</code>, as most others do I write a class <code>ThingTest</code>, which holds all the unit tests for that class. Each <code>ThingTest</code> has a method</p>
<pre><code> public static void checkInvariants(final Thing thing) {
...
}
</code></pre>
<p>and if the <code>Thing</code> class overrides hashCode and equals it has a method</p>
<pre><code> public static void checkInvariants(final Thing thing1, Thing thing2) {
ObjectTest.checkInvariants(thing1, thing2);
... invariants that are specific to Thing
}
</code></pre>
<p>That method is responsible for checking <em>all</em> invariants that are designed to hold between any pair of <code>Thing</code> objects. The <code>ObjectTest</code> method it delegates to is responsible for checking all invariants that must hold between any pair of objects. As <code>equals</code> and <code>hashCode</code> are methods of all objects, that method checks that <code>hashCode</code> and <code>equals</code> are consistent.</p>
<p>I then have some test methods that create pairs of <code>Thing</code> objects, and pass them to the pairwise <code>checkInvariants</code> method. I use equivalence partitioning to decide what pairs are worth testing. I usually create each pair to be different in only one attribute, plus a test that tests two equivalent objects.</p>
<p>I also sometimes have a 3 argument <code>checkInvariants</code> method, although I finds that is less useful in findinf defects, so I do not do this often</p>
| 22,830
|
<p>I have a table with a TEXT column where the contents is just strings of CSV numbers. Example ",1,76,77,115," Each string can have an arbitrary number of numbers.</p>
<p>I am trying to set up Full Text Indexing so that I can search this column rapidly. This works great. Instead of running queries with</p>
<pre><code>where MY_COL LIKE '%,77,%' and MY_COL LIKE '%,115,%'
</code></pre>
<p>I can do</p>
<pre><code>where CONTAINS(MY_COL,'77 and 115')
</code></pre>
<p>However, when I try to search for a single character it doesn't work.</p>
<pre><code>where CONTAINS(MY_COL,'1')
</code></pre>
<p>But I know that there should be records returned! I quickly found that I need to edit the Noise file and rebuild the index. But even after doing that it still doesn't work.</p>
|
<p>Working with relational databases that way is going to hurt.</p>
<p>Use a proper schema. Either store the values in different rows or use an array datatype for the column.</p>
<p>That will make solving the problem trivial.</p>
|
<p>I fixed my own problem, although I'm not exactly sure what fixed it.</p>
<p>I dropped my table and populated a new one (my program does batch processing) and created a new Full Text Index. Maybe I wasn't being patient enough to allow the indexing to fully rebuild.</p>
| 39,912
|
<p>I have a somewhat messily-formatted Objective-C code base. Is there a way to have Xcode reformat an entire project to conform to a coding standard (i.e., properly indent, spaces v. tabs, etc.)? Are there other tools that might accomplish this?</p>
|
<p>Uncrustify: <a href="http://uncrustify.sourceforge.net/" rel="noreferrer">http://uncrustify.sourceforge.net/</a></p>
<blockquote>
<p>Source Code Beautifier for C, C++, C#, ObjectiveC, D, Java, Pawn and VALA</p>
</blockquote>
<p>If you want something simpler, you could probably get some way by simply stripping out all the white-space/line-breaks, and adding a new line-break on <code>;</code> <code>{</code> <code>}</code>, and manually re-indenting the code. It won't be anywhere near perfectly laid out code, and reindenting could be a pain on large code, but it will be consistent.</p>
|
<p>One way to go that uses uncrustify in a different context is</p>
<p><a href="http://universalindent.sourceforge.net/" rel="nofollow">http://universalindent.sourceforge.net/</a></p>
| 20,581
|
<p>I have a class <code>Application</code> that my global.asax inherits from. The class has this method:</p>
<pre><code>protected void Application_Start(object sender, EventArgs e)
{
// ...
}
</code></pre>
<p>In my understanding this is basically an event handler that is automatically added to an event (based on the method name [*]). I tried to find out what event exactly, so I put a breakpoint inside the method and checked the call stack:</p>
<blockquote>
<p>Foo.DLL!Foo.Application.Application_Start(object
sender =
{System.Web.HttpApplicationFactory},
System.EventArgs e =
{System.EventArgs})</p>
</blockquote>
<p>The sender is <code>System.Web.HttpApplicationFactory</code>, but I can't find that class using the Object Browser in Visual Studio 2008 or on the MSDN library website. </p>
<p>Where can I find more information about this class?</p>
<p>Thank you!</p>
<hr>
<p>[*] Compare it to the <code>Application_BeginRequest(object sender, EventArgs e)</code> method, which is added as a handler to the <code>BeginRequest</code> event of the <code>System.Web.HttpApplication</code> class.</p>
|
<p>HttpApplicationFactory is an internal class defined in System.Web.dll.
You can check it out in .NET Reflector if you are interested. </p>
<p>Internal means that it is not normally visible outside the dll where it is defined, so you can't use it in your own code.</p>
|
<p>Like Rune said, <code>HttpApplicationFactory</code> is an internal class defined in System.Web.dll.</p>
<p>What it does is create the application and start it, basically managing the runtime of your web application.</p>
| 41,507
|
<p>We use GNU Make for our system. At the end of our makefiles, we have an include called Makedepends which generates a bunch of .d files using -MM switch on gcc. We then include the .d file for each .cc file using an include $(CXXFILES:.cc=.d) line. But when we delete file or move files, the dependancies step breaks and we have to manually delete the .d files (even a make clean doesn't work because the dependencies fail)</p>
<p>Is there a way to generate these dependency .d files or include these dependency .d files which will gracefully handle a file deletion or relocation?</p>
<p>EDIT: For example: I have serial.cc and the makefiles generate a serial.d file which has a dependency on buffer.h but then I change it so I don't need buffer.h any more and I delete buffer.h. Next time I run make, it will choke because it includes the .d file which still makes serial.o depend on buffer.h.</p>
|
<p><a href="http://make.mad-scientist.net/papers/advanced-auto-dependency-generation" rel="nofollow noreferrer">http://make.mad-scientist.net/papers/advanced-auto-dependency-generation</a> has a description of this exact problem, and a couple of ways around it. The first is a bit misguided, but the "advanced" is essentially spot on.</p>
|
<p>Two possibilities:</p>
<p>First, can you add a rule to your Makefile to run the dependency step:</p>
<pre><code>.SUFFIXES: .d
%.d::
makedepend_command_here
</code></pre>
<p>If not, then from the <code>Last Resort</code> section of the <code>info</code> page for GNU Make:</p>
<blockquote>
<p>For example, when testing a
makefile, you might not care if the
source files contain real data, only
that they exist. Then you might do
this:</p>
<pre><code> %::
touch $@
</code></pre>
<p>to cause all the source files needed
(as prerequisites) to be created
automatically.</p>
</blockquote>
<p>Will this work to create empty <code>.d</code> files for you?</p>
| 29,570
|
<p>WinXP Pro
Oracle 10g Instant Client 10.2.0.1
MS Access 2003</p>
<p>When I link a table in MS Access, the pick list that appears shows me every table and view in the system I have access to. This list is quite large. Normally, I really only want to look at the tables that I own. Is there a way to filter the items displayed based on owner, or any other criteria?</p>
|
<p>You may want to mark the constants as final.</p>
|
<p>That seems to be a fairly easy way to do that. Although I would name the images with the same name as what they are for ("ok.png", "cancel.png"). And make sure that it is clear that removing or renaming the images may cause issues.</p>
| 48,238
|
<p>Is there a Rails plugin or a rubygem that gives you a starting point for adding an api to your Rails app? We want to use the API Key/Secret Key model, the API should also be versionable. Is there something out there that will give us some, if not all of this?</p>
|
<p>Check out this plugin for AuthLogic:</p>
<p><a href="http://github.com/phurni/authlogic_api" rel="noreferrer">http://github.com/phurni/authlogic_api</a></p>
<p>I think that does what you are looking for.</p>
|
<p>The <a href="http://code.google.com/p/oauth/" rel="nofollow noreferrer">OAuth plugin</a> could be useful for the keys. It may look like <a href="http://oauth.net/" rel="nofollow noreferrer">OAuth</a> is only for user authentication, but if you autogenerate the access tokens and give them to developers, instead of having an interactive user process with request tokens and account authorization, then you basically have a quite secure API key system. And the plugin will just drop in nicely.</p>
<p>Other than that, some nice use of rails' routes (with conditions to call a different action on get, post, put, etc, and a prefix of /api/v1/) and format (format.xml, format.js, etc) provides a pretty nice way to build RESTful APIs, withought really needing a plugin.</p>
| 45,593
|
<p>I want to know how to make a mold of a 3D design in .stl format.</p>
<p>Suppose I have a 3D partin .stl format (for e.g. a cylinder) and I want to make/design a mold for this object (i.e. the structure through which I could make the cylinder). Is there any way to do so? Are there any tools to do so?</p>
<p>My requirement is as follows: I have an .stl file of a design and need to develop the CAD files for its mold. I will then need to 3D print these molds. I would require to add a hole to pour in liquid (resin based) raw material which hardens with time. </p>
|
<p>You can also bring the model and a big box into slic3r, align and orient them (enclose the model in the box), and do a subtract modifier, leaving a hollow where the two intersected. You probably want to do this twice, for a top mould and a botom mould. I've done this, but I don't see any instructions online for it. :(</p>
<p>EDIT: Unfortunately, this would be very tedious. It's much easier to use meshmixer or another publicly available program to subtract one stl from another.</p>
<p>In Slic3r, using another stl as a modifier has no effect unless you are also printing that second stl (normally from another head). So you would have to manually remove all the gcode for the second head. Sorry for the bad advice.</p>
|
<p>In addition to the answer of Davo (which describes a surprising feature of the slicer software I was unaware of), a more generic description would involve the use of a 3D solid model CAD program. You should be aware that a model in STL format is not a solid model, it is a surface model. In order to make a mold you would have to import the STL model into a CAD program (there are a few free ones available like Fusion 360 or FreeCAD or maybe many more that will work also) and make a solid body from the surface model. Next thing is to create a large rectangular block and subtract the positive model from the block. Now a negative lives inside this block so you will need to conveniently cut the block through your negative to create 2 mold parts. Be sure that you divide the block so that you can take out the casting from the mold parts and also add an entry to pour in the liquid casting material and add risers (holes) to de-aerate the cavity. Furthermore, for alignment, you could add pins and holes to the mold parts.</p>
| 894
|
<p>The "instruments" that are used with Guitar Hero and Rock Band have USB connections. Is there any documentation or reverse-engineering info out there about how to read the messages they generate?</p>
|
<p>Check out <a href="http://www.wiiuse.net/?nav=docs" rel="nofollow noreferrer">Wiiuse</a> - it suppors the Guitar Hero 3 controller, as well as Wiimotes :)</p>
|
<p>You could check <a href="http://fretsonfire.sourceforge.net/" rel="nofollow noreferrer">Frets on Fire</a> project. It's opensource GH-like game, and as far as I remember documentation said you could use Guitar Hero controller instead of the keyboard.</p>
<p>Here's some additional semi-info: <a href="http://kotaku.com/gaming/guitar-hero/frets-on-fire-and-the-360-guitar-249579.php" rel="nofollow noreferrer">Frets on Fire and the 360 Guitar</a>.</p>
| 25,769
|
<p>I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.</p>
<p>How can I do it?</p>
<hr />
<p>When I click the submit button for the textbox below, the message box must show <em>Lorem ipsum</em>. Because "Lorem ipsum" is selected in the area.</p>
<hr />
<p>If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.</p>
<p>Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.</p>
<p>How is it to be done?</p>
|
<p>OK, here is the code I have:</p>
<pre><code>function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
</code></pre>
<p>The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of <a href="https://en.wikipedia.org/wiki/Internet_Explorer_6" rel="nofollow noreferrer">Internet Explorer 6</a> on my current system. Perhaps it will work for you, and that's why I give it.</p>
<p>The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.</p>
<p>I got the right result (the selection content) with the <em>onKeyDown</em> event:</p>
<pre><code>document.onkeydown = function (e) { ShowSelection(); }
</code></pre>
<p>So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.</p>
<p>I didn't have any success with a button drawn with a <code>li</code> tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple <code>input</code> button, though...</p>
|
<pre><code>// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);
// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);
</code></pre>
| 34,759
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.