instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I am reading WIX script written by others. There are some code really confuses me. </p>
<pre><code><Custom Action='UnLoadSchedulerPerfCounters' After='InstallInitialize'>
<![CDATA[(Installed) AND (!Scheduler = 3)]]>
</Custom>
<Custom Action='RollbackSchedulerPerfCounters' After='WriteRegistryValues'>
<![CDATA[(&Scheduler = 3)]]>
</Custom>
</code></pre>
<p>So, what's the difference between <code>!Scheduler</code> and <code>&Scheduler</code>?
Is any special meaning when property is prefix-ed by <code>&</code> or <code>!</code>?</p>
|
<p>From <a href="http://www.tramontana.co.hu/wix/lesson5.php#5.3" rel="nofollow noreferrer">http://www.tramontana.co.hu/wix/lesson5.php#5.3</a>:</p>
<blockquote>
<p>Prepending some special characters to
the names will give them extra
meaning:</p>
<pre><code>% environment variable (name is case insensitive)
$ action state of component
? installed state of component
& action state of feature
! installed state of feature
</code></pre>
<p>The last four can return the following
integer values:</p>
<pre><code>-1 no action to be taken
1 advertised (only for components)
2 not present
3 on the local computer
4 run from the source
</code></pre>
</blockquote>
|
<p>Those are operators on the Windows Installer condition syntax. See this MSI SDK documentation for a complete list: <a href="http://msdn.microsoft.com/en-us/library/aa368012.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa368012.aspx</a>. </p>
| 30,575
|
<p>I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image.
how to do this</p>
|
<p>That depends on where you need to display the image. If you are looking for something along the lines of an icon next to or behind the link, you could accomplish this through CSS using a background image on the hover state of the link:</p>
<pre><code>a:link
{
background-image:none;
}
a:hover
{
background-image:url('images/icon.png');
background-repeat:no-repeat;
background-position:right;
padding-right:10px /*adjust based on icon size*/
}
</code></pre>
<p>I did this off the top of my head, so you may need to make some minor adjustments.</p>
<p>If you wanted to show an image somewhere else on the page, you could accomplish that using javascript to hide/show the image on the link's mouseover event.</p>
<p>If this doesn't solve your problem, maybe you could supply some additional information to help guide everybody to the right answer.</p>
|
<p>you can do this using javascript..</p>
<p>This will create a square that follows your mouse on div or element hover.</p>
<p>Create a .js file with those contents here: </p>
<pre><code>
var WindowVisible = null;
function WindowShow() {
this.bind = function(obj,url,height,width) {
obj.url = url;
obj.mheight = height;
obj.mwidth = width;
obj.onmouseover = function(e) {
if (WindowVisible == null) {
if (!e) e = window.event;
var tmp = document.createElement("div");
tmp.style.position = 'absolute';
tmp.style.top = parseInt(e.clientY + 15) + 'px';
tmp.style.left = parseInt(e.clientX + 15) + 'px';
var iframe = document.createElement('iframe');
iframe.src = this.url;
iframe.style.border = '0px';
iframe.style.height = parseInt(this.mheight)+'px';
iframe.style.width = parseInt(this.mwidth)+'px';
iframe.style.position = 'absolute';
iframe.style.top = '0px';
iframe.style.left = '0px';
tmp.appendChild(iframe);
tmp.style.display = 'none';
WindowVisible = tmp;
document.body.appendChild(tmp);
tmp.style.height = parseInt(this.mheight) + 'px';
tmp.style.width = parseInt(this.mwidth) + 'px';
tmp.style.display = 'block';
}
}
obj.onmouseout = function() {
if (WindowVisible != null) {
document.body.removeChild(WindowVisible);
WindowVisible = null;
}
}
obj.onmousemove = function(e) {
if (!e) e = window.event;
WindowVisible.style.top = parseInt(e.clientY + 15) + 'px';
WindowVisible.style.left = parseInt(e.clientX + 15) + 'px';
}
}
}
</code></pre>
<p>Then in your html do the following:</p>
<ol>
<li><p>Include the .js file <code> <script type="text/javascript" src="myfile.js"></script> </code></p></li>
<li><p>Put in your web page: </p></li>
</ol>
<pre><code>
<script type="text/javascript">
var asd = new WindowShow();
asd.bind(document.getElementById('go1'),'IMAGE URL HERE!',400,480);
</script>
</code></pre>
<p>Here is a full implementation in a HTML:</p>
<pre><code><html>
<head>
<title>test page</title>
<style>
div.block { width: 300px; height: 300px; background-color: red; }
iframe { border: 0px; padding: 0px; margin: 0px; }
</style>
<script type="text/javascript" src="window_show.js"></script>
</head>
<body>
<div id="go1" style="background-color: red; width: 200px; height: 200px;"></div>
<script type="text/javascript">
var asd = new WindowShow();
asd.bind(document.getElementById('go1'),'IMAGE URL HERE!',400,480);
</script>
</body>
</code></pre>
<p></p>
<p>bye bye!</p>
| 36,798
|
<p>I am new to 3D printing. I own jewelry stores and want to 3D print my jewelry packaging for rings, necklaces, and bangles as in the picture below:</p>
<p><a href="https://i.stack.imgur.com/NVwgE.png" rel="nofollow noreferrer" title="Product photo of a jewelry ring box"><img src="https://i.stack.imgur.com/NVwgE.png" alt="Product photo of a jewelry ring box" title="Product photo of a jewelry ring box" /></a></p>
<p>I have two main problems:</p>
<ol>
<li><p>Is 3D printing capable of building this package?</p>
</li>
<li><p>I know I can build boxes for jewelry with the outside being made of plastic. But I want the inside to be like a sponge. Is there a filament or a way to print a filament to make it look like cloth or a sponge?</p>
</li>
<li><p>Are there printers on the market which are able to print several copies without the need to set up each time it finishes a single box?</p>
</li>
</ol>
|
<h1>With the right materials</h1>
<p>With the right material, you can get flexible surfaces and prints. Just two random examples:</p>
<ul>
<li>TPU is a flexible material, which can be used to print something like "Lips" that flex and take the jewelry or even strings that suspend the piece in the center.</li>
<li>Foaming TPU is a variant of normal TPU that expands during printing. This makes it somewhat spongey.</li>
</ul>
<p>However, those have downsides: they don't make good rigid shells, so you will need two different materials: one hard for the shell, and something flexible for the holder.</p>
<p>Luckily, any direct drive filament printer can work with flexible filaments, and there are some flexible filaments that work with a Bowden setup. Due to dissimilar materials though, you need to either assemble the part or buy a somewhat specialized printer: one with two nozzles. These are available but are way out of hobby-grade pricing.</p>
<p>Also, you will never get the "smooth" silky look of a fabric insert cover, but always a clearly industrial printed surface.</p>
|
<p>I would advise against this, as you will get layer lines which isn't visible in normal form, and the fit wont be as smooth etc, resulting in a cheaper look & feel. You will spend a lot of effort modifiying the parameters to get a foamy look, but still end up with a worse product.
Instead the best option is probably to buy EVA foam, and cut it with hot hire, or even a blade/knife.</p>
<p>I understand the jewelry is (probably) expensive, and thus you will want to give it a premium feel. One advice I would give is for the plastic box, consider SLA / Resin printing, and you will get almost injection moulding quality. However the chemicals involved with this are not as user friendly, and you will need to wear PPE and ensure a large amount of ventilation (as resin fumes can be toxic), however the quality will be much better</p>
| 2,181
|
<p>how can i figure out the last modified date of a html file im importing into my web app?</p>
<p>The html file is on another server and different users can make updates, when i retrieve the page i want to be able see when it was last updated so i can label the updated date on my homepage. I</p>
|
<p>I assume you are using HTTP to retrieve the page.</p>
<p>In that case you can use the HEAD method of HTTP to get the header data of the file. (See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a>, 9.4)</p>
<p>Then you can check the "Last-Modified" header of the response. (See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a>, 14.29)</p>
<p>In case of some caching mechanism (proxy, browser caching) it might be necessary to include "Cache-Control: must-revalidate" in the request header. (See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html</a>, 14.9.4)</p>
|
<p>There are some proposed meta tag keys representing Dublin Core values that may be used. See: <a href="https://stackoverflow.com/a/14893974/895245">https://stackoverflow.com/a/14893974/895245</a> </p>
| 24,957
|
<p>I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void * or int.</p>
<pre><code>
struct my_interface {
void (*func_a)(int i);
void *(*func_b)(const char *bla);
...
int (*func_z)(char foo);
};
</code></pre>
<p>But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist.</p>
<p>Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature.</p>
<pre><code>
#include <stdio.h>
int nothing(void) {return 0;}
typedef int (*cb_t)(int);
int main(void)
{
cb_t func;
int i;
func = (cb_t) nothing;
i = func(1);
printf("%d\n", i);
return 0;
}
</code></pre>
<p>I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems?</p>
<p>EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.</p>
|
<p>By the C specification, casting a function pointer results in undefined behavior. In fact, for a while, GCC 4.3 prereleases would return NULL whenever you casted a function pointer, perfectly valid by the spec, but they backed out that change before release because it broke lots of programs.</p>
<p>Assuming GCC continues doing what it does now, it will work fine with the default x86 calling convention (and most calling conventions on most architectures), but I wouldn't depend on it. Testing the function pointer against NULL at every callsite isn't much more expensive than a function call. If you really want, you may write a macro:</p>
<pre>#define CALL_MAYBE(func, args...) do {if (func) (func)(## args);} while (0)</pre>
<p>Or you could have a different dummy function for every signature, but I can understand that you'd like to avoid that.</p>
<h2>Edit</h2>
<p>Charles Bailey called me out on this, so I went and looked up the details (instead of relying on my holey memory). The <a href="http://c0x.coding-guidelines.com/6.3.2.3.html" rel="noreferrer">C specification</a> says</p>
<blockquote>
<p>766 A pointer to a function of one type may be converted to a pointer to a function of another type and back again;<br>
767 the result shall compare equal to the original pointer.<br>
768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.</p>
</blockquote>
<p>and GCC 4.2 prereleases (this was settled way before 4.3) was following these rules: the cast of a function pointer did not result in NULL, as I wrote, but attempting to call a function through a incompatible type, i.e.</p>
<pre><code>func = (cb_t)nothing;
func(1);
</code></pre>
<p>from your example, would result in an <code>abort</code>. They changed back to the 4.1 behavior (allow but warn), partly because this change broke OpenSSL, but OpenSSL has been fixed in the meantime, and this is undefined behavior which the compiler is free to change at any time.</p>
<p>OpenSSL was only casting functions pointers to other function types taking and returning the same number of values of the same exact sizes, and this (assuming you're not dealing with floating-point) happens to be safe across all the platforms and calling conventions I know of. However, anything else is potentially unsafe.</p>
|
<p>Casting a function pointer to NULL is explicitly not supported by the C standard. You're at the mercy of the compiler writer. It works OK on a lot of compilers.</p>
<p>It is one of the great annoyances of C that there is no equivalent of NULL or void* for function pointers.</p>
<p>If you really want your code to be bulletproof, you can declare your own nulls, but you need one for each function type. For example, </p>
<pre><code>void void_int_NULL(int n) { (void)n; abort(); }
</code></pre>
<p>and then you can test</p>
<pre><code>if (my_thing->func_a != void_int_NULL) my_thing->func_a(99);
</code></pre>
<p>Ugly, innit?</p>
| 22,900
|
<p>I've been programming in C,C++,C# and a few other languages for many years, mainly for Windows and Linux but also embedded platforms. Recently started to do some iPhone programming as a side project so I'm using Apple platforms for the first time since my Apple II days. I'm wondering what other developers that are coming to Mac OSX, Xcode and iPhone SDK think. Here are my impressions, so far:</p>
<ul>
<li><p>Mac OSX: very confusing, I tend to end up with too many open windows and don't know what's where. Luckily there's the bird's eye view, without it I'd be lost. With the shell at least there's all the familiar stuff so that helps me a lot.</p></li>
<li><p>Xcode: doesn't feel as good as VisualStudio or Eclipse, the two environments I'm familiar with. I think I could get used to it but I'm wondering if Apple wouldn't be better off with Eclipse. Before I found the setting where all the windows are stuck together I hated it, now I can tolerate it.</p></li>
<li><p>iPhone SDK: strange indeed. I understand Apple's desire to control their environment but in this day and age it just seems a little sleazy and they are missing out on so much by destroying developer goodwill.</p></li>
<li><p>Objective-C: I've known about it for years but never even took a look at it. The syntax is off-putting but I'm actually very intrigued by the language. I think it's an interesting third leg between C++ and C#, both of which I like a lot. Is there any chance Obj-C will break out of the Mac sandbox due to the uptick in the popularity of Apple technology?</p></li>
</ul>
<p>Curious to read your thoughts,</p>
<p>Andrew</p>
|
<p>I'm in the same boat as you (somewhat). I've been developing in C# for 7 years, ever since .NET 1.0. Over the past couple weeks I've been teaching myself Cocoa and Objective-C. Here are my impressions (note for note with yours)</p>
<ul>
<li><p>Agreed in that clutter can be a problem. I tend to use Spaces heavily when developing in XCode (put XCode in one space, Interface Builder in another space, Instruments in a third space). If you don't have Leopard (and thus, no spaces), then use Command-H to hide your active window. Using that tends to clean things up quite a bit (however it'd be nice if you could command-h automagically the current window when command-tab'ing to another app).</p></li>
<li><p>I'm liking XCode more and more. I hate Visual Studio - I find it to be unstable, slow, and well, just kind of a crappy IDE. Comparatively I've found XCode to be fast, stable, and I like how it organizes and filters your files. I'm not too up on my XCode shortcuts, but I'm hoping there's a way I can quick-switch from one class to another (similar to ctrl +n shortcut in ReSharper). Intellisense could be better with regards to how it displays to the user, but I really like how it essentially creates a template and you can ctrl + / to jump to the next argument in a message.</p></li>
<li><p>I'm hating the documentation in XCode. The help system sucks, and for whatever reason it <em>never</em> finds what I'm searching for. I end up just googling for anything I need to know... I hope they improve the documentation. This is my biggest beef right now.</p></li>
<li><p>Not quite there yet, as I'm going through the full Cocoa framework for Mac desktops. So far I'm really, really liking what I see. One thing I will say is that it would be nice if the iPhone SDK allowed for garbage collection...</p></li>
<li><p>Objective-C - I've never used it, this is my first foray into it. At first I was kinda wierded out by the syntax and the square brackets for messaging, but it's really growing on me. It's so quick to skim a method and see the message calls that method makes. The more I use it, the more Objective-C just feels nice... however templating/generics would be a welcome addition to the language.</p></li>
</ul>
<p>All in all, my foray into Mac development has been enjoyable, and I'm excited to start working (today! yay!) on some actual mac/iphone projects.</p>
|
<p>I came from a C# background as well and have been working with the iPhone SDK since beta 2. I totally agree with cranley about VS being a bit clunky compared to Xcode. Xcode is WAY different, and totally foreign when you start using it. So was VS though back in the day. Once you get by the learning curve it is a wonderful experience. The apps I am developing use C# server side (web service) and I absolutely hate having to switch to VS to write the web service code from Xcode. Obj-C is also quite fun to use once you learn how it works best: delegates (very different than .NET delegates), messages, Categories and all the other oddities present.</p>
<p>I did some Java and Flex programming previous to .NET and I always hated the .NET docs compared to Java docs. They just don't cut it. I have personally found Xcodes docs and search system to be nothing short of amazing. There are countless PDF guides linked from the docs that have tons of sample code. Think about this: the iPhone SDK has been out of beta for about 2 months now. The docs show a maturity level of many years. And yes, it is because Obj-C has been around over a year and the frameworks are similar.</p>
<p>Overall, the biggest issue I have found is that there are a LOT of .NET developers jumping on the iPhone bandwagon and trying to use Obj-C as if it were C# or VB. They fail to read the basic Obj-C docs let alone the iPhone docs and then they get very frustrated and eventually fail. The discussion forums are full of this scenario. iPhone programming is not easy. Learning a new language is not easy. It takes time and a lot of try.fail.try. It's not .NET so lose that mindset before you even begin and things will be wonderful.</p>
| 12,905
|
<p>My code runs inside a JAR file, say <strong>foo.jar</strong>, and I need to know, in the code, in which folder the running <strong>foo.jar</strong> is.</p>
<p>So, if <strong>foo.jar</strong> is in <code>C:\FOO\</code>, I want to get that path no matter what my current working directory is.</p>
|
<pre><code>return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
</code></pre>
<p>Replace "MyClass" with the name of your class.</p>
<p>Obviously, this will do odd things if your class was loaded from a non-file location.</p>
|
<p>This method, called from code in the archive, returns the folder where the .jar file is. It should work in either Windows or Unix.</p>
<pre><code>
private String getJarFolder() {
String name = this.getClass().getName().replace('.', '/');
String s = this.getClass().getResource("/" + name + ".class").toString();
s = s.replace('/', File.separatorChar);
s = s.substring(0, s.indexOf(".jar")+4);
s = s.substring(s.lastIndexOf(':')-1);
return s.substring(0, s.lastIndexOf(File.separatorChar)+1);
}
</code></pre>
<p>Derived from code at: <a href="http://www.rgagnon.com/javadetails/java-0391.html" rel="nofollow">Determine if running from JAR</a></p>
| 41,471
|
<p>We need to build an administration portal website to support our client/server application. Since we're a .Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend?</p>
<p>The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application.</p>
<p>I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills.</p>
<p>Are there any big no-nos from the experience of StackOverflowers? What are the big positives?</p>
|
<p>I would recommend against building a pure Silverlight site.</p>
<p>Silverlight suffers from the same issues as Flash does: Unintuitive Bookmarking, issues with printing, accessibility issues, not working back buttons and so on.</p>
<p>Also, you would require your users to have Silverlight installed or at least to have the ability to install it. </p>
<p>In controlled environements (eg. in large companies or health care) or on mobile devices, this might not be the case.</p>
|
<p>There are some <a href="https://stackoverflow.com/questions/56266/using-silverlight-for-an-entire-website#56302">downsides</a> with developing a site completely in Flash / Silverlight, but if those downsides won't matter to you or won't have an impact then there is nothing stopping you. Choose whatever tool you think meets your needs more fully. I wouldn't be put off creating a site purely in Silverlight based on the downsides, because it brings a lot more positives to the user experience.</p>
| 8,015
|
<p>I've generated some JSON and I'm trying to pull it into an object in JavaScript. I keep getting errors. Here's what I have:</p>
<pre><code>var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = eval('('+data+')');
</code></pre>
<p>This gives me an error: </p>
<pre><code>unterminated string literal
</code></pre>
<p>With <code>JSON.parse(data)</code>, I see similar error messages: "<code>Unexpected token ↵</code>" in Chrome, and "<code>unterminated string literal</code>" in Firefox and IE.</p>
<p>When I take out the <code>\n</code> after <code>sometext</code> the error goes away in both cases. I can't seem to figure out why the <code>\n</code> makes <code>eval</code> and <code>JSON.parse</code> fail. </p>
|
<p>This is what you want:</p>
<pre><code>var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';
</code></pre>
<p>You need to escape the <code>\</code> in your string (turning it into a double-<code>\</code>), otherwise it will become a newline in the JSON source, not the JSON data.</p>
|
<p>I encountered that problem while making a class in PHP 4 to emulate json_encode (available in PHP 5). Here's what I came up with:</p>
<pre><code>class jsonResponse {
var $response;
function jsonResponse() {
$this->response = array('isOK'=>'KO', 'msg'=>'Undefined');
}
function set($isOK, $msg) {
$this->response['isOK'] = ($isOK) ? 'OK' : 'KO';
$this->response['msg'] = htmlentities($msg);
}
function setData($data=null) {
if(!is_null($data))
$this->response['data'] = $data;
elseif(isset($this->response['data']))
unset($this->response['data']);
}
function send() {
header('Content-type: application/json');
echo '{"isOK":"' . $this->response['isOK'] . '","msg":' . $this->parseString($this->response['msg']);
if(isset($this->response['data']))
echo ',"data":' . $this->parseData($this->response['data']);
echo '}';
}
function parseData($data) {
if(is_array($data)) {
$parsed = array();
foreach ($data as $key=>$value)
array_push($parsed, $this->parseString($key) . ':' . $this->parseData($value));
return '{' . implode(',', $parsed) . '}';
}
else
return $this->parseString($data);
}
function parseString($string) {
$string = str_replace("\\", "\\\\", $string);
$string = str_replace('/', "\\/", $string);
$string = str_replace('"', "\\".'"', $string);
$string = str_replace("\b", "\\b", $string);
$string = str_replace("\t", "\\t", $string);
$string = str_replace("\n", "\\n", $string);
$string = str_replace("\f", "\\f", $string);
$string = str_replace("\r", "\\r", $string);
$string = str_replace("\u", "\\u", $string);
return '"'.$string.'"';
}
}
</code></pre>
<p>I followed the rules mentioned <a href="http://www.json.org/fatfree.html" rel="nofollow noreferrer">here</a>. I only used what I needed, but I figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as I originally thought, but about the / not being escaped. I hope this prevent someone else from the little headache I had figuring out what I did wrong.</p>
| 6,345
|
<p>I have an SVN repository and I need the commits to fail if no description is entered. Is this possible to do, preferably server-side? (The users use several different tools for interacting with the repository; although if this were possible client-side in TortoiseSVN, that would alleviate the problem)</p>
<p>Google has not been very helpful, can you give me some pointers?</p>
<p>Thanks.</p>
|
<p>Yup, you'll want to write a pre-commit hook in the repository which fails with an appropriate error message to send back to the client.</p>
<p>If you look in the "hooks" directory of a freshly created repository, you'll find a <code>pre-commit.tmpl</code> file. That contains instructions, and the sample even checks that the log message contains text - just what you want.</p>
<p>So, you should be able to rename <code>pre-commit.tmpl</code> to <code>pre-commit</code> and make it executable, then give it a whirl. I suggest you try it on a sandbox repository before a production one though, to avoid angry users being unable to commit while you get it right :)</p>
|
<p>You can do that using <a href="http://svnbook.red-bean.com/en/1.5/svn.reposadmin.create.html#svn.reposadmin.create.hooks" rel="nofollow noreferrer">repository hooks</a>. In your case, you want a pre-commit hook that will check the message and reject the commit if it is empty.</p>
| 48,456
|
<p>How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?</p>
|
<p>It's not very unique as shipped. In the default configuration it's the result of a hash of various things including the result of gettimeofday (which isn't terribly unique), but if you're worried, you should configure it to draw some entropy from /dev/urandom, like so</p>
<pre><code>ini_set("session.entropy_file", "/dev/urandom");
ini_set("session.entropy_length", "512");
</code></pre>
<p>search for "php_session_create_id" in <a href="https://github.com/php/php-src/blob/34792280bcd2210784ba574d52fc3619cc06160d/ext/session/session.c#L279" rel="noreferrer">the code</a> for the actual algorithm they're using.</p>
<p>Edited to add:
There's a DFA random-number generator seeded by the pid, mixed with the time in usecs. It's not a firm uniqueness condition <a href="http://seclists.org/vuln-dev/2001/Jul/33" rel="noreferrer">especially from a security perspective</a>. Use the entropy config above.</p>
<p><strong>Update:</strong> </p>
<blockquote>
<p>As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or
/dev/arandom if it is available. In PHP 5.3.0 this directive is left
empty by default. <a href="http://www.php.net/manual/en/session.configuration.php#ini.session.entropy-file" rel="noreferrer">PHP Manual</a></p>
</blockquote>
|
<pre><code><?php
session_start();
$_SESSION['username']="username";
?>
<!DOCTYPE html>
<html>
<head>
<title>Update</title>
</head>
<body>
<table border="2">
<tr>
<th>Username</th>
<th>Email</th>
<th>Edit</th>
</tr>
<?php
$conn=mysqli_connect("localhost","root","","telephasic");
$q2="select * from register where username = '".$_SESSION['username']."'";
$run=mysqli_query($conn, $q2);
while($row=mysqli_fetch_array($run))
{
$name=$row[1];
$email=$row[2];
?>
<tr>
<td><?php echo $name; ?></td>
<td><?php echo $email; ?></td>
<td><a href="edit.php"> Edit </a></td>
</tr>
<?php } ?>
</table>
</body>
</code></pre>
<p>if your username is different or unique you can use this code for session </p>
| 16,796
|
<p>As we all know, when we derive a class and use polymorphism, someone, somewhere needs to know what class to instanciate. We can use factories, a big switch statement, if-else-if, etc. I just learnt from Bill K this is called Dependency Injection.</p>
<p><strong>My Question: Is it good practice to use reflection and attributes as the dependency injection mechanism?</strong> That way, the list gets populated dynamically as we add new types.</p>
<p>Here is an <strong>example</strong>. <em>Please no comment about how loading images can be done other ways, we know</em>.</p>
<p>Suppose we have the following IImageFileFormat interface:</p>
<pre><code>public interface IImageFileFormat
{
string[] SupportedFormats { get; };
Image Load(string fileName);
void Save(Image image, string fileName);
}
</code></pre>
<p>Different classes will implement this interface:</p>
<pre><code>[FileFormat]
public class BmpFileFormat : IImageFileFormat { ... }
[FileFormat]
public class JpegFileFormat : IImageFileFormat { ... }
</code></pre>
<p>When a file needs to be loaded or saved, a manager needs to iterate through all known loader and call the Load()/Save() from the appropriate instance depending on their SupportedExtensions.</p>
<pre><code>class ImageLoader
{
public Image Load(string fileName)
{
return FindFormat(fileName).Load(fileName);
}
public void Save(Image image, string fileName)
{
FindFormat(fileName).Save(image, fileName);
}
IImageFileFormat FindFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
return formats.First(f => f.SupportedExtensions.Contains(extension));
}
private List<IImageFileFormat> formats;
}
</code></pre>
<p>I guess the important point here is whether the list of available loader (formats) should be populated by hand or using reflection.</p>
<p>By hand:</p>
<pre><code>public ImageLoader()
{
formats = new List<IImageFileFormat>();
formats.Add(new BmpFileFormat());
formats.Add(new JpegFileFormat());
}
</code></pre>
<p>By reflection:</p>
<pre><code>public ImageLoader()
{
formats = new List<IImageFileFormat>();
foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())
{
if(type.GetCustomAttributes(typeof(FileFormatAttribute), false).Length > 0)
{
formats.Add(Activator.CreateInstance(type))
}
}
}
</code></pre>
<p>I sometimes use the later and it never occured to me that it could be a very bad idea. Yes, adding new classes is easy, but the mechanic registering those same classes is harder to grasp and therefore maintain than a simple coded-by-hand list.</p>
<p>Please discuss.</p>
|
<p>My personal preference is neither - when there is a mapping of classes to some arbitrary string, a configuration file is the place to do it IMHO. This way, you <strong>never</strong> need to modify the code - especially if you use a dynamic loading mechanism to add new dynamic libraries. </p>
<p>In general, I always prefer some method that allows me to write code once as much as possible - both your methods require altering already-written/built/deployed code (since your reflection route makes no provision for adding file format loaders in new DLLs).</p>
<p><strong>Edit by Coincoin:</strong></p>
<p>Reflection approach could be effectively combined with configuration files to locate the implmentations to be injected.</p>
<ul>
<li>The type could be declared explicitely in the config file using canonical names, similar to MSBuild <UsingTask></li>
<li>The config could locate the assemblies, but then we have to inject all matching types, ala Microsoft Visual Studio Packages.</li>
<li>Any other mechanism to match a value or set of condition to the needed type.</li>
</ul>
|
<p>I know this borders on the "no comment about loading images other ways", but why not just flip your dependencies -- rather than have ImageLoader depend on ImageFileFormats, have each IImageFileFormat depend on an ImageLoader? You'll gain a few things out of this:</p>
<ul>
<li>Each time you add a new IImageFileFormat, you won't need to make any changes anywhere else (and you won't have to use reflection, either)</li>
<li>If you take it one step further and abstract ImageLoader, you can mock it in Unit Tests, making testing the concrete implementations of each IImageFileFormat that much easier</li>
</ul>
| 41,204
|
<p>On the site we are building. We need to be able to redirect the user to a default page when his session has ended.</p>
<p>At first sight we used the Session_End with a Response.Redirect to do this job.</p>
<pre><code>Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Response.Redirect("~/global/exit.aspx")
End Sub
</code></pre>
<p>But it generates a crapload of <em>Response is not available in this context</em> errors. Naturally we don't want to spam our servers error logs.</p>
<p>What is the most efficient way to handle session ending with ASP.NET 2.0?</p>
|
<p>We handled it by checking if the session data existed in Application.Begin_Request for the pages that were user specific and if it didn't then redirecting the user to login or homepage.</p>
|
<p>We handled it by checking if the session data existed in Application.Begin_Request for the pages that were user specific and if it didn't then redirecting the user to login or homepage.</p>
| 24,585
|
<p>I'm learning XML, currently of Wikibooks, but that is kinda huge and not oversee-able...</p>
<p>anybody know a better place?</p>
|
<p><a href="http://www.w3schools.com/xml/default.asp" rel="noreferrer">W3Schools</a> are generally good for this type of stuff.</p>
|
<p>Even though there are plenty of tutorials about XML , I agree with Galwegian . I learned XML from <a href="http://www.w3schools.com/xml/default.asp" rel="nofollow noreferrer">W3Schools</a>.</p>
| 9,709
|
<ul>
<li><p>How do I utilize a ?: operator in the SELECT clause of a LINQ query? If this can't be done, how can I emulate one? The goal is to get a CASE block in my select clause. As you might suspect, I'm getting an error: <em>Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.</em></p></li>
<li><p>Is this the proper way, or a sufficient way, to say "from a inner join i on a.ipid=i.id inner join u on i.uid=u.id"? If not, please provide one. Thanks.</p>
<pre><code>var query =
from a in db.tblActivities
from i in db.tblIPs
from u in db.tblUsers
select new {
u.UserName == null
? i.Address
: u.UserName,
a.Request,
a.DateTime };
</code></pre></li>
</ul>
|
<p>When creating an anonymous type (what you're doing with the "new" without specifying a type) you have to specify the member name for each property. From your example, it would look something like this: (also fixed your joins)</p>
<pre><code>var query = from a in db.tblActivities
join i in db.tblIPs on a.ipid equals i.id
join u in db.tblUsers on i.uid equals u.id
select new {
UserName = (u.UserName ?? i.Address),
Request = a.Request,
Date = a.DateTime
};
</code></pre>
<p>You could probably do the UserName your way, too:</p>
<pre><code>UserName = (u.UserName == null) ? i.Address : u.UserName,
</code></pre>
<p>but the ?? operator is more concise. It's similar to "isnull" in SQL.</p>
|
<p>I'm fairly new to Linq to SQL but I'm pretty sure it would go like this:</p>
<pre><code>var query =
from a in db.tblActivities
from i in a.tblIPs
from u in i.tblUsers
select new
{
userName = (u.UserName == null)
? i.Address
: u.UserName,
a.Request,
a.DateTime
};
</code></pre>
<p>The if statement needs to be in parentheses and the results outside of them. As for the joins, you follow the chain down from one->many.</p>
| 35,824
|
<p>I am going to be starting a javascript reporting engine for my website, and have started some prototyping using MooTools. I really like being able to do things like this:</p>
<pre><code>function showLeagues(leagues) {
var leagueList = $("leagues");
leagueList.empty();
for(var i = 0; i<leagues.length; ++i) {
var listItem = getLeagueListElement(leagues[i]);
leagueList.adopt(listItem);
}
}
function getLeagueListElement(league) {
var listItem = new Element('li');
var newElement = new Element('a', {
'html': league.name,
'href': '?league='+league.key,
'events': {
'click': function() { showLeague(league); return false; }
}
});
listItem.adopt(newElement);
return listItem;
}
</code></pre>
<p>From what I've seen, jQuery's "adopt" type methods only take html strings or DOM Elements. Is there any jQuery equivalent to MooTools' <a href="http://mootools.net/docs/Element/Element#Element:constructor" rel="nofollow noreferrer">Element</a>?
<hr/>
EDIT: The big thing I'm looking for here is the programmatic attachment of my click event to the link.</p>
|
<p>syntactically, it may be nicer to use jQuery to do it, but its probably more efficient to use</p>
<pre><code> document.createElement('li')
</code></pre>
<p>And eliminate the need for at the bare minimum a string comparison test and a minor token parse. </p>
<p><a href="http://flydom.socianet.com/" rel="noreferrer">flydom</a> may also tickle your interest if you insist on generating a lot of dom nodes. ( It should be faster in theory, but have not tested it )</p>
<hr>
<p>Note: Internally, jQuery("<html></html>") looks like it effectively does this(oversimplified):</p>
<pre><code>jQuery(matcher) --> function(matcher)
{
return jQuery.fn.init(matcher) --> function(matcher)
{
return this.setArray(
jQuery.makeArray(
jQuery.clean(matcher) --> function(matcher)
{
div = document.createElement('div');
div.innerHTML = matcher;
return div.childNodes;
}
)
);
}
}
</code></pre>
<p>So one would presume "<code>document.createElement</code>" is thus a "requirement", and if you <em>know</em> what you want out ( ie: not parising some 3rd party data with <code>$( datahere )</code> ) then <code>document.createElement</code> would imho be just as logical and with a speed boost to avoid the numerous regexps and slow string manipulations. </p>
<p>By comparison: <code>jQuery(document.createElement('div'))</code>
looks like it effectively does this(oversimplified):</p>
<pre><code>jQuery(matcher) --> function(matcher)
{
return jQuery.fn.init(matcher) --> function(matcher)
{
this[0] = matcher;
this.length = 1;
return this;
}
}
</code></pre>
|
<p>Here's that same thing in jQuery. Basically to create a new element, you just put in the HTML you want.</p>
<pre><code>function showLeagues(leagues) {
var $leagueList = $("#leagues");
$leagueList.empty();
$.each(leagues, function (index, league) {
$leagueList.append(getLeagueListElement(league));
});
}
function getLeagueListElement(league) {
return $('<li></li>')
.append($('<a></a>')
.html(league.name)
.attr('href', '?league=' + league.key)
.click(function() {
showLeague(league);
return false;
})
)
;
}
</code></pre>
| 21,267
|
<p>So if I have to choose between a hash table or a prefix tree what are the discriminating factors that would lead me to choose one over the other. From my own naive point of view it seems as though using a trie has some extra overhead since it isn't stored as an array but that in terms of run time (assuming the longest key is the longest english word) it can be essentially O(1) (in relation to the upper bound). Maybe the longest english word is 50 characters?</p>
<p>Hash tables are instant look up <em>once you get the index</em>. Hashing the key to get the index however seems like it could easily take near 50 steps.</p>
<p>Can someone provide me a more experienced perspective on this? Thanks!</p>
|
<p>Advantages of tries:</p>
<p>The basics:</p>
<ul>
<li>Predictable O(k) lookup time where k is the size of the key</li>
<li>Lookup can take less than k time if it's not there</li>
<li>Supports ordered traversal</li>
<li>No need for a hash function</li>
<li>Deletion is straightforward</li>
</ul>
<p>New operations:</p>
<ul>
<li>You can quickly look up prefixes of keys, enumerate all entries with a given prefix, etc.</li>
</ul>
<p>Advantages of linked structure:</p>
<ul>
<li>If there are many common prefixes, the space they require is shared.</li>
<li>Immutable tries can share structure. Instead of updating a trie in place, you can build a new one that's different only along one branch, elsewhere pointing into the old trie. This can be useful for concurrency, multiple simultaneous versions of a table, etc.</li>
<li>An immutable trie is compressible. That is, it can share structure on the <em>suffixes</em> as well, by hash-consing.</li>
</ul>
<p>Advantages of hashtables:</p>
<ul>
<li>Everyone knows hashtables, right? Your system will already have a nice well-optimized implementation, faster than tries for most purposes.</li>
<li>Your keys need not have any special structure. </li>
<li>More space-efficient than the obvious linked trie structure (<strong>see comments below</strong>)</li>
</ul>
|
<p>Some (usually embedded, real-time) applications require that the processing time be independent of the data. In that case, a hash table can guarantee a known execution time, while a trie varies based on the data.</p>
| 30,507
|
<p>I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.</p>
<p>For the screenshot of my profiling application go <a href="http://sites.google.com/site/javaperformacescreenshot/Home/profile.png" rel="noreferrer">here</a></p>
|
<blockquote>
<p>Are you dynamically creating new classes on the fly somehow?</p>
</blockquote>
<p>Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.</p>
<pre><code>JAXBContext context = JAXBContext.newInstance(this.getClass());
</code></pre>
<p>So although the JAXBContext wasn't saying around in the heap, the classes had been loaded.</p>
<p>I have run my program again, and I see a normal plateau as I would expect.</p>
|
<p>Yes, it's usually a memory leak (since we don't really deal with memory directly, it's more of a class instance leak). I've gone through this process before and usually it's some listener added to an old toolkit that didn't remove it self.</p>
<p>In older code, A listener relationship causes the "listener" object to remain around. I'd look at older toolkits or ones that haven't been through many revs. Any long-existing library running on a later JDK would know about reference objects which removes the requirement for "Remove Listener".</p>
<p>Also, call dispose on your windows if you recreate them each time. I don't think they ever go away if you don't (Actually there is also a dispose on close setting).</p>
<p>Don't worry about Swing or JDK listeners, they should all use references so you should be okay.</p>
| 20,260
|
<p>I'm trying to implement a dynamic OPTION list in JavaScript. Depending on other selections in the web form, some of the OPTIONS in a specific SELECT are not valid. Things I've tried that don't work in IE are: </p>
<ul>
<li>populate all options, then set the disabled property for those that are invalid</li>
<li>populate all options and use option groups, then disable invalid option groups </li>
<li>I even tried using a style of text-decoration:line-through</li>
</ul>
<p>At this point I'm resigned to repopulating the SELECT with only valid OPTIONs, but it seems like there ought to be a better way that actually works in IE. I require compatibility with IE6 and up. How have you dealt with this?</p>
|
<p><a href="http://webbugtrack.blogspot.com/2007/11/bug-293-cant-disable-options-in-ie.html" rel="nofollow noreferrer">IE doesn't support the disabled attribute on options</a>, and worse yet, <a href="http://webbugtrack.blogspot.com/2007/11/bug-280-lack-of-events-for-options.html" rel="nofollow noreferrer">IE doesn't support events on options</a>, and the <a href="http://webbugtrack.blogspot.com/2007/11/bug-291-no-styling-options-in-ie.html" rel="nofollow noreferrer">styling abilities are very limited in IE</a>.</p>
<p>Until IE joins the rest of the browser world in terms of common support for basic elements and basic functionality, you are SOL.</p>
|
<p>Is it such a problem to repopulate the select with just the valid options? I've used this method many times and haven't encountered any problems.</p>
| 39,034
|
<p>I have a listview working in virtual mode, in the LargeIcons view. Retrieves are expensive, so I want to ask for the data for all the visible items. How do I get the start index and total number of the visible items?</p>
<p>Update: I am aware of the CacheVirtualItems event. The third-party database we're using takes ~3s to retrieve a single record, but ~4s to retrieve a thousand records, so I have to do them in large blocks. I need to make sure the visible records are among those we retrieve, so I need to know the start index and total number of the visible items. If that's not feasible, I'll have to find a workaround (which will probably involve using a DataGridView with a load of image cells to imitate the LargeIcons view) but I would like to do this properly if possible.</p>
|
<p>THE REAL Answer is :<br>
* get the ScrollViewer of the ListView.<br>
* ScrollViewer.VerticalOffset is the index of first shown item.<br>
* ScrollViewer.ViewportHeight is the number of items shown. </p>
<p>To get the ScrollViewer, you will need a function,
FindDescendant(FrameworkElement, Type) that will search
within the childs of the
ListView. Call it after Window was loaded.</p>
<p>Code in VB.Net and in C# :</p>
<pre><code>Public Function FindDescendant(ByVal MyElementToSeek As FrameworkElement, _
ByVal TypeToFind As Type) As FrameworkElement
If MyElementToSeek Is Nothing Then Return Nothing
If MyElementToSeek.GetType() = TypeToFind Then Return MyElementToSeek
For i = 0 To VisualTreeHelper.GetChildrenCount(MyElementToSeek) - 1
Dim OneChild = TryCast(VisualTreeHelper.GetChild(MyElementToSeek, i), FrameworkElement)
Dim Result = FindDescendant(OneChild, TypeToFind)
If Result IsNot Nothing Then Return Result
Next
Return Nothing
End Function
</code></pre>
<p>.</p>
<pre><code>public FrameworkElement FindDescendant(FrameworkElement MyElementToSeek,
Type TypeToFind)
{
if (MyElementToSeek == null) return null;
if (MyElementToSeek.GetType() == TypeToFind) return MyElementToSeek;
for (i = 0;
(i<= (VisualTreeHelper.GetChildrenCount(MyElementToSeek) - 1)); i++)
{
object OneChild = TryCast(VisualTreeHelper.GetChild(MyElementToSeek, i),
FrameworkElement);
object Result = FindDescendant(OneChild, TypeToFind);
if (Result) return Result;
}
return null;
}
}
' MyScrollViewer = FindDescendant(MyListView, ScrollViewer)
</code></pre>
|
<pre><code>foreach (var t in listView1.Items)
{
var lvitem = listView1.ItemContainerGenerator.ContainerFromItem(t) as ListViewItem;
if (lvitem == null) continue;
//lvitem will = null if it is not visible
// otherwise do stuff with lvitem such as:
lvitem.Foreground = Brushes.Green;
}
</code></pre>
| 48,623
|
<p>Do any of the existing JavaScript frameworks have a non-regex <code>replace()</code> function,
or has this already been posted on the web somewhere as a one-off function?</p>
<p>For example I want to replace <code>"@!#$123=%"</code> and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.</p>
|
<p>i may be misunderstanding your question, but javascript does have a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer"><code>replace()</code></a></p>
<pre><code>var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');
</code></pre>
<p><strong>edit</strong>: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i <a href="http://safari.informit.com/0596101996/jscript5-CHP-11-SECT-2" rel="noreferrer">link directly</a> to it. here's the relevant part:</p>
<blockquote>
<p>The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. <strong>If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.</strong></p>
</blockquote>
|
<p>You can do it with or without ignoring case sensitivity. <br />
Sadly, JavaScript's indexOf doesn't take locale vs. invariant as argument, so you'll have to replace <code>toLowerCase</code> with <code>toLocaleLowerCase</code> if you want to preserve culture-specifity. </p>
<pre><code>function replaceAll(str, find, newToken, ignoreCase)
{
var i = -1;
if (!str)
{
// Instead of throwing, act as COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find) // sanity check
return str;
ignoreCase = ignoreCase || false;
find = ignoreCase ? find.toLowerCase() : find;
while ((
i = (ignoreCase ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
} // Whend
return str;
}
</code></pre>
<p>or as prototype:</p>
<pre><code>if (!String.prototype.replaceAll ) {
String.prototype.replaceAll = function (find, replace) {
var str = this, i = -1;
if (!str)
{
// Instead of throwing, act as COALESCE if find == null/empty and str == null
if ((str == null) && (find == null))
return newToken;
return str;
}
if (!find) // sanity check
return str;
ignoreCase = ignoreCase || false;
find = ignoreCase ? find.toLowerCase() : find;
while ((
i = (ignoreCase ? str.toLowerCase() : str).indexOf(
find, i >= 0 ? i + newToken.length : 0
)) !== -1
)
{
str = str.substring(0, i) +
newToken +
str.substring(i + find.length);
} // Whend
return str;
};
}
</code></pre>
| 36,705
|
<p>I'm using <code>System.Windows.Media.MediaPlayer</code> to play some sounds, and I would like to load these sounds from a ZIP file. It would be nice to be able to load these files as a stream directly from the zip file instead of having to unzip to a temp directory. However, <code>MediaPlayer.open</code> only accepts an URI. </p>
<p>So, is there a way to create a URI that will reference the contents of a stream? Something like an in-memory localhost? Is there any connector from Stream to URI? </p>
|
<p>This is only useful if you are actually vigilant with tracking and reviewing. When I was working on a team, no matter how much documented that for example our servers in the production environment were natted and would not be able to resolve their own domain names or public IP addresses, every 6 months, I'd get a call at 4 AM from the deployment team or dev team that a new developer was responsible for, and they either forgot or were unaware. </p>
<p>I remember a particular engineer who was repsonsible for deploying and he had paper checklists, we built him deployment tools that forced him to record his checklist, yet he would always forgot to set the connection string (resulting in the 4 am phone call). Point is it's only worth it if your going to use it vigilantly.</p>
<p>I've found the best way to use this is by implementing your rules into a code analyzer like fxcop. </p>
|
<p>I would also want to ask the question of how much time would be required to accurately track the mistakes, and if that time could be better spent directly on improving the software instead. If you can do this in a minimal amount of time and are able to refer back to your records to prevent future mistakes, it may be valuable. In the long run though, I think it will be better to stick with an absolutely high level list of common mistakes you make.</p>
| 38,114
|
<p>I'd like to line up items approximately like this:</p>
<pre><code>item1 item2 i3 longitemname
i4 longitemname2 anotheritem i5
</code></pre>
<p>Basically items of varying length arranged in a table like structure. The tricky part is the container for these can vary in size and I'd like to fit as many as I can in each row - in other words, I won't know beforehand how many items fit in a line, and if the page is resized the items should re-flow themselves to accommodate. E.g. initially 10 items could fit on each line, but on resize it could be reduced to 5.</p>
<p>I don't think I can use an html table since I don't know the number of columns (since I don't know how many will fit on a line). I can use css to float them, but since they're of varying size they won't line up.</p>
<p>So far the only thing I can think of is to use javascript to get the size of largest item, set the size of all items to that size, and float everything left.</p>
<p>Any better suggestions?</p>
|
<p>This can be done using floated div's, calculating the max width, and setting all widths to the max. Here's jquery code to do it:</p>
<p>html:</p>
<pre><code><div class="item">something</div>
<div class="item">something else</div>
</code></pre>
<p>css:</p>
<pre><code>div.item { float: left; }
</code></pre>
<p>jquery:</p>
<pre><code>var max_width=0;
$('div.item').each( function() { if ($(this).width() > max_width) { max_width=$(this).width(); } } ).width(max_width);
</code></pre>
<p>Not too ugly but not too pretty either, I'm still open to better suggestions...</p>
|
<p>You could use block level elements floated left, but you will need some javascript to check the sizes, find the largest one, and set them all to that width.</p>
<p>EDIT: Just read the second half of your post, and saw that you suggested just this fix. Count this post as +1 for your current idea :)</p>
| 14,962
|
<p>Basically I would like to find a way to ddo something like:</p>
<pre><code><asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
</code></pre>
<p>I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution.
(MyProperty is a string property)
cheers</p>
|
<p>You can do </p>
<pre><code><asp:Label runat="server" Text='<%# MyProperty %>' />
</code></pre>
<p>And then a Page.DataBind() in the codebehind.</p>
|
<p>Call lID.Databind() from code-behind</p>
| 9,916
|
<p>I'd like to add a drop-down list to a Windows application. It will have two choices, neither of which are editable. What's the best control to use? Is it a combo box with the editing property set to No?</p>
<p>I'm using Visual Studio 2008.</p>
|
<p>I'd suggest taking a look at the <a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" rel="nofollow noreferrer">Windows Vista User Experience Guide</a>. It sounds like you might be better off with radio buttons, or, if it's an explicit on/off type of situation, using a check box. I think we'd really need more info, though.</p>
|
<p>Set the DropDownStyle property to DropDownList.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle(VS.80).aspx</a></p>
| 12,779
|
<p>Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it?</p>
<p>I have an a "multi-environment" scenario where there are multiple versions of the same database schema. Examples of environments might be "Development", "Staging", & "Production". "Development" is going to have one version of the stored procedure and "Staging" is going to have another.</p>
<p>All I want to do is validate that a parameter is going to be there before passing it a value and calling the stored procedure. Avoiding that SqlException rather than having to catch it is a plus for me.</p>
<p>Joshua</p>
|
<p>You can use SqlCommandBuilder.DeriveParameters() (see <a href="https://web.archive.org/web/20110304121600/http://www.davidhayden.com/blog/dave/archive/2006/11/01/SqlCommandBuilderDeriveParameters.aspx" rel="nofollow noreferrer">SqlCommandBuilder.DeriveParameters - Get Parameter Information for a Stored Procedure - ADO.NET Tutorials</a>) or there's <a href="http://www.codeproject.com/KB/database/enumeratesps.aspx" rel="nofollow noreferrer">this way</a> which isn't as elegant.</p>
|
<p>All of these ADO.NET solutions are are asking the code library to query the database's metadata on your behalf. If you are going to take that performance hit anyhow, maybe you should just write some helper functions that call </p>
<pre><code>Select count(*) from information_schema.parameters
where ...(proc name =.. param name=...) (pseudo-code)
</code></pre>
<p>Or maybe even generate your parameters based on the param list you get back. This technique will work with multiple versions of MS SQL and sometimes other ANSI SQL databases.</p>
| 5,385
|
<p>I'd like to find a few large .NET projects that have public source code available.</p>
|
<p>For winforms development, <a href="http://www.icsharpcode.net/OpenSource/SD/" rel="nofollow noreferrer">SharpDevelop</a>.</p>
|
<p>Data & Object Factory has a sample application that they publish (<em>Patterns in Action</em>) to showcase design patterns in .NET. The application shows implemetation of the design patterns from the Gang of Four and .NET versions of the patterns from <em>Head First Design Patterns</em>. It's all done in C#, and shows UIs done in ASP.NET, WPF, and WinForms. I don't regret the subscription one bit (and it wasn't much at all).</p>
<p>If you don't mind spending a few bucks for something that gives you lots of really useful, heavily documented, working code that models a real-world application (a shopping cart for an online store), it's worth it (at least, in my opinion).</p>
<p>I heartily recommend them. </p>
<p><a href="http://www.dofactory.com/Default.aspx" rel="nofollow noreferrer">Data & Object Factory</a></p>
| 49,740
|
<p>I'm using the Fish Gadget (<a href="http://abowman.com/google-modules/fish/" rel="noreferrer">http://abowman.com/google-modules/fish/</a>) within a wiki based CMS, and need to reposition the gadget from one HTML element to another. (Note: the fish gadget is an example -- the problem occurs with other gadgets as well.)</p>
<p>If I directly reposition the gadget using the gadgets base class "ig_reset", then everything works. If I try to reposition using a surrounding wrapper, then the iframe used by the gadget seems to take over. Unfortunately I need the flexibility of repositioning using the surrounding wrapper. </p>
<p>This seems to have something to do with moving a SCRIPT tag around in the DOM. The gadget dynamically creates a script and a style tag. If I <em>remove</em> the dynamically created script tag from the DOM, and then reposition the wrapper to another location in the DOM, all works well. If I try to <em>move</em> the script tag to another DOM element then the original problem occurs. So <em>moving</em> a script tag around the DOM seems to be the cause -- regardless of when the move occurs (even post-load).</p>
<p>I'd like to understand what is happening here to cause the frame to take over the page, and also find a better solution than removing the dynamically created script tag.</p>
<p>I put a test up here: <a href="http://solidgone.com/jquery/google-gadget.html" rel="noreferrer">http://solidgone.com/jquery/google-gadget.html</a> -- the demo uses jQuery, but I don't think this is related to jQuery...</p>
|
<p>Whenever you append a script element into a page, using jQuery, it will attempt to execute it. Thus when you move ig_reset (which is only a table - no script) it works without issue. When you try to move the wrapper - which contains the script - the script is moved and re-executed.</p>
<p>We're working to fix this re-execution issue in jQuery core but for the time being that's what is going on here.</p>
|
<p>As John Resig notes, this <em>is</em> a jQuery issue. You can verify this by replacing your handler</p>
<pre><code>$("#with-wrapper").click(function ()
{
$('.sidebar-content-wrapper').contents().appendTo($("#sidebar"));
});
</code></pre>
<p>with one that avoids using the jQuery methods to actually move each element:</p>
<pre><code>$("#with-wrapper").click(function()
{
var sidebar = $("#sidebar")[0];
$('.sidebar-content-wrapper').contents().each(function()
{
// raw DOM method rather than jQuery's
// appendTo() -> domManip() -> execute script blocks behavior
sidebar.appendChild(this);
});
});
</code></pre>
| 41,138
|
<p>I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it</p>
<pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)
BEGIN
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,
FROM
ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID
WHERE ShoppingCartItem.PurchID = @PurchID
EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity
IF @ErrorCode <> 0
BEGIN
Goto Cleanup
END
DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID
-- @@ROWCOUNT is 1 after this
END
</code></pre>
<p>Facts:</p>
<ol>
<li>There's only one or two records matching the first select-clause</li>
<li>RowCount from the DELETE statement indicates that it has been removed</li>
<li>The WHILE-clause will loop forever</li>
</ol>
<p>The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.</p>
<p>Why does it loop forever?</p>
<p><strong>Clarification</strong>: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged)
<strong>Clarification 2</strong>: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.</p>
<p><strong>Update</strong>: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.</p>
<p><strong>Update clarification</strong>: <a href="https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400">brien</a> pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand</p>
|
<p>Are you operating in explicit or implicit <a href="http://doc.ddart.net/mssql/sql70/ta-tz_8.htm" rel="nofollow noreferrer">transaction mode</a>?</p>
<p>Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements.</p>
<pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)
BEGIN
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,
FROM
ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID
WHERE ShoppingCartItem.PurchID = @PurchID
EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity
IF @ErrorCode <> 0
BEGIN
Goto Cleanup
END
BEGIN TRANSACTION delete
DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID
-- @@ROWCOUNT is 1 after this
COMMIT TRANSACTION delete
END
</code></pre>
<p><strong>Clarification:</strong> The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful.</p>
<p>In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to <strong>really</strong> make the changes.</p>
|
<p>I not sure if I understand the problem, but in the select clause it's making an inner join with another table. That join can cause to get no records and then the delete fails. Try using a left join.</p>
| 18,107
|
<p>What is the data that Process and Thread will not share ? </p>
<p>An advance thanks goes to everybody who provide their time</p>
|
<p>Separate processes do not share any data with each other.</p>
<p>Threads can share any heap-allocated or static data if they are running within the same process.</p>
|
<p>On UNIX, processes can share file descriptors with their child processes if the file descriptors are not set to close on exec (<code>FD_CLOEXEC</code>). Likewise, Windows supports sharing handles with child processes by setting <code>lpSecurityAttributes->bInheritHandle</code> to <code>TRUE</code> when calling <code>CreateFile()</code> and then setting <code>bInheritHandles</code> to <code>TRUE</code> when calling <code>CreateProcess</code>. Not to mention that the Microsoft C runtime <code>_open()</code> function accepts a <code>_O_NOINHERIT</code> flag.</p>
<p>On Linux, the <a href="http://linux.die.net/man/2/clone" rel="nofollow noreferrer"><code>clone()</code></a> syscall gives you a lot of control over what the child process shares with its parent: everything from the address space (<code>CLONE_VM</code>) to the file descriptor table (<code>CLONE_FILES</code>) to the parent process ID (<code>CLONE_PARENT</code>) can be either shared or not shared. Of course, this functionality was added to support kernel threads.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms686749.aspx" rel="nofollow noreferrer">Thread-local storage (TLS)</a> is indexed differently for each thread in a process, but the actual memory is shared between threads.</p>
| 21,344
|
<p>I'm looking around for a Java <a href="http://en.wikipedia.org/wiki/Code_signing" rel="noreferrer">code signing</a> certificate so my Java applets don't throw up such scary security warnings. However, all the places I've found offering them charge (in my opinion) way too much, like over USD200 per year. While doing research, a code signing certificate seems almost exactly the same as an <a href="http://en.wikipedia.org/wiki/SSL" rel="noreferrer">SSL</a> certificate.</p>
<p>The main question I have: is it possible to buy an SSL certificate, but use it to sign Java applets?</p>
|
<p>Short answer: No, they're different.</p>
<p>Long answer: It's the same sort of certificate and it uses the same crypto software, but the certificate has flags indicating what it is allowed to be used for. Code signing and web server are different uses. </p>
|
<p>Thawte offers code signing certificates <a href="http://www.thawte.com/code-signing/" rel="nofollow noreferrer">here</a>. I imagine other Certificate Authorities offer this service as well. You can also create self-signed certificates, with <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/solaris/keytool.html" rel="nofollow noreferrer">Java keytool</a>.</p>
| 10,431
|
<p>I have a UserControl Library solution which has the following </p>
<p>UserControl
---UserControl project</p>
<pre><code> ---UserControl Test Project
</code></pre>
<p>IN my test project, I am able to add my usercontrol to the tool box. When i drag it and drop it in my forms, it fails. I put in logging and found out that my usercontrol reads a config file. The config file is marked to copy always and exists in the obj\debug and the bin\debug directory/.</p>
<p>However when i drag the usercontrol to a form on my test project, it is trying to get a file from </p>
<p>C:\Documents and Settings\jondoe\Local Settings\Application Data\Microsoft\VisualStudio\8.0\ProjectAssemblies\vqjlihdl01</p>
<p>The above is a result of this</p>
<pre><code>string pluginAssemblyPath = Assembly.GetExecutingAssembly().Location;
DirectoryInfo dirInfo = new DirectoryInfo(pluginAssemblyPath);
pluginAssemblyPath = pluginAssemblyPath.Replace(dirInfo.Name.ToString(),"");
string configFilePath = pluginAssemblyPath + "FileConfig.xml";
</code></pre>
<p>I would have assumed that if i compile in debug mode, the file should be under obj\debug and that should be my assembly path. what gives or is there some setting that i need to do to get it to run correctly so that it can find my config file in the right location?</p>
|
<p>Beware, I have found the DesignMode property to be unreliable where you have a control on another control on a form (say). It only seems to work for controls placed directly on the design surface.</p>
|
<p>Do you need the config file at design time? If not, you could change your code to test if it is running at design time, something like:</p>
<pre><code>if (this.Site != null && this.Site.DesignMode)
{
... design time behavior
}
else
{
... runtime behavior (read config file)
}
</code></pre>
| 46,963
|
<p>I may be barking up the wrong tree... However, what I have is a MySQL server that accepts connections only from a client with a valid SSL cert (see <a href="http://dev.mysql.com/doc/refman/5.0/en/secure-create-certs.html" rel="nofollow noreferrer">this link</a>). This works great for example with Rails. I have my database on one server, and a Rails app that connects using the client certificate. Maybe not the fastest, but it works.</p>
<p>The configuration in <strong>database.yml</strong> looks something like this:</p>
<pre><code>sslkey: /path/to/client-key.pem
sslcert: /path/to/client-cert.pem
sslca: /path/to/ca-cert.pem
</code></pre>
<p>The problem is that I'd like to host phpMyAdmin on the same server as the Rails app. I think that phpMyAdmin is simply more limited in its connection options because I can't seem to find a way for it to use a client certificate to connect. But what I found odd was that Googling for answers didn't turn up much on this subject (which makes me wonder if I'm taking the wrong approach to this).</p>
<p>Obviously, I can easily set up phpMyAdmin itself to be hosted behind an SSL certificate (which will encrypt requests between the client browser and my phpMyAdmin server) but I want the phpMyAdmin <-> db connection to be encrypted as well.</p>
<p>Is this possible? Is this a bad design choice? Are there better ways to do this?</p>
|
<p>in your <code>config.inc.php</code> add this line after applicable server stuff: </p>
<pre><code>$cfg['Servers'][$i]['ssl']=true;
</code></pre>
<p>Assuming your php and its mysql client is configured with SSL in mind this should work. </p>
|
<p>I agree, the answer is not sufficient. The place everybody tells you to put your SSL certificate and pointer is in a <code>conf.d</code> virtualhost block. But that is for inbound traffic. Only if your <code>phpmyadmin</code> is being accessed from the IP address of the mysql server but that is NOT the case with this example. Here we are using <code>phpmyadmin</code> to go out and make a REMOTE request to a REMOTE server from a local machine. </p>
<p>In order to do it, <code>phpmyadmin</code> must have a config setting to allow specification of where the <code>cert</code> files are. Otherwise, I don't see how this will work. Although maybe the virtualhost block will work for outgoing traffic too. I suppose we can try ... My thoughts are that virtualhost works only for INBOUND traffic.</p>
| 42,995
|
<p>In a <strong>Win32</strong> environment, you can use the <strong>GetLastInputInfo API</strong> call in <a href="https://learn.microsoft.com/windows/desktop/api/winuser/nf-winuser-getlastinputinfo" rel="nofollow noreferrer">Microsoft documentation</a>. Basically, this method returns the last tick that corresponds with when the user last provided input, and you have to compare that to the current tick to determine how long ago that was.</p>
<p>Xavi23cr has a good example for C# at <a href="http://www.codeproject.com/KB/cs/GetIdleTimeWithCS.aspx" rel="nofollow noreferrer">codeproject</a>.</p>
<p>Any suggestions for other environments?</p>
|
<p>As for Linux, I know that Pidgin has to determine idle time to change your status to away after a certain amount of time. You might open the source and see if you can find the code that does what you need it to do.</p>
|
<p>You seem to have answered your own question there Nathan ;-)
"GetLastInputInfo" is the way to go.</p>
<p>One trick is that if your application is running on the desktop, and the user connects to a virtual machine, then GetLastInputInfo will report no activity (since there is no activity on the host machine).</p>
<p>This can be different to the behaviour you want, depending on how you wish to apply the user input.</p>
| 2,480
|
<p>I use ssh-agent with password-protected keys on Linux. Every time I log into a certain machine, I do this:</p>
<pre><code>eval `ssh-agent` && ssh-add
</code></pre>
<p>This works well enough, but every time I log in and do this, I create another ssh-agent. Once in a while, I will do a <code>killall ssh-agent</code> to reap them. Is there a simple way to reuse the same ssh-agent process across different sessions?</p>
|
<p>have a look at Keychain. It was written b people in a similar situation to yourself.
<a href="http://www.gentoo.org/proj/en/keychain/" rel="noreferrer">Keychain</a></p>
|
<p>Depending on which shell you use, you can set different profiles for login shells and mere regular new shells. In general you want to start ssh-agent for login shells, but not for every subshell. In bash these files would be <code>.bashrc</code> and <code>.bash_login</code>, for example.</p>
<p>Most desktop linuxes these days run ssh-agent for you. You just add your key with ssh-add, and then forward the keys over to remote ssh sessions by running </p>
<pre>
ssh -A
</pre>
| 12,791
|
<p>Im using asynchronous threading in my application WITH httpClient. I make a call using the Future Api like so </p>
<pre><code>mStrResults = (String) rssFuture.get();
</code></pre>
<p>this call attempts to retrieve an html string returned from my Callable httpClient call() method.</p>
<p>What i want to do however is ensure that the get method does not wait too long while executing the call() method. Should i pass a timeout parameter when calling rssFuture.get() or is it ok to just surround with a InterruptedException catch block?</p>
<p>Also is there a default time which the asynchronous thread will wait before throwing an InterruptedException and if so can i set a custom value?</p>
|
<p>I'm not sure I understand your format exactly (it displays a little strange to me) but the easiest way to do this is <code>with - (NSArray *)componentsSeparatedByString:(NSString *)separator</code> which is a method in the NSString class... example:</p>
<pre><code>NSArray *components = [myString componentsSeperatedByString:@"\t"];
</code></pre>
<p>This returns an <code>NSArray</code> of <code>NSStrings</code>, one for each tab-delimited field. If the new-line separators are important you can use <code>- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator</code> (also on <code>NSString</code>) to split using more than one kind of delimiter.</p>
|
<p>I had a feeling more than a flat list is wanted. If you want a multidimensional structure you can do something like this:</p>
<pre><code>NSArray *lines = [data componentsSeparatedByString:@"\n"];
for (NSString *line in lines) {
NSArray *fields = [line componentsSeparatedByString:@"\t"];
// Do something here with each two-element array, such as add to an NSDictionary or to an NSArray (to make a multidimensional array.)
}
</code></pre>
| 45,969
|
<p>I'd like to make a video tutorial for my SDK--one of those videos that shows the screen while some dude talks about what he's doing. Can someone direct me to easy and preferably free tools for doing so?</p>
<p>Desired features:
- Cuts (recording several snippets of video and putting them together afterward)
- Subtitles (not only for user convenience but because I'd rather not disturb the other cubicles by talking in a microphone at work :))</p>
<p>(<a href="https://stackoverflow.com/questions/139621/can-we-get-rid-of-video-tutorials-please">who doesn't like video tutorials?</a>)</p>
<p>Update: I'm using Windows.</p>
|
<p>Camtasia is very good. I've also used wink, it is flash instead of video, but you can add navigation controls and text boxes. </p>
|
<p>a cool tool for screencasting is Camtasia Studio <a href="http://www.techsmith.com/camtasia.asp" rel="nofollow noreferrer">http://www.techsmith.com/camtasia.asp</a> with a free 30 day trial</p>
<p>example : <a href="http://static.interspire.com/isc-demo/index.html" rel="nofollow noreferrer">http://static.interspire.com/isc-demo/index.html</a></p>
| 41,142
|
<p>Is there a way on the CVS command line to list all files associated with a tag?</p>
|
<p>About the closest you'll be able to get is with this:</p>
<p>cvs -q log -R -N -S -rTAGNAME</p>
<p>This works against local copy, it doesn't pull from the server.</p>
<p>EDIT:</p>
<p>As Ken mentioned, a slight variation will make it pull from the server, but in this situation you need to specify the module name too.</p>
<p>cvs -q rlog -R -N -S -rTAGNAME MODULENAME</p>
|
<p>I think it's</p>
<pre><code>cvs ls -lR -r tag
</code></pre>
<p>but I'm on SVN now, so you'll have to test it.</p>
| 34,277
|
<p>While calculating the hash table bucket index from the hash code of a key, why do we avoid use of remainder after division (modulo) when the size of the array of buckets is a power of 2?</p>
|
<p>When calculating the hash, you want as much information as you can cheaply munge things into with good distribution across the entire range of bits: e.g. 32-bit unsigned integers are usually good, unless you have a lot (>3 billion) of items to store in the hash table.</p>
<p>It's converting the hash code into a bucket index that you're really interested in. When the number of buckets n is a power of two, all you need to do is do an AND operation between hash code h and (n-1), and the result is equal to h mod n.</p>
<p>A reason this may be bad is that the AND operation is simply discarding bits - the high-level bits - from the hash code. This may be good or bad, depending on other things. On one hand, it will be very fast, since AND is a lot faster than division (and is the usual reason why you would choose to use a power of 2 number of buckets), but on the other hand, poor hash functions may have poor entropy in the lower bits: that is, the lower bits don't change much when the data being hashed changes.</p>
|
<p>Let us say that the table size is m = 2^p.
Let k be a key.
Then, whenever we do k mod m, we will only get the last p bits of the binary representation of k. Thus, if I put in several keys that have the same last p bits, the hash function will perform VERY VERY badly as all keys will be hashed to the same slot in the table. Thus, avoid powers of 2</p>
| 35,042
|
<p>I was in the process of printing a 16 hour print, but I must have failed to copy the G-code correctly, because the print stopped after 107 of 223 layers. Looking at the G-code, It also stops there. </p>
<p>However, I had the full G-code on my computer, and decided to try and resume the print from layer 108. It seemed to work, with the exception of a little excess extrusion at a single point in the beginning, but after three layers, i noticed that it wasn't extruding anymore. I am not completely positive that it isn't due to nozzle jamming, but I have a strong feeling that the problem is the G-code itself, as it does extrude some plastic just before printing starts.</p>
<p>Here are the first lines of my manually edited G-code. Can anyone see why I get the blob in the beginning, or why I don't get anything at all later on? Or does it look good, and my problem is probably the nozzle? </p>
<pre><code>;FLAVOR:UltiGCode
;TIME:60308
;MATERIAL:119047
;MATERIAL2:0
;NOZZLE_DIAMETER:0.400000
;NOZZLE_DIAMETER2:0.400000
;MTYPE:PLA
;Layer count: 222
;LAYER:109
G0 F9000 X208.213 Y107.948 Z16.610
;TYPE:FILL
G1 F3600 X210.390 Y105.771 E4104.65185
G0 F9000 X210.390 Y103.170
G1 F3600 X168.331 Y61.111 E4107.77457
G0 F9000 X167.074 Y61.111
G1 F3600 X120.237 Y107.949 E4111.25208
G0 F9000 X121.695 Y107.949
G1 F3600 X74.857 Y61.111 E4114.72962
G0 F9000 X73.600 Y61.111
G1 F3600 X26.763 Y107.948 E4118.20709
</code></pre>
|
<p>According to the RepRap.org <a href="http://reprap.org/wiki/G-code" rel="nofollow noreferrer">list of G-Code commands</a>, see <strong><a href="http://reprap.org/wiki/G-code#G0_.26_G1:_Move" rel="nofollow noreferrer">G0 & G1: Move</a></strong>:</p>
<blockquote>
<p>The <code>Ennn</code> command is <em>The amount to extrude between the starting point and ending point</em>. </p>
</blockquote>
<p>However, according to <strike><a href="https://github.com/daid/Cura/issues/385" rel="nofollow noreferrer">this</a></strike> a discussion, that is now deleted from GitHub, about the Cura slicing engine:</p>
<p>The <strong>E</strong> values are in <em>absolute mode</em>, so perhaps the firmware is attempting to move the stepper motor to the absolute position (which is almost 50% through your print). This may lead to clogging or skipping depending on how hot your extruder is at that point.</p>
<p>As a last resort, you can perform a Boolean subtract on your model of the section that's already printed and re-slice the model to print the remaining bit. Then glue, or ABS weld, the remaining piece to the main print. I've done this in the past, it's not super glamorous, but it gets the job done if the part doesn't require a lot of structural integrity.</p>
<p><strong>I was incorrect with the following statements with regard to the Cura slicing engine:</strong> </p>
<p><s>It's been a while since I've looked at 3D printer G-Code, but from what I remember, <strong>E</strong> values can be the bane of any manually written G-Code. Usually the slicing engine generates the <strong>E</strong> value as an incremental step value throughout the G-Code (at least this was true for Skeinforge and early MakerWare, please verify this). So, if the value is incremental and depending on the controller, this value could be lost or corrupt if a new print is initialized.</p>
<p>I would hope, that if you're using a slicing engine's <em>custom G-Code</em> input, that the software would be able to compensate situations like this and reformat your provided G-Code to match the value of <strong>E</strong> or any similar command.</s></p>
|
<p>Is the hotend temperature set correctly? If you only preheat the hotend but then turn it off, it will behave exactly as you described (while you're above <code>EXTRUDE_MINTEMP</code> it will behave normally, but once the temperature drops too low it will continue doing the XYZ-moves, but stop extruding). Perhaps you need to add a <code>M109</code> command to set the temperature properly.</p>
<p><a href="https://3dprinting.stackexchange.com/questions/850/no-extrusion-when-trying-to-resume-failed-print-with-manually-edited-gcode/851#851">In his answer</a>, tbm0115 mentions absolute and relative coordinates. Whether absolute or relative coordinates are used is set using the <code>G90</code>/<code>G91</code> commands and will always be the same for all axes (XYZ and E). He also mentions that:</p>
<blockquote>
<p>so perhaps the firmware is attempting to move the stepper motor to the absolute position (which is almost 50% thru your print). This may lead to clogging or skipping depending on how hot your extruder is at that point.</p>
</blockquote>
<p>This shouldn't happen, as extremely long extrude moves are ignored by Marlin. When the printer encounters</p>
<pre><code>G1 F3600 X210.390 Y105.771 E4104.65185
</code></pre>
<p>it performs only the XYZ-part of the move, but doesn't move the extruder (assuming the printer was reset and the current extruder position is 0). However, it does update the internal value for the extruder position, so the next move happens normally. Perhaps missing the initial extrude segment isn't a big deal, but if you want the print to resume perfectly where you left off, you should add a <code>G92</code> command to the beginning to initialize the extruder position correctly, for example:</p>
<pre><code>G92 E4104.4
</code></pre>
<p>(but the exact value depends on the last extruder position in the previous layer).</p>
| 230
|
<p>I am wondering what makes sense in relation to what objects to expose through a WCF service - should I add WCF Serialization specifications to my business entities or should I implement a converter that maps my business entities to the DataContracts that I want to expose through my WCF service?</p>
<p>Right now I have entities on different levels: DataAccess, Business and Contract. I have converters in place that can map entities from DataAccess to Business and from Business to Contract and vice versa. Implementing and Maintaining those is time consuming and pretty tedious. What are best practices in relation to this? </p>
<p>If I were using an OR/M such as NHibernate or Entity Framework should I be exposing the entities from the ORM directly or should I abstract them the same way I am doing now?</p>
|
<p>In general, I think from a best practices standpoint, you should not expose the structure of your business objects as data contracts, but rather define "data contract-specific" classes and convert Business to Contract. It may require extra work, but from a separation of concerns and protection from change standpoint the extra work is probably worth it.</p>
<p>The <a href="http://www.codeplex.com/servicefactory" rel="noreferrer">Microsoft patterns & practices "Service Factory Modeling Edition"</a> implements this, and also provides tooling to auto-generate Business <=> Contract converter classes -- it's an excellent VS add-in, and also represents Microsoft's best practices for WCF.</p>
|
<p>Just to add to the above answers:
The object that the webservice exposes is called the Data Transfer Object (DTO). Having a DTO to map your Business Entity object (BEO) is good because of the separation it provides between your webservice and the actual implementation/logic that lies behind the web-service.</p>
<p>Finally, here is how you can decorate the DTO so that when it is exposed by the WSDL the names reflect the actual objects it represent (instead of objectNameDTO or something ugly like that).</p>
<pre><code>//Business Entity
class Person
{
public string Name{ get; set; }
public int Age{ get; set; }
}
//Data transfer object
[DataContract(Name="Person")] //<-- this is what makes the WSDL look nice and clean
class PersonDTO
{
[DataMember(Name = "Name", Order = 0)]
public string Name{ get; set; }
[DataMember(Name = "Age", Order = 1)]
public int Age{ get; set; }
}
</code></pre>
| 10,919
|
<p>Im trying to extract a line from wget's result but having trouble with it.
This is my wget call:</p>
<pre><code>$ wget -SO- -T 1 -t 1 http://myurl.com:15000/myhtml.html
</code></pre>
<p>Output:</p>
<pre>
--18:24:12-- http://xxx.xxxx.xxxx:15000/myhtml.html
=> `-'
Resolving xxx.xxxx.xxxx... xxx.xxxx.xxxx
Connecting to xxx.xxxx.xxxx|xxx.xxxx.xxxx|:15000... connected.
HTTP request sent, awaiting response...
HTTP/1.1 302 Found
Date: Tue, 18 Nov 2008 23:24:12 GMT
Server: IBM_HTTP_Server
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Location: https://xxx.xxxx.xxxx/siteminderagent/...
Content-Length: 508
Keep-Alive: timeout=10, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
Location: https://xxx.xxxx.xxxx//siteminderagent/...
--18:24:13-- https://xxx.xxxx.xxxx/siteminderagent/...
=> `-'
Resolving xxx.xxxx.xxxx... failed: Name or service not known.
</pre>
<p>if I do this: <br/><br/></p>
<pre><code>$ wget -SO- -T 1 -t 1 http://myurl.com:15000/myhtml.html | egrep -i "302" <br/>
</code></pre>
<p>It doesnt return me the line that contains the string. I just want to check if the site or siteminder is up.</p>
|
<p>The output of wget you are looking for is written on stderr. You must redirect it:</p>
<pre><code>$ wget -SO- -T 1 -t 1 http://myurl.com:15000/myhtml.html 2>&1 | egrep -i "302"
</code></pre>
|
<p>I found this question trying to scrape response codes to large lists of URLs after finding <code>curl</code> very slow (5+s per request).</p>
<p>Previously, I was using this:</p>
<p><code>curl -o /dev/null -I --silent --head --write-out %{http_code} https://example.com</code></p>
<p>Building off Piotr and Adam's answers, I came up with this:</p>
<p><code>wget -Sq -T 1 -t 1 --no-check-certificate --spider https://example.com 2>&1 | egrep 'HTTP/1.1 ' | cut -d ' ' -f 4</code></p>
<p>This has a few bugs e.g. redirects return <code>302 200</code>, but overall is greased lightning in comparison.</p>
| 38,796
|
<p>I have an ASP.NET 2.0 application that spends an excessive amount of time in garbage collection, over 40%, when load tested on a production grade server (dual quad-core, 4g).
I have been trying to isolate the problem but it is a large, complex code base making for slow going. There are no GC.Collect() calls. Which tools, techniques, etc. are helpful when trying to isolate this type of problem?</p>
|
<p>I've found the debugging labs on <a href="http://blogs.msdn.com/tess/" rel="nofollow noreferrer">Tess Ferrandez's blog</a> very helpful when looking at these sorts of issues.</p>
|
<p>Well, first off, my trick knee is acting up, and when it does that, it either means it's about to snow, or someone has been using a lot of "+" operators for string concatenation instead of using StringBuilder as the good lord intended.</p>
<p>What about <a href="http://www.red-gate.com/Products/ants_profiler/index.htm" rel="nofollow noreferrer">ANTS Profiler</a>? I'd used that a while back and liked it. There's also a <a href="http://msdn.microsoft.com/en-us/magazine/cc300553.aspx" rel="nofollow noreferrer">Profiling API</a> you can use to catch your own data.</p>
| 49,774
|
<p>In the clocks application, the timer screen shows a picker (probably a <code>UIPicker</code> in <code>UIDatePickerModeCountDownTimer</code> mode) with some text in the selection bar ("hours" and "mins" in this case).</p>
<p>(edit) Note that these labels are <strong>fixed</strong>: They don't move when the picker wheel is rolling.</p>
<p>Is there a way to show such fixed labels in the selection bar of a standard <code>UIPickerView</code> component?</p>
<p>I did not find any API that would help with that. A suggestion was to add a <code>UILabel</code> as a subview of the picker, but that didn't work.</p>
<hr>
<p><strong>Answer</strong></p>
<p>I followed Ed Marty's advice (answer below), and it works! Not perfect but it should fool people. For reference, here's my implementation, feel free to make it better...</p>
<pre><code>- (void)viewDidLoad {
// Add pickerView
self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectZero];
[pickerView release];
CGSize pickerSize = [pickerView sizeThatFits:CGSizeZero];
CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
#define toolbarHeight 40.0
CGFloat pickerTop = screenRect.size.height - toolbarHeight - pickerSize.height;
CGRect pickerRect = CGRectMake(0.0, pickerTop, pickerSize.width, pickerSize.height);
pickerView.frame = pickerRect;
// Add label on top of pickerView
CGFloat top = pickerTop + 2;
CGFloat height = pickerSize.height - 2;
[self addPickerLabel:@"x" rightX:123.0 top:top height:height];
[self addPickerLabel:@"y" rightX:183.0 top:top height:height];
//...
}
- (void)addPickerLabel:(NSString *)labelString rightX:(CGFloat)rightX top:(CGFloat)top height:(CGFloat)height {
#define PICKER_LABEL_FONT_SIZE 18
#define PICKER_LABEL_ALPHA 0.7
UIFont *font = [UIFont boldSystemFontOfSize:PICKER_LABEL_FONT_SIZE];
CGFloat x = rightX - [labelString sizeWithFont:font].width;
// White label 1 pixel below, to simulate embossing.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, top + 1, rightX, height)];
label.text = labelString;
label.font = font;
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[self.view addSubview:label];
[label release];
// Actual label.
label = [[UILabel alloc] initWithFrame:CGRectMake(x, top, rightX, height)];
label.text = labelString;
label.font = font;
label.backgroundColor = [UIColor clearColor];
label.opaque = NO;
label.alpha = PICKER_LABEL_ALPHA;
[self.view addSubview:label];
[label release];
}
</code></pre>
|
<p>Create your picker, create a label with a shadow, and push it to a picker's subview below the selectionIndicator view. </p>
<p>It would look something like this</p>
<pre><code>
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(135, 93, 80, 30)] autorelease];
label.text = @"Label";
label.font = [UIFont boldSystemFontOfSize:20];
label.backgroundColor = [UIColor clearColor];
label.shadowColor = [UIColor whiteColor];
label.shadowOffset = CGSizeMake (0,1);
[picker insertSubview:label aboveSubview:[picker.subviews objectAtIndex:5]];
//When you have multiple components (sections)...
//you will need to find which subview you need to actually get under
//so experiment with that 'objectAtIndex:5'
//
//you can do something like the following to find the view to get on top of
// define @class UIPickerTable;
// NSMutableArray *tables = [[NSMutableArray alloc] init];
// for (id i in picker.subviews) if([i isKindOfClass:[UIPickerTable class]]) [tables addObject:i];
// etc...
</code></pre>
<p>-- Pay it forward</p>
|
<p>Can you show where you define pickerTop and pickerSize?</p>
<pre><code> CGFloat pickerTop = timePicker.bounds.origin.y;
CGSize pickerSize = timePicker.bounds.size;
</code></pre>
<p>That is what I have, but pickerTop seems to be wrong.</p>
<p>mike</p>
| 47,964
|
<p>I need to increase the max_allowed_packet param, to fit some theoretically very large items. If I set this param to say 10M, what price if any am I paying compared to setting it to 1M or 4M.
Thanks for any input!
Tomas</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,768
|
<p>I need to use JUnit 4.4 (or newer) in a set of eclipse plugin tests, but I've run into the following problem:</p>
<p>Tests are not detected when running with the junit 4.4 or 4.5 bundles from springsource
(<a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&version=4.4.0" rel="nofollow noreferrer">junit44</a> and <a href="http://www.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.junit&version=4.5.0&searchType=bundlesByName&searchQuery=junit" rel="nofollow noreferrer">junit45</a>). The org.junit4 bundle that can be obtained with eclipse supplies junit 4.3 (as of Ganymead / Eclipse 3.4). The org.junit4 bundle <em>does</em> work in that it identifies and runs the tests, but it is not compatible with the latest versions of JMock, and I need to use a mocking library.</p>
<p>Here is a sample test:</p>
<pre><code>package testingplugin;
import static org.junit.Assert.*;
import org.junit.Test;
public class ActivatorTest {
@Test
public final void testDoaddTest() {
fail("Not yet implemented");
}
}
</code></pre>
<p>When running this test, I receive the following exception:</p>
<pre><code>java.lang.Exception: No runnable methods
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:33)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.pde.internal.junit.runtime.RemotePluginTestRunner.main(RemotePluginTestRunner.java:62)
at org.eclipse.pde.internal.junit.runtime.CoreTestApplication.run(CoreTestApplication.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.internal.app.EclipseAppContainer.callMethodWithException(EclipseAppContainer.java:574)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:195)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:549)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:504)
at org.eclipse.equinox.launcher.Main.run(Main.java:1236)
at org.eclipse.equinox.launcher.Main.main(Main.java:1212)
</code></pre>
<p>However, if I switch the project dependencies from com.springsource.org.junit to org.junit4, then the test runs and fails (as expected).</p>
<p>I am running the test as a JUnit Plug-in Test in Eclipse, with the following program arguments:</p>
<p>-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}</p>
<p>The following plug-ins selected during launch (selected by me, then I used "add required plugins" to get the rest of the dependencies.):</p>
<pre><code>Workspace:
testingPlugin
Target Platform:
com.springsource.org.hamcrest.core (1.1.0)
com.springsource.org.junit (4.5.0)
....and a bunch of others... (nothing related to testing was auto-selected)
</code></pre>
<p>Here is my MANIFEST.MF:</p>
<pre><code>Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: TestingPlugin Plug-in
Bundle-SymbolicName: testingPlugin
Bundle-Version: 1.0.0
Bundle-Activator: testingplugin.Activator
Import-Package: org.osgi.framework;version="1.3.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.6
Require-Bundle: com.springsource.org.junit;bundle-version="4.5.0"
</code></pre>
<p>Switching the last line to:</p>
<pre><code>Require-Bundle: org.junit4;bundle-version="4.3.1"
</code></pre>
<p>And updating the selected plugins at launch to:</p>
<pre><code>Workspace:
testingPlugin
Target Platform:
org.junit4 (4.3.1)
...bunches of auto-selected bundles... (again, nothing else test related)
</code></pre>
<p>Causes the test to run properly (but with the wrong version of junit).</p>
|
<p>I cannot test this right now as I don't have an Eclipse 3.4 installation handy, but I've run across a similar problem a while ago in (I think) IntelliJ IDEA 7.0.x, and a workaround was to explicitly specify a test runner. </p>
<p>With JUnit 4.5:</p>
<pre><code>import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class ActivatorTest {
//...
}
</code></pre>
<p>If this does not work you may have more success with <code>org.junit.runners.BlockJUnit4ClassRunner</code></p>
<p>For JUnit 4.4 I would try <code>org.junit.internal.runners.JUnit4ClassRunner</code></p>
<p>EDIT : not too sure about the <code>com.springsource.</code> part as I don't use Springsource. From your question it seems that springsource repackages JUnit under <code>com.springsource.org.junit</code> but you use just <code>org.junit</code> in your code so I'll stick with that.</p>
|
<p>I don't know which version of JUnit it was, but to succesfully find test the test methods name must start with the word "<strong>test</strong>".</p>
<p>In newer version you can simply mark test with @Test,
for me it works in this combination:</p>
<pre><code>import static junit.framework.Assert.*;
...
@Test
public void testDummy() throws Exception
</code></pre>
| 31,369
|
<p>Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?</p>
|
<p>Believe it or not, you can actually use <a href="http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)" rel="noreferrer"><code>java.awt.Robot</code></a> to "create an image containing pixels read from the screen." You can then write that image to a file on disk.</p>
<p>I just tried it, and the whole thing ends up like:</p>
<pre><code>Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
</code></pre>
<p>NOTE: This will only capture the primary monitor. See <a href="http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html" rel="noreferrer">GraphicsConfiguration</a> for multi-monitor support.</p>
|
<p>You can use <code>java.awt.Robot</code> to achieve this task.</p>
<p>below is the code of server, which saves the captured screenshot as image in your Directory.</p>
<pre><code>import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
public class ServerApp extends Thread
{
private ServerSocket serverSocket=null;
private static Socket server = null;
private Date date = null;
private static final String DIR_NAME = "screenshots";
public ServerApp() throws IOException, ClassNotFoundException, Exception{
serverSocket = new ServerSocket(61000);
serverSocket.setSoTimeout(180000);
}
public void run()
{
while(true)
{
try
{
server = serverSocket.accept();
date = new Date();
DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
String fileName = server.getInetAddress().getHostName().replace(".", "-");
System.out.println(fileName);
BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
System.out.println("Image received!!!!");
//lblimg.setIcon(img);
}
catch(SocketTimeoutException st)
{
System.out.println("Socket timed out!"+st.toString());
//createLogFile("[stocktimeoutexception]"+stExp.getMessage());
break;
}
catch(IOException e)
{
e.printStackTrace();
break;
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
ServerApp serverApp = new ServerApp();
serverApp.createDirectory(DIR_NAME);
Thread thread = new Thread(serverApp);
thread.start();
}
private void createDirectory(String dirName) {
File newDir = new File("D:\\"+dirName);
if(!newDir.exists()){
boolean isCreated = newDir.mkdir();
}
}
}
</code></pre>
<p>And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.</p>
<pre><code>package com.viremp.client;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;
import javax.imageio.ImageIO;
public class ClientApp implements Runnable {
private static long nextTime = 0;
private static ClientApp clientApp = null;
private String serverName = "192.168.100.18"; //loop back ip
private int portNo = 61000;
//private Socket serverSocket = null;
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
clientApp = new ClientApp();
clientApp.getNextFreq();
Thread thread = new Thread(clientApp);
thread.start();
}
private void getNextFreq() {
long currentTime = System.currentTimeMillis();
Random random = new Random();
long value = random.nextInt(180000); //1800000
nextTime = currentTime + value;
//return currentTime+value;
}
@Override
public void run() {
while(true){
if(nextTime < System.currentTimeMillis()){
System.out.println(" get screen shot ");
try {
clientApp.sendScreen();
clientApp.getNextFreq();
} catch (AWTException e) {
// TODO Auto-generated catch block
System.out.println(" err"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
}
//System.out.println(" statrted ....");
}
}
private void sendScreen()throws AWTException, IOException {
Socket serverSocket = new Socket(serverName, portNo);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimensions = toolkit.getScreenSize();
Robot robot = new Robot(); // Robot class
BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
serverSocket.close();
}
}
</code></pre>
| 8,267
|
<p>So here's what I've got: </p>
<ul>
<li>An NSTableView with an NSMutableArray data source</li>
<li>FSEvents monitoring a folder that contains the file that contains the data for the table view (Using <a href="http://stuconnolly.com/blog/archive/2008/05/08/fsevents-objectivec-wrapper" rel="nofollow noreferrer">SCEvents</a> for Objective-C abstraction goodness)</li>
<li>The FSEvents triggers the same function that a reload button in the UI does. This function refreshes the table view with a new data source based on the contents of said file via <code>setDataSource:</code>.</li>
</ul>
<p>And here's what happens:</p>
<ul>
<li>If I make a change to the file, the FSEvent gets triggered and the refresh method gets called.</li>
<li>The array that the table view should be accepting does indeed include the changes that triggered the FSEvent.</li>
<li><code>setDataSource:</code> gets sent to the NSTableView with the correct data source.</li>
<li>The changes do not appear in the table view!</li>
</ul>
<p>But then:</p>
<ul>
<li>If I hit the refresh button, which triggers the exact same method as the FSEvent, the table view gets updated with the new data.</li>
</ul>
<p>I also tried replacing the FSEvent with an NSNotification (<code>NSApplicationDidBecomeActiveNotification</code>), but the same thing happens.</p>
<p>Anyone have any idea why this is happening?</p>
<p>Edit: For clarification, the jist of my question is this: Why does my NSTableView reload as it should when triggered by a button press, but not when triggered by an FSEvent or an NSNotification?</p>
<p>Edit: Thanks to <a href="https://stackoverflow.com/questions/328277/nstableview-setdatasource-not-working-when-triggered-by-fsevents#328648">diciu</a>, I've figured out that in fact all of my UI references point to 0x0 when triggered by the event, but then have valid addresses when triggered by the button click. These objects are all declared in IB, so there's no instantiation or allocation for them going on in my code. So my question is now: what can I do to stop these pointers from pointing to nil?</p>
|
<p>We call <strong>reloadData</strong> on NSTableView when we have new data to add/remove to the table.</p>
<p>This might help, to force the NSTableView to redraw. </p>
<p>I'm not really sure if this is what your asking though. The wording of your question is kind of confusing, you state a series of events, but never a true question. </p>
|
<p>Have you tried calling your method from your FSEvent on a second pass of the run-loop?</p>
<pre><code>[myObject performSelector:@selector(reloadAction:) withObject:nil afterDelay:0.0];
</code></pre>
| 42,540
|
<p>I asked a question about Lua perfromance, and on of the <a href="https://stackoverflow.com/questions/124455/how-do-you-pre-size-an-array-in-lua#152894">responses</a> asked:</p>
<blockquote>
<p>Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.</p>
</blockquote>
<p>This is a slightly different question from <a href="https://stackoverflow.com/questions/89523/lua-patternstips-and-tricks">Lua Patterns,Tips and Tricks</a> because I'd like answers that specifically impact performance and (if possible) an explanation of why performance is impacted.</p>
<p>One tip per answer would be ideal.</p>
|
<p>In response to some of the other answers and comments:</p>
<p>It is true that as a programmer you should generally avoid premature optimization. <em>But</em>. This is not so true for scripting languages where the compiler does not optimize much -- or at all.</p>
<p>So, whenever you write something in Lua, and that is executed very often, is run in a time-critical environment or could run for a while, it is a good thing to know things to <em>avoid</em> (and avoid them).</p>
<p>This is a collection of what I found out over time. Some of it I found out over the net, but being of a suspicious nature when <em>the interwebs</em> are concerned I tested all of it myself. Also, I have read the Lua performance paper at Lua.org.</p>
<p>Some reference:</p>
<ul>
<li><a href="http://www.lua.org/gems/sample.pdf">Lua Performance Tips</a></li>
<li><a href="http://lua-users.org/wiki/OptimisationTips">Lua-users.org Optimisation Tips</a></li>
</ul>
<h1>Avoid globals</h1>
<p>This is one of the most common hints, but stating it once more can't hurt.</p>
<p>Globals are stored in a hashtable by their name. Accessing them means you have to access a table index. While Lua has a pretty good hashtable implementation, it's still a lot slower than accessing a local variable. If you have to use globals, assign their value to a local variable, this is faster at the 2nd variable access.</p>
<pre><code>do
x = gFoo + gFoo;
end
do -- this actually performs better.
local lFoo = gFoo;
x = lFoo + lFoo;
end
</code></pre>
<p>(Not that simple testing may yield different results. eg. <code>local x; for i=1, 1000 do x=i; end</code> here the for loop header takes actually more time than the loop body, thus profiling results could be distorted.)</p>
<h1>Avoid string creation</h1>
<p>Lua hashes all strings on creation, this makes comparison and using them in tables very fast and reduces memory use since all strings are stored internally only once. But it makes string creation more expensive.</p>
<p>A popular option to avoid excessive string creation is using tables. For example, if you have to assemble a long string, create a table, put the individual strings in there and then use <code>table.concat</code> to join it <em>once</em></p>
<pre><code>-- do NOT do something like this
local ret = "";
for i=1, C do
ret = ret..foo();
end
</code></pre>
<p>If <code>foo()</code> would return only the character <code>A</code>, this loop would create a series of strings like <code>""</code>, <code>"A"</code>, <code>"AA"</code>, <code>"AAA"</code>, etc. Each string would be hashed and reside in memory until the application finishes -- see the problem here?</p>
<pre><code>-- this is a lot faster
local ret = {};
for i=1, C do
ret[#ret+1] = foo();
end
ret = table.concat(ret);
</code></pre>
<p>This method does not create strings at all during the loop, the string is created in the function <code>foo</code> and only references are copied into the table. Afterwards, concat creates a second string <code>"AAAAAA..."</code> (depending on how large <code>C</code> is). Note that you <em>could</em> use <code>i</code> instead of <code>#ret+1</code> but often you don't have such a useful loop and you won't have an iterator variable you can use.</p>
<p>Another trick I found somewhere on lua-users.org is to use gsub if you have to parse a string</p>
<pre><code>some_string:gsub(".", function(m)
return "A";
end);
</code></pre>
<p>This looks odd at first, the benefit is that gsub creates a string "at once" in C which is only hashed after it is passed back to lua when gsub returns. This avoids table creation, but possibly has more function overhead (not if you call <code>foo()</code> anyway, but if <code>foo()</code> is actually an expression)</p>
<h1>Avoid function overhead</h1>
<p>Use language constructs instead of functions where possible</p>
<h2>function <code>ipairs</code></h2>
<p>When iterating a table, the function overhead from ipairs does not justify it's use. To iterate a table, instead use</p>
<pre><code>for k=1, #tbl do local v = tbl[k];
</code></pre>
<p>It does exactly the same without the function call overhead (pairs actually returns another function which is then called for every element in the table while <code>#tbl</code> is only evaluated once). It's a lot faster, even if you need the value. And if you don't...</p>
<p><strong>Note for Lua 5.2</strong>: In 5.2 you can actually define a <code>__ipairs</code> field in the metatable, which <em>does</em> make <code>ipairs</code> useful in some cases. However, Lua 5.2 also makes the <code>__len</code> field work for tables, so you might <em>still</em> prefer the above code to <code>ipairs</code> as then the <code>__len</code> metamethod is only called once, while for <code>ipairs</code> you would get an additional function call per iteration.</p>
<h2>functions <code>table.insert</code>, <code>table.remove</code></h2>
<p>Simple uses of <code>table.insert</code> and <code>table.remove</code> can be replaced by using the <code>#</code> operator instead. Basically this is for simple push and pop operations. Here are some examples:</p>
<pre><code>table.insert(foo, bar);
-- does the same as
foo[#foo+1] = bar;
local x = table.remove(foo);
-- does the same as
local x = foo[#foo];
foo[#foo] = nil;
</code></pre>
<p>For shifts (eg. <code>table.remove(foo, 1)</code>), and if ending up with a sparse table is not desirable, it is of course still better to use the table functions.</p>
<h1>Use tables for SQL-IN alike compares</h1>
<p>You might - or might not - have decisions in your code like the following</p>
<pre><code>if a == "C" or a == "D" or a == "E" or a == "F" then
...
end
</code></pre>
<p>Now this is a perfectly valid case, however (from my own testing) starting with 4 comparisons and excluding table generation, this is actually faster:</p>
<pre><code>local compares = { C = true, D = true, E = true, F = true };
if compares[a] then
...
end
</code></pre>
<p>And since hash tables have constant look up time, the performance gain increases with every additional comparison. On the other hand if "most of the time" one or two comparisons match, you might be better off with the Boolean way or a combination.</p>
<h1>Avoid frequent table creation</h1>
<p>This is discussed thoroughly in <a href="http://www.lua.org/gems/sample.pdf">Lua Performance Tips</a>. Basically the problem is that Lua allocates your table on demand and doing it this way will actually take more time than cleaning it's content and filling it again.</p>
<p>However, this is a bit of a problem, since Lua itself does not provide a method for removing all elements from a table, and <code>pairs()</code> is not the performance beast itself. I have not done any performance testing on this problem myself yet.</p>
<p>If you can, define a C function that clears a table, this should be a good solution for table reuse.</p>
<h1>Avoid doing the same over and over</h1>
<p>This is the biggest problem, I think. While a compiler in a non-interpreted language can easily optimize away a lot of redundancies, Lua will not.</p>
<h2>Memoize</h2>
<p>Using tables this can be done quite easily in Lua. For single-argument functions you can even replace them with a table and __index metamethod. Even though this destroys transparancy, performance is better on cached values due to one less function call.</p>
<p>Here is an implementation of memoization for a single argument using a metatable. (Important: This variant does <em>not</em> support a nil value argument, but is pretty damn fast for existing values.)</p>
<pre><code>function tmemoize(func)
return setmetatable({}, {
__index = function(self, k)
local v = func(k);
self[k] = v
return v;
end
});
end
-- usage (does not support nil values!)
local mf = tmemoize(myfunc);
local v = mf[x];
</code></pre>
<p>You could actually modify this pattern for multiple input values</p>
<h2><a href="http://en.wikipedia.org/wiki/Partial_application">Partial application</a></h2>
<p>The idea is similar to memoization, which is to "cache" results. But here instead of caching the results of the function, you would cache intermediate values by putting their calculation in a constructor function that defines the calculation function in it's block. In reality I would just call it clever use of closures.</p>
<pre><code>-- Normal function
function foo(a, b, x)
return cheaper_expression(expensive_expression(a,b), x);
end
-- foo(a,b,x1);
-- foo(a,b,x2);
-- ...
-- Partial application
function foo(a, b)
local C = expensive_expression(a,b);
return function(x)
return cheaper_expression(C, x);
end
end
-- local f = foo(a,b);
-- f(x1);
-- f(x2);
-- ...
</code></pre>
<p>This way it is possible to easily create flexible functions that cache some of their work without too much impact on program flow.</p>
<p>An extreme variant of this would be <a href="http://en.wikipedia.org/wiki/Currying">Currying</a>, but that is actually more a way to mimic functional programming than anything else.</p>
<p>Here is a more extensive ("real world") example with some code omissions, otherwise it would easily take up the whole page here (namely <code>get_color_values</code> actually does a lot of value checking and recognizes accepts mixed values)</p>
<pre><code>function LinearColorBlender(col_from, col_to)
local cfr, cfg, cfb, cfa = get_color_values(col_from);
local ctr, ctg, ctb, cta = get_color_values(col_to);
local cdr, cdg, cdb, cda = ctr-cfr, ctg-cfg, ctb-cfb, cta-cfa;
if not cfr or not ctr then
error("One of given arguments is not a color.");
end
return function(pos)
if type(pos) ~= "number" then
error("arg1 (pos) must be in range 0..1");
end
if pos < 0 then pos = 0; end;
if pos > 1 then pos = 1; end;
return cfr + cdr*pos, cfg + cdg*pos, cfb + cdb*pos, cfa + cda*pos;
end
end
-- Call
local blender = LinearColorBlender({1,1,1,1},{0,0,0,1});
object:SetColor(blender(0.1));
object:SetColor(blender(0.3));
object:SetColor(blender(0.7));
</code></pre>
<p>You can see that once the blender was created, the function only has to sanity-check a single value instead of up to eight. I even extracted the difference calculation, though it probably does not improve a lot, I hope it shows what this pattern tries to achieve.</p>
|
<p>Keep tables short, the larger the table the longer the search time.
And in the same line iterating over numerically indexed tables (=arrays) is faster than key based tables (thus ipairs is faster than pairs)</p>
| 18,699
|
<p>I was wondering how common it is to find genetic algorithm approaches in commercial code.</p>
<p>It always seemed to me that some kinds of schedulers could benefit from a GA engine, as a supplement to the main algorithm.</p>
|
<p>Genetic Algorithms have been widely used commercially. Optimizing train routing was an early application. More recently fighter planes have used GAs to optimize wing designs. I have used GAs extensively at work to generate solutions to problems that have an extremely large search space.</p>
<p>Many problems are unlikely to benefit from GAs. I disagree with Thomas that they are too hard to understand. A GA is actually very simple. We found that there is a huge amount of knowledge to be gained from optimizing the GA to a particular problem that might be difficult and as always managing large amounts of parallel computation continue to be a problem for many programmers.</p>
<p>A problem that would benefit from a GA is going to have the following characteristics:</p>
<ul>
<li>A good way to encode potential solutions</li>
<li>A way to compute an a numerical score to evaluate the quality of the solution</li>
<li>A large multi-dimensional search space where the answer is non-obvious</li>
<li>A good solution is good enough and a perfect solution is not required</li>
</ul>
<p>There are many problems that could probably benefit from GAs and in the future they will probably be more widely deployed. I believe that GAs are used in cutting edge engineering more than people think however most people (like my company does) guards those secrets extremely closely. It is only long after the fact that it is revealed that GAs were used.</p>
<p>Most people that deal with "normal" applications probably don't have much use for them though.</p>
|
<p>LibreOffice Calc uses it in its Solver module.</p>
| 39,147
|
<p>I have some code which collects points (consed integers) from a loop which looks something like this:</p>
<pre><code>(loop
for x from 1 to 100
for y from 100 downto 1
collect `(,x . ,y))
</code></pre>
<p>My question is, is it correct to use <code>`(,x . ,y)</code> in this situation?</p>
<p>Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.</p>
|
<p>It would be much 'better' to just do (cons x y). </p>
<p>But to <strong>answer the question</strong>, there is nothing wrong with doing that :) (except making it a tad slower).</p>
|
<p>Why not just</p>
<pre><code>(cons x y)
</code></pre>
<p>By the way, I tried to run your code in CLISP and it didn't work as expected. Since I'm not a big fan of the loop macro here's how you might accomplish the same thing recursively:</p>
<pre><code>(defun genint (stop)
(if (= stop 1) '(1)
(append (genint (- stop 1)) (list stop))))
(defun genpairs (x y)
(let ((row (mapcar #'(lambda (y)
(cons x y))
(genint y))))
(if (= x 0) row
(append (genpairs (- x 1) y)
row))))
(genpairs 100 100)
</code></pre>
| 12,697
|
<p>I have a SQL Server 2005 database and I have 4 GB of text files that I need to import into it. The question is, if these 4 GB of text files are 1.2 GB when they are zipped, how big would the database be if they are imported? Does SQL Server shrink data by default, or how would I set this (think create a database as a detached item, to be attached to another DB later).</p>
|
<p>SQL Server will not shrink data by default. In fact, there will be a small overhead per column and row, so it would require more space. </p>
<p>If you really must store those files in the DB (it is recommended that you don't), take a look at this <a href="http://mitch-wheat.blogspot.com/2007/05/save-and-restore-filesimages-to-sql.html" rel="nofollow noreferrer">article</a> I blogged a while back. In SQL Server 2008, they have introduced the FILESTREAM type.</p>
|
<p>There is no automatic compression - although you could put compressed data in columns it will be difficult to search.</p>
<p>Are these being imported into a set of normalized tables? Are there spaces or other data which will be stripped (commas)?</p>
<p>If so, you can expect space savings from the normalization and the trimming of spaces.</p>
| 21,490
|
<p>I have a J2ee application where I basically want two objects, created by two separate servlets to communicate directly and I need these intances to be stable, i.e. to "know" each other during the session.</p>
<p>The sequence is roughly: <br></p>
<ol>
<li>Client sends a request to Servlet #1, which creates object A</li>
<li>Client sends a second request (after the first returns) to servlet #2 which creates object B.</li>
<li>Object B finds A, using JNDI, and the two objects interact.</li>
<li>The client now continues to send requests to object A which needs to find B again.</li>
</ol>
<p>How do I make sure that these two instances know each throughout the session?
Binding them to JNDI doesn't entirely solve the problem, since object B needs to communicate with its original servlet (servlet #2), which is not kept stable across requests.</p>
<p>Any ideas?</p>
<p>Thanks in advance.</p>
<hr>
<p>Yes, I admit the problem description is a bit vague. But it's not a very simple application.
Still, I will try to ask it better:</p>
<p>My end goal is to create a sort of a "semantic debugger" for my application that, as opposed to a java debugger which simply debugs the java statements.</p>
<p>The application debugged is basically a servlet. which my tool connects to.
The tool maintains a connection to the application through another servlet which controls the debugging process.
These two servlets need to communicate with each other constantly and directly.</p>
<p>My current thought is to set up a stateful session bean that will facilitate this communication (never done it, still struggling with setting it up).</p>
<p>But I would appreciate any thoughts on how to achieve this better.</p>
|
<p>And what stops you from using the Session? You don't need JNDI, just place your object into session under a predefined name. If the communication object is application-wide, use Singleton. </p>
<p>P.S. It looks to me you're doing something weird, while the solution could in fact be simpler. Can you describe the task, not the proposed implementation? What is a "semantic debugger" anyway?</p>
|
<p>To be honest: I don't fully understand what you are trying to achieve.
Can you perhaps try to explain the problem you are trying to solve instead of the solution?</p>
<p>What do these objects depend on? Are they user specific? Then put them into the session and you can retrieve them from the session again (request.getSession().getAttribute("A")).</p>
<p>Are they global for all users? In that case put them into a spring configuration and retrieve them from there.</p>
<p>Never store any information inside the servlet.</p>
<p>EDIT:
ok, so from what I understand storing the values in the session is imho the best way to solve this problem (in "Java-Pseudo-Code"):</p>
<pre><code>public class BusinessServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
HttpSession session = req.getSession(true);
BusinessCode business = session.getAttribute("A");
if (business == null) {
business = new BusinessCode();
session.setAttribute("A", business);
}
DebugObject debug = session.getAttribute("B");
if (debug == null) {
debug = new DebugObject();
session.setAttribute("B", debug);
}
business.doSomeWork(debug);
}
}
public class DebugServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
HttpSession session = req.getSession(true);
DebugObject debug = session.getAttribute("B");
if (debug != null) {
debug.printDebugMessages(res);
}
}
}
</code></pre>
<p>Does this help? </p>
| 31,406
|
<p>There are various documents describing threading on Solaris/Linux, but nowwhere describing the Windows implementation. I have a passing interest in this, it seems strange that something so critical is (seemingly) not documented.</p>
<p>Threading is not the same on different OS' - "Write Once, Run Anywhere" isn't true for threading.</p>
<p>See <a href="http://java.sun.com/docs/hotspot/threads/threads.html" rel="nofollow noreferrer">http://java.sun.com/docs/hotspot/threads/threads.html</a></p>
|
<p>It really depends on the specific JVM implementation. I assume you're wondering about Sun's Windows JVM, and I can tell you with certainty that the Sun JVM maps a Java thread to an OS thread.</p>
<p>You could try spawning up a couple of threads from Java code, open up Task Manager and see what happened.</p>
|
<p>That document is a little more about Solaris threading than the Java threading model. All JVMs call the native thread API of the OS they're written for so there is always one Java thread for an OS thread. The diagram in the document shows that it's not until the threads are in the OS space that they change. Each OS can handle threads in different ways for Windows specific documentation here is a good place to start: <a href="http://msdn.microsoft.com/en-us/library/ms681917(VS.85).aspx" rel="nofollow noreferrer">MSDN About Processes and Threads</a>.</p>
<p>For a long time various flavours of *nix have implemented their threads with processes rather than actual threads it seems that those specific tuning parameters where there to sort of ease the transition to a newer threading model in Solaris. Which made the older model and those JVM options obsolete.</p>
<p>For a list of JVM options for the HotSpot JVM you can look at: <a href="http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp" rel="nofollow noreferrer">HotSpot VM Options</a>. A lot of these are useful for tuning long running applications but you can also get into trouble with them if you don't understand what they're doing. Also keep in mind that each implementation of the JVM can have a different set of options you won't find some of them on IBM's VM or BEA's. </p>
| 9,277
|
<p>How can you depend on test code from another module in Maven? </p>
<p>Example, I have 2 modules:</p>
<ul>
<li>Base</li>
<li>Main</li>
</ul>
<p>I would like a test case in Main to extend a base test class in Base. Is this possible?</p>
<p>Update: Found an <a href="https://stackoverflow.com/questions/174560/sharing-test-code-in-maven#174670">acceptable answer</a>, which involves creating a test jar.</p>
|
<p>I recommend using <a href="https://maven.apache.org/pom.html#Dependencies" rel="noreferrer">type instead of classifier</a> (see also: <a href="http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html" rel="noreferrer">classifier</a>). It tells Maven a bit more explicitly what you are doing (and I've found that m2eclipse and q4e both like it better).</p>
<pre><code><dependency>
<groupId>com.myco.app</groupId>
<artifactId>foo</artifactId>
<version>1.0-SNAPSHOT</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
</code></pre>
|
<p>Yep ... just include the Base module as a dependency in Main. If you're only inheriting test code, then you can use the scope tag to make sure Maven doesn't include the code in your artifact when deployed. Something like this should work:</p>
<pre><code><dependency>
<groupId>BaseGroup</groupId>
<artifactId>Base</artifactId>
<version>0.1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</code></pre>
| 21,039
|
<p>I'm on Windows Vista and IE7.</p>
<p>Here's what I'd like to do:</p>
<ol>
<li>I have two flash files: <code>page1.swf</code> and <code>page2.swf</code>. They are just page from a magazine.</li>
<li>Display <code>page1.swf</code></li>
<li>Have a button that says "Change page"</li>
<li>When I click the button; display <code>page2.swf</code> instead of <code>page1.swf</code> (only <code>page2.swf</code>, not both pages)
That's it. </li>
</ol>
<p>If anyone can give me a script to do that I would greatly appreciate it.</p>
|
<p>This is more complicated but I've had to resort to this scenario before because machine and user profile settings sometimes don't match your visitor's preferences. For example, a UK visitor accessing your site temporarily from an Australian server.</p>
<ol>
<li><p>Use a geolocation service (e.g MaxMind.com) as suggested by @balabaster, to get the zone matching their IP (Global.Session_Start is best). This is a good match for local ISPs, but not so good for AOL. Store the offset from this in a session cookie.</p></li>
<li><p>Or use JavaScript to get the time zone offset as part of a form submission/redirect when the user enters the site. This is the browser's current offset, but <em>not necessarily the visitor's preferred zone.</em> Use this value as a default; store in another session cookie.</p>
<pre><code>
<script type="text/javascript" language="JavaScript">
var offset = new Date();
document.write('<input type="hidden" id="clientTzOffset" name="clientTzOffset" value="' + offset.getTimezoneOffset() + '"/>');
</script>
</code></pre></li>
<li><p>Allow the visitor to update the zone via a persistent cookie (for anonymous users) and a field in their account profile (if authenticated).</p></li>
</ol>
<p>The persistent value #3 from overrides the session values. You can also store the same persistent cookie for authenticated users for displaying times before they login.</p>
|
<p>In any of the events prior to Page Unload...Request.ServerVariables. If you want their physical timezone then you check their IP address and use an IP to Geo-Location conversion tool. </p>
<p>I'm not sure if there's another way you can do it, so if you require the timezone their computer is configured for, it would have to wait for the page load for a javascript...</p>
| 43,940
|
<p>I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:</p>
<pre><code>boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
</code></pre>
|
<p>I read (well scanned) through the <a href="http://thread.gmane.org/gmane.comp.lib.boost.devel/180008" rel="noreferrer">development list discussion</a>. There's no easy solution. To sum up:</p>
<ol>
<li><p>Wrapping header files in a namespace declaration </p>
<pre><code>namespace boost_1_36_0 {
#include <boost_1_36_0/boost/regex.hpp>
}
namespace boost_1_35_0 {
#include <boost_1_35_0/boost/shared_ptr.hpp>
}
</code></pre>
<ul>
<li>Requires modifying source files</li>
<li>Doesn't allow for both versions to be included in the same translation unit, due to the fact that macros do not respect namespaces. </li>
</ul></li>
<li><p>Defining boost before including headers </p>
<pre><code>#define boost boost_1_36_0
#include <boost_1_36_0/boost/regex.hpp>
#undef boost
#define boost boost_1_35_0
#include <boost_1_35_0/boost/shared_ptr.hpp>
#undef boost
</code></pre>
<ul>
<li>Source files can simply be compiled with <code>-Dboost=boost_1_36_0</code></li>
<li>Still doesn't address macro conflicts in a single translation unit.</li>
<li><p>Some internal header file inclusions may be messed up, since this sort of thing does happen.</p>
<pre><code>#if defined(SOME_CONDITION)
# define HEADER <boost/some/header.hpp>
#else
# define HEADER <boost/some/other/header.hpp>
#endif
</code></pre>
<p>But it may be easy enough to work around those cases.</p></li>
</ul></li>
<li>Modifying the entire boost library to replace <code>namespace boost {..}</code> with <code>namespace boost_1_36_0 {...}</code> and then providing a namespace alias. Replace all <code>BOOST_XYZ</code> macros and their uses with <code>BOOST_1_36_0_XYZ</code> macros.
<ul>
<li>This would likely work if you were willing to put into the effort.</li>
</ul></li>
</ol>
|
<p>You'll have a world of trouble linking because the mangled names will be different. And yes, I see you knew that, but it seems like it will be trouble all around.</p>
| 14,940
|
<p>I am wondering what copy-local=true for references exactly does. Does it copy the referenced assembly along with all of its dependencies to the output directory?</p>
<p>My scenario is the following:
I have a custom log wrapper that utilizes log4net. I build a release assembly of MyLogWrapper.dll with log4net.dll reference set to copy-local true. Referencing MyLogWrapper.dll from MyProject with copy local set to true should result in log4net.dll being copied as well right? I am only referencing MyLogWrapper.dll and none of its dependencies in MyProject. log4net.dll is not being copied to MyProject output directory but all other dependencies of MyLogWrapper are. What could be the problem?</p>
<p>I have made some more experiments and it seems that if I remove the assembly (log4net.dll) from GAC it starts to get copied locally. Can anyone confirm that this is the problem?</p>
|
<p>Unfortunately it appears that according to the following statement taken from the <a href="http://msdn.microsoft.com/en-us/library/ez524kew(VS.80).aspx" rel="noreferrer">MSDN documentation</a> the CopyLocal functionality does not work as expected for assemblies already in the GAC.</p>
<blockquote>
<p>If you deploy an application that contains a reference to a custom component that is registered in the GAC, the component will not be deployed with the application, regardless of the CopyLocal setting. In previous versions of Visual Studio, you could set the CopyLocal property on a reference to ensure that the assembly was deployed. Now, you must manually add the assembly to the \Bin folder. This puts all custom code under scrutiny, reducing the risk of publishing custom code with which you are not familiar.</p>
</blockquote>
<p>More information can be found at the following page which explains details about how project references work.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ez524kew(VS.80).aspx" rel="noreferrer">MSDN: Project References</a></p>
|
<p>I've found that this is no more respected in Visual Studio 2015 with project references if the referenced project has a dependency to a GAC assembly. The GAC assembly is always copied to the root project output and copy local = false being respected only regarding the output of the project holding the reference to the GAC dll.</p>
<p><a href="https://connect.microsoft.com/VisualStudio/Feedback/Details/1804765" rel="nofollow">Connect feedback</a></p>
| 41,431
|
<p>I run a 3D printer farm and I have to replace my Bowden tubes on the printers after about a month or two of use(roughly 1000 hours of use). The Bowden tubes continually melt on the side of the tube very near to where it pushes against the nozzle. I am running Ender 3 Pros and I run at about 205 °C with PLA. The Bowden tubes I have are some I found on Amazon and they are not Capricorn tubes. </p>
<p><a href="https://i.stack.imgur.com/xnhmZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xnhmZ.png" alt="Note how the hole is very near the base of the tube closest to the nozzle"></a></p>
<p>EDIT1: I have added more pictures below of a new failure. This time you can see the marks of the teeth of the coupler a good inch below the failure point.
<a href="https://i.stack.imgur.com/QPk6E.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QPk6E.jpg" alt="New photo of tube 1"></a>
<a href="https://i.stack.imgur.com/A3xXQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A3xXQ.jpg" alt="New photo of tube 2"></a>
<a href="https://i.stack.imgur.com/P9l5a.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P9l5a.jpg" alt="New photo of tube 3"></a>
<a href="https://i.stack.imgur.com/PB7Ox.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PB7Ox.jpg" alt="New potho of tube 4"></a></p>
|
<p>If the tube is PTFE, the tube is not likely to be melting unless your hotend temperature is out of control. You would probably notice the PLA cooking.</p>
<p>So, perhaps they aren't PTFE, or perhaps it is wear.</p>
<p>If it wasn't PTFE, you should be able to tell by the texture, slipperiness, and bending force.</p>
<p>The four thinned faces look like they would correspond to four of the barbs in the connector. The thinned ring below the four thinned faces look like a wear line where the tube is pressing against the exit of the connector. It looks to me as if the tube is moving or flexing in the connector. The barbs act as little chisels cutting into the tube, which is how they restrain such a slippery material as PTFE.</p>
<p>It might work better if the tube were a little longer. This might reduce the forces at the limits of movement which may be placing strain on the tubes. If you can, you might also fashion a strain relief for the tube so that it doesn't bend right as it exist from the connector. If you can cut down on the movement, you will help with the external wear.</p>
<p>It is also possible that the tubes are being strained by a high filament pressure. All the drive to push filament into the hot end is matched by an equivalent reverse pressure from the tube onto the connector. If you can stand a higher print temperature, the life of the tube may be increased.</p>
<p>@towe added a comment:</p>
<blockquote>
<p>I don't think those are marks from the teeth of the pneumatic coupler. The questions states "where it pushes against the nozzle", and the Ender 3 Pro seems to have a hot-end where the Bowden tube reaches all the way through the cold end and heat break to the nozzle.</p>
</blockquote>
<p>A mechanical drawing of what may be a MK-10 hot-end as used on the Ender 3 Pro also suggests that the Ender 3 Pro has a PTFE lined hot end. Lets accept that drawing as confirming that @towe is right. Never-the-less, the marks you show in the photo look like the types of cuts I have seen from a pneumatic coupler. How can we reconcile this contradiction?</p>
<p>The most direct answer would be that the tube is not reaching through to the nozzle. In the photo you don't show enough of the blue tube to show the coupler scars which should be a little further up the tube. Suppose that, in fact, the tube is not pressing against the nozzle. This might not be the case if any of these are true:</p>
<ol>
<li>There is a separate piece of PTFE that is permanently in hot end.
The Creality Ender 3 Pro looks as if
it is not configured for a Bowden feed. A PTFE lined hot-end for a
direct extruder would have a piece of PTFE cut to length in the
hot-end. A simple mod to make that a Bowden would leave that
sculpted PTFE tube in place.</li>
<li>The pneumatic couplers have been replaced. Many couplers do not
permit the tube to pass through them, although the hole in the end
can be drilled to 4mm diameter. In fact, preventing the tube from
passing through a pneumatic coupler is a feature in the intended
application of coupling to air tubes in moderate pressure
applications.</li>
<li>There is a bump in the path that is catching the tube and
preventing it from extending through to the cold end and onward.</li>
</ol>
|
<p>After a lot of hard work and months of replacing and inspecting this issue I realized what's going on. The bowden tube gets soft as it gets hotter and hotter which allows the filament which is being extruded and retracted at a high speed to wear down the side of the tube. After some time the tube gets stretched out and it will eventually tear and that is seens as the hole in the pictures I provided. The solution to this problem is to upgrade to an all metal hotend, instate less aggressive retraction settings (which is what I did), or closely monitor your prints and replace your bowden tubing when it does eventually get damaged (which I also do).</p>
| 1,592
|
<p>I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.</p>
<p>The existing C application works fine but I want to have a single script I can maintain for all platforms. At the same time, I do not want to lose a lot of performance but am willing to lose some.</p>
<p>Startup cost of the script is very important. This script can be called anywhere from every minute to many times per second. As a consequence, keeping it's memory and startup time low are important.</p>
<p>So basically I'm looking for the best scripting languages that is:</p>
<ul>
<li>Cross platform.</li>
<li>Capable of XML parsing and HTTP Posts.</li>
<li>Low memory and low startup time.</li>
</ul>
<p>Possible choices include but are not limited to: bash/ksh + curl, Perl, Python and Ruby. What would you recommend for this type of a scenario?</p>
|
<p>Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available.</p>
|
<p>I agree with others in that you should probably try to make this a more portable C app instead of porting it over to something else since any scripting language is going to introduce significant overhead from a startup perspective, have a much larger memory footprint, and will probably be much slower.</p>
<p>In my experience, Python is the most efficient of the three, followed by Perl and then Ruby with the difference between Perl and Ruby being particularly large in certain areas. If you really want to try porting this to a scripting language, I would put together a prototype in the language you are most comfortable with and see if it comes close to your requirements. If you don't have a preference, start with Python as it is easy to learn and use and if it is too slow with Python, Perl and Ruby probably won't be able to do any better.</p>
| 42,526
|
<p>In PowerShell, even if it's possible to know if a drive is a network drive: see <a href="https://stackoverflow.com/questions/158359/in-powershell-how-can-i-determine-if-the-current-drive-is-a-networked-drive-or">In PowerShell, how can I determine if the current drive is a networked drive or not?</a></p>
<p>When I try to get the "root" of the drive, I get back the drive letter.</p>
<p>The setup:
MS-Dos "net use" shows that H: is really a mapped network drive:</p>
<pre><code>New connections will be remembered.
Status Local Remote Network
-------------------------------------------------------------------------------
OK H: \\spma1fp1\JARAVJ$ Microsoft Windows Network
The command completed successfully.
</code></pre>
<p>Get-PSDrive tells us that the Root is H:</p>
<pre><code>PS:24 H:\temp
>get-psdrive h
Name Provider Root CurrentLocation
---- -------- ---- ---------------
H FileSystem H:\ temp
</code></pre>
<p>and using system.io.driveinfo does not give us a complete answer:</p>
<pre><code>PS:13 H:\
>$x = new-object system.io.driveinfo("h:\")
PS:14 H:\
>$x.DriveType
Network
PS:15 H:\
>$x.RootDirectory
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 29/09/2008 16:45 h:\
</code></pre>
<p>Any idea of how to get that info?</p>
<p>Thanks</p>
|
<p>Try WMI:</p>
<pre><code>Get-WMIObject -query "Select ProviderName From Win32_LogicalDisk Where DeviceID='H:'"
</code></pre>
|
<p>$drive = gwmi win32_logicaldisk -filter "DeviceID='H:'"
if($drive.DriveType -eq 4) {write-host "drive is a network share"}</p>
| 19,173
|
<p>The method signature of a Java <code>main</code>method is:</p>
<pre><code>public static void main(String[] args) {
...
}
</code></pre>
<p><strong>Is there a reason why this method must be static?</strong></p>
|
<p>The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:</p>
<pre><code>public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
</code></pre>
<p>Should the JVM call <code>new JavaClass(int)</code>? What should it pass for <code>x</code>?</p>
<p>If not, should the JVM instantiate <code>JavaClass</code> without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.</p>
<p>There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why <code>main</code> is static.</p>
<p>I have no idea why <code>main</code> is always marked <code>public</code> though.</p>
|
<p>because, a static members are not part of any specific class and that main method, not requires to create its Object, but can still refer to all other classes.</p>
| 17,649
|
<p>I tried the example from Rails Cookbook and managed to get it to work. However the <code>text_field_with_auto_complete</code> works only for one value.</p>
<pre><code>class Expense < ActiveRecord::Base
has_and_belongs_to_many :categories
end
</code></pre>
<p>In the New Expense View rhtml</p>
<pre><code><%= text_field_with_auto_complete :category, :name %>
</code></pre>
<p>Auto complete works for the first category. How do I get it working for multiple categories? e.g. Category1, Category2<br>
<em>Intended behavior: like the StackOverflow Tags textbox</em></p>
<p><strong>Update:</strong><br>
With some help and some more tinkering, I got multiple comma-seperated autocomplete to show up (will post code-sample here).<br>
<em>However on selection, the last value replaces the content of the text_field_with_auto_complete.</em> So instead of Category1, Category2.. the textbox shows Category2 when the second Category is selected via auto-complete. Any ideas how to rectify this? </p>
|
<p>If you are just trying to support multiple instances of autocomplete per field, you can pass a delimiter to the autocomplete options with the symbol :token. This provides a delimiter to allow multiple results. Stackoverflow would use :token => ' ' (there should be a space between the quotes, but the autoformat is removing it) to specify space at the delimiter between multiple takes although ',' is more commonly used.</p>
|
<p>This is not quite your question, but I wouldn't recommend using HABTM anymore. You should create a join model and use has_many :through. (In your case you'd create a new model called ExpenseCategoryAssignment, or something)</p>
<p>The problem is that HABTM creates ambiguities that rails doesn't like, and it tends to expose bugs you wouldn't see otherwise.</p>
| 31,155
|
<p>I need to send and receive data over serial connections (RS-232 and RS-422).</p>
<p>How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them?</p>
<p>In particular I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.</p>
|
<p>Build a time machine and go back to 1987? Ho ho.</p>
<p>Ok, no more snarky comments.</p>
<blockquote>
<p>How do I figure out what the configuration settings (e.g. baud rate) should be...</p>
</blockquote>
<p>Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure.</p>
<p>Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out.</p>
<blockquote>
<p>one of the major Unix shells</p>
</blockquote>
<p>In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there.</p>
<p>On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. </p>
<p><strike>See: <a href="http://www.easysw.com/~mike/serial/serial.html#3_1" rel="noreferrer">http://www.easysw.com/~mike/serial/serial.html#3_1</a></strike>
<strong>(NOT AVAILABLE ANYMORE)</strong></p>
<blockquote>
<p>but I also have some interest in serial programming using Windows/Hyperterminal.</p>
</blockquote>
<p>Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days.</p>
|
<p>I have been using purejavacomm:
<a href="http://www.sparetimelabs.com/purejavacomm/index.html" rel="nofollow">It is an implementation of javax.comm written in pure java + JNA</a></p>
<p>Unlike rxtx, you don't need to install a dll. It is written in pure Java + JNA, which solved the problem of portability between Windows and Linux for me. It should be easy to port to other OS-es that JNA supports, such as Solaris and FreeBSD, but I haven't tried it. </p>
<p>You might expect a pure java library to lag behind a native implementation such as rxtx in performance, but with modern CPU's, the bottleneck is very likely to be the bitrate of your serial port, not CPU cycles. Also, it's much easier to debug than a mixed Java/Native library or pure compiled native code. </p>
| 2,519
|
<p>Which XML validation tools can you recommend for both performance and accuracy, each of which is a critical issue on our system? We have the following requirements:</p>
<ul>
<li>It is <em>not</em> xmllint (see below)</li>
<li>Supports RelaxNG</li>
<li>Can easily integrate with Perl (this is optional, but it would be nice)</li>
</ul>
<p>Why not xmllint? (This is background and you can skip it if you like)</p>
<p>We have a large Perl system which uses RelaxNG to validate our XML. We use the <a href="http://www.relaxng.org/compact-tutorial-20030326.html" rel="noreferrer">compact RelaxNG format</a> and <a href="http://www.thaiopensource.com/relaxng/trang.html" rel="noreferrer">trang</a> to convert it to the standard RelaxNG format. Then we do the actual validation via <a href="http://xmlsoft.org/xmllint.html" rel="noreferrer">xmllint</a>.</p>
<p>That's when the problems kick in. xmllint routinely has issues in reporting validation errors incorrectly. It doesn't give false positives or negatives, but if the document fails to validate, xmllint will often report the wrong element or attribute for a given error. Sometimes the error is correct ("did not expect to see element 'bar'), but only because a previous error was not reported (because 'bar' was supposed to be following the required but missing element 'foo', but xmllint doesn't tell us that bit). Note that this is a long-standing problem with xmllint and even the latest version has the same problems. We often have huge XML documents and misreporting the errors causes much grief for both clients and developers.</p>
|
<p>I think that JDrago has the right idea, that you need to avoid libxml2-based tools for RNG validation, at least for now. I'm discovering this as well in my project. I recently logged two bugs against libxml2 concerning RNG validation.</p>
<p>I recommend <a href="http://code.google.com/p/jing-trang/" rel="noreferrer">jing</a>. It was written by James Clark, the creator of Relax NG and one of the leading lights in the XML world. He is also the author of trang, which you are already using. Development of this code (and of trang) recently resumed at the Google Code site I link to above.</p>
<p>Jing has proved consistently correct with our content and schema, and to give much better error messages than libxml2, though there is still a lot of room for improvement in that regard.</p>
<p>The one shortcoming of jing vis a vis libxml2/xmllint is that it doesn't at present use OASIS XML catalogs to resolve public and system identifiers and URIs pointing to schemas. This would be an issue in case you have included schemas that are referred to by 'http' URI--those would always be fetched over the network.</p>
|
<p>I suspect xmllint uses the same underlying libraries (libxml2, etc) as anything else. It is counterintuitive to think that another front-end to the same library would give different results.</p>
| 32,267
|
<p>How would you reccommend handling RSS Feeds in ASP.NET MVC? Using a third party library? Using the RSS stuff in the BCL? Just making an RSS view that renders the XML? Or something completely different?</p>
|
<p>Here is what I recommend:</p>
<ol>
<li>Create a class called RssResult that
inherits off the abstract base class
ActionResult.</li>
<li>Override the ExecuteResult method.</li>
<li>ExecuteResult has the ControllerContext passed to it by the caller and with this you can get the data and content type.</li>
<li><p>Once you change the content type to rss, you will want to serialize the data to RSS (using your own code or another library) and write to the response.</p></li>
<li><p>Create an action on a controller that you want to return rss and set the return type as RssResult. Grab the data from your model based on what you want to return.</p></li>
<li><p>Then any request to this action will receive rss of whatever data you choose.</p></li>
</ol>
<p>That is probably the quickest and reusable way of returning rss has a response to a request in ASP.NET MVC.</p>
|
<p>I got this from Eran Kampf and a Scott Hanselman vid (forgot the link) so it's only slightly different from some other posts here, but hopefully helpful and copy paste ready as an example rss feed.</p>
<p><a href="http://achadwick.com/Blog/Result/MVC%20RSS%20Feed" rel="nofollow noreferrer">From my blog</a></p>
<p><a href="http://www.developerzen.com/2009/01/11/aspnet-mvc-rss-feed-action-result/" rel="nofollow noreferrer">Eran Kampf</a></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;
using System.Xml;
namespace MVC3JavaScript_3_2012.Rss
{
public class RssFeed : FileResult
{
private Uri _currentUrl;
private readonly string _title;
private readonly string _description;
private readonly List<SyndicationItem> _items;
public RssFeed(string contentType, string title, string description, List<SyndicationItem> items)
: base(contentType)
{
_title = title;
_description = description;
_items = items;
}
protected override void WriteFile(HttpResponseBase response)
{
var feed = new SyndicationFeed(title: this._title, description: _description, feedAlternateLink: _currentUrl,
items: this._items);
var formatter = new Rss20FeedFormatter(feed);
using (var writer = XmlWriter.Create(response.Output))
{
formatter.WriteTo(writer);
}
}
public override void ExecuteResult(ControllerContext context)
{
_currentUrl = context.RequestContext.HttpContext.Request.Url;
base.ExecuteResult(context);
}
}
}
</code></pre>
<p>And the Controller Code....</p>
<pre><code> [HttpGet]
public ActionResult RssFeed()
{
var items = new List<SyndicationItem>();
for (int i = 0; i < 20; i++)
{
var item = new SyndicationItem()
{
Id = Guid.NewGuid().ToString(),
Title = SyndicationContent.CreatePlaintextContent(String.Format("My Title {0}", Guid.NewGuid())),
Content = SyndicationContent.CreateHtmlContent("Content The stuff."),
PublishDate = DateTime.Now
};
item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri("http://www.google.com")));//Nothing alternate about it. It is the MAIN link for the item.
items.Add(item);
}
return new RssFeed(title: "Greatness",
items: items,
contentType: "application/rss+xml",
description: String.Format("Sooper Dooper {0}", Guid.NewGuid()));
}
</code></pre>
| 3,302
|
<p>For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)</p>
|
<p>9 out of 10 times, code folding means that you have failed to use the <a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="noreferrer">SoC principle</a> for what its worth.<br />
I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up.<br />It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method.<br />
<br />
Whenever you can, pull some code out of the main class, and into a helper or factory class.
<br /></p>
<pre><code>foreach (var item in Items)
{
//.. 100 lines of validation and data logic..
}
</code></pre>
<p>is not as readable as</p>
<pre><code>foreach (var item in Items)
{
if (ValidatorClass.Validate(item))
RepositoryClass.Update(item);
}
</code></pre>
<p><br />
<br />
My $0.02 anyways.</p>
|
<p>I prefer #regions myself, but an old coworker couldn't stand to have things hidden. I understood his point once I worked on a page with 7 #regions, at least 3 of which had been auto-generated and had the same name, but in general I think they're a useful way of splitting things up and keeping everything less cluttered.</p>
| 2,780
|
<p>Anyone have any idea how to do the following?</p>
<p>declare cursor
open cursor
fetch cursor
<< Start reading the cursor in a LOOP >>
Lets say the cursor have 10 records.
Read until 5th record then go to the 6th record and do some checking.</p>
<p>Now, is it possible to go back to 5th record from 6th record ?</p>
|
<p>Depends on the requirements.</p>
<p>You can use the LAG() and LEAD() analytic functions to get information for the next and prior rows, i.e.</p>
<pre><code>SQL> ed
Wrote file afiedt.buf
1 select ename,
2 sal,
3 lead(sal) over (order by ename) next_sal,
4 lag(sal) over (order by ename) prior_sal
5 from emp
6* order by ename
SQL> /
ENAME SAL NEXT_SAL PRIOR_SAL
---------- ---------- ---------- ----------
ADAMS 1100 1600
ALLEN 1600 2850 1100
BLAKE 2850 2450 1600
CLARK 2450 3000 2850
FORD 3000 950 2450
JAMES 950 2975 3000
JONES 2975 5000 950
KING 5000 1250 2975
MARTIN 1250 1300 5000
MILLER 1300 3000 1250
SCOTT 3000 800 1300
ENAME SAL NEXT_SAL PRIOR_SAL
---------- ---------- ---------- ----------
SMITH 800 1500 3000
TURNER 1500 1250 800
WARD 1250 1500
14 rows selected.
</code></pre>
<p>If you don't want to use analytic functions, you can use PL/SQL collections, BULK COLLECT the data into those collections (using the LIMIT clause if you have more data than you want to store in your PGA) and then move forward and backward through your collections.</p>
|
<p>How far do you need to go back? If you only need a look-ahead of one row, you could buffer just the previous row in your loop (application-side).</p>
| 20,841
|
<p>Can anyone recommend a good 3rd party control(s) for MS SQL 2005 Reporting Services. If you know some open library or implementation of such controls that could be very useful too.</p>
|
<p>Dundas do great RS add-ins if you have the budget:</p>
<p><a href="http://www.dundas.com/index.aspx" rel="nofollow noreferrer">http://www.dundas.com/index.aspx</a></p>
|
<p>I agree, Dundas has great controls. I used it in one of my projects.</p>
<p>This was the sample which I used to test out the CRI:
<a href="http://www.codeplex.com/MSFTRSProdSamples/Wiki/View.aspx?title=SS2005%21Custom%20Report%20Item%20Sample&referringTitle=Home" rel="nofollow noreferrer">http://www.codeplex.com/MSFTRSProdSamples/Wiki/View.aspx?title=SS2005%21Custom%20Report%20Item%20Sample&referringTitle=Home</a></p>
| 13,090
|
<p>In ColdFusion, under Request Tuning in the administrator, how do I determine what is an optimal number (or at least a good guess) for the Maximum Number of Simultaneous Template Requests?</p>
<p>Environment:<br/>
CF8 Standard<br/>
IIS 6<br/>
Win2k3<br/>
SQL2k5 on a separate box</p>
|
<p>The way of finding the right number of requests is load testing. That is, measuring changes in throughput under load when you vary the request number. Any significant change would require retesting. But I suspect most folks are going to baulk at that amount of work.</p>
<p>I think a good rule of thumb is about 8 threads per CPU (core).</p>
<p>In terms of efficiency, the lower the thread count (up to a point) the less swapping will be going on as the CPU processes your requests. If your pages execute very quickly then a lower number of requests is optimal. </p>
<p>If you have longer running requests, and especially if you have requests that are waiting on third-parties (like a database) then increasing the number of working threads will improve your throughput. That is, if your CPU is not tied up processing stuff you can afford to have more simultaneous requests working on the tasks at hand.</p>
<p>Although its a little bit dated, many of the principles on request tuning in Grant Straker's book on <a href="http://www.cfperformance.com/" rel="nofollow noreferrer">CF Performance & Troubleshooting</a> would be worthwhile.</p>
|
<p>I would say at least 8 <em>per core</em>, not per CPU. And I think 8 is a little low given modern CPU cores, I would say at least 12.</p>
| 11,353
|
<p>I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom <code>IEnumerator</code> interface that iterates through the values.</p>
<pre><code>public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
public void Add(K key, T value)
{
KToTMap.Add(key, value);
TToKMap.Add(value, key);
}
public int Count
{
get { return KToTMap.Count; }
}
public K this[T obj]
{
get
{
return TToKMap[obj];
}
}
public T this[K obj]
{
get
{
return KToTMap[obj];
}
}
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Values.GetEnumerator();
}
public T Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
;
}
public void Reset()
{
throw new NotImplementedException();
}
}
</code></pre>
|
<p>First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection). </p>
<p>Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' statement.</p>
<p>Raymond Chen's recent series of blog posts ("The implementation of iterators in C# and its consequences") is a good place to get up to speed. </p>
<ul>
<li>Part 1: <a href="https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20081216071723/http://blogs.msdn.com/oldnewthing/archive/2008/08/12/8849519.aspx</a></li>
<li>Part 2: <a href="https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20080907004812/http://blogs.msdn.com/oldnewthing/archive/2008/08/13/8854601.aspx</a></li>
<li>Part 3: <a href="https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20080824210655/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx</a></li>
<li>Part 4: <a href="https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx" rel="nofollow noreferrer">https://web.archive.org/web/20090207130506/http://blogs.msdn.com/oldnewthing/archive/2008/08/15/8868267.aspx</a></li>
</ul>
|
<p>Use yield return.</p>
<p><a href="https://stackoverflow.com/questions/39476/what-is-the-yield-keyword-used-for-in-c#39496">What is the yield keyword used for in C#?</a></p>
| 7,755
|
<p>I'm performing a bulk insert with an ADO.NET 2.0 SqlBulkCopy object from a C# method into a MS SQL 2005 database, using a database user with limited permissions. When I try to run the operation, I get the error message:</p>
<blockquote>
<p>Bulk copy failed. User does not have
ALTER TABLE permission on table
'theTable'. ALTER
TABLE permission is required on the
target table of a bulk copy operation
if the table has triggers or check
constraints, but <code>'FIRE_TRIGGERS'</code> or
<code>'CHECK_CONSTRAINTS'</code> bulk hints are not
specified as options to the bulk copy
command.</p>
</blockquote>
<p>I read some documentation and created the bulk copy object with the constructor that lets me specify such things:</p>
<pre><code> SqlBulkCopy bc = new SqlBulkCopy(
System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"],
SqlBulkCopyOptions.FireTriggers & SqlBulkCopyOptions.CheckConstraints);
</code></pre>
<p>But this doesn't change anything - I get the same error message as before. I tried fiddling with some of the other SqlBulkCopyOptions values but no luck. I really thought this would fix the problem, am I missing something?</p>
<p>I tested the procedure after granting ALTER on the table to my user, and the operation succeeded. However this is not an option for my situation.</p>
|
<p>Solved it! Looks like I need a refresher on flags enums. I was bitwise ANDing the enum values when I should have been ORing them.</p>
<pre><code>SqlBulkCopyOptions.FireTriggers & SqlBulkCopyOptions.CheckConstraints
</code></pre>
<p>evaluates to zero (which is equivalent to SqlBulkCopyOptions.Default.)</p>
<pre><code>SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.CheckConstraints
</code></pre>
<p>Worked correctly and allowed the bulk insert to complete.</p>
|
<p>Possibilities only, I'm sorry</p>
<p>SQL documentation for <a href="http://msdn.microsoft.com/en-us/library/ms188365(SQL.90).aspx" rel="nofollow noreferrer">BULK INSERT</a> specifies 3 cases where ALTER TABLE is needed. You listed 2 of them. Is the KeepIdentity option being set, even if not needed?</p>
<p>Another option is that the trigger on the table is disabled already, confusing the issue. Use <code>ALTER TABLE dbo.SomeTable ENABLE TRIGGER ALL</code> to ensure enabled.</p>
| 48,778
|
<p>Say I have a data structure, such as</p>
<pre><code>d dog DS qualified
d name 20
d breed 20
d birthdate 8 0
</code></pre>
<p>I can then define </p>
<pre><code>d poochie likeds(dog)
</code></pre>
<p>and use poochie.name, etc.</p>
<p>But can I just set up the 'dog' as a template without creating the structure in memory? </p>
|
<p>Two options come to mind. The first is to create a source member with the d-specs for the dog attributes and instead of using likeds(dog), have a /copy after each data structure that will use that subfield definition. In my opinion, this can make for some sloppy code and can make things difficult for someone to analyze down the road. On the other hand, if you are using this same data structure in multiple programs, there are benefits.</p>
<p>The second option that comes to mind is to use the Based() keyword on the dog data structure and then define a pointer field. The pointer field will take up some memory, but the dog data structure will not take up any memory until your program allocates it. The Based() keyword does not carry over into other data structures defined against it with LikeDS(). So that way you have your data structure defined in your program source. You don't have to allocate memory for it and you don't have to set your pointer to any value. It defaults to Null. Just be careful not to access the dog data structure in your code. You'll get a pointer error that looks the same as if your program was called without a required parameter.</p>
|
<p>To the best of my knowledge, no. But it might be possible to do something similar with subprocedures.</p>
<p>Post this question on <a href="http://lists.midrange.com/listinfo/rpg400-l" rel="nofollow noreferrer">Midrange.com RPG-L</a> and someone smarter than me might be able to answer your question.</p>
| 27,399
|
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p>
<p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p>
<pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')
</code></pre>
<p>WTF ?</p>
<p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p>
<p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
|
<p>If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)</p>
<pre><code>>>> import ntpath
>>> filepath = r"c:\ttemp\FILEPA~1.EXE"
>>> print ntpath.basename(filepath)
FILEPA~1.EXE
>>> print ntpath.splitdrive(filepath)
('c:', '\\ttemp\\FILEPA~1.EXE')
</code></pre>
|
<p>See the documentation <a href="http://pydoc.org/2.5.1/posixpath.html" rel="nofollow noreferrer">here</a>, specifically: </p>
<blockquote>
<p>splitdrive(p) Split a pathname into
drive and path. <strong>On Posix, drive is
always empty.</strong></p>
</blockquote>
<p>So this won't work on a Linux box.</p>
| 22,022
|
<p>is there an if statement when it comes to mysql query statements?</p>
<p>when i am updating a table record, i want to only update certain columns if they have a value to be updated.</p>
<p>for example, i want an update table function, and there is a table for volunteers and a table for people who just want email updates.</p>
<p>i want to use the same function (there will be a function that only deals w/ the upd queries) and is it possible to do this in theory...</p>
<p>if you are updating volunteer table, only update these columns, if mailing_list, then update these</p>
<p>i know this can by done using an if statement w/ two query statements, based on what table you're updating, but i am wondering is it possible to use only one query statement w/ the conditionals in it to update the appropriate columns in the table.</p>
<p>this may sound like something you would dream about, let me know.</p>
<p>thanks.</p>
|
<p>I think this should work:</p>
<pre><code>UPDATE volunteer, people
SET volunteer.email = 'me@email.com',
people.email = 'other@gmail.com',
people.first_name = 'first',
WHERE people.id = 2 AND volunteer.id = 5;
</code></pre>
<p>I got this from the <a href="http://dev.mysql.com/doc/refman/5.1/en/update.html" rel="nofollow noreferrer">update syntax</a> on the MySQL website.</p>
|
<p>You <em>could</em> do this in one query, but it's not making sense to me why you would want to.
Maybe describe the arguments to your desired function and what effect they would have?</p>
<p>You can conditionally update something like this:</p>
<pre><code>update tablereferences
set foo.bar = if( somebooleanexpression, newbarvalue, foo.bar ),
baz.quux = if( somebooleanexpression, newbazvalue, baz.quux )
where ...
</code></pre>
<p>allowing you to use the same query but control which tables are updated.</p>
| 23,038
|
<p>... say I check out some code, do a little dev or refactoring or whatever .. do I only check it back in when I'm completely happy? ... what if I change my mind about stuff while i'm coding? can I go back to a previous local version? is there a history of my local development?</p>
<p>Is version control about deployment history or development history?</p>
|
<p>Short answer. It's both.</p>
<p>You need to be able to roll back to earlier versions for lots of reasons.</p>
|
<p>That depends how your Version Control system is used...</p>
<p>In my experience, most companies use it for deployment history in most senses. That is, only working code should be put in. If you check something out and then are in the process of adding a block of code that doesn't yet work - then checking it back in means that there's the possibility of someone else checking out a broken product.</p>
<p>I have come across situations where companies use it such that you check your code out each morning and whatever state you're in at the end of the day you check it back in. That way if someone else wants to add something they can, regardless of what state it's currently in... and while I can see <em>some</em> sense in the logic, that just doesn't work for me.</p>
| 43,937
|
<p>There is a MSBuild script, that includes number if Delphi and C# projects, unit tests etc. </p>
<p>The problem is: how to mark build failed if warnings were raised (for testing purposes, not for release builds)? Using LogError instead of LogWarning in custom tasks seems to be not a good option, because the build should test as much as it's able (until real error) to report as much warnings as possible in a time (build project is using in CruiseControl.NET).</p>
<p>May be, the solution is to create my own logger that would store warnings flag inside, but I cannot find if there is a way to read this flag in the end of build?</p>
<p>P.S. There is no problem to fail the build immediately after receiving a warning (Delphi compiler output is processed by custom task, and /warnaserror could be used for C#), but the desired behavior is "build everything; collect all warnings; fail the build" to report about all warnings, not only about the first one.</p>
<p><strong>P.P.S. As far as I really need not number of warnings, but just flag of their presence, I decided to simplify signaling mechanism, and use trivial Mutex instead of shared memory. Code is below:</strong></p>
<pre><code>using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Threading;
namespace Intrahealth.Build.WarningLogger
{
public sealed class WarningLoggerCheck : Task
{
public override bool Execute()
{
Log.LogMessage("WarningLoggerCheck:" + mutexName + "...");
result = false;
Mutex m = null;
try
{
m = Mutex.OpenExisting(mutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
result = true;
}
catch (Exception)
{
}
if (result)
Log.LogMessage("WarningLoggerCheck PASSED");
else
Log.LogError("Build log contains warnings. Build is FAILED");
return result;
}
private bool result = true;
[Output]
public bool Result
{
get { return result; }
}
private string mutexName = "WarningLoggerMutex";
public string MutexName
{
get { return mutexName; }
set { mutexName = value ?? "WarningLoggerMutex"; }
}
}
public class WarningLogger : Logger
{
internal static int warningsCount = 0;
private string mutexName = String.Empty;
private Mutex mutex = null;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
}
private void SetMutex()
{
if (mutexName == String.Empty)
{
mutexName = "WarningLoggerMutex";
if (this.Parameters != null && this.Parameters != String.Empty)
{
mutexName = this.Parameters;
}
}
mutex = new Mutex(false, mutexName);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
if (e.Message != null && e.Message.Contains("MSB3146"))
return;
if (e.Code != null && e.Code.Equals("MSB3146"))
return;
if (warningsCount == 0)
SetMutex();
warningsCount++;
}
}
}
</code></pre>
|
<p>AFAIK MSBuild has no built-in support to retrieve the warning count at a given point of the build script. You can however follow these steps to achieve this goal:</p>
<ol>
<li>Create a custom logger that listens for the warning event and counts the number of warnings</li>
<li>Create a custom task that exposes an [Output] WarningCount property</li>
<li>The custom task gets somehow the value of the warning count from the custom logger</li>
</ol>
<p>The most difficult step is step 3. For this there are several options and you can freely search them under IPC - Inter Process Comunication. Follows a working example of how you can achieve this. Each item is a different <em>Class Library</em>.</p>
<p><strong>SharedMemory</strong></p>
<p><a href="http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx" rel="noreferrer">http://weblogs.asp.net/rosherove/archive/2003/05/01/6295.aspx</a></p>
<blockquote>
<p>I've created a wrapper for named
shared memory that was part of a
larger project. It basically allows
serialized types and object graphs to
be stored in and retrieved from shared
memory (including as you'd expect
cross process). Whether the larger
project ever gets completed is another
matter ;-).</p>
</blockquote>
<p><strong>SampleLogger</strong></p>
<p>Implements the custom logger that keeps track of the warning count.</p>
<pre><code>namespace SampleLogger
{
using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using DM.SharedMemory;
public class MySimpleLogger : Logger
{
private Segment s;
private int warningCount;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
this.s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Create, 65535);
this.s.SetData(this.warningCount.ToString());
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
this.warningCount++;
this.s.SetData(this.warningCount.ToString());
}
public override void Shutdown()
{
this.s.Dispose();
base.Shutdown();
}
}
}
</code></pre>
<p><strong>SampleTasks</strong></p>
<p>Implements the custom task that reads the number of warnings raised in the MSbuild project. The custom task reads from the shared memory written by the custom logger implemented in class library <em>SampleLogger</em>.</p>
<pre><code>namespace SampleTasks
{
using System;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using DM.SharedMemory;
public class BuildMetadata : Task
{
public int warningCount;
[Output]
public int WarningCount
{
get
{
Segment s = new Segment("MSBuildMetadata", SharedMemoryCreationFlag.Attach, 0);
int warningCount = Int32.Parse(s.GetData() as string);
return warningCount;
}
}
public override bool Execute()
{
return true;
}
}
}
</code></pre>
<p>Going for a spin.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Main">
<UsingTask TaskName="BuildMetadata" AssemblyFile="F:\temp\SampleLogger\bin\debug\SampleTasks.dll" />
<Target Name="Main">
<Warning Text="Sample warning #1" />
<Warning Text="Sample warning #2" />
<BuildMetadata>
<Output
TaskParameter="WarningCount"
PropertyName="WarningCount" />
</BuildMetadata>
<Error Text="A total of $(WarningCount) warning(s) were raised." Condition="$(WarningCount) > 0" />
</Target>
</Project>
</code></pre>
<p>If you run the following command:</p>
<pre><code>c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild test.xml /logger:SampleLogger.dll
</code></pre>
<p>This will be the output:</p>
<pre><code>Microsoft (R) Build Engine Version 2.0.50727.3053
[Microsoft .NET Framework, Version 2.0.50727.3053]
Copyright (C) Microsoft Corporation 2005. All rights reserved.
Build started 30-09-2008 13:04:39.
__________________________________________________
Project "F:\temp\SampleLogger\bin\debug\test.xml" (default targets):
Target Main:
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
Done building target "Main" in project "test.xml" -- FAILED.
Done building project "test.xml" -- FAILED.
Build FAILED.
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #1
F:\temp\SampleLogger\bin\debug\test.xml : warning : Sample warning #2
F:\temp\SampleLogger\bin\debug\test.xml(15,3): error : A total of 2 warning(s) were raised.
2 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.01
</code></pre>
|
<p>The C# compiler (csc.exe) has a /warnaserror switch will will treat warnings as errors and fail the build. This is also available as a setting in the .csproj file. I assume Delphi has a similar ability.</p>
| 18,401
|
<p>At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.</p>
<p>Is this possible?</p>
|
<p>From <a href="http://www.functionx.com/vcsharp2003/Lesson06.htm" rel="nofollow noreferrer">here</a></p>
<p>Double-click the Closing field, and implement it as follows:</p>
<pre><code>private void Second_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
// When the user attempts to close the form, don't close it...
e.Cancel = (dropdown.selecteditemindex >= 0);
}
</code></pre>
|
<p>If you want check for something, you allways need some code behind the designer.
For your case, you can use a "Closing" event in the form, check what you need and if you want, set "e.Cancel = true;" - then form will not be closed.</p>
| 33,837
|
<p>I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.).
Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?</p>
|
<p>Here's a link to add HTML to the clipboard using VB:</p>
<p><a href="http://support.microsoft.com/kb/274326" rel="noreferrer">http://support.microsoft.com/kb/274326</a></p>
<p>Once you have the HTML on the clipboard, paste it into your word doc using something like this:</p>
<pre><code>ActiveDocument.Range.PasteSpecial ,,,,WdPasteDataType.wdPasteHTML
</code></pre>
<p>This is pretty much the equivalent of you cutting and pasting it in manually. </p>
|
<p>AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse <code><b>, <i>, <a> and <p>,</code> for example. All other tags would have to be ignored.</p>
| 19,525
|
<p>I am a newbie for Visual Basic 6 project. I downloaded some tutorials for testing; however, I am not able to drag, move, or edit the UI form designer objects in those projects.</p>
<p>Does anybody know there is an object lock function in VB6?<br />
If there is, how can I unlock it?</p>
|
<p>In this case I wouldn't go for an enum, I'd go for a "score" column. So the columns might be:</p>
<pre><code>userid, questionid, score
1,1,4
1,2,4
1,3,3
2,1,1
2,2,4
...
</code></pre>
<p>1 being very unsatisfied and 4 being very satisfied.</p>
<p>Then a query like:</p>
<pre><code>select 25*avg(score) from Blah
</code></pre>
<p>will give you your overall percentage.</p>
<pre><code>select 25*avg(score), questionid from Blah group by questionid
</code></pre>
<p>will give you a % per question.</p>
<p>Access isn't really a database, so don't listen to your boss ;)</p>
|
<p>Just in case anyone else has this problem; I have also found a tutorial which is quite useful.
<a href="http://www.roughguidetophp.com/generating-reports-using-mysqls-aggregate-functions-sum-max-min-and-more/" rel="nofollow noreferrer">http://www.roughguidetophp.com/generating-reports-using-mysqls-aggregate-functions-sum-max-min-and-more/</a></p>
<p>It clarifies what JD and Genehack have said.</p>
| 42,138
|
<p>How can I create a query for a full outer join across a M2M relationchip using the django QuerySet API?</p>
<p>It that is not supported, some hint about creating my own manager to do this would be welcome.</p>
<p><strong>Edited to add:</strong>
@S.Lott:
Thanks for the enlightenment.
The need for the OUTER JOIN comes from the application. It has to generate a report showing the data entered, even if it still incomplete.
I was not aware of the fact that the result would be a new class/model. Your hints will help me quite a bit.</p>
|
<p>Django doesn't support "joins" in the usual SQL sense -- it supports object navigation.</p>
<p>Note that a relational join (inner or outer) creates a new "class" of entities. One that doesn't have a definition in Django. So there's no proper "result set" since there's no class definition for the things you get back. The best you can do is define a tuple which will be packed with None's for missing combinations.</p>
<p>A left (or right) outer join looks like this. It creates two disjoint subsets, those who have an associated set of related entities, and those who don't.</p>
<pre><code>for obj in Model1.objects.all():
if obj.model2_set().count() == 0:
# process (obj, None) -- no Model2 association
else:
for obj2 in obj.model2_set.all():
# process (obj, obj2) -- the "inner join" result
</code></pre>
<p>A "Full" outer join is a union of the remaining items that have no relationships.</p>
<pre><code>for obj2 in Model2.objects.all():
if obj2.model1_set().count() == 0:
# process (None, obj2) -- no Model1 association
</code></pre>
<p>The issue is always, what processing are you doing with this weird collection of three different subsets of objects? </p>
<p>The point of an object database is to focus the processing on the object and it's associated objects. </p>
<p>The peculiar collection called a "relational join" is never in the original object model. It's a new class of objects built from two (or more) original objects. </p>
<p>Worse, outer joins create a collection with multiple subclasses (inner join, left outer join and right outer join). What does that collection of things <strong>mean</strong>?</p>
<p>Wait, it can get worse. If the processing includes checks for the missing attributes (i.e. <code>if someObj.anObj2attribute is None</code>: we're essentially looking for <code>Model1</code> items with no <code>Model2</code> object associated. Ummm... why did we put those in the outer join, only to filter them using an <code>if</code> statement? Why not just do separate queries amd process each subset properly?</p>
<hr>
<p>Edit: When you're showing "incomplete" status, it isn't an outer-join at all. It's much simpler. You need to create one (or two) separate collections in your view function for your template to display.</p>
<p>First, you should use status codes, not the presence or absence of a foreign key. Optional foreign keys don't have "reasons" -- they're either there or not there. A status code can provide useful shades of meaning ("incomplete", "in error", "broken", "not applicable", "to be deleted", etc.)</p>
<pre><code>errorList1 = Model1.objects.filter( status="Incomplete" )
errorList2 = Model2.objects.filter( status="Incomplete" )
</code></pre>
<p>These two are the two non-join parts of a full outer join. You can then display these two error lists in your template with appropriate column titles and status codes and everything.</p>
<p>You can even put them into a single table to mimic the old full outer join report people used to see</p>
<pre><code><table>
<tr><th>Model1</th><th>Model2</th></tr>
{% for e1 in errorList1 %}
<tr><td>e1</td><td>NULL</td></tr>
{% endfor %}
{% for e2 in errorList2 %}
<tr><td>NULL</td><td>e2</td></tr>
{% endfor %}
</table>
</code></pre>
<p>Looks like a full outer join report. Without the full outer join.</p>
|
<p>Colin, one of the guys I work with, wrote a post awhile back about doing custom joins in Django:</p>
<p><a href="http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/" rel="nofollow noreferrer">http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/</a></p>
<p>You might be able to find something useful there!</p>
| 31,526
|
<p>I have a database full of small HTML documents and I need to programmatically insert several into, say, a PDF document with <em>iText</em> or a Word document with <em>Aspose.Words</em>. I need to preserve any formatting within the HTML documents (within reason, honouring <b> tags is a must, CSS like <span style="blah"> is a nice-to-have). </p>
<p>Both iText and Aspose work (roughly) along the lines:</p>
<pre><code>Document document = new Document( Size.A4, Aspect.PORTRAIT );
document.setFont( "Helvetica", 20, Font.BOLD );
document.insert( "some string" )
document.setBold( true );
document.insert( "A bold string" );
</code></pre>
<p>Therefore (I think) I need some kind of HTML parser which will I can inspect for strings and styles to insert into my document.</p>
<p>Can anybody suggest a good library or a sensible approach to this problem? Platform is Java</p>
|
<p><a href="http://htmlparser.sourceforge.net/" rel="nofollow noreferrer">HTMLparser</a> is a good HTML parser.</p>
<p>I have used this to parse HTML on one of my projects.</p>
<p>You can write your own filters to parse the HTML for what you want, so the
<code><br></code> tag shouldn't be difficult to parse out</p>
<p>Yo can parse out CSS usin the <a href="http://htmlparser.sourceforge.net/javadoc/org/htmlparser/filters/CssSelectorNodeFilter.html" rel="nofollow noreferrer">CssSelectorNodeFilter</a></p>
|
<p>Adobe Acrobat Pro allows you to grab sites via HTTP and does an excellent job of preserving the style and layout. I haven't used it from an API aspect, but it may be worth looking into.</p>
| 26,888
|
<p>Here's a software design question I've encountered several times and have never found an ideal solution for (I'm also dealing with it now again.)</p>
<p>Many applications need some form of user/role management. You have base users, groups that these users can belong to (not limited to just one), roles and permissions they have, organizational units, and a whole bunch of properties and other features that are project-specific.</p>
<p>My question is, what ways do people know of and/or have experience with to design and build a really dynamic, flexible user management system? Are there any design patterns you know of that really help?</p>
|
<p>You should adapt your design because every organization is different.
<a href="http://en.wikipedia.org/wiki/Role-based_access_control" rel="noreferrer">Check this page</a>, you can see a pattern for role-based administration.</p>
|
<p>Take a look at Scott Mitchell's ASP.NET 2.0 Membership, Roles and Profile Tutorial series:</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/2006/05/07/ASP.NET-2.0-Membership-and-Roles-Tutorial-Series.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2006/05/07/ASP.NET-2.0-Membership-and-Roles-Tutorial-Series.aspx</a></p>
| 38,498
|
<p>I`d like to be able to read the content of office documents (for a custom crawler). </p>
<p>The office version that need to be readable are from 2000 to 2007. I mainly want to be crawling words, excel and powerpoint documents.</p>
<p>I don`t want to retrieve the formatting, only the text in it. </p>
<p>The crawler is based on lucene.NET if that can be of some help and is in c#.</p>
<p>I already used iTextSharp for parsing PDF</p>
|
<p>If you're already using Lucene.NET you might just want to take advantage of the various IFilters already available for doing this. Take a look at the open source <a href="http://sourceforge.net/projects/seekafile/"SeekAFile"" rel="nofollow noreferrer">SeekAFile</a> project. It will show you how to use an IFilter to open and extract this information from any filetype where an IFilter is available. There are IFilters for Word, Excel, Powerpoint, PDf, and most of the other common document types.</p>
|
<p>You might also consider checking out DtSearch (www.DtSearch.com). Although it is primarily a searching tool, it does a great job of extracting text from a large number of file types and is considerably cheaper than other options like the Oracle/Stellent OutsideIn technology or the equivalent from Autonomy.</p>
<p>I've been using DtSearch for years and find it indispensible for this type of task.</p>
| 14,075
|
<p>This morning, I was reading <a href="http://steve.yegge.googlepages.com/when-polymorphism-fails" rel="noreferrer">Steve Yegge's: When Polymorphism Fails</a>, when I came across a question that a co-worker of his used to ask potential employees when they came for their interview at Amazon.</p>
<blockquote>
<p>As an example of polymorphism in
action, let's look at the classic
"eval" interview question, which (as
far as I know) was brought to Amazon
by Ron Braunstein. The question is
quite a rich one, as it manages to
probe a wide variety of important
skills: OOP design, recursion, binary
trees, polymorphism and runtime
typing, general coding skills, and (if
you want to make it extra hard)
parsing theory.</p>
<p>At some point, the candidate hopefully
realizes that you can represent an
arithmetic expression as a binary
tree, assuming you're only using
binary operators such as "+", "-",
"*", "/". The leaf nodes are all
numbers, and the internal nodes are
all operators. Evaluating the
expression means walking the tree. If
the candidate doesn't realize this,
you can gently lead them to it, or if
necessary, just tell them.</p>
<p>Even if you tell them, it's still an
interesting problem.</p>
<p>The first half of the question, which
some people (whose names I will
protect to my dying breath, but their
initials are Willie Lewis) feel is a
Job Requirement If You Want To Call
Yourself A Developer And Work At
Amazon, is actually kinda hard. The
question is: how do you go from an
arithmetic expression (e.g. in a
string) such as "2 + (2)" to an
expression tree. We may have an ADJ
challenge on this question at some
point.</p>
<p>The second half is: let's say this is
a 2-person project, and your partner,
who we'll call "Willie", is
responsible for transforming the
string expression into a tree. You get
the easy part: you need to decide what
classes Willie is to construct the
tree with. You can do it in any
language, but make sure you pick one,
or Willie will hand you assembly
language. If he's feeling ornery, it
will be for a processor that is no
longer manufactured in production.</p>
<p>You'd be amazed at how many candidates
boff this one.</p>
<p>I won't give away the answer, but a
Standard Bad Solution involves the use
of a switch or case statment (or just
good old-fashioned cascaded-ifs). A
Slightly Better Solution involves
using a table of function pointers,
and the Probably Best Solution
involves using polymorphism. I
encourage you to work through it
sometime. Fun stuff!</p>
</blockquote>
<p>So, let's try to tackle the problem all three ways. How do you go from an arithmetic expression (e.g. in a string) such as "2 + (2)" to an expression tree using cascaded-if's, a table of function pointers, and/or polymorphism? </p>
<p>Feel free to tackle one, two, or all three.</p>
<p>[update: title modified to better match what most of the answers have been.]</p>
|
<p><strong>Polymorphic Tree Walking</strong>, Python version</p>
<pre><code>#!/usr/bin/python
class Node:
"""base class, you should not process one of these"""
def process(self):
raise('you should not be processing a node')
class BinaryNode(Node):
"""base class for binary nodes"""
def __init__(self, _left, _right):
self.left = _left
self.right = _right
def process(self):
raise('you should not be processing a binarynode')
class Plus(BinaryNode):
def process(self):
return self.left.process() + self.right.process()
class Minus(BinaryNode):
def process(self):
return self.left.process() - self.right.process()
class Mul(BinaryNode):
def process(self):
return self.left.process() * self.right.process()
class Div(BinaryNode):
def process(self):
return self.left.process() / self.right.process()
class Num(Node):
def __init__(self, _value):
self.value = _value
def process(self):
return self.value
def demo(n):
print n.process()
demo(Num(2)) # 2
demo(Plus(Num(2),Num(5))) # 2 + 3
demo(Plus(Mul(Num(2),Num(3)),Div(Num(10),Num(5)))) # (2 * 3) + (10 / 2)
</code></pre>
<p>The tests are just building up the binary trees by using constructors.</p>
<p>program structure:</p>
<p>abstract base class: Node</p>
<ul>
<li>all Nodes inherit from this class</li>
</ul>
<p>abstract base class: BinaryNode</p>
<ul>
<li>all binary operators inherit from this class</li>
<li>process method does the work of evaluting the expression and returning the result</li>
</ul>
<p>binary operator classes: Plus,Minus,Mul,Div</p>
<ul>
<li>two child nodes, one each for left side and right side subexpressions</li>
</ul>
<p>number class: Num</p>
<ul>
<li>holds a leaf-node numeric value, e.g. 17 or 42</li>
</ul>
|
<p>should use a functional language imo. Trees are harder to represent and manipulate in OO languages.</p>
| 3,354
|
<p>I have an OpenGl program in which I am displaying an image using textures. I want to be able to load a new image to be displayed. </p>
<p>In my Init function I call:</p>
<pre><code>Gl.glGenTextures(1, mTextures);
</code></pre>
<p>Since only one image will be displayed at time, I am using the same texture name for each image. </p>
<p>Each time a new image is loaded I call the following:</p>
<pre><code>Gl.glBindTexture(Gl.GL_TEXTURE_2D, mTexture[0]);
Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_LUMINANCE, mTexSizeX, mTexSizeY, 0, Gl.GL_LUMINANCE, Gl.GL_UNSIGNED_SHORT, mTexBuffer);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);
</code></pre>
<p>The first image will display as expected. However, all images load after the first, display as all black.</p>
<p>What am I doing wrong?</p>
|
<p>I don't think the problem is in the code you're showing. You'll need to provide more information as to how you draw with the texture, as well as what the texture data passed to <code>glTexImage2D</code> looks like. Are you sure it's still valid by the time you call <code>glTexImage2D</code> ?</p>
|
<p>When do you submit the geometry using these textures? I assume that is interleaved with the texture loading, although you don't show that. Of course, if you are going to replace the texture name with different images, you don't need to use texture names at all, do you? You could just do the <code>glTextImage2D</code> call when you need to set a new texture, and then use that for as long as necessary, never involving <code>glBindTexture()</code> at all.</p>
<p>An obvious thing to do is of course to insert error-checking code, OpenGL stores an error code when an operation fails and this code is not overwritten until read by the application. See <a href="http://www.opengl.org/sdk/docs/man/xhtml/glGetError.xml" rel="nofollow noreferrer">glGetError()</a> for more on this.</p>
| 43,034
|
<p>Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms164303.aspx" rel="noreferrer">It turns out that Dev Studio only honors this setting for Web Services.</a></p>
<p>For non-web services you can get this to work by adding an AfterBuild target to your project file:</p>
<pre><code> <Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
<Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
</SGen>
</Target>
</code></pre>
<p>See also:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms164303.aspx" rel="noreferrer">SGen MSBuild Task</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/xzw8335a(VS.80).aspx" rel="noreferrer">AfterBuild Event</a></li>
</ul>
|
<p>It can be done manually with <a href="http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx" rel="nofollow noreferrer">sgen.exe</a>.</p>
| 16,476
|
<p>Here is the functionality I want:</p>
<p>User selects an image from their machine, hits an Upload button (or better yet the following fires on the onchange event of the file input), and is able to see a preview of the image they are about to upload.</p>
<p>Here is the current workflow I am using, but it seems suboptimal:</p>
<p>I have an image control, a file input control and a submit button control. When the submit button is clicked, the codebehind handles the OnClick event and loads the image from the file input element. It then stores it into a temporary folder on the web server and sets the image control's ImageUrl to point to it.</p>
<p>This works, but results in me having to do a lot of janitorial duty in cleaning up these temporary images. Is there a cleaner workflow for doing this?</p>
|
<p>If you have memory to burn:</p>
<ul>
<li>cache the image bytes in memory</li>
<li>set your ImageUrl to an image handler (.ashx) with some sort of cache identifier</li>
<li>serve the image bytes from cache</li>
<li>if the user cancels or leaves, discard the cached bytes</li>
<li>if the user accepts, write the cached bytes to their final destination</li>
</ul>
|
<p>You should upload and rename the image to match some sort of ID for your current record. Then, when you upload a new file, delete any old ones first, all in the codebehind.</p>
<p>If you are only showing a thumbnail, you should try to use an image library to resize the image before saving. This will save on bandwidth and storage space.</p>
| 32,908
|
<p>Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.</p>
<p>For example</p>
<pre><code>byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}
</code></pre>
|
<p>May I suggest something that doesn't involve creating strings, copying arrays or unsafe code:</p>
<pre><code>using System;
using System.Collections.Generic;
static class ByteArrayRocks
{
static readonly int[] Empty = new int[0];
public static int[] Locate (this byte[] self, byte[] candidate)
{
if (IsEmptyLocate(self, candidate))
return Empty;
var list = new List<int>();
for (int i = 0; i < self.Length; i++)
{
if (!IsMatch(self, i, candidate))
continue;
list.Add(i);
}
return list.Count == 0 ? Empty : list.ToArray();
}
static bool IsMatch (byte[] array, int position, byte[] candidate)
{
if (candidate.Length > (array.Length - position))
return false;
for (int i = 0; i < candidate.Length; i++)
if (array[position + i] != candidate[i])
return false;
return true;
}
static bool IsEmptyLocate (byte[] array, byte[] candidate)
{
return array == null
|| candidate == null
|| array.Length == 0
|| candidate.Length == 0
|| candidate.Length > array.Length;
}
static void Main()
{
var data = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 };
var pattern = new byte[] { 12, 3, 5, 76, 8, 0, 6, 125 };
foreach (var position in data.Locate(pattern))
Console.WriteLine(position);
}
}
</code></pre>
<p><strong>Edit (by IAbstract)</strong> - <em>moving contents of <a href="https://stackoverflow.com/a/283815/210709">post</a> here since it is not an answer</em></p>
<p>Out of curiosity, I've created a small benchmark with different answers.</p>
<p>Here are the results for a million iterations:</p>
<pre><code>solution [Locate]: 00:00:00.7714027
solution [FindAll]: 00:00:03.5404399
solution [SearchBytePattern]: 00:00:01.1105190
solution [MatchBytePattern]: 00:00:03.0658212
</code></pre>
|
<p>You can put the byte array into <a href="http://msdn.microsoft.com/en-us/library/ezh7k8d5.aspx" rel="nofollow noreferrer">String</a> and run match by IndexOf. Or you can at least reuse <a href="http://en.wikipedia.org/wiki/String_searching_algorithm" rel="nofollow noreferrer">existing algorithms</a> on string matching.</p>
<pre><code> [STAThread]
static void Main(string[] args)
{
byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};
string needle, haystack;
unsafe
{
fixed(byte * p = pattern) {
needle = new string((SByte *) p, 0, pattern.Length);
} // fixed
fixed (byte * p2 = toBeSearched)
{
haystack = new string((SByte *) p2, 0, toBeSearched.Length);
} // fixed
int i = haystack.IndexOf(needle, 0);
System.Console.Out.WriteLine(i);
}
}
</code></pre>
| 35,932
|
<p>I'm running a django instance behind nginx connected using fcgi (by using the manage.py runfcgi command). Since the code is loaded into memory I can't reload new code without killing and restarting the django fcgi processes, thus interrupting the live website. The restarting itself is very fast. But by killing the fcgi processes first some users' actions will get interrupted which is not good.
I'm wondering how can I reload new code without ever causing any interruption. Advices will be highly appreciated!</p>
|
<p>I would start a new fcgi process on a new port, change the nginx configuration to use the new port, have nginx reload configuration (which in itself is graceful), then eventually stop the old process (you can use netstat to find out when the last connection to the old port is closed).</p>
<p>Alternatively, you can change the fcgi implementation to fork a new process, close all sockets in the child except for the fcgi server socket, close the fcgi server socket in parent, exec a new django process in the child (making it use the fcgi server socket), and terminate the parent process once all fcgi connections are closed. IOW, implement graceful restart for runfcgi.</p>
|
<p>You can use spawning instead of FastCGI</p>
<p><a href="http://www.eflorenzano.com/blog/post/spawning-django/" rel="nofollow noreferrer">http://www.eflorenzano.com/blog/post/spawning-django/</a></p>
| 47,229
|
<p>How can I find out the size of a file I opened with an application written in C ?
I would like to know the size, because I want to put the content of the loaded file into a string, which I allocate using <code>malloc()</code>. Just writing <code>malloc(10000*sizeof(char));</code> is IMHO a bad idea. </p>
|
<p>You need to seek to the end of the file and then ask for the position:</p>
<pre><code>fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
</code></pre>
<p>You can then seek back, e.g.:</p>
<pre><code>fseek(fp, 0L, SEEK_SET);
</code></pre>
<p>or (if seeking to go to the beginning)</p>
<pre><code>rewind(fp);
</code></pre>
|
<pre><code>#include <stdio.h>
#define MAXNUMBER 1024
int main()
{
int i;
char a[MAXNUMBER];
FILE *fp = popen("du -b /bin/bash", "r");
while((a[i++] = getc(fp))!= 9)
;
a[i] ='\0';
printf(" a is %s\n", a);
pclose(fp);
return 0;
}
</code></pre>
<p>HTH</p>
| 29,510
|
<p>In a <a href="http://www.pygame.org/" rel="nofollow noreferrer">pyGame</a> application, I would like to render resolution-free GUI widgets described in SVG.</p>
<p>How can I achieve this?</p>
<p>(I like the <a href="http://ocemp.sourceforge.net/gui.html" rel="nofollow noreferrer">OCEMP GUI</a> toolkit but it seems to be bitmap dependent for its rendering)</p>
|
<p>This is a complete example which combines hints by other people here.
It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0.</p>
<pre><code>#!/usr/bin/python
import array
import math
import cairo
import pygame
import rsvg
WIDTH = 512
HEIGHT = 512
data = array.array('c', chr(0) * WIDTH * HEIGHT * 4)
surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_ARGB32, WIDTH, HEIGHT, WIDTH * 4)
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
svg = rsvg.Handle(file="test.svg")
ctx = cairo.Context(surface)
svg.render_cairo(ctx)
screen = pygame.display.get_surface()
image = pygame.image.frombuffer(data.tostring(), (WIDTH, HEIGHT),"ARGB")
screen.blit(image, (0, 0))
pygame.display.flip()
clock = pygame.time.Clock()
while True:
clock.tick(15)
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
</code></pre>
|
<p>Based on other answers, here's a function to read a SVG file into a pygame image - including correcting color channel order and scaling:</p>
<pre><code>def pygame_svg( svg_file, scale=1 ):
svg = rsvg.Handle(file=svg_file)
width, height= map(svg.get_property, ("width", "height"))
width*=scale; height*=scale
data = array.array('c', chr(0) * width * height * 4)
surface = cairo.ImageSurface.create_for_data( data, cairo.FORMAT_ARGB32, width, height, width*4)
ctx = cairo.Context(surface)
ctx.scale(scale, scale)
svg.render_cairo(ctx)
#seemingly, cairo and pygame expect channels in a different order...
#if colors/alpha are funny, mess with the next lines
import numpy
data= numpy.fromstring(data, dtype='uint8')
data.shape= (height, width, 4)
c= data.copy()
data[::,::,0]=c[::,::,1]
data[::,::,1]=c[::,::,0]
data[::,::,2]=c[::,::,3]
data[::,::,3]=c[::,::,2]
image = pygame.image.frombuffer(data.tostring(), (width, height),"ARGB")
return image
</code></pre>
| 14,660
|
<p>Which of these queries is the faster?</p>
<p>NOT EXISTS:</p>
<pre><code>SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE NOT EXISTS (
SELECT 1
FROM Northwind..[Order Details] od
WHERE p.ProductId = od.ProductId)
</code></pre>
<p>Or NOT IN:</p>
<pre><code>SELECT ProductID, ProductName
FROM Northwind..Products p
WHERE p.ProductID NOT IN (
SELECT ProductID
FROM Northwind..[Order Details])
</code></pre>
<p>The query execution plan says they both do the same thing. If that is the case, which is the recommended form?</p>
<p>This is based on the NorthWind database.</p>
<p>[Edit]</p>
<p>Just found this helpful article:
<a href="http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx" rel="noreferrer">http://weblogs.sqlteam.com/mladenp/archive/2007/05/18/60210.aspx</a></p>
<p>I think I'll stick with NOT EXISTS.</p>
|
<p>I always default to <code>NOT EXISTS</code>.</p>
<p>The execution plans may be the same at the moment but if either column is altered in the future to allow <code>NULL</code>s the <code>NOT IN</code> version will need to do more work (even if no <code>NULL</code>s are actually present in the data) and the semantics of <code>NOT IN</code> if <code>NULL</code>s <em>are</em> present are unlikely to be the ones you want anyway.</p>
<p>When neither <code>Products.ProductID</code> or <code>[Order Details].ProductID</code> allow <code>NULL</code>s the <code>NOT IN</code> will be treated identically to the following query.</p>
<pre><code>SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
</code></pre>
<p>The exact plan may vary but for my example data I get the following.</p>
<p><img src="https://i.stack.imgur.com/lCTsG.png" alt="Neither NULL"></p>
<p>A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.</p>
<pre><code>/*Not valid syntax but better reflects the plan*/
SELECT p.ProductID,
p.ProductName
FROM Products p
LEFT ANTI SEMI JOIN [Order Details] od
ON p.ProductId = od.ProductId
</code></pre>
<p>If <code>[Order Details].ProductID</code> is <code>NULL</code>-able the query then becomes</p>
<pre><code>SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
</code></pre>
<p>The reason for this is that the correct semantics if <code>[Order Details]</code> contains any <code>NULL</code> <code>ProductId</code>s is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.</p>
<p><img src="https://i.stack.imgur.com/mPYhd.png" alt="One NULL"></p>
<p>If <code>Products.ProductID</code> is also changed to become <code>NULL</code>-able the query then becomes</p>
<pre><code>SELECT ProductID,
ProductName
FROM Products p
WHERE NOT EXISTS (SELECT *
FROM [Order Details] od
WHERE p.ProductId = od.ProductId)
AND NOT EXISTS (SELECT *
FROM [Order Details]
WHERE ProductId IS NULL)
AND NOT EXISTS (SELECT *
FROM (SELECT TOP 1 *
FROM [Order Details]) S
WHERE p.ProductID IS NULL)
</code></pre>
<p>The reason for that one is because a <code>NULL</code> <code>Products.ProductId</code> should not be returned in the results <strong>except</strong> if the <code>NOT IN</code> sub query were to return no results at all (i.e. the <code>[Order Details]</code> table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.</p>
<p><img src="https://i.stack.imgur.com/8XAh1.png" alt="Both NULL"></p>
<p>The effect of this is shown in <a href="http://sqlinthewild.co.za/index.php/2010/02/18/not-exists-vs-not-in/" rel="noreferrer">the blog post already linked by Buckley</a>. In the example there the number of logical reads increase from around 400 to 500,000.</p>
<p>Additionally the fact that a single <code>NULL</code> can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no <code>NULL</code> rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, <a href="https://dba.stackexchange.com/q/117306/3690">with inappropriate nested loops causing repeated execution of an expensive sub tree for example</a>. </p>
<p>This is not the only possible execution plan for a <code>NOT IN</code> on a <code>NULL</code>-able column however. <a href="http://bradsruminations.blogspot.co.uk/2011/10/t-sql-tuesday-023-flip-side-of-join.html" rel="noreferrer">This article shows another one</a> for a query against the <code>AdventureWorks2008</code> database.</p>
<p>For the <code>NOT IN</code> on a <code>NOT NULL</code> column or the <code>NOT EXISTS</code> against either a nullable or non nullable column it gives the following plan.</p>
<p><img src="https://i.stack.imgur.com/nahUD.png" alt="Not EXists"></p>
<p>When the column changes to <code>NULL</code>-able the <code>NOT IN</code> plan now looks like</p>
<p><img src="https://i.stack.imgur.com/8o9PQ.png" alt="Not In - Null"></p>
<p>It adds an extra inner join operator to the plan. This apparatus is <a href="https://dba.stackexchange.com/a/14812/3690">explained here</a>. It is all there to convert the previous single correlated index seek on <code>Sales.SalesOrderDetail.ProductID = <correlated_product_id></code> to two seeks per outer row. The additional one is on <code>WHERE Sales.SalesOrderDetail.ProductID IS NULL</code>. </p>
<p>As this is under an anti semi join if that one returns any rows the second seek will not occur. However if <code>Sales.SalesOrderDetail</code> does not contain any <code>NULL</code> <code>ProductID</code>s it will double the number of seek operations required.</p>
|
<p>It depends..</p>
<pre><code>SELECT x.col
FROM big_table x
WHERE x.key IN( SELECT key FROM really_big_table );
</code></pre>
<p>would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.</p>
<p>But, depending on the DBMS's optimizer, this could be no different.</p>
<p>As an example of when EXISTS is better</p>
<pre><code>SELECT x.col
FROM big_table x
WHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);
AND id = very_limiting_criteria
</code></pre>
| 20,849
|
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/795746/warning-mysql-fetch-array-supplied-argument-is-not-a-valid-mysql-result">Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result</a> </p>
</blockquote>
<p>When I run my php page, I get this error and do not know what's wrong, can anyone help? If anyone needs more infomation, I'll post the whole code.</p>
<pre>Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
H:\Program Files\EasyPHP 2.0b1\www\test\info.php on line 16</pre>
<pre><code><?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
</code></pre>
|
<p>It generally means that you've got an error in your SQL.</p>
<pre><code>$sql = "SELECT * FROM myTable"; // table name only do not add tb
$result = mysql_query($sql);
var_dump($result); // bool(false)
</code></pre>
<p>Obviously, <code>false</code> is not a MySQL resource, hence you get that error.</p>
<p><strong>EDIT with the code pasted now</strong>:</p>
<p>On the line before your <code>while</code> loop, add this:</p>
<pre><code>if (!$result) {
echo "Error. " . mysql_error();
} else {
while ( ... ) {
...
}
}
</code></pre>
<p>Make sure that the <code>tb_address_book</code> table actually exists and that you've connected to the DB properly.</p>
|
<pre><code><?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
</code></pre>
| 20,467
|
<p>I'm starting to get comfortable with the idea of fakes, stubs, mocks, and dynamic mocks. But I am still a little iffy in my understanding of when to use partial mocks. </p>
<p>It would seem that if you're planning on mocking a service and need to resort to a partial mock then it is a sign of bad design. Is it that partial mocks are mostly for getting legacy code under test coverage?</p>
<p>On the flip side of this, say I am testing a class which has a Reset() method. If I have already confirmed in a separate test that the Reset() method works, and I have some functionality of the class that should end with a call to this method, is it poor test design to do a partial mock of the object and run tests against the partial mock, defining an Expectation on the Reset() method. </p>
<p>I currently have several tests set up in this manner, is this sort of thing going to get me in trouble later on?</p>
|
<p>Its good design, imho. What happens when somebody comes after you and changes your method, removing the call to Reset? (btw, why so much state in your objects?) You might never know they screwed up until you hit production. By mocking it and asserting on that method call, you can assure nobody is going to mess up while maintaining your code.</p>
|
<p>My understanding of partial mock was that it was for mocking abstract classes, with only the abstract methods being mocked, and the existing concrete methods being left as they are?</p>
| 16,903
|
<p>If you could go back in time and tell yourself to read a specific book at the beginning of your career as a developer, which book would it be?</p>
<p>I expect this list to be varied and to cover a wide range of things.</p>
<p><strong>To search:</strong> Use the search box in the upper-right corner. To search the answers of the current question, use <code>inquestion:this</code>. For example:</p>
<pre><code>inquestion:this "Code Complete"
</code></pre>
|
<ul>
<li><em>Code Complete</em> (2nd edition) by Steve McConnell</li>
<li><em>The Pragmatic Programmer</em></li>
<li><em>Structure and Interpretation of Computer Programs</em></li>
<li><em>The C Programming Language</em> by Kernighan and Ritchie</li>
<li><em>Introduction to Algorithms</em> by Cormen, Leiserson, Rivest & Stein</li>
<li><em>Design Patterns</em> by the Gang of Four</li>
<li><em>Refactoring: Improving the Design of Existing Code</em></li>
<li><em>The Mythical Man Month</em></li>
<li><em>The Art of Computer Programming</em> by Donald Knuth</li>
<li><em>Compilers: Principles, Techniques and Tools</em> by Alfred V. Aho, Ravi Sethi and Jeffrey D. Ullman</li>
<li><em>Gödel, Escher, Bach</em> by Douglas Hofstadter</li>
<li><em>Clean Code: A Handbook of Agile Software Craftsmanship</em> by Robert C. Martin</li>
<li><em>Effective C++</em></li>
<li><em>More Effective C++</em></li>
<li><em>CODE</em> by Charles Petzold</li>
<li><em>Programming Pearls</em> by Jon Bentley</li>
<li><em>Working Effectively with Legacy Code</em> by Michael C. Feathers</li>
<li><em>Peopleware</em> by Demarco and Lister</li>
<li><em>Coders at Work</em> by Peter Seibel</li>
<li><em>Surely You're Joking, Mr. Feynman!</em></li>
<li><em>Effective Java</em> 2nd edition</li>
<li><em>Patterns of Enterprise Application Architecture</em> by Martin Fowler</li>
<li><em>The Little Schemer</em></li>
<li><em>The Seasoned Schemer</em></li>
<li><em>Why's (Poignant) Guide to Ruby</em></li>
<li><em>The Inmates Are Running The Asylum: Why High Tech Products Drive Us Crazy and How to Restore the Sanity</em></li>
<li><em>The Art of Unix Programming</em></li>
<li><em>Test-Driven Development: By Example</em> by Kent Beck</li>
<li><em>Practices of an Agile Developer</em></li>
<li><em>Don't Make Me Think</em></li>
<li><em>Agile Software Development, Principles, Patterns, and Practices</em> by Robert C. Martin</li>
<li><em>Domain Driven Designs</em> by Eric Evans</li>
<li><em>The Design of Everyday Things</em> by Donald Norman</li>
<li><em>Modern C++ Design</em> by Andrei Alexandrescu</li>
<li><em>Best Software Writing I</em> by Joel Spolsky</li>
<li><em>The Practice of Programming</em> by Kernighan and Pike</li>
<li><em>Pragmatic Thinking and Learning: Refactor Your Wetware</em> by Andy Hunt</li>
<li><em>Software Estimation: Demystifying the Black Art</em> by Steve McConnel</li>
<li><em>The Passionate Programmer (My Job Went To India)</em> by Chad Fowler</li>
<li><em>Hackers: Heroes of the Computer Revolution</em></li>
<li><em>Algorithms + Data Structures = Programs</em></li>
<li><em>Writing Solid Code</em></li>
<li><em>JavaScript - The Good Parts</em></li>
<li><em>Getting Real</em> by 37 Signals</li>
<li><em>Foundations of Programming</em> by Karl Seguin</li>
<li><em>Computer Graphics: Principles and Practice in C</em> (2nd Edition)</li>
<li><em>Thinking in Java</em> by Bruce Eckel</li>
<li><em>The Elements of Computing Systems</em></li>
<li><em>Refactoring to Patterns</em> by Joshua Kerievsky</li>
<li><em>Modern Operating Systems</em> by Andrew S. Tanenbaum</li>
<li><em>The Annotated Turing</em></li>
<li><em>Things That Make Us Smart</em> by Donald Norman</li>
<li><em>The Timeless Way of Building</em> by Christopher Alexander</li>
<li><em>The Deadline: A Novel About Project Management</em> by Tom DeMarco</li>
<li><em>The C++ Programming Language (3rd edition)</em> by Stroustrup</li>
<li><em>Patterns of Enterprise Application Architecture</em></li>
<li><em>Computer Systems - A Programmer's Perspective</em></li>
<li><em>Agile Principles, Patterns, and Practices in C#</em> by Robert C. Martin</li>
<li><em>Growing Object-Oriented Software, Guided</em> by Tests</li>
<li><em>Framework Design Guidelines</em> by Brad Abrams</li>
<li><em>Object Thinking</em> by Dr. David West</li>
<li><em>Advanced Programming in the UNIX Environment</em> by W. Richard Stevens</li>
<li><em>Hackers and Painters: Big Ideas from the Computer Age</em></li>
<li><em>The Soul of a New Machine</em> by Tracy Kidder</li>
<li><em>CLR via C#</em> by Jeffrey Richter</li>
<li><em>The Timeless Way of Building</em> by Christopher Alexander</li>
<li><em>Design Patterns in C#</em> by Steve Metsker</li>
<li><em>Alice in Wonderland</em> by Lewis Carol</li>
<li><em>Zen and the Art of Motorcycle Maintenance</em> by Robert M. Pirsig</li>
<li><em>About Face - The Essentials of Interaction Design</em></li>
<li><em>Here Comes Everybody: The Power of Organizing Without Organizations</em> by Clay Shirky</li>
<li><em>The Tao of Programming</em></li>
<li><em>Computational Beauty of Nature</em></li>
<li><em>Writing Solid Code</em> by Steve Maguire</li>
<li><em>Philip and Alex's Guide to Web Publishing</em></li>
<li><em>Object-Oriented Analysis and Design with Applications</em> by Grady Booch</li>
<li><em>Effective Java</em> by Joshua Bloch</li>
<li><em>Computability</em> by N. J. Cutland</li>
<li><em>Masterminds of Programming</em></li>
<li><em>The Tao Te Ching</em></li>
<li><em>The Productive Programmer</em></li>
<li><em>The Art of Deception</em> by Kevin Mitnick</li>
<li><em>The Career Programmer: Guerilla Tactics for an Imperfect World</em> by Christopher Duncan</li>
<li><em>Paradigms of Artificial Intelligence Programming: Case studies in Common Lisp</em></li>
<li><em>Masters of Doom</em></li>
<li><em>Pragmatic Unit Testing in C# with NUnit</em> by Andy Hunt and Dave Thomas with Matt Hargett</li>
<li><em>How To Solve It</em> by George Polya</li>
<li><em>The Alchemist</em> by Paulo Coelho</li>
<li><em>Smalltalk-80: The Language and its Implementation</em></li>
<li><em>Writing Secure Code</em> (2nd Edition) by Michael Howard</li>
<li><em>Introduction to Functional Programming</em> by Philip Wadler and Richard Bird</li>
<li><em>No Bugs!</em> by David Thielen </li>
<li><em>Rework</em> by Jason Freid and DHH</li>
<li><em>JUnit in Action</em></li>
</ul>
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0201485672" rel="nofollow noreferrer" rel="nofollow noreferrer">Refactoring</a></p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321127420" rel="nofollow noreferrer" rel="nofollow noreferrer">Patterns of Enterprise Application Architecture</a></p>
| 2,403
|
<p>Here's a relatively common task for me, and, I think, for many a .NET programmer:<br>
I want to use the .NET ThreadPool for scheduling worker threads that need to process a given type of tasks.</p>
<p>As a refresher, the signatures for the queueing method of the ThreadPool and its associated delegate are:</p>
<pre><code>public static bool QueueUserWorkItem (
WaitCallback callBack,
Object state
)
public delegate void WaitCallback (Object state)
</code></pre>
<p>Therefore, a typical generic worker thread class would look something like:</p>
<pre><code>public class Worker<T> {
public void schedule(T i_task) {
ThreadPool.QueueUserWorkItem(execute, i_task)
}
private void execute(Object o){
T task = (T)o; //What happened to the type safety?
executeTask(task);
}
private void executeTask(T i_task){
//process i_task
}
}
</code></pre>
<p>Notice the type of the <code>state</code> parameter? It's <em><code>Object</code></em> !</p>
<p>What's the compelling reason why the .NET team chose not to make the <code>QueueUserWorkItem</code> method (or the whole <code>ThreadPool</code> class) generic? I can't believe they just overlooked it.</p>
<p>Here's how I'd like to see it:</p>
<pre><code>//in the ThreadPool class:
public static bool QueueUserWorkItem<T> (
WaitCallback<T> callBack,
T state
)
public delegate void WaitCallback<T> (T state)
</code></pre>
<p>This would make the worker class type-safe (and a lot clearer, IMHO):</p>
<pre><code>public class Worker<T> {
public void schedule(T i_task) {
ThreadPool.QueueUserWorkItem<T>(execute, i_task)
}
private void execute(T i_task){
//process i_task
}
}
</code></pre>
<p>I must be missing something.</p>
|
<p>It sounds like you are talking about a work queue? (and I sound like clippy...)</p>
<p>For the record, thread-pool threads should typically be used for short pieces of work. You should ideally create your own threads for a long-lived queue. Note that .NET 4.0 may be adopting the CCR/TPL libraries, so we'll get some inbuilt work queues for free - but it isn't hard to write a threaded work-queue. And you can make it generic, too ;-p</p>
<p>Re the question - I prefer the captured variables approach to passing state into threads (be they <code>Thread</code>, <code>ThreadPool</code>, or <code>Control.Invoke</code>):</p>
<pre><code> Thread t = new Thread(() => SomeMethod(arg));
t.IsBackground = true;
t.Name = "Worker n";
t.Start();
</code></pre>
<p>This gives you much more granular control over the thread, without saturating the <code>ThreadPool</code>.</p>
|
<p>ThreadPool exists since .NET 1.1 which didn't have Generics.</p>
<p>I like how they chose not to break backwards compatibility :-)</p>
| 41,884
|
<p>I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.</p>
<p>Here is how I have the library and application folders set up. (I'm not sure if this is right)</p>
<pre><code>AppFolder
App.sln
App.ncb
*.h
*.cpp
Debug
*.obj
App.exe
</code></pre>
<p>and somewhere else on the hard drive...</p>
<pre><code>LibraryFolder
lib
Library.lib
include
LibrarySolutionFolder
Library.sln
Library.ncb
*.h
*.cpp
Debug
*.obj
Library.lib
</code></pre>
<p>I've been #including the library *.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib
files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories.
How can I get this to link? (And am I structuring the library folders correctly?)</p>
|
<p>On the project properties:</p>
<p>Configuration Properties -> Linker -> Input -> Additional Dependancies</p>
<p>Add it in there.</p>
<p>Or, in your .h file for the library, add:</p>
<pre><code>#pragma comment(lib, "Library")
</code></pre>
<p>This will do it automatically for you.</p>
|
<p>VC does not simply link the library if you include the header-file.</p>
<p>You have to tell the linker to use the library. For good reasons: You alredy have thousands of libs in your library folder. If MSVC had to search all of them each time you link your program it would have to wade through hundrets of megabytes of data. </p>
<p>That would take quite a while, therefore it's not done by default.</p>
<p>For VC you can also give a hint to the linker inside your source. To do so you add the following line somewhere in your source-code (the header of the lib may be a good place).</p>
<pre><code>#pragma comment(lib,"c:\\path_to_library\\libname.lib")
</code></pre>
<p>That's not platform independet but the most convenient way to get a lib automatically linked to a project using MSVC.</p>
<p>Another way is to simply add the linker to the project settings. The relevant info can be found lin the linker settings of your project. Don't forget to add the lib to the release and debug configurations.</p>
| 27,655
|
<p>I am working on a website that currently has a number of disparate search functions, for example:</p>
<ul>
<li>A crawl 'through the front door' of the website</li>
<li>A search that communicates with a web-service</li>
<li>etc...</li>
</ul>
<p>What would be the best way to tie these together, and provide what appears to be a unified search function?</p>
<p>I found the following <a href="http://en.wikipedia.org/wiki/List_of_enterprise_search_vendors" rel="nofollow noreferrer">list on wikipedia</a></p>
<h3>Free and open source enterprise search software</h3>
<ul>
<li>Lucene and Solr</li>
<li>Xapian</li>
</ul>
<h3>Vendors of proprietary enterprise search software</h3>
<ul>
<li>AskMeNow</li>
<li>Autonomy Corporation</li>
<li>Concept Searching Limited</li>
<li>Coveo</li>
<li>Dieselpoint, Inc.</li>
<li>dtSearch Corp.</li>
<li>Endeca Technologies Inc.</li>
<li>Exalead</li>
<li>Expert System S.p.A.</li>
<li>Funnelback</li>
<li>Google Search Appliance</li>
<li>IBM</li>
<li>ISYS Search Software</li>
<li>Microsoft (includes Microsoft Search Server, Fast Search & Transfer):</li>
<li>Open Text Corporation</li>
<li>Oracle Corporation</li>
<li>Queplix Universal Search Appliance</li>
<li>SAP</li>
<li>TeraText</li>
<li>Vivísimo</li>
<li>X1 Technologies, Inc.</li>
<li>ZyLAB Technologies</li>
</ul>
<p>Thanks for any advice regarding this.</p>
|
<p>Solr is an unbelievably flexible solution for search. Just in the last year I coded 2 solr-based websites and worked on a third existing one, each worked in a very different way.</p>
<p>Solr simply eats XML requests to add something to index, and XML requests to search for something inside an index. It doesn't do crawling or text extraction for you, but most of the time these are easy to do. There are many existing addons to Solr/Lucene stack so maybe something for you already exists.</p>
<p>I would avoid proprietary software unless you're sure Solr is insufficient. It's one of the nicest programs I've worked with, very flexible when you need it and at the same time you can start in minutes without reading long manuals.</p>
|
<p>Two other solutions that weren't as well-known &/or available around the time the original question was asked:</p>
<ul>
<li><a href="https://www.google.com/cse/" rel="nofollow">Google Custom Search</a> - especially since the disable public URL option was recently added</li>
<li><a href="http://yacy.net/en/index.html" rel="nofollow">YaCy</a> - you can join the network or download and roll your own independent servers</li>
</ul>
| 49,756
|
<p>My website was recently attacked by, what seemed to me as, an innocent code:</p>
<pre><code><?php
if ( isset( $ _GET['page'] ) ) {
include( $ _GET['page'] . ".php" );
} else {
include("home.php");
}
?>
</code></pre>
<p>There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.</p>
<p>This website has an explanation and a few examples of avoiding code injection: <a href="http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html" rel="noreferrer">http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html</a></p>
<p>How would you protect this code from code injection?</p>
|
<p>Use a whitelist and make sure the page is in the whitelist:</p>
<pre><code> $whitelist = array('home', 'page');
if (in_array($_GET['page'], $whitelist)) {
include($_GET['page'].'.php');
} else {
include('home.php');
}
</code></pre>
|
<p>@pek - That won't work, as your array keys are 0 and 1, not 'home' and 'page'.</p>
<p>This code should do the trick, I believe:</p>
<pre><code><?php
$whitelist = array(
'home',
'page',
);
if(in_array($_GET['page'], $whitelist)) {
include($_GET['page'] . '.php');
} else {
include('home.php');
}
?>
</code></pre>
<p>As you've a whitelist, there shouldn't be a need for <code>file_exists()</code> either.</p>
| 5,987
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.