instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Yes we're talking about ASCII codes. My appologies I'm not the Delphi dev here.</p>
|
<p>For Delphi 7, I'd get <a href="http://www.soft-gems.net/index.php/libs/unicode-library" rel="nofollow noreferrer">the free Unicode Library by Mike Lischke</a> who is the author of Virtual Treeview.</p>
<p>The libary includes a lot of conversion functions to go to and from Unicode, so you can use the ones that make most sense in your application.</p>
<p><a href="https://stackoverflow.com/questions/305016/what-are-major-incentives-to-upgrade-to-d2009-unicode-excluded#307419">Or you can upgrade to Delphi 2009</a> which has built-in encoding routines, and its own library of conversion functions.</p>
|
<p>It depends what your definition of conversion is. If you want to map the 127 lowest characters to the Unicode equivalent, you can use an explicit cast. But this creates garbage if the string contains higher characters.</p>
<p>If you want mappings like ë -> e and û -> u, you can write your own code. But be aware that there are always characters that can't be converted.</p>
| 39,243
|
<blockquote>
<p>Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:</p>
<ul>
<li>Running the tests becomes automate-able and repeatable</li>
<li>You can test at a much more granular level than point-and-click testing via a GUI</li>
</ul>
<p><a href="https://stackoverflow.com/questions/1383/what-is-unit-testing">Rytmis</a></p>
</blockquote>
<p>My question is, what are the current "best practices" in terms of tools as well as when and where to use unit testing as part of your daily coding?</p>
<p>Lets try to be somewhat language agnostic and cover all the bases.</p>
|
<p>Ok here's some best practices from some one who doesn't unit test as much as he should...cough.</p>
<ol>
<li>Make sure your tests test <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=35578" rel="noreferrer" title="one">one</a>
thing and one thing only.</li>
<li>Write unit tests as you go. Preferably <a href="http://en.wikipedia.org/wiki/Test-driven_development" rel="noreferrer" title="before">before</a> you write the code you are testing against.</li>
<li>Do not unit test the GUI. </li>
<li><a href="http://en.wikipedia.org/wiki/Separation_of_concerns" rel="noreferrer" title="Separate your concerns">Separate your concerns</a>. </li>
<li>Minimise the dependencies of your tests.</li>
<li>Mock behviour with <a href="http://en.wikipedia.org/wiki/Mock_object" rel="noreferrer" title="mocks">mocks</a>.</li>
</ol>
|
<p>NUnit is a good tool for any of the .NET languages.</p>
<p>Unit tests can be used in a number of ways: </p>
<ol>
<li>Test Logic</li>
<li>Increase separation of code units. If you can't fully test a function or section of code, then the parts that make it up are too interdependant.</li>
<li>Drive development, some people write tests <em>before</em> they write the code to be tested. This forces you to think about what you want the code to <em>do</em>, and then gives you a definite guideline on when you have acheived that.</li>
</ol>
| 3,755
|
<p>While debugging a Linux app, I found a pointer with the suspicious value 0x7c7c7c7c. Does that particular value indicate anything?</p>
<p>(I ask because I know from my MSVC days that in a debug build, values like 0xcdcdcdcd or 0xdddddddd would be stored into heap blocks that were uninitialized, freed, or otherwise invalid. Some people use magic values like 0xdeadbeef or 0xcafebabe in uninitialized memory. I'm guessing something in libc or elsewhere uses 0x7c7c7c7c as a magic value, but I can't find it documented.)</p>
|
<p>I don't recognize that magic number, and neither does <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)" rel="nofollow noreferrer">Wikipedia</a>. I would guess that some code in your program (or in a library you're using) is using <code>memset()</code> and hitting your pointer. Have you grepped your code base case-insensitively for the string "0x7c"?</p>
|
<p>0x7c7c = 01111100 01111100 in binary. That could be one of those "most difficult to read" bit patterns that format utilities fill unused space on hard drives with.</p>
| 46,904
|
<p>I have a big load of documents, text-files, that I want to search for relevant content. I've seen a searching tool, can't remeber where, that implemented a nice method as I describe in my requirement below.</p>
<p>My requirement is as follows:</p>
<ul>
<li>I need an optimised search function: I supply this search function with a list (one or more) partially-complete (or complete) words separated with spaces. </li>
<li>The function then finds all the documents containing words starting or equal to the first word, then search these found documents in the same way using the second word, and so on, at the end of which it returns a list containing the actual words found linked with the documents (name & location) containing them, for the complete the list of words. </li>
<li>The documents must contain <strong>all</strong> the words in the list.</li>
<li>I want to use this function to do an as-you-type search so that I can display and update the results in a tree-like structure in real-time.</li>
</ul>
<p>A possible approach to a solution I came up with is as follows:
I create a database (most likely using mysql) with three tables: 'Documents', 'Words' and 'Word_Docs'.</p>
<ul>
<li>'Documents' will have (idDoc, Name, Location) of all documents.</li>
<li>'Words' will have (idWord, Word) , and be a list of unique words from all the documents (a specific word appears only once).</li>
<li>'Word_Docs' will have (idWord, idDoc) , and be a list of unique id-combinations for each word and document it appears in.</li>
</ul>
<p>The function is then called with the content of an editbox on each keystroke (except space):</p>
<ul>
<li>the string is tokenized</li>
<li>(here my wheels spin a bit): I am sure a single SQL statement can be constructed to return the required dataset: (actual_words, doc_name, doc_location); (I'm not a hot-number with SQL), alternatively a sequence of calls for each token and parse-out the non-repeating idDocs?</li>
<li>this dataset (/list/array) is then returned </li>
</ul>
<p>The returned list-content is then displayed:</p>
<p>e.g.: called with: "seq sta cod"
displays:</p>
<pre><code>sequence - start - code - Counting Sequences [file://docs/sample/con_seq.txt]
- stop - code - Counting Sequences [file://docs/sample/con_seq.txt]
sequential - statement - code - SQL intro [file://somewhere/sql_intro.doc]
</code></pre>
<p>(and-so-on)</p>
<p>Is this an optimal way of doing it? The function needs to be fast, or should it be called only when a space is hit?
Should it offer word-completion? (Got the words in the database) At least this would prevent useless calls to the function for words that does not exist.
If word-completion: how would that be implemented?</p>
<p>(Maybe SO could also use this type of search-solution for browsing the tags? (In top-right of main page))</p>
|
<p>What you're talking about is known as an <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="nofollow noreferrer">inverted index</a> or posting list, and operates similary to what you propose and what Mecki proposes. There's a lot of literature about inverted indexes out there; the Wikipedia article is a good place to start.</p>
<p>Better, rather than trying to build it yourself, use an existing inverted index implementation. Both MySQL and recent versions of PostgreSQL have full text indexing by default. You may also want to check out <a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a> for an independent solution. There are a lot of things to consider in writing a <em>good</em> inverted index, including tokenisation, stemming, multi-word queries, etc, etc, and a prebuilt solution will do all this for you.</p>
|
<p>Not sure about the syntax (this is sql server syntax), but:</p>
<pre><code>-- N is the number of elements in the list
SELECT idDoc, COUNT(1)
FROM Word_Docs wd INNER JOIN Words w on w.idWord = wd.idWord
WHERE w.Word IN ('word1', ..., 'wordN')
GROUP BY wd.idDoc
HAVING COUNT(1) = N
</code></pre>
<p>That is, without using like. With like things are MUCH more complex.</p>
| 17,821
|
<p>Using qsort in C we pass in a comparison function e.g.</p>
<pre><code>int cmp(const void*, const void*);
</code></pre>
<p>the protoype of qsort expects a <code>int (* )(const void* , const void*)</code> so we call:</p>
<pre><code>qsort(..., cmp);
</code></pre>
<p>but it is equally valid to call:</p>
<pre><code>qsort(..., &cmp);
</code></pre>
<p>and this is what we would have to do if we passed in a static member-function in C++. Kernighan & Ritchie (2nd Edition, 5.11 "Pointers To Functions" p119) states that "since [cmp] is known to be a function, the & operator is not necessary, in the same way that it is not needed before an array name."</p>
<p>Does anyone else feel slightly uncomfortable with this (esp. regarding type-safety)?</p>
|
<p>Whether you feel uncomfortable or not doesn't change the fact that C is not considered a type-safe language. Case in point:</p>
<pre><code>int main()
{
int integer = 0xFFFFFF;
void (*functionPointer)() = (void(*)())integer;
functionPointer();
return 0;
}
</code></pre>
<p>This is completely valid at compile time, but it is obviously not safe.</p>
|
<p>It's not so much a sense of discomfort as a distaste for valid-yet-conflicting syntax options. Either <code>cmp</code> is pointer, and should be treated consistently as such, or it's some other type--which, IMHO is syntactically misleading.</p>
<p>Going a bit further, I'd also require a call either to dereference the pointer (to highlight the fact that it's a pointer) or not (because a function name <em>is</em> a pointer) ... but not allow both. </p>
<p>Function pointers can be extremely powerful, yet they seem to be a source of confusion to both new and experienced programmers alike. Part of the difficulty could be alleviated by requiring a single, meaningful syntax that <em>clarifies</em> their use, rather than <em>obscuring</em> it.</p>
| 32,263
|
<p>I have these two <code>CREATE TABLE</code> statements: </p>
<pre><code>CREATE TABLE GUEST (
id int(15) not null auto_increment PRIMARY KEY,
GuestName char(25) not null
);
CREATE TABLE PAYMENT (
id int(15) not null auto_increment
Foreign Key(id) references GUEST(id),
BillNr int(15) not null
);
</code></pre>
<p>What is the problem in the second statement? It did not create a new table.</p>
|
<p>The answer to your question is almost the same as the answer to <a href="https://stackoverflow.com/questions/236668/foreign-keys-in-mysql#236677">this one</a> . </p>
<p>You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using "references").</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html" rel="noreferrer">This</a> has some code showing how to create foreign keys by themselves, and in CREATE TABLE.</p>
<p>Here's one of the simpler examples from that:</p>
<pre><code>CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
INDEX par_ind (parent_id),
FOREIGN KEY (parent_id) REFERENCES parent(id)
ON DELETE CASCADE
) ENGINE=INNODB;
</code></pre>
|
<p>There should be space between <code>int(15)</code> and <code>not null</code></p>
| 29,626
|
<p>I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in <code>$_SESSION</code>) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the <code>?destroy=1</code> parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.</p>
<p>I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.</p>
<p>I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...</p>
<p>See code here:</p>
<pre><code><?php
if ($_POST['destroy']) {
session_destroy();
} else {
session_start();
}
?>
<html>
<head>
<title>Session test</title>
</head>
<body>
<?php
if (isset($_POST['destroy'])) {
echo "Destroy set";
}
$_SESSION['counter']++;
echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>";
echo "I am tracking you using the session id " . session_id() . "<BR>";
echo "Click <a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\">here</a> to destroy the session.";
?>
</code></pre>
|
<p>I think you put</p>
<pre><code>$_POST['destroy']
</code></pre>
<p>Instead of</p>
<pre><code>$_GET['destroy']
</code></pre>
<p>You need to use a form if you'd like to use a $_POST variable. $_GET variables are stored in the URL.</p>
|
<blockquote>
<p>I know I'm doing something silly (I'm a php newbie) but I can't seem to find what it is...</p>
</blockquote>
<p>that is how you are going to learn a lot ;) enjoy it ...</p>
| 3,750
|
<p>We are porting an app which formerly used Openbase 7 to now use MySQL 5.0.</p>
<p>OB 7 did have quite badly defined (i.e. undocumented) behavior regarding case-sensitivity. We only found this out now when trying the same queries with MySQL.</p>
<p>It appears that OB 7 treats lookups using "=" differently from those using "LIKE": If you have two values "a" and "A", and make a query with WHERE f="a", then it finds only the "a" field, not the "A" field. However, if you use LIKE instead of "=", then it finds both.</p>
<p>Our tests with MySQL showed that if we're using a non-binary collation (e.g. latin1), then both "=" and "LIKE" compare case-insensitively. However, to simulate OB's behavior, we need to get only "=" to be case-sensitive.</p>
<p>We're now trying to figure out how to deal with this in MySQL without having to add a lot of LOWER() function calls to all our queries (there are a lot!).</p>
<p>We have full control over the MySQL DB, meaning we can choose its collation mode as we like (our table names and unique indexes are not affected by the case sensitivity issues, fortunately).</p>
<p>Any suggestions how to simulate the OpenBase behaviour on MySQL with the least amount of code changes?</p>
<p>(I realize that a few smart regex replacements in our source code to add the LOWER calls might do the trick, but we'd rather find a different way)</p>
|
<p>Another idea .. does MySQL offer something like User Defined Functions? You could then write a UDF-version of like that is case insesitive (ci_like or so) and change all like's to ci_like. Probably easier to do than regexing a call to lower in ..</p>
|
<p>These two articles talk about case sensitivity in mysql:</p>
<ul>
<li><a href="http://dev.mysql.com/doc/refman/5.1/en/case-sensitivity.html" rel="nofollow noreferrer">Case Sensitive mysql</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.1/en/case-sensitivity.html" rel="nofollow noreferrer">mySql docs "Case Sensitivity"</a></li>
</ul>
<p>Both were early hits in this Google search:</p>
<ul>
<li><a href="http://www.google.com/search?client=safari&rls=en-us&q=case+sensitive+mysql&ie=UTF-8&oe=UTF-8" rel="nofollow noreferrer">case sensitive mysql</a></li>
</ul>
| 49,460
|
<p>Newbie question...</p>
<p>If I have a file that is in the root of the web app. How do I programmaticaly query the path of that file? ie, what directory it is in?</p>
|
<pre><code>System.Web.HttpServerUtility.MapPath( "~/filename.ext" );
</code></pre>
<p>will give you the physical (disk) path, which you would use with System.IO methods and such.</p>
<pre><code>System.Web.Hosting.VirtualPathUtility.ToAbsolute( "~/filename.ext" );
</code></pre>
<p>will give you the "absolute" virtual path. This won't be the full url, but isn't necessarily the root of the domain, either. It could be something like</p>
<pre>
/admin/filename.ext
</pre>
<p>if the application is rooted in a subdirectory.</p>
|
<p>was close to what I was wanting..... except that didn't seem to compile or wasn't valid in the context I was calling it.</p>
<p>However I found what I needed with System.Web.HttpRuntime.AppDomainAppPath</p>
| 25,908
|
<p>So I get that most of you are frowning at me for not currently using any source control. I want to, I really do, now that I've spent some time reading the questions / answers here. I am a hobby programmer and really don't do much more than tinker, but I've been bitten a couple of times now not having the 'time machine' handy...</p>
<p>I still have to decide which product I'll go with, but that's not relevant to this question.</p>
<p>I'm really struggling with the flow of files under source control, so much so I'm not even sure how to pose the question sensibly.</p>
<p>Currently I have a directory hierarchy where all my PHP files live in a Linux Environment. I edit them there and can hit refresh on my browser to see what happens.</p>
<p>As I understand it, my files now live in a different place. When I want to edit, I check it out and edit away. But what is my substitute for F5? How do I test it? Do I have to check it back in, then hit F5? I admit to a good bit of trial and error in my work. I suspect I'm going to get tired of checking in and out real quick for the frequent small changes I tend to make. I have to be missing something, right?</p>
<p>Can anyone step me through where everything lives and how I test along the way, while keeping true to the goal of having a 'time machine' handy?</p>
|
<p>Eric Sink has a great <a href="http://www.ericsink.com/scm/source_control.html" rel="noreferrer">series of posts</a> on source control basics. His company (Sourcegear) makes a source control tool called Vault, but the how-to is generally pretty system agnostic.</p>
|
<p>If you are using Subversion, you check out your files <em>once</em> . Then, whenever you have made big changes (or are going to lunch or whatever), you <em>commit</em> them to the server. That way you can keep your old work flow by pressing F5, but every time you <em>commit</em> you save a copy of all the files in their current state in your SVN-repository.</p>
| 9,265
|
<p>I'm working on an app that takes data from our DB and outputs an xml file using the FOR XML AUTO, ELEMENTS on the end of the generated query, followed by an XSLT to transform it the way we want. However in a particular case where we are generating some data using an sql scalar function, it always puts that element into a sub-table node named the same as the table node it's already in (so say it's a table xyz, it'd be <code>print("<xyz><node1></node1><xyz><generated-node-from-function></generated-node-from-function></xyz>");</code></p>
<p>No matter what I try (even directly manipulating a copy of the sql as generated by the app) it always seems to create this extra node layer, which causes problems later when we try to process this xml to extract the data later. Is there any particular property causing the xml generator in sql server to work this way, and is there any way to prevent it so I can keep the generated data node on the same level as the rest of the data for the table it's associated with?</p>
<p>Edit: renamed columns/tables in some cases but otherwise should be the same sql.</p>
<pre><code>SELECT * FROM (SELECT column1,column2,column3,iduser,jstart,jstop,jbatchperiod,jinactive,processed,column4,lock,column5,batchticketmicr,machineid,sjobopex,szopexrefid,jreceived,jstartopex,jstopopex,idspecialmicr,idp2batchoriginal,stateflags,bcrossrefid,bidentifier1,bidentifier2,bidentifier3,bidentifier4,bidentifier5,idexport,idimport,rsahash FROM table1) table1
LEFT JOIN (SELECT column21,ienvelope,isort,column1,idtemplate,processed,column4,lock,envelopetypecode,szqueuesvisitedunique,exportdate,jcompleted,status,ipriority,idbankaccount,iprioritybeforerzbump,fstoredrecondata,cscountyid,column10,column11,checkbox1,checkbox2,column12,column13,column14,xxxempfein,column15,column16,originalenvelopeid,column17,column18,xxxoag,trackingnumber,csldc,ecrossrefid,postmark,routingflags,eidentifier1,eidentifier2,eidentifier3,eidentifier4,eidentifier5,idexport FROM envelope) envelope ON table1.column1=Envelope.column1
LEFT JOIN (SELECT column21,column22,isort,column23,processed,side,pagetypecode,rawmicrline,rawscanline,rawbarcode,exportid,szlocandconf,szlocandconfpagefields,idformtemplate,szparms,rawmarksense,audittrail,audittrailelectronic,pixheight,pixwidth,ocrattemptcounter,idspecialmicr,idpageexception,pagemodifierflags,column10,csldc,rejectdate,rejectuser,rejectqueue,fsupervisorreject,xxxempno,xxxtraceno,xxxemplcnt,checkbox1,keyword,templatealtered,templateflags,pidentifier1,pidentifier2,pidentifier3,pidentifier4,pidentifier5,isscanlinevalid,idexport,clickcount FROM Table2) Table2 ON Envelope.column21=Page.column21
LEFT JOIN (select column22, column21, dbo.Fileimagepath(column21, column22) as path from Table2) Fileimg ON Table2.column21=FileImg.column21 AND Table2.column22=FileImg.column22
WHERE Envelope.column21 = 8
FOR XML AUTO, ELEMENTS
</code></pre>
<p>Another edit: basically FileImg's results are getting wrapped in an extra set of Table2 tags inside existing table2 tab with the rest of the data.</p>
<p>Yet another Edit: Testing against another database with the same sql it worked correctly, it appears there is a bad setting in my database or the stored proc is different <em>goes to investigate farther</em>.</p>
<p>If that doesn't work I'll try some of the other suggestions above, thanks for the help so far :)</p>
|
<p>I would try to get rid of the sub query parts "(SELECT..." and do regular joins, like:</p>
<pre><code>SELECT table1.column1, table1.column2, ..., envelope.column21, ...
FROM table1 LEFT JOIN envelope on table1.column1 = envelope.column1 ...
WHERE envelope.column21 = 8
FOR XML AUTO, ELEMENTS
</code></pre>
<p>To be clearer I ommitted most of your columns and joins. Just insert the columns you need and the njoins which are necessary.</p>
<p>Does this return you the right XML or am I missing the point? </p>
|
<p>I would try to get rid of the sub query parts "(SELECT..." and do regular joins, like:</p>
<pre><code>SELECT table1.column1, table1.column2, ..., envelope.column21, ...
FROM table1 LEFT JOIN envelope on table1.column1 = envelope.column1 ...
WHERE envelope.column21 = 8
FOR XML AUTO, ELEMENTS
</code></pre>
<p>To be clearer I ommitted most of your columns and joins. Just insert the columns you need and the njoins which are necessary.</p>
<p>Does this return you the right XML or am I missing the point? </p>
| 33,259
|
<p>So, I got ZF MVC site and want to force SSL connection on everything under my /checkout/
I tried using mod_rewrite for that, so my .htaccess would look like this:</p>
<pre><code>RewriteEngine on
RewriteRule (\/checkout.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R]
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|xml|avi|flv|mov|mp3|wav)$ index.php [L]
</code></pre>
<p>Sure enough, it does kick in SSL, but second rule, that's ZF specific and redirects everything to index.php sorta erases the protocol specification.</p>
<p>Unfortunately my level of proficiency with mod_rewrite is stupendously terrible. Maybe someone could help me out to solve this? </p>
|
<p>Tim Lytle's answer is mostly there.</p>
<p>I'd change it be a little more strict in checking HTTPS and the flags need a delimiter.</p>
<pre><code>RewriteCond %{HTTPS} !^on$
RewriteRule ^/checkout/? https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|xml|avi|flv|mov|mp3|wav)$ index.php [L]
</code></pre>
|
<p>This may help you, add the RewriteCond to only apply when the connection is not SSL, then add the 'L' option to your redirect rule so rewrite processing stops at that point (so the last rule doesn't override the SSL redirect).</p>
<pre><code>RewriteCond %{HTTPS} !on
RewriteRule (\/checkout.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [RL]
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|xml|avi|flv|mov|mp3|wav)$ index.php [L]
</code></pre>
| 49,802
|
<p>I'm trying to use the Stream.BeginWrite Async I/O API in .NET for a high-throughput situation with many short messages. As such, a scatter/gather API will reduce the number of context switches (and CPU usage) tremendously. Does this API use the LPBUFFERS Win32 API at all? Is there an alternative API for Scatter/Gather I/O?</p>
|
<p>Looking at the .net sources, the accepted answer seems to be wrong.</p>
<p><code>SocketAsyncEventArgs</code> has a <a href="https://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.bufferlist%28v=vs.90%29.aspx" rel="nofollow"><code>BufferList</code></a> attribute. When that is used, instead of the <code>Buffer</code> attribute that can only hold a single contiguous block of memory, operations can make use of scatter/gather DMA, as <a href="http://referencesource.microsoft.com/#System/net/System/Net/Sockets/Socket.cs,102e8374338a49cb" rel="nofollow"><code>Socket.SendAsync(SocketAsyncEventArgs)</code></a> uses <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms742203(v=vs.85).aspx" rel="nofollow"><code>WSASend</code></a> internally, that</p>
<blockquote>
<p>allows multiple send buffers to be specified making it applicable to the scatter/gather type of I/O</p>
</blockquote>
<p>and <a href="http://referencesource.microsoft.com/#System/net/System/Net/Sockets/Socket.cs,194ae41217fbaf74" rel="nofollow"><code>Socket.SendAsync(SocketAsyncEventArgs)</code></a> uses <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms741688%28v=vs.85%29.aspx" rel="nofollow"><code>WSARecv</code></a>, that</p>
<blockquote>
<p>allows multiple receive buffers to be specified making it applicable to the scatter/gather type of I/O</p>
</blockquote>
<p>I don't have the .net 3.5 sources handy, but <code>BufferList</code> exists since .net 3.5, so scatter/gather might have been supported since .net 3.5. The minimum OS requirements for WSASend and WSARecv exist are documented as Windows Vista / Server 2003.</p>
<p>N.B. I don't know what stream you are using, but <code>NetworkStream.BeginWrite</code> sends a single buffer to the WSASend, so you cannot use that for scatter/gathering.</p>
|
<p>There is no way to do socket scatter/gather I/O in .NET. According to a MSFT blog post, there may be a similar API in .NET 4.5 (whatever that is...)</p>
| 14,014
|
<p>I know the mantra is that the database is always the long pole in the tent anytime a page is being generated server-side.</p>
<p>But there's also a good bit of file i/o going on on a web server. Scripted code is replete with include/require statements. Moreover, its typically a practice to store templated html outside the application in files which are loaded and filled in accordingly.</p>
<p>How much of a role does file i/o play when concened with web development? Does it ever become an issue? When is it too much? Do web servers/languages cache anything?</p>
<p>Has it ever really mattered in your experience?</p>
|
<p>10 years ago, disks were so much faster than processors that you didn't have to worry about it so much. You'd run out of CPU (or saturate your NIC) before disk became an issue. Nowadays, CPUs and gigabit NICs could make disk the bottleneck, <strong>BUT</strong>....</p>
<p>Most non-database disk usage is so easily parallelizable. If you haven't designed your hosting architecture to scale horizontally by adding more systems, that's more important than fine-tuning disk access.</p>
<p>If you have designed to scale horizontally, usually just buying more servers is cheaper than trying to figure out how to optimize disk. Not to mention, things like SSD or even RAM disks for your templates will make it a non-issue.</p>
<p>It's very rare to have a serving architecture that scales horizontally, popular enough to cause scalability problems, but not profitable enough to afford another 1u in your rack.</p>
|
<p>I would say that file IO speed only becomes an issue if you are serving tons of static content. When you are processing data, and executing code to render the pages, the time to read the page itself from disk is negligible. File I/O is important in cases where the static files you are serving up are unable to fit into memory, such as when you are serving video or image files. It could also happen with html files, but since the size is so small with html files, this is less likely.</p>
| 18,822
|
<p>Short of cutting and pasting, is there a way to sort the methods in my classes in Visual Studio 2008? I like orderly code.</p>
|
<p>This is a free plug-in that does what you are asking: <a href="http://www.visualstudiogallery.com/ExtensionDetails.aspx?ExtensionID=800978aa-2aac-4440-8bdf-6d1a76a5c23c" rel="nofollow noreferrer">http://www.visualstudiogallery.com/ExtensionDetails.aspx?ExtensionID=800978aa-2aac-4440-8bdf-6d1a76a5c23c</a></p>
<h3>Update</h3>
<p>Unfortunately the link is outdated. You can download Regionerate at <a href="http://www.rauchy.net/regionerate/docs/2007/05/download.html" rel="nofollow noreferrer">http://www.rauchy.net/regionerate/docs/2007/05/download.html</a></p>
|
<p>Resharper will do a good job in a limited way. It depends on how much you want. For example, it wont go and reorder your overrides in an asp.net page based on lifecycle, or anything like that, but it will keep properties, fields, methods and what not clearly grouped</p>
<p>EDIT: By the eway i was refering to auto reordering aka reformatting.</p>
| 19,332
|
<p>I recently saw <a href="https://www.youtube.com/watch?v=TpvNEZCvk84" rel="noreferrer">this</a> video of super-swellable polymer and felt inspired. Printing a swellable structure would be sort of interesting. However, sodium polyacrylate isn't a printable material. Does anyone know of a material that is? Preferably, swelling activated by water. </p>
|
<p>To print with 2 extruders simultaneously you need a firmware that supports that. Luckily, there is a firmware called Sailfish that is able to do that. The feature you are looking for is called <code>Ditto</code> printing.</p>
<p>Sailfish firmware is found <a href="http://www.sailfishfirmware.com" rel="nofollow noreferrer">here</a></p>
|
<p>If you want a ditto printing is not mandatory to have a specific firmware (or g-code), you only need to add extruder to your end effector and - because of electrical power requirements - add further stepper driver for further stepper motor.
Please note that the maximum footprint of your printed object is less than the extruders distance, for obvious physical reasons, therefore is not that common to see, the typical dual extruder goal is to use different filament/color.
Of course, you have to achieve a notable calibration skill, and of course you have to modify the electronics of your printer (but this can be done quite easily, you only have to share the enable/step/dir signals with all the stepper driver).
This has been already done with the <a href="https://www.youtube.com/watch?time_continue=5&v=DeVeyUas5vU" rel="nofollow noreferrer">MPCNC project</a>.</p>
<p>Otherwise, if you want something more flexible, there are commercial printers with independent extruder. <a href="https://www.lpfrg.com/en/benefits-of-independent-dual-extruders/" rel="nofollow noreferrer">This one, for example</a></p>
<p>Edit: i can't comment your answer yet, but can you describe your current 3d printer setup? Because if you have the two hot ends that are only few mm apart it makes little sense to ditto-print something.</p>
| 913
|
<p>I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.</p>
<p>I'm using a simple Allow or Deny option for each 'Resource' or screen.</p>
<p>We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group.</p>
<p>I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance.</p>
<p><strong>Option A</strong>
The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied.</p>
<p>I think this will mean a smaller table, but would queries search the whole table to determine there is no match?</p>
<p><strong>Option B</strong>
A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table.</p>
<p>Thoughts?</p>
|
<p>If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access.</p>
<pre><code>UserResources
-------------
UserId FK->Users
ResourceId FK->Resources
</code></pre>
<p>and the sql would be something like </p>
<pre><code>if exists (select 1 from UserResources
where UserId = @uid and ResourceId=@rid)
set @allow=1;
</code></pre>
<p>With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.</p>
|
<p>B. It allows for much better checks whether the data is complete (for example, when you add an allowable/deniable feature).</p>
<p>Also, table size should only be a consideration for tables that you know will contain many records (as in, 100,000+). You even taking the time to type the table size consideration into this question already cost more than the extra hard drive space it would take.</p>
| 4,338
|
<p>I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using <code>cin.get( input, '\0' )</code> but <code>'\0'</code> is not really the EOF character, that just reads until EOF or <code>'\0'</code>, whichever comes first.</p>
<p>Or is using loops the only way to do it? If so, what is the best way?</p>
|
<p>The only way you can read a variable amount of data from <code>stdin</code> is using loops. I've always found that the <a href="http://en.cppreference.com/w/cpp/string/basic_string/getline" rel="noreferrer"><code>std::getline()</code></a> function works very well:</p>
<pre><code>std::string line;
while (std::getline(std::cin, line))
{
std::cout << line << std::endl;
}
</code></pre>
<p>By default <code>getline()</code> reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to <code>getline()</code>.</p>
|
<pre><code>while(std::cin) {
// do something
}
</code></pre>
| 24,682
|
<p>I'm looking for a Ruby's equivalent of <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow noreferrer">Code Like a Pythonista: Idiomatic Python</a></p>
<p>Desirable features:</p>
<ul>
<li>easy to read</li>
<li>single document which covers all topics: tips, tricks, guidelines, caveats, and pitfalls</li>
<li>size less than a book</li>
<li>idioms should work out of the box for the standard distribution (<code>% sudo apt-get install ruby irb rdoc</code>)</li>
</ul>
<p>Please, put one tutorial per answer if possible, with an example code from the tutorial and its meaning.</p>
<p>UPDATE:</p>
<p>These are the most closest to the above description resources I've encountered:</p>
<ul>
<li><a href="http://blog.angelbob.com/posts/244" rel="nofollow noreferrer">Ruby Idioms</a></li>
<li><a href="http://www.rubyist.net/~slagell/ruby/index.html" rel="nofollow noreferrer">Ruby User's Guide</a></li>
</ul>
|
<p><a href="http://blog.angelbob.com/posts/244" rel="noreferrer">Ruby Idioms (originally from RubyGarden)</a> is my usual reference for idioms. It's clearly organized and fairly complete. As the author says, these are from RubyGarden, which <a href="http://web.archive.org/web/20071016094753/www.rubygarden.org/Ruby/page/show/HomePage" rel="noreferrer">used to be</a> really cool (thanks <a href="http://www.archive.org/" rel="noreferrer">Wayback Machine</a>). But now seems to be <a href="http://rubygarden.org/" rel="noreferrer">offline</a>.</p>
|
<p>An executable guide to understanding Ruby's closures, <a href="http://innig.net/software/ruby/closures-in-ruby.rb" rel="nofollow noreferrer">closures-in-ruby.rb</a>.</p>
| 11,138
|
<p>For those who did not know, linking to off-site content in answers is a no-go at SE sites unless you provide context. From <a href="https://3dprinting.stackexchange.com/help/how-to-answer">help</a>:</p>
<blockquote>
<p><strong>Provide context for links</strong><br>Links to external resources are encouraged,
but please add context around the link so your fellow users will have
some idea what it is and why it’s there. Always quote the most
relevant part of an important link, in case the target site is
unreachable or goes permanently offline.</p>
</blockquote>
<p>What about linking to off-site content for questions? <a href="https://3dprinting.stackexchange.com/help/how-to-ask">How do I ask a good question?</a> is not clear about that.</p>
<p>A question on meta.stackexchange reads: <a href="https://meta.stackexchange.com/questions/94807/auto-ban-questions-that-use-pastebin">"Auto-ban questions that use pastebin?"</a>. This hints to banning people that use external linking in their answer.</p>
<p>I can image for large sites (hundreds to thousands questions a day) or specific sites (about programming) you definitely want a method to shift the quality of questions. But we are small. Furthermore, it is sometimes necessary (as the OP does not have the knowledge, and we don't have the overview) to ask for the complete file (e.g. configuration.h or G-code). You sure don't want people to post their complete configuration.h or G-code file into the question.</p>
<p>As links to off-site content seem to die over time, what can we do best to preserve the information for the question?</p>
|
<p><em>Copied from chat</em></p>
<hr>
<p>I agree about the posting of the entire configuration file or G-code in a question is too big to fit, etc. What is really needed, and I've thought this for a long time, is a SE sanctioned version of PasteBin [functionality]. A persistent scrapbook/scratchpad site internal to SE (like the i.stack.imgur.com site) where <em>over-sized</em> chunks of code/configs/text can be pasted, without it being an external link (which carry the inherent risk of link death). That would be the correct solution, and I don't understand why that hasn't been set up. Seems odd to me.</p>
|
<p>A possibility is to allow off-site content for the OP to post. Once the problem is spotted, the one answering the question could update the question with relevant parts of the off-site content, or copy the relevant parts into the answer.</p>
| 63
|
<p>We have been looking at g++ versions 3.2.3 and 4.2.4. With 4.2.4, the performance improvements on some of our code base is significant.</p>
<p>I've tried searching the <a href="http://gcc.gnu.org/bugzilla/" rel="nofollow noreferrer">gcc buzilla database</a> to find hints as to what bugs may have had such a dramatic improvement but I didn't find any individual bug that stood out as being a candidate.</p>
<p>Are the improvements the result of many small changes that have slowly had an affect? Or was there say a top 5 set of improvements that may have made a difference?</p>
<p>For some background, our code base does make good use of STL containers and algorithms, as well as C++ features such as the 'inline' keyword.</p>
|
<p>In my experience, 3.4 is where the performance basically peaked; 4.2 is actually slower than 3.4 on my project, with 4.3 being the first to roughly equal 3.4's performance. 4.4 is slightly faster than 3.4.</p>
<p>There are a specific few cases I've found where older versions of gcc did some unbelievably retarded things in code--there was a particular function that went from 128 to 21 clocks from 3.4 to 4.3, but that was obviously a special case (it was a short loop where the addition of just a few unnecessary instructions massively hurt performance).</p>
<p>I personally use 3.4 just because it compiles so much faster, making testing much quicker. I also try to avoid the latest versions because they seem to have nasty habits of miscompiling code; --march core2 on recent gcc versions causes segfaults in my program, for example, because it emits autovectorized code that tries to perform aligned accesses on unaligned addresses.</p>
<p>Overall though the differences are rarely large; 3-5% is the absolute <em>most</em> I've seen in terms of performance change.</p>
<p>Now, note this is C; things may be different in C++.</p>
|
<p>Streams were very slow in 3.3 and got much faster in 3.4. (<a href="http://gcc.gnu.org/ml/libstdc++/2004-06/msg00272.html" rel="nofollow noreferrer">message on gcc mailing list</a>)
I bet other things improved too.</p>
| 14,580
|
<p>While designing a table my colleague here says that I should avoid identity column as it is specific to SQL Server and MS Access, But I differ with his views as it makes my coding simpler. </p>
<p>Should I use identity column or not? If not what is best way to create the identity columns from application code?</p>
|
<p>You can't completely divorce an application from the database vendor. If you do you won't be able to take advantages of whatever features your database provides you.</p>
<p>I'd say use the identity column. If you move over to Oracle (for example), you can use a Sequence. Hardly a big change.</p>
<p>I don't know what technology you're using, but one thing that would help is using a tool such as Hibernate or iBATIS (I think they're both available for Java and .NET) which separates you a bit from the database implementation details. Then if you change database vendor you won't need to change application code, just configuration. (In theory, at least!)</p>
|
<p>As far as i am aware, every slightly serious RDBMS has some sort of unique numbering scheme per table.</p>
<ol>
<li>Access and SQL Server have identity columns</li>
<li>MySQL has auto increment columns</li>
<li>PostgreSQL has sequences</li>
<li>sqlite has an implicit ROWID column</li>
<li>Oracle has some sort of sequence though I'm not at all familiar with it</li>
</ol>
<p>I mostly use it, theoretically it's not always a requirement but if you want to maintain referential integrity an int is less to store and easier to compare than a varchar, especially if your foreign keys would be more complex than a single column.</p>
| 22,547
|
<p>Is there any Oracle database ( around version 10 ) front end that we can use in Linux, free or open source?</p>
<p>I am currently using Ubuntu 8.10 and if possible I just want it to need the thin JDBC to connect to oracle and not the whole (huge) client of oracle installed in it.</p>
|
<p>I use <a href="http://www.oracle.com/technology/products/database/sql_developer/index.html" rel="nofollow noreferrer">Oracle SQL Developer</a> which is similar to TOAD (which is not free). SQL Developer is free and supported by Oracle. Make sure you get the latest version as they're improving it all the time. It has a nice graphical UI and support for editing PL/SQL stored procedures. I think there are even plugins for other databases (like MySQL).</p>
<p>Its a Java application and there is a Linux distribution, though I use the Windows version. It does not require an Oracle client, though it does support one, like the <a href="http://www.oracle.com/technology/tech/oci/instantclient/index.html" rel="nofollow noreferrer">Oracle Instant Client</a>, should you have it installed.</p>
|
<p>Pretty much any JDBC tool will be able to talk compentantly to Oracle.</p>
<p>I've used SQuirrel SQL Client, SQL Workbench, DbVisualizer (free edition).
There's even plug-ins for jEdit that can talk to a database.</p>
| 46,282
|
<p>I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). </p>
<p>I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this:</p>
<pre><code>MemoryStream stream = new MemoryStream();
XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1"));
xmlTextWriter.Formatting = Formatting.Indented;
xmlTextWriter.WriteStartDocument(); //Start doc
</code></pre>
<p>Then I add my Norwegian text like this:</p>
<pre><code>xmlTextWriter.WriteCData(myNorwegianText);
</code></pre>
<p>Then I write the file to disk like this:</p>
<pre><code>FileStream myFile = new FileStream(myPath, FileMode.Create);
StreamWriter sw = new StreamWriter(myFile);
stream.Position = 0;
StreamReader sr = new StreamReader(stream);
string content = sr.ReadToEnd();
sw.Write(content);
sw.Flush();
myFile.Flush();
myFile.Close();
</code></pre>
<p>Now the problem is that in the file on this, all the Norwegian characters look funny.</p>
<p>I'm probably doing the above in some stupid way. Any suggestions on how to fix it?</p>
|
<p>Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. </p>
<p>If you still want to do the double write, for whatever reason, do one of two things. Either</p>
<ol>
<li><p>Make sure that the StreamReader and StreamWriter objects you use <em>all</em> use the <em>same</em> encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or</p></li>
<li><p>Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.</p></li>
</ol>
|
<p>After investigating, this is that worked best for me:</p>
<pre><code>var doc = new XDocument(new XDeclaration("1.0", "ISO-8859-1", ""));
using (XmlWriter writer = doc.CreateWriter()){
writer.WriteStartDocument();
writer.WriteStartElement("Root");
writer.WriteElementString("Foo", "value");
writer.WriteEndElement();
writer.WriteEndDocument();
}
doc.Save("dte.xml");
</code></pre>
| 16,851
|
<p>I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method <code>validate</code> that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say <code>Validatable</code>. The following are the two basic solutions I can have.</p>
<pre><code>interface Validatable {
public void validate() throws ValidateException;
}
interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate() throws ValidateException {
throw new UnsupportedOperationException();
}
}
class Object2 implements Validatable {
...
public void validate() throws ValidateException {
...
}
}
</code></pre>
<p>This is the first solution whereby I have a general global interface that something that's validatable implements and I could use <code>validate()</code> to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes.</p>
<p>Alternatively I could have the following which would leave me without a top level interface.</p>
<pre><code>interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate(Object1Converse converse) throws ValidateException {
...
}
}
interface Object2Validatable {
public void validate() throws ValidateException;
}
class Object2 implements Object2Validatable {
...
public void validate() throws ValidateException {
...
}
}
</code></pre>
<p>I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.</p>
|
<p>what about this : </p>
<pre><code>interface Validatable {
void validate(Validator v);
}
class Object1 implements Validatable{
void validate(Validator v){
v.foo
v.bar
}
}
class Object1Converse implements Validator{
//....
}
class Object2 implements Validatable{
void validate(Validator v){
//do whatever you need and ingore validator ?
}
}
</code></pre>
<p>What do you care if Object2 receives an unneeded argument ? if it is able to operatee correctly without it it can just ignore it right ?</p>
<p>If you are worried about introducing an unneeded dependency between object2 and Object1Converse then simply specify an interface to decouple them and use that as the validator. </p>
<p>Now I must add that having a mixed model where you have both object able to self validate and object which need external state information to validate sounds weird. </p>
<p>care to illustrate ?</p>
|
<p>Perhaps the <a href="http://commons.apache.org/validator/" rel="nofollow noreferrer">apache commons validator</a> project would be useful here - either directly or as a model for how to attack your problem. They effectively have a parallel set of objects that do the validation - so there is no interface on the objects, just the presence/absence of a related validator for the object/class.</p>
| 22,011
|
<p>Which component is best to use for receiving HTTP requests in Delphi application?</p>
|
<p><a href="http://www.indyproject.org" rel="noreferrer">Indy</a> is the way to go. but you need a server component, not a client one. <a href="http://www.indyproject.org/docsite/html/frames.html?frmname=topic&frmfile=TIdHTTPServer.html" rel="noreferrer">TIDHTTPServer</a> should fit the bill</p>
|
<p>I've been playing around with HTTP components before, and I've also implemented IInternetProtocol to integrate with Internet Explorer and build ISAPI extensions to integrate with IIS.
I've started <a href="http://xxm.sourceforge.net/" rel="nofollow noreferrer">http://xxm.sourceforge.net/</a> to open-source this, and combine it with a generic interface, a pre-parser and an auto-compile option, so I could join HTML and Delphi into the same source-files and code websites much like PHP, Cold Fusion and oldskool ASP.</p>
| 32,841
|
<p>My new project is targeting an embedded ARM processor. I have a build system that uses a cross-compiler running on an Ubuntu linux box. I like to use unit testing as much as possible, but I'm a little bit confused about how to proceed with this setup.</p>
<p>I can't see how to run unit tests on the ARM device itself (somebody correct me if I'm wrong). I think that my best option is to compile the code on the build machine using its own native compiler for the unit tests. Is this approach fundamentally flawed? Is unit testing on a different platform a waste of time?</p>
<p>I'm planning to use CppUnit on the build machine using the native compiler for the unit tests. Then I'll cross compile the code for the ARM processor and do integration and system testing on the target device itself. How would you structure the source code and the test code to keep this from turning into a tangled mess?</p>
|
<p>With embedded device it depends on what interfaces (hardware) you have.</p>
<p>For example the motion control cards I deal with uses a command line interface. The IDE they ship uses it as it primary method of interacting with the cards. It works the same way regardless if I am using PCI, IDE, Serial, or Ethernet. </p>
<p>The DLL they ship for programming give access to the command line interface. So I can send a string, and read back the response. So what I do for my unit tests is have a physical card hooked (or in) my development machine. I send it commands after uploading the software, read the response and if they are correct it passes the test. </p>
<p>I also have extra hardware, a black box if you will, that simulates a machine that motion control card is normally hooked up too. It helps with the automated sets but there is a manual phase as I have to set switches to simulate different setups on the machine. </p>
<p>I have achieved a greater degree of automation by taking a digital I/O card and using it outputs to feed into the inputs of the motion control card and the same in reverse.</p>
<p>I found that for most hardware you have to have some type of simulator hardware. </p>
<p>The exception being the rare package that comes with a software simulator. </p>
<p>I know this isn't probably ideal as not every developer can have one of these on their desk. My hardware simulator so I can give it to whoever it working on the motion control software at the time. If it can't be portable then having a dedicated testing or hardware development computer would be in order.</p>
<p>Finally it boils down on the specifics of your hardware and what support the manufacturer gives in terms of software and simulators. To help you more you will need to post more specifics.</p>
|
<p>In ten-plus years in the embedded industry, I've seen it done quite a few ways. At my current company:</p>
<ul>
<li>one of our products has enough horsepower (and space) to run tests on the target board. It's somewhat slow, and we can't stick all the python on the box we'd like, but it works well.</li>
<li>one of our products doesn't have the space, so we compile all the libs we can in x86 (anything that isn't hardware-dependent) and run unit tests on desktops. It's not perfect, but far better than nothing.</li>
<li>one of our components is a super-lightweight power-miser on exotic hardware, so virtually no unit tests are possible. Core algorithms (DES, etc.) are tested on x86 as above, but much of the code simply has to be tested as a whole, in situ. This entails lot of code reviews.</li>
</ul>
| 33,797
|
<p>I know that the JVM can do some pretty serious optimizations at runtime, especially in -server mode. Of course, it takes a little while for the JVM to settle down and reach peak performance. Is there any way to take a snapshot of those optimizations so they can be applied immediately the next time you run your app?</p>
<p>"Hey JVM! Great job optimizing my code. Could you write that down for me for later?"</p>
|
<p>Basically not yet with Sun's VM, but they have it in mind.</p>
<p>See various postings/comments under here:</p>
<p><a href="http://blogs.oracle.com/fatcatair/category/Java" rel="nofollow noreferrer">http://blogs.oracle.com/fatcatair/category/Java</a></p>
<p>(Sorry: I can't find quite the right one about retaining stats over restart for immediate C1 compilation of known-hot-at-startup methods.)</p>
<p>But I don't know where all this stuff is right now.</p>
<p>Note that optimisations appropriate in steady-state may well not be appropriate at start-up and might indeed reduce start-up performance, and indeed two runs may not have the same hotspots...</p>
|
<p>Perhaps this might help: <a href="http://wikis.sun.com/display/HotSpotInternals/PrintAssembly" rel="nofollow noreferrer"><a href="http://wikis.sun.com/display/HotSpotInternals/PrintAssembly" rel="nofollow noreferrer">http://wikis.sun.com/display/HotSpotInternals/PrintAssembly</a></a>.</p>
| 48,839
|
<p>Can someone please let me know how do I implement "Did you mean" feature in Lucene.net?</p>
<p>Thanks!</p>
|
<p>You should look into the <a href="https://svn.apache.org/repos/asf/lucene/lucene.net/trunk/C%23/contrib/SpellChecker.Net/" rel="nofollow noreferrer">SpellChecker</a> module in the contrib dir. It's a port of Java lucene's <a href="https://lucene.apache.org/core/6_3_0/suggest/index.html?org/apache/lucene/search/spell/SpellChecker.html" rel="nofollow noreferrer">SpellChecker</a> module, so its <a href="http://wiki.apache.org/jakarta-lucene/SpellChecker" rel="nofollow noreferrer">documentation</a> should be helpful.</p>
<p>(From the javadocs:)</p>
<p>Example Usage:</p>
<pre><code> import org.apache.lucene.search.spell.SpellChecker;
SpellChecker spellchecker = new SpellChecker(spellIndexDirectory);
// To index a field of a user index:
spellchecker.indexDictionary(new LuceneDictionary(my_lucene_reader, a_field));
// To index a file containing words:
spellchecker.indexDictionary(new PlainTextDictionary(new File("myfile.txt")));
String[] suggestions = spellchecker.suggestSimilar("misspelt", 5);
</code></pre>
|
<p>Take a look at google code project called semanticvectors.
There's a decent amount of discussion on the Lucene mailing lists for doing functionality like what you're after using it - however it is written in java.</p>
<p>You will probably have to parse and use some machine learning algorithms on your search logs to build a feature like this!</p>
| 45,294
|
<p>I am currently refactoring an application that prints its status to the console window. At the moment I am doing something like this:</p>
<pre><code> Console.Write("Print some status.....")
//some code
Console.WriteLine("Done!")
</code></pre>
<p>Now while this works fine, all the logic is hidden between console.writelines and I find makes it very hard to read.</p>
<p>I don't know if there is a better way of doing this, but I just wanted to ask and see if anyone has come up with a better/more clean way of print application status to the console.</p>
<p>Any ideas?</p>
|
<p>Take a look at Log4Net, it handles everything, but might be an overkill for your app, no idea. However knowing Log4Net will likely help you down the road someday so maybe this is a good chance too learn it.</p>
|
<p>Why not use a Logger object that write errors into a text file? You could come with some "priority" error messages such as: Logger.print(new priority("important"), "blabla");
This way, you could find in your file the exact time and all the message you want. </p>
<p>If you absolutely want the console, you could use the priority on the console.. so it would only prints what you tell the logger to print, such as network error, etc..</p>
| 36,374
|
<p>My first instinct is to say each key is an object, and has a hash code, which is what is used to determine if a duplicate is being inserted. However, I can't find anything to back that up for sure. Can someone provide a link that says that, or provide the real answer here? Thanks!</p>
|
<p>The <code>Map</code> interface specifies that if two keys are <code>null</code> they are duplicates, otherwise if there's a key <code>k</code> such that <code>key.equals(k)</code>, then there is a duplicate. See the contains or get method here:</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Map.html#containsKey(java.lang.Object)" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/util/Map.html#containsKey(java.lang.Object)</a></p>
<p>However, it's up to the <code>Map</code> implementation how to go about performing that check, and a <code>HashMap</code> will use a hash code to narrow the potential keys it will check with the <code>equals</code> method. So in practice, for a typical hash based map, to check for duplicates a map will take the hashcode (probably mod some size), and use <code>equals</code> to compare against any keys whose hashcode mod the same size gives the same remainder.</p>
|
<p>Careful on an edge case here. Null keys are not always duplicates. In fact, null keys turn out to be out to cause much frustration inbetween Map implementations (see my post on <a href="http://scanningcrew.blogspot.com/2008/12/consistency.html" rel="nofollow noreferrer">Consistency</a>).</p>
<p>For example null keys are OK in HashMaps, but not in a TreeMap that uses natural ordering, or ConccurentHashMap where null keys are forbidden. The problem here is that they throw uncaught exceptions on many of their methods if you use a null key and that introduces scary run-time bugs when you switch implementations during refactoring.</p>
| 47,619
|
<p>I am using the jQuery library to implement drag and drop. </p>
<p>How do I get at the element that is being dragged when it is dropped?</p>
<p>I want to get the id of the image inside the div. The following element is dragged:</p>
<pre><code><div class="block">
<asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>
</code></pre>
<p>I have the standard dropped function from their example:</p>
<pre><code>$(".drop").droppable({
accept: ".block",
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
drop: function(ev, ui) { }
});
</code></pre>
<p>I have tried various <code>ui.id</code> etc. which doesn't seem to work.</p>
|
<p>Is it not the ui.draggable?</p>
<p>If you go here (in Firefox and assuming you have firebug) and look in the firebug console youll see I am doing a console.dir of the ui.draggable object which is the div being dragged</p>
<p><a href="http://jsbin.com/ixizi" rel="noreferrer">http://jsbin.com/ixizi</a></p>
<p>Therefore the code you need in the drop function is</p>
<pre><code> drop: function(ev, ui) {
//to get the id
//ui.draggable.attr('id') or ui.draggable.get(0).id or ui.draggable[0].id
console.dir(ui.draggable)
}
</code></pre>
|
<p><strong>How to manipulate clone object in any jquery ui operation ?</strong></p>
<p>Just target ui outer html and use normal html jquery selectors</p>
<pre><code>var target_ui_object_html=$(ui.item.context).attr("your attributes");
</code></pre>
<blockquote>
<p>attributes => id ,class ,rel,alt ,title or custom attr like data-name
, data-user</p>
</blockquote>
| 24,034
|
<p>Here is my code, which takes two version identifiers in the form "1, 5, 0, 4" or "1.5.0.4" and determines which is the newer version.</p>
<p>Suggestions or improvements, please!</p>
<pre><code> /// <summary>
/// Compares two specified version strings and returns an integer that
/// indicates their relationship to one another in the sort order.
/// </summary>
/// <param name="strA">the first version</param>
/// <param name="strB">the second version</param>
/// <returns>less than zero if strA is less than strB, equal to zero if
/// strA equals strB, and greater than zero if strA is greater than strB</returns>
public static int CompareVersions(string strA, string strB)
{
char[] splitTokens = new char[] {'.', ','};
string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
int[] versionA = new int[4];
int[] versionB = new int[4];
for (int i = 0; i < 4; i++)
{
versionA[i] = Convert.ToInt32(strAsplit[i]);
versionB[i] = Convert.ToInt32(strBsplit[i]);
}
// now that we have parsed the input strings, compare them
return RecursiveCompareArrays(versionA, versionB, 0);
}
/// <summary>
/// Recursive function for comparing arrays, 0-index is highest priority
/// </summary>
private static int RecursiveCompareArrays(int[] versionA, int[] versionB, int idx)
{
if (versionA[idx] < versionB[idx])
return -1;
else if (versionA[idx] > versionB[idx])
return 1;
else
{
Debug.Assert(versionA[idx] == versionB[idx]);
if (idx == versionA.Length - 1)
return 0;
else
return RecursiveCompareArrays(versionA, versionB, idx + 1);
}
}
</code></pre>
<hr>
<p>@ <a href="https://stackoverflow.com/questions/30494/compare-version-identifiers#30510">Darren Kopp</a>:</p>
<p>The version class does not handle versions of the format 1.0.0.5.</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.version.aspx" rel="nofollow noreferrer">System.Version</a> class does not support versions with commas in it, so the solution presented by <a href="https://stackoverflow.com/questions/30494#30510">Darren Kopp</a> is not sufficient.</p>
<p>Here is a version that is as simple as possible (but no simpler).</p>
<p>It uses <a href="http://msdn.microsoft.com/en-us/library/system.version.aspx" rel="nofollow noreferrer">System.Version</a> but achieves compatibility with version numbers like "1, 2, 3, 4" by doing a search-replace before comparing.</p>
<pre><code> /// <summary>
/// Compare versions of form "1,2,3,4" or "1.2.3.4". Throws FormatException
/// in case of invalid version.
/// </summary>
/// <param name="strA">the first version</param>
/// <param name="strB">the second version</param>
/// <returns>less than zero if strA is less than strB, equal to zero if
/// strA equals strB, and greater than zero if strA is greater than strB</returns>
public static int CompareVersions(String strA, String strB)
{
Version vA = new Version(strA.Replace(",", "."));
Version vB = new Version(strB.Replace(",", "."));
return vA.CompareTo(vB);
}
</code></pre>
<p>The code has been tested with:</p>
<pre><code> static void Main(string[] args)
{
Test("1.0.0.0", "1.0.0.1", -1);
Test("1.0.0.1", "1.0.0.0", 1);
Test("1.0.0.0", "1.0.0.0", 0);
Test("1, 0.0.0", "1.0.0.0", 0);
Test("9, 5, 1, 44", "3.4.5.6", 1);
Test("1, 5, 1, 44", "3.4.5.6", -1);
Test("6,5,4,3", "6.5.4.3", 0);
try
{
CompareVersions("2, 3, 4 - 4", "1,2,3,4");
Console.WriteLine("Exception should have been thrown");
}
catch (FormatException e)
{
Console.WriteLine("Got exception as expected.");
}
Console.ReadLine();
}
private static void Test(string lhs, string rhs, int expected)
{
int result = CompareVersions(lhs, rhs);
Console.WriteLine("Test(\"" + lhs + "\", \"" + rhs + "\", " + expected +
(result.Equals(expected) ? " succeeded." : " failed."));
}
</code></pre>
|
<p>If you can assume that each place in the version string will only be one number (or at least the last 3, you can just remove the commas or periods and compare...which would be a lot faster...not as robust, but you don't always need that.</p>
<pre><code>public static int CompareVersions(string strA, string strB)
{
char[] splitTokens = new char[] {'.', ','};
string[] strAsplit = strA.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
string[] strBsplit = strB.Split(splitTokens, StringSplitOptions.RemoveEmptyEntries);
int versionA = 0;
int versionB = 0;
string vA = string.Empty;
string vB = string.Empty;
for (int i = 0; i < 4; i++)
{
vA += strAsplit[i];
vB += strBsplit[i];
versionA[i] = Convert.ToInt32(strAsplit[i]);
versionB[i] = Convert.ToInt32(strBsplit[i]);
}
versionA = Convert.ToInt32(vA);
versionB = Convert.ToInt32(vB);
if(vA > vB)
return 1;
else if(vA < vB)
return -1;
else
return 0; //they are equal
}
</code></pre>
<p>And yes, I'm also assuming 4 version places here...</p>
| 5,036
|
<p>I'm writing a WCF service and want to expose some custom configuration elements (e.g. Custom ConfigurationSection and ConnectionStringSettings) so that I can modify the service's configuration. </p>
<p>One of my custom configuration elements inherits from <code>System.Configuration.ConfigurationElementCollection</code>. When I try to start my WCF service I get the following error message...</p>
<blockquote>
<p>Type 'System.Configuration.ConfigurationElementCollection' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. </p>
</blockquote>
<p>Is there a way to implement the DataContract for this Type? I have my inherited class marked with the [DataContract] attribute.</p>
|
<p>Just hit this issue today. It was confusing because the problem came up moving a project from machine to machine. This article seems relevant:</p>
<p><a href="http://blogs.msdn.com/youssefm/archive/2009/08/10/serializing-plain-old-clr-objects-poco-types-with-datacontractserializer.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/youssefm/archive/2009/08/10/serializing-plain-old-clr-objects-poco-types-with-datacontractserializer.aspx</a></p>
<p>To summarize in case of link rot, the issue seems to emerge in runtime 3.5 and go away in runtime 3.5 SP1.</p>
|
<p>Ok, well in the end I had to re-architect my solution. I found the SerializableConfigurationSection most beneficial. It's in the patterns and practices EnterpriseLibrary. So rather than trying to pass my Custom Configuration Sections through WCF, I perform the seralization/deserialization manually and pass the configuration sections through WCF as a string.</p>
| 31,132
|
<p>Can we call functions using function pointer? if yes how?</p>
|
<p>Yes. Trivial example:</p>
<pre><code>
// Functions that will be executed via pointer.
int add(int i, int j) { return i+j; }
int subtract(int i, int j) {return i-j; }
// Enum selects one of the functions
typedef enum {
ADD,
SUBTRACT
} OP;
// Calculate the sum or difference of two ints.
int math(int i, int j, OP op)
{
int (*func)(int i, int j); // Function pointer.
// Set the function pointer based on the specified operation.
switch (op)
{
case ADD: func = add; break;
case SUBTRACT: func = subtract; break;
default:
// Handle error
}
return (*func)(i, j); // Call the selected function.
}
</code></pre>
|
<p>Yes. An example: </p>
<p>Before code...</p>
<pre>
typedef int ( _stdcall *FilterTypeTranslatorType )
(
int TypeOfImportRecord,
PMAType *PMA
);
FilterTypeTranslatorType FilterTypeTranslator = {NULL};
</pre>
<p>Now in the code...</p>
<pre>
PMAType *PMA;
HANDLE hFilterDll;
// assume DLL loaded
// Now find the address...
...
FilterTypeTranslator[TheGroup] =
( FilterTypeTranslatorType ) GetProcAddress( hFilterDll,
"FilterTypeTranslator" );
...
// now call it
FilterTypeTranslator(1,PMA);
...
</pre>
| 31,466
|
<p>Is there a way to create a <code>JButton</code> with your own button graphic and not just with an image inside the button? </p>
<p>If not, is there another way to create a custom <code>JButton</code> in java?</p>
|
<p>When I was first learning Java we had to make Yahtzee and I thought it would be cool to create custom Swing components and containers instead of just drawing everything on one <code>JPanel</code>. The benefit of extending <code>Swing</code> components, of course, is to have the ability to add support for keyboard shortcuts and other accessibility features that you can't do just by having a <code>paint()</code> method print a pretty picture. It may not be done the best way however, but it may be a good starting point for you.</p>
<p>Edit 8/6 - If it wasn't apparent from the images, each Die is a button you can click. This will move it to the <code>DiceContainer</code> below. Looking at the source code you can see that each Die button is drawn dynamically, based on its value.</p>
<p><img src="https://i.stack.imgur.com/pgyQp.jpg" alt="alt text"><br>
<img src="https://i.stack.imgur.com/jkYRd.jpg" alt="alt text"><br>
<img src="https://i.stack.imgur.com/9BI34.jpg" alt="alt text"></p>
<p>Here are the basic steps:</p>
<ol>
<li>Create a class that extends <code>JComponent</code></li>
<li>Call parent constructor <code>super()</code> in your constructors</li>
<li>Make sure you class implements <code>MouseListener</code></li>
<li><p>Put this in the constructor:</p>
<pre><code>enableInputMethods(true);
addMouseListener(this);
</code></pre></li>
<li><p>Override these methods:</p>
<pre><code>public Dimension getPreferredSize()
public Dimension getMinimumSize()
public Dimension getMaximumSize()
</code></pre></li>
<li><p>Override this method:</p>
<pre><code>public void paintComponent(Graphics g)
</code></pre></li>
</ol>
<p>The amount of space you have to work with when drawing your button is defined by <code>getPreferredSize()</code>, assuming <code>getMinimumSize()</code> and <code>getMaximumSize()</code> return the same value. I haven't experimented too much with this but, depending on the layout you use for your GUI your button could look completely different.</p>
<p>And finally, the <a href="https://github.com/kdeloach/labs/blob/master/java/yahtzee/src/Dice.java" rel="noreferrer">source code</a>. In case I missed anything. </p>
|
<p>I haven't done SWING development since my early CS classes but if it wasn't built in you could just inherit <code>javax.swing.AbstractButton</code> and create your own. Should be pretty simple to wire something together with their existing framework.</p>
| 2,436
|
<p>I was wondering about implementing my own sessions (more for an exercise than anything else) for a GAE app I'm working ... at first I was thinking of using the datastore to store the session data. However, every time something needs to be added to the session 'bucket', it would require saving to the datastore. Obviously that's bad since we want to minimize our writes. Then I thought about using memcache ... seemed like a good idea but then we're faced with issues of possible session corruption due to memcache being "evicted through memory pressure" by Google. So does that mean we are left with only the following options:</p>
<ol>
<li>Storing all session data in cookies</li>
<li>Writing all session data to datastore and memcache, and then only reading from memcache</li>
</ol>
<p>Anyone have any other ideas?</p>
|
<p>I suggest checking out (and contributing to) these three implementations of appengine sessions before rolling out your own:</p>
<ul>
<li><a href="http://code.google.com/p/app-engine-patch/" rel="nofollow noreferrer">app-engine-patch</a></li>
<li><a href="http://gaeutilities.appspot.com/" rel="nofollow noreferrer">gaeutilities</a></li>
<li><a href="https://github.com/dound/gae-sessions" rel="nofollow noreferrer">gae-session</a></li>
</ul>
<p>Your options look fine but choosing between them probably depends on the size of the session data in your application.</p>
|
<p>If you use web2py (version 1.46 or latter) sessions are on by default on GAE.
This achieved by the following three lines of web2py code at the top of the scaffoling model:</p>
<pre><code>from gluon.contrib.gql import *
db=GQLDB()
session.connect(request,response,db=db)
</code></pre>
<p>Here is a sample action that counts:</p>
<pre><code>def index():
session.c=session.c+1 if session.c else 1
return dict(counter=session.c)
</code></pre>
| 29,152
|
<p>I have a just one table mapped in a datacontext. Here's the property and attribute on the column of interest:</p>
<pre><code>[Column(Storage="_CustomerNumber", DbType="VarChar(25)")]
public string CustomerNumber
{
</code></pre>
<p>This column is, in fact, a varchar(25) and has an index.</p>
<p>I've got some simple code:</p>
<pre><code>DataClasses1DataContext myDC = new DataClasses1DataContext();
myDC.Log = Console.Out;
List<string> myList = new List<string>() { "111", "222", "333" };
myDC.Customers
.Where(c => myList.Contains(c.CustomerNumber))
.ToList();
</code></pre>
<p>Which generates this SQL text:</p>
<pre><code>SELECT [t0].[CustomerNumber], [t0].[CustomerName]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerNumber] IN (@p0, @p1, @p2)
-- @p0: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [111]
-- @p1: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [222]
-- @p2: Input NVarChar (Size = 3; Prec = 0; Scale = 0) [333]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>Notice that the paramaters are nvarchar!</p>
<p>When this query hits the database, it generates a horrible plan which involves <strong>converting the multi-million row index on CustomerNumber to nvarchar</strong> before seeking within it.</p>
<p>I'm not allowed to change the table, but I can change the query and the dbml. What can I do to get the data out without getting this index conversion?</p>
|
<p>Here's the way I solve this problem now-a-days. This converts the parameters to the desired type and then runs the query. It generates the same sql as originally generated, just with different parameter types.</p>
<pre><code>DbCommand myCommand = myDataContext.GetCommand(query);
foreach (DbParameter dbParameter in myCommand.Parameters)
{
if (dbParameter.DbType == System.Data.DbType.String)
{
dbParameter.DbType = System.Data.DbType.AnsiString;
}
}
myDataContext.Connection.Open();
System.Data.Common.DbDataReader reader = myCommand.ExecuteReader();
List<RecordType> result = myDataContext.Translate<RecordType>(reader).ToList();
myDataContext.Connection.Close();
</code></pre>
|
<p>Here's what I've got as a possible work around. I'm interested in seeing other solutions as well:</p>
<pre><code>List<IQueryable<Customer>> myQueries =
myList.Select(s => myDC.Customers.Where(c => c.CustomerNumber == s)).ToList();
IQueryable<Customers> myQuery = myQueries.First();
foreach(IQueryable<Customer> someQuery in myQueries.Skip(1))
{
myQuery = myQuery.Concat(someQuery);
}
myQuery.ToList();
</code></pre>
<p>This generates the following SQL:</p>
<pre><code>SELECT [t4].[CustomerNumber], [t4].[CustomerName]
FROM (
SELECT [t2].[CustomerNumber], [t2].[CustomerName]
FROM (
SELECT [t0].[CustomerNumber], [t0].[CustomerName]
FROM [dbo].[Customer] AS [t0]
WHERE [t0].[CustomerNumber] = @p0
UNION ALL
SELECT [t1].[CustomerNumber], [t1].[CustomerName]
FROM [dbo].[Customer] AS [t1]
WHERE [t1].[CustomerNumber] = @p1
) AS [t2]
UNION ALL
SELECT [t3].[CustomerNumber], [t3].[CustomerName]
FROM [dbo].[Customer] AS [t3]
WHERE [t3].[CustomerNumber] = @p2
) AS [t4]
-- @p0: Input VarChar (Size = 3; Prec = 0; Scale = 0) [111]
-- @p1: Input VarChar (Size = 3; Prec = 0; Scale = 0) [222]
-- @p2: Input VarChar (Size = 3; Prec = 0; Scale = 0) [333]
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
| 39,939
|
<p>I am using <code>DirectoryInfo.GetDirectories()</code> recursively to find the all the sub-directories under a given path.
However, I want to exclude the System folders and there is no clear way for that.
In FindFirstFile/FindNextFile things were clearer with the attributes.</p>
|
<p>@rslite is right, .NET doesn't give such filtering out-of-box, but it's not hard to implement:</p>
<pre><code>static IEnumerable<string> GetNonSystemDirs(string path)
{
var dirs = from d in Directory.GetDirectories(path)
let inf = new DirectoryInfo(d)
where (inf.Attributes & FileAttributes.System) == 0
select d;
foreach (var dir in dirs)
{
yield return dir;
foreach (var subDir in GetNonSystemDirs(dir))
{
yield return subDir;
}
}
}
</code></pre>
<p>MSDN links:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx" rel="nofollow noreferrer">FileSystemInfo.Attributes Property</a> </p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx" rel="nofollow noreferrer">FileAttributes Enumeration</a></p>
|
<p>You'd probably have to loop through the results and reject those with the attributes that you don't want (use the Attributes property).</p>
| 12,601
|
<p>I need to replace the contents of a node in an XElement hierarchy when the element name and all the attribute names and values match an input element. (If there is no match, the new element can be added.)</p>
<p>For example, if my data looks like this:</p>
<pre><code><root>
<thing1 a1="a" a2="b">one</thing1>
<thing2 a1="a" a2="a">two</thing2>
<thing2 a1="a" a3="b">three</thing2>
<thing2 a1="a">four</thing2>
<thing2 a1="a" a2="b">five</thing2>
<root>
</code></pre>
<p>I want to find the last element when I call a method with this input:</p>
<pre><code><thing2 a1="a" a2="b">new value</thing2>
</code></pre>
<p>The method should have no hard-coded element or attribute names - it simply matches the input to the data.</p>
|
<p>This will match any given element with exact tag name and attribute name/value pairs:</p>
<pre><code>public static void ReplaceOrAdd(this XElement source, XElement node)
{
var q = from x in source.Elements()
where x.Name == node.Name
&& x.Attributes().All(a =>node.Attributes().Any(b =>a.Name==b.Name && a.Value==b.Value))
select x;
var n = q.LastOrDefault();
if (n == null) source.Add(node);
else n.ReplaceWith(node);
}
var root = XElement.Parse(data);
var newElem =XElement.Parse("<thing2 a1=\"a\" a2=\"b\">new value</thing2>");
root.ReplaceOrAdd(newElem);
</code></pre>
|
<p>You can do an XPathSelectElement with the path (don't quote me, been to the bar; will clean up in the morn) /root/thing2[@a1='a' and @a2='b'] and then take .LastOrDefault() (XPathSelectElement is an extension method in system.Linq.Xml).</p>
<p>That will get you the node you wish to change. I'm not sure how you want to change it, however. The result you get is the actual XElement, so changing it will change the tree element.</p>
| 18,832
|
<p>A project I'm working on supposed to authenticate users agains AD. I've never worked with AD before, neither did I work in organizations that use AD, so here's my stupid question: in case if AD involved, who manages roles, groups and users for application? Is it my responsibility to provide an UI for site admin to assign AD users to my app roles or AD admins should take care of creating appropriate groups expected by my app and assign existing AD users there?</p>
<p>What are the best practices in this department?</p>
<hr>
<p>Once thing to note -- this is not an in-house app, so it is supposed to work with an existing AD. The question is if my expects roles like "Teachers" and "Students" (just to illustrate the point), may I expect that IT people will create appropriate groups in AD and assign users to them?</p>
|
<p>I don't think you should supply a Gui for active directory. Most organization that use active directory manage it with the standard active directory tools.</p>
<p>If you want to handle the case of small shops. Then make the groups internal to the application DB. You will still be able to use the active directory users. But the group management and membership will be internal to your application. This will avoid most problem of dealing with the complex rules of active directory, and still benefit from single sign on.</p>
<p>One more thing to note. The group names should be customizable. Most places have naming convention for group names. </p>
|
<p>This really depends on who owns the AD, and who is going to be responsible for managing user accounts. If this AD is isolated from your coporate domain, and you want your support or sales, or other business person to manage the accounts then by all means create them an admin tool.</p>
<p>If your trying to tie into your existing AD, then you should work closely with your IT department, they will probally want to create the accounts their own way (especially if your using your existing credentials).</p>
<p>Essentially this boils down to how your IT operates, and what exactly the relationship btw the AD your using and the AD which runs the coporate site.</p>
<h1>Edited</h1>
<p>Based on your additional info, I think you need to offer an admin concsole. Especially if you want to target the smaller shops out there. Your solution should make it optional so if they want to use the admin UI they can but if the IT department wants to use Powershell for example they can do that as well.</p>
| 47,609
|
<p>I am completely new to programming - my interest lies in PHP & MySql for building a dynamic web application for Military Band Administration purposes. i.e. General info and social networking for members + added functionality for the management team to communicate effectively.</p>
<p>OK so the question - as I learn more about PHP there are terms used that I do not understand that must come from a common basis of familiarity between all languages i.e. "stack overflow" appears to be an obvious one - "using too many recursive functions may smash the stack" is another. </p>
<p>So is there a book (a primer perhaps) about programming in general which allows someone like me to have a better understanding of what all this means?</p>
<p>Bear in mind I am 57 years old (young) and am really just starting out.</p>
<p>Steve </p>
|
<p><a href="http://www.wikipedia.org/" rel="nofollow noreferrer">Wikipedia</a> is probably your best resource for general information on programming terminology. A large segment of their community overlaps with the programming community, so tech-related pages are normally very accurate, educational, and up to date. See their pages on <a href="http://en.wikipedia.org/wiki/Stack_overflow" rel="nofollow noreferrer">stack overflows</a> and <a href="http://en.wikipedia.org/wiki/Recursion_(computer_science)" rel="nofollow noreferrer">recursion</a> as examples.</p>
<p>Also, PHP.net is the best place to learn about PHP specifically, but skip the main page and <a href="http://us2.php.net/tut.php" rel="nofollow noreferrer">go straight to the tutorial</a> if you're just starting out.</p>
<p>Finally, I highly recommend the book <a href="http://headfirstlabs.com/books/hfsql/" rel="nofollow noreferrer">Head First SQL</a> for learning about databases. All of the examples in the book use MySQL. The entire Head First series is great. I hear they have a PHP book as well, but I haven't read that one.</p>
<p>Update: <a href="http://www.amazon.ca/Head-First-MySQL-Lynn-Beighley/dp/0596006306" rel="nofollow noreferrer">Head First PHP & MySQL</a> is now available.</p>
|
<p>I'm not sure if there's one book that'll teach you "The Fundamentals of Programming." The only way I know of learning all these things is simply <b>practice</b>. Get a PHP tutorial and start building things. Always keep your mind open to learning new things. When you find a better way to do something than a likely very inefficient hack you put together from incomplete knowledge, then use it and learn it and integrate it into your knowledge... after a few years of this you'll be golden.</p>
| 26,365
|
<p>I've generated a certificate request, submitted it to the Microsoft Certificate Services program. It issues the certificate. I downloaded it to conf/ssl/server.cert</p>
<p>I configured it in apache to using </p>
<pre><code>SSLCertificateFile conf/ssl/server.cert
SSLCertificateKeyFile conf/ssl/server.key
</code></pre>
<p>When I start the server with this config I get </p>
<p>Secure Connection Failed
An error occurred during a connection to 192.168.1.100.</p>
<p>Certificate type not approved for application. (Error code: sec_error_inadequate_cert_type)
The page you are trying to view can not be shown because the authenticity of the received data could not be verified.</p>
<ul>
<li>Please contact the web site owners to inform them of this problem.</li>
</ul>
<p>If I download the CA Certificate and install it with</p>
<pre><code>SSLCertificateFile conf/ssl/server.crt
SSLCertificateKeyFile conf/ssl/server.key
SSLCACertificateFile conf/ssl/cacert.crt
</code></pre>
<p>The server fails to start.</p>
<p>It works fine if I generate a self signed certificate an install it, but I need it to come from Microsoft Certificate Services so it won't warn internal users about the certificate.</p>
|
<p>Sounds like your cert isn't allowed to be used for a server. IIRC, you can view the certificate in a browser and look for Usage or some such language, and it should say SSL Server (possibly among other things).</p>
|
<p>You need to make sure that the issued certificate has "Server Authentication" specified as one of the permitted uses in the extended key usage extension. The easiest way to do this (and only way on Win2k3 Standard) is to use the Web Server certificate template.</p>
<p>You need to use the Certificate Services MMC snap-in to add this certificate template to the list of those allowed, and then need to configure permissions so the appropriate user(s) can request certificates.</p>
| 47,575
|
<p>Do you know of a [free] library for graphing or charting, similar to Zedgraph, but that works for developing on windows mobile 6?</p>
|
<p>A basic, free chart API is <a href="http://www.codeproject.com/KB/mobile/pocketbargraph.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/mobile/pocketbargraph.aspx</a></p>
<p>If web access and bandwidth are not a problem, <a href="http://code.google.com/apis/chart/" rel="nofollow noreferrer">http://code.google.com/apis/chart/</a> might be an (admittedly unconventional) option. </p>
<p>Regards, tamberg</p>
|
<p>I once used a listbox to create a (horizontal) bar graph. I needed to catch a paint event for the listbox items to be able to draw the bars. Not easy, but free if your time is free...</p>
| 36,483
|
<p>I am looking for validation framework and while I am already using NHibernate I am thinking of using NHibernate.validator from contrib project however I also look at MS Validation Block which seem to be robust but i am not yet get into detail of each one yet so I wonder has anyone had step into these two frameworks and how is the experience like?</p>
|
<p>NHibernate Validator does not require you to use NHibernate for persistence. Usage can be as simple as:</p>
<pre><code>var engine = new ValidatorEngine();
InvalidValue[] errors = engine.Validate(someModelObjectWithAttributes);
foreach(var error in errors)
{
Console.WriteLine(error.Message);
}
</code></pre>
<p>Of course it can hook into NHibernate and prevent persistence of invalid objects, but you may use it to validate non-persistent objects as well.</p>
|
<p>How about D) None of the above.
I remember evaluating this last year and decided on going with Spring.NET's validation framework.</p>
<p>If your using NHibernate your probably want to use Spring.NET's facilities for using NHibernate as well.</p>
| 18,564
|
<p>We have an Sqlite DB on our Linux/PHP production webserver. What is the best way to manage it remotely? I've found some server wrappers are available and some applications claim to offer remote access methods. Any suggestions?</p>
|
<p>SSH in and use the SQLite command-line client.</p>
<p>But...why are you using SQLite on a <em>production</em> webserver!? Even the SQLite website advises against this!</p>
|
<p>SSH in and use the SQLite command-line client.</p>
<p>But...why are you using SQLite on a <em>production</em> webserver!? Even the SQLite website advises against this!</p>
| 23,035
|
<p>I have written the following simple test in trying to learn Castle Windsor's Fluent Interface:</p>
<pre><code>using NUnit.Framework;
using Castle.Windsor;
using System.Collections;
using Castle.MicroKernel.Registration;
namespace WindsorSample {
public class MyComponent : IMyComponent {
public MyComponent(int start_at) {
this.Value = start_at;
}
public int Value { get; private set; }
}
public interface IMyComponent {
int Value { get; }
}
[TestFixture]
public class ConcreteImplFixture {
[Test]
public void ResolvingConcreteImplShouldInitialiseValue() {
IWindsorContainer container = new WindsorContainer();
container.Register(Component.For<IMyComponent>().ImplementedBy<MyComponent>().Parameters(Parameter.ForKey("start_at").Eq("1")));
IMyComponent resolvedComp = container.Resolve<IMyComponent>();
Assert.AreEqual(resolvedComp.Value, 1);
}
}
}
</code></pre>
<p>When I execute the test through TestDriven.NET I get the following error:</p>
<pre><code>System.TypeLoadException : Could not load type 'Castle.MicroKernel.Registration.IRegistration' from assembly 'Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc'.
at WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue()
</code></pre>
<p>When I execute the test through the NUnit GUI I get:</p>
<pre><code>WindsorSample.ConcreteImplFixture.ResolvingConcreteImplShouldInitialiseValue:
System.IO.FileNotFoundException : Could not load file or assembly 'Castle.Windsor, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc' or one of its dependencies. The system cannot find the file specified.
</code></pre>
<p>If I open the Assembly that I am referencing in Reflector I can see its information is:</p>
<pre><code>Castle.MicroKernel, Version=1.0.3.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc
</code></pre>
<p>and that it definitely contains <strong>Castle.MicroKernel.Registration.IRegistration</strong></p>
<p>What could be going on? </p>
<p>I should mention that the binaries are taken from the <a href="http://builds.castleproject.org/cruise/DownloadBuild.castle?number=956" rel="noreferrer">latest build of Castle</a> though I have never worked with nant so I didn't bother re-compiling from source and just took the files in the bin directory. I should also point out that my project compiles with no problem.</p>
|
<p>Is the assembly in the Global Assembly Cache (GAC) or any place the might be overriding the assembly that you think is being loaded? This is usually the result of an incorrect assembly being loaded, for me it means I usually have something in the GAC overriding the version I have in bin/Debug.</p>
|
<p>I just resolved this by running the iisreset command using the command prompt...
Always the first thing I do when I get such errors.</p>
| 15,175
|
<p>A legacy embedded system is implemented using a cooperative multi-tasking scheduler. </p>
<p>The system essentially works along the following lines:</p>
<ul>
<li>Task A does work</li>
<li>When Task A is done, it yields the processor.</li>
<li>Task B gets the processor and does work.</li>
<li>Task B yields<br>
... </li>
<li>Task n yields</li>
<li>Task A gets scheduled and does work</li>
</ul>
<p>One big Circular Queue: A -> B -> C -> ... -> n -> A</p>
<p>We are porting the system to a new platform and want to minimize system redesign.</p>
<p>Is there a way to implement that type of cooperative multi-tasking in vxWorks?</p>
|
<p>While VxWorks is a priority based OS, it is possible to implement this type of cooperative multi-tasking.</p>
<p>Simply put all the tasks at the <strong>same</strong> priority.<br>
In your code, where you do your <em>yield</em>, simply insert a 'taskDelay(0);'</p>
<p>Note that you have to make sure the kernel time slicing is disabled (kernelTimeSlice(0)).</p>
<p>All tasks at the same priority are in a Queue. When a task yields, it gets put at the end of the queue. This would implement the type of algorithm described.</p>
|
<p>This isn't specific to VxWorks, but the system you have described is a variant of Round Robin Scheduling (I'm assuming you are using priority queues, otherwise it is just Round Robin Scheduling).</p>
<p>The <a href="http://en.wikipedia.org/wiki/Round-robin_scheduling" rel="nofollow noreferrer">wiki article</a> provides a bit of background and then you could go from there.</p>
<p>Good Luck</p>
| 17,243
|
<p>Is it possible for a JPA entity class to contain two embedded (<code>@Embedded</code>) fields? An example would be:</p>
<pre><code>@Entity
public class Person {
@Embedded
public Address home;
@Embedded
public Address work;
}
public class Address {
public String street;
...
}
</code></pre>
<p>In this case a <code>Person</code> can contain two <code>Address</code> instances - home and work. I'm using JPA with Hibernate's implementation. When I generate the schema using Hibernate Tools, it only embeds one <code>Address</code>. What I'd like is two embedded <code>Address</code> instances, each with its column names distinguished or pre-pended with some prefix (such as home and work). I know of <code>@AttributeOverrides</code>, but this requires that each attribute be individually overridden. This can get cumbersome if the embedded object (<code>Address</code>) gets big as each column needs to be individually overridden.</p>
|
<p>If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNamingStrategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be defaulted even if used twice in the same entity.</p>
<p>From Hibernate Annotations Doc: <a href="http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714" rel="noreferrer">http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714</a></p>
|
<p>In case you are using hibernate you can also use a different naming scheme which adds unique prefixes to columns for identical embedded fields. See <a href="https://stackoverflow.com/questions/3046677/automatically-add-a-prefix-to-column-names-for-embeddable-classes/43018343#43018343">Automatically Add a Prefix to Column Names for @Embeddable Classes</a></p>
| 42,982
|
<p>Ok</p>
<p>I'm working on a little project at the moment, the Report expects an int but the ReportParameter class only lets me have a value that's a string or a string[]</p>
<p>How can I pass an int?</p>
<p>thanks</p>
<p>dan</p>
|
<p>You can call the method <code>GetReportParameters()</code> which will return a <code>ReportParameter[]</code> array. If you iterate through each parameter and look at its Type property it will indicate if it is an <code>int</code>. The Type property is an <code>enum</code> of type <code>ParameterTypeEnum</code> and would be <code>ParameterTypeEnum.Integer</code> for an <code>int</code>. </p>
|
<p>I would try:</p>
<pre><code>var rp = new ReportParameter("IntValue", intValue.ToString());
report.SetParameters(new ReportParameter[]{rp});
</code></pre>
| 28,918
|
<p>Assuming Visual C/C++ 6, I have a complex data structure of 22399 elements that looks like this:</p>
<pre><code>{
{ "(SAME", "AS", "U+4E18)", "HILLOCK", "OR", "MOUND"},
{ "TO", "LICK;", {1, 1, 0}, "TASTE,", "A", "MAT,", "BAMBOO", "BARK"},
{ "(J)", "NON-STANDARD", "FORM", "OF", "U+559C", ",", {1, 1, 0}, "LIKE,", "LOVE,", "ENJOY;", {1, 1, 4}, "JOYFUL", "THING"},
{ "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"},
...
}
</code></pre>
<p>What's the best way to declare this? I've tried things like </p>
<pre><code>char * abbrevs3[22399][] = { ... };
</code></pre>
<p>and </p>
<pre><code>char * abbrevs3[22399][][] = { ... };
</code></pre>
<p>but the compile whinges something chronic. </p>
<p><strong>EDIT</strong>: The data is a database of descriptions of certain Unihan characters. I've been exploring various ways of compacting the data. As it stands you have 22399 entries, each of which may contain a varying number of strings, or triplets of { abbrev marker, line where last seen, element of that line where last seen }. </p>
<p>By the way Greg's talking, I may need to have each line contain the same number of elements, even if some of them are empty strings. Is that the case?</p>
<p><strong>EDIT #2</strong>: And it occurs to me that some of the numeric values in the triplets are way outside the limits of char.</p>
|
<p>I just read your new posts and re-read the original post, and I think I just fully understood the goal here. Sorry it took so long, I'm kind of slow.</p>
<p>To paraphrase the question, on line 4 of the original example:</p>
<pre><code>{ "(AN", "ANCIENT", {1, 2, 2}, {1, 2, 3}, "U+4E94)", "FIVE"},
</code></pre>
<p>You'd want to translate the triples into references to strings used earlier, in an attempt to compress the data. That line becomes:</p>
<pre><code>{ "(AN", "ANCIENT", "FORM", "OF", "U+4E94)", "FIVE"},
</code></pre>
<p>If the goal is compression I don't think you'll see much gain here. The self-referencing triples are each 3 bytes, but the strings that are being substituted out are only 8 bytes total, counting null terminators, and you only save 2 bytes on this line. And that's for using chars. Since your structure is so big that you're going to need to use ints for references, your triple is actually 12 bytes, which is even worse. In this case you'll only ever save space by substituting for words that are 12 ascii characters or more.</p>
<p>If I'm totally off base here then feel free to ignore me, but I think the approach of tokenizing on spaces and then removing duplicate words is just kind of a poor man's <a href="http://en.wikipedia.org/wiki/Huffman_coding" rel="nofollow noreferrer">Huffman compression</a>. Huffman where the alphabet is a list of <a href="http://en.wikipedia.org/wiki/Longest_common_substring_problem" rel="nofollow noreferrer">longest common substrings</a>, or some other standard text compression method would probably work well for this problem.</p>
<p>If for some reason this isn't an option though, I think I would get a list of all unique words in your data and use that as a lookup table. Then store all strings as a list of indexes into that table. You'd have to use two tables, but in the end it might be simpler, and it would save you the space being used by the leading 1's you're using as the "abbrev marker" now. Basically, your abbreviation markers would become a single index instead of a triplet.</p>
<p>So,</p>
<pre><code>const char * words[] = {
"hello", "world", "goodbye", "cruel"
};
const int strings[] = {
{ 0, 1 },
{ 2, 3, 1 }
};
</code></pre>
<p>You'd still lose a lot of space if your strings aren't of roughly uniform length though.</p>
|
<p>The saga is not over yet it seems. I eventually ended up turning everything into a ragged array of <code>int</code>. But with that is lost the idea of items in a line which the self-referential mechanism behind the triplets was depending on.</p>
<p>Am now looking into using <a href="http://rapideuphoria.com" rel="nofollow noreferrer">Euphoria</a> rather than C, because of its superior support for ragged arrays. One can build standard DLLs with Euphoria and, once I figure out how to hand back a variant array of BSTR and write a Typelib ...</p>
<p>Mind you, I suppose I could stick with C and store triplets as just three ints in a row, and store the strings as pointers cast as integers. And that would save me a rather large rewrite of the VBScript that built the self-referential dictionary in the first place.</p>
| 23,791
|
<p>I've been reading the legacy code,which invloves in the customized memory pooling system, then I found that the code uses _aligned_malloc. I wonder what is this function and when do I have to use it. </p>
<hr>
<p>Thanks all of you. </p>
<p>I did read MSDN but what I wanted was the answer like "An example of a reason for wanting a certain alignment is to use the data with the SSE instruction set on x86 where the data must be aligned to a multiple 16".</p>
<p>I finally understood what those code means. thanks again.</p>
|
<p>This function is useful when the alignment of your memory allocation is important to you.</p>
<p>Alignment means that the numerical value of the pointer returned must be evenly divisible by a certain number, ie. <code>((unsigned int)ptr) % alignment</code> should evaluate to 0.</p>
<p>An example of a reason for wanting a certain alignment is to use the data with the SSE instruction set on x86 where the data must be aligned to a multiple 16.</p>
|
<p>Have you checked the MSDN documentation?
You can find the respective entry
<a href="http://msdn.microsoft.com/en-us/library/8z34s9c6(VS.80).aspx" rel="nofollow noreferrer">here</a>.</p>
| 15,279
|
<p>My client wants to send email announcements and reports for customers. Now. The python-side code doesn't seem too hard but there's the rest of the story.</p>
<p>What do I require in order to send such emails that won't end up getting blocked by email servers and clients?</p>
|
<p>Your program makes an SMTP connection to a sendmail server. If you own that server, you control it's configuration. Nothing will be blocked going out.</p>
<p>Spam, however, is spam. Your client may think their email is golden, but their customers may think it's spam. Oh well.</p>
<p>First, you have to make your email campaign "opt-in". If customers want email notification, they request. If they don't request, they don't get email.</p>
<p>Second, you have to record the bounce you get from the supplied email address. Hard bounces come back with "no such address" kinds of replies in various forms. Soft bounces are "we're still trying or mailbox full." You have to make a judgement on what to do about bounces.</p>
<p>That's about the best you can do. You can't make people recognize that your client's email is really important, but other spam is just spam.</p>
|
<p>There's no sure fire way, as email filters can do as they wish, but a few recommendations:</p>
<ul>
<li>Use a real SMTP server, usually your client's (Authenticating if needs be). By real I mean one that's in real usage not a special one to send your emails only.</li>
<li>Send from a real account able to receive responses.</li>
<li>Avoid HTML if possible, if not possible, send a <a href="http://www.python.org/doc/2.5.2/lib/module-email.mime.text.html" rel="nofollow noreferrer">multipart message</a>.</li>
<li>Send all mandatory headers plus some headers usually sent by common MUAs.</li>
</ul>
<p>Generally, check the common spam <a href="http://www.rulesemporium.com/rules.htm" rel="nofollow noreferrer">detection rules</a> to get a feel what's common in spam mails.</p>
| 30,056
|
<p>I'm involved in creating a web based business solution. The idea is that the customers will use it, get their business processes and information into one place and also receive added business value by inter-system communication. In short they will use it as a core tool in their daily work and will depend highly upon it.</p>
<p>One problem in need of a solution is how to get this web system secure enough to be an alternative which both we and the customers will find satisfactory. I am looking for good advice from others who have been or are in the same situation.</p>
<p>In our specific scenario we're currently looking at using Java SE 6, Tomcat (as a Servlet container, needed as we will use Wicket), Hibernate (to interact with our database) and MySQL (as DBMS).</p>
<p>I think the problem and advice will be of interest for other technology users as well. As many of the issues are general ones regarding HDD failure, network accessibility and other things.</p>
<p>Feel free to give any advice you have! I still provide some questions and thoughts to get us going:</p>
<ul>
<li>The system needs to be reachable through the Internet. What should we think about when deciding on how to host it? (i.e. do we need our web host to have multiple physical paths connecting them to the Internet and similar questions.)</li>
<li>Are there check lists for these kinds of things? Maybe ISO standards or some other way of seeing that we are on the right track by looking through an article/check list/academic paper/book?</li>
<li>Later in the project we think it would be a good idea to get someone involved who has extensive experience in the field. In that case we're not looking for a normal web developer. It is likely that more consulting firms will tell us they are capable of providing this expertise then there actually are. Any tips on how we will get in contact with the right people? (We're based in Scandinavia, so it would be preferable to find someone there.)</li>
<li>How high up time is good enough? 99.99% seems like a reasonable goal. But any downtime might result in loss of business for our customers.</li>
<li>How do we guarantee that each customer only will be able to access its own data? As the system will be able to access it's own database, it seems hard. A proper development process, involving lots of testing, is really all we have regarding user privileges.</li>
<li>How do we deal with HDD failures? Is RAID 5 in combination with a daily incremental backup and a weekly full backup enough? Or would you go for RAID 6?</li>
<li>If one server is enough to serve the clients. Would you still use a cluster? (I would think so.) And in that case, how many nodes would you have in the cluster?</li>
<li>Which backup strategy would you use?</li>
<li>Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.)</li>
<li>Would you use hard disk encryption? And if so, which kind? (One clarification: Yes it's only good if someone steals the hard disk, but that's still added security and may prevent (physical) intruders access to vital client business data.)</li>
<li>Is providing the customer with a way to do their own backups as well a good alternative? These customers won't be technically oriented. So in that case downloading the information in a ZIP archive containing Microsoft Office files might be a good way?</li>
<li>How would you monitor the solution?</li>
<li>Which of these things do you think we should do in house and which should be out sourced? We will develop the core system our self's, of course.</li>
<li>If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure?</li>
</ul>
<p>Thank you for your time! I hope you have some input to share. More questions might be added later.</p>
|
<p>I too make web apps in my personal time and job so I can understand why you ask the above questions. While at work none of the above issues are discussed, I pay a lot of attention to these things in my personal work. I can't answer all your questions, but for the ones I can, I will say this:</p>
<p>How would you monitor the solution? I am developing an ASP.NET web app, and so I'm using performance monitors, logging, tracing (only for dev though), health monitoring, and a custom Sql Server performance monitoring system which I'm writing (although before this gets rolled out, I will use AppManager by AdventNet).</p>
<p><code>Which of these things do you think we should do in house and which should be out sourced? We will develop the core system our self's, of course.</code></p>
<p>This is an excellent question as I have the same decision to make, all the time. I would outsource what doesn't lie in my skillset (so if I need to do 3d work, outsource it). Also, stick to the strengths of your team, concentrate on business functionality as this is what will please/draw the users (I say this from a commercial point of view for a home-user facing web app), and outsource the critical internal systems like backup, monitoring, logging, etc (I haven't outsourced this due to the cost/financial resources I have available, and I make stuff so I can learn - thus code it myself even though this is the long approach - but I enjoy it).</p>
<p><code>Are there check lists for these kinds of things? Maybe ISO standards or some other way of seeing that we are on the right track by looking through an article/check list/academic paper/book?</code></p>
<p>You say you are using Java/MySQL/Hibernate, but Microsoft have some excellent guides on web application security and generally building scalable and secure applications (both web and windows based). Look at Microsoft Patterns and Practises.</p>
<p><code>Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.)</code></p>
<p>Yes. This is cheap, effective, and will take stress off your internal architecture (I'm thinking of how you can use CDNs and Amazon EC2 to store static files). I say static files, so you can store content which doesn't change often, and which can be cached.</p>
<p><code>If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure?</code></p>
<p>Ask them to cause a breach.</p>
<p><code>How do we guarantee that each customer only will be able to access its own data? As the system will be able to access it's own database, it seems hard. A proper development process, involving lots of testing, is really all we have regarding user privileges.</code></p>
<p>I am not sure I understand what this question is asking, but you can use login systems, membership/roles (this is ASP.NET only though), and stored procedures to ensure that a user can only ever see his or her own data and not anyone elses.</p>
<p>I too would be interested in answers to the rest of the questions.</p>
|
<blockquote>
<p>The system needs to be reachable
through the Internet. What should we
think about when deciding on how to
host it? (i.e. do we need our web host
to have multiple physical paths
connecting them to the Internet and
similar questions.)</p>
</blockquote>
<p>If you want 99% uptime, then yes you will. I would look at a company called Server Vault. </p>
<blockquote>
<p>Are there check lists for these kinds
of things? Maybe ISO standards or some
other way of seeing that we are on the
right track by looking through an
article/check list/academic
paper/book?</p>
</blockquote>
<p>Official checklists, not that I have seen. Normally it means going through and having policies in places for each disaster and a mitigation. </p>
<blockquote>
<p>Later in the project we think it would
be a good idea to get someone involved
who has extensive experience in the
field. In that case we're not looking
for a normal web developer. It is
likely that more consulting firms will
tell us they are capable of providing
this expertise then there actually
are. Any tips on how we will get in
contact with the right people? (We're
based in Scandinavia, so it would be
preferable to find someone there.)</p>
</blockquote>
<p>I would check with Internet Security Solutions or At Stake. I believe they are located all over the world.</p>
<blockquote>
<p>How high up time is good enough?
99.99% seems like a reasonable goal. But any downtime might result in loss
of business for our customers.</p>
</blockquote>
<p>If you really want your customers to have their business rely on what you build, then down time really isn't acceptable. You can achieve this by having clustered servers and DR sites. At this point this might be feasible for you, so I would say having a maintence window maybe for a couple hours a month would be acceptable. You're going to have to check where your customers are located as having down time in the middle of the night for you may well be during the middle of the day for your customers.</p>
<blockquote>
<pre><code>How do we guarantee that each customer only will be able to access
</code></pre>
<p>its own data? As the system will be
able to access it's own database, it
seems hard. A proper development
process, involving lots of testing, is
really all we have regarding user
privileges.</p>
</blockquote>
<p>Lots of testing. I would suggest frequent penetration tests to make sure you don't leave a hole somewhere. </p>
<blockquote>
<p>How do we deal with HDD failures? Is
RAID 5 in combination with a daily
incremental backup and a weekly full
backup enough? Or would you go for
RAID 6?</p>
</blockquote>
<p>I would go with some type of Raid and multiple servers. You'll need some sort of monitoring to alert you if a server goes down. Depending on where you host it, they may have some sort of monitoring solution you can hire them for, so they will be responsible for letting you know if something goes offline. I would reccomend using Nagios for server montoring. </p>
<pre><code>If one server is enough to serve the clients. Would you still use a cluster? (I would think so.) And in that case, how many nodes would you have in the cluster?
</code></pre>
<p>Yes you never know what might happen.</p>
<pre><code> Which backup strategy would you use?
</code></pre>
<p>A clustered solution with a DR site, log shipping (I know sql server I know there is a process to keep multiple db servers in sync), and nightly backups. All backups should be shipped offsite and kept for at least 7 days. They should also be encrypted to ensure data safety. </p>
<pre><code>Do you think hosting the system in a computer cloud is a good alternative? (i.e. as provided by Amazon, Google or others.)
</code></pre>
<p>I don't know if I would trust them yet, and I have heard they are very expensive. For a mission critical system, I go with what I know and use proven technologies. That's my opinion though. They may work fine. </p>
<pre><code>Would you use hard disk encryption? And if so, which kind? (One clarification: Yes it's only good if someone steals the hard disk, but that's still added security and may prevent (physical) intruders access to vital client business data.)
</code></pre>
<p>Probably not. It will slow the servers down too much. I would rather go with a hosting service that I can trust to keep the servers secure. </p>
<pre><code>Is providing the customer with a way to do their own backups as well a good alternative? These customers won't be technically oriented. So in that case downloading the information in a ZIP archive containing Microsoft Office files might be a good way?
</code></pre>
<p>It might be nice to offer the option, but if you can show them a comprehensive backup strategy, I would say that would suffice. </p>
<pre><code>How would you monitor the solution?
</code></pre>
<p>Something like Nagios, and hire the hosting service to watch the server health. For 100% uptime it really needs to be in something like a NOC where someone is always there watching the server monitors.</p>
<p>Which of these things do you think we should do in house and which should be out sourced? We will develop the core system our self's, of course. </p>
<p>Do the things you are comfortable with and compentent at. It sounds like programming and testing. I would hire people to do server setup, hosting and monitoring. The key to this is don't go with the lowest bidder. Go with the people who will do a good job. </p>
<pre><code>If you feel that the system is secure, as a technical person. How do you convince a non technical person that it's safe and secure?
</code></pre>
<p>You have a written set of policies and procedures that you follow. You have a list of all vendors you use with what purchase from them and how they are configured to run. You make sure that all vendors you contract from are reputable and have a proven track record.</p>
| 28,416
|
<p>I m just starting using gwt and so far so good, however after reading some sample code I wonder is it necesary to have a high level of test coverage? (I can see that most code is declarative and then add some attributes I can see the sense in checking so me particular attributes are there but not all)</p>
<p>Also i would be interested to know anything about what are the gotchas in TDDing with GWT</p>
<p>I m using eclipse so also if you are really happy with some particualrs add ins for GWT I would be happy to hear about that
Thanks for the input</p>
<p>edit: maybe I m asking a very wide question, but even little pieces of information will help
I come from having nvelocity views with jquery/extJs/prototype/scriptaculous and this is a bit different</p>
|
<p>I think you asked a pretty broad question, which is part of the reason why you didn't get a reply for a while.</p>
<p>Compared to traditional AJAX web development, one could argue a GWT application requires less testing. Because the GWT team has worked so hard to make sure that its widgets work consistently across all web browsers, you don't have to worry about cross-browser compatibility nearly as much for your own application.</p>
<p>That frees you up to focus on your own application. Create a separate test case for each of your own custom widgets and test that they behave as you expect, and then write higher-level tests for each module. Take the extra step to make your tests fully automatable - that way every time you make a change or are about to release, it's easy to run all of your tests.</p>
<p><a href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration" rel="nofollow noreferrer">http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration</a></p>
|
<p>I think you asked a pretty broad question, which is part of the reason why you didn't get a reply for a while.</p>
<p>Compared to traditional AJAX web development, one could argue a GWT application requires less testing. Because the GWT team has worked so hard to make sure that its widgets work consistently across all web browsers, you don't have to worry about cross-browser compatibility nearly as much for your own application.</p>
<p>That frees you up to focus on your own application. Create a separate test case for each of your own custom widgets and test that they behave as you expect, and then write higher-level tests for each module. Take the extra step to make your tests fully automatable - that way every time you make a change or are about to release, it's easy to run all of your tests.</p>
<p><a href="http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration" rel="nofollow noreferrer">http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJUnitIntegration</a></p>
| 28,385
|
<p>How is it possible to read/write to the Windows registry using Java?</p>
|
<p>I know this question is old, but it is the first search result on google to "java read/write to registry". Recently I found this amazing piece of code which:</p>
<ul>
<li>Can read/write to ANY part of the registry. </li>
<li>DOES NOT USE JNI.</li>
<li>DOES NOT USE ANY 3rd PARTY/EXTERNAL APPLICATIONS TO WORK.</li>
<li>DOES NOT USE THE WINDOWS API (directly)</li>
</ul>
<p>This is pure, Java code.</p>
<p>It uses reflection to work, by actually accessing the private methods in the <code>java.util.prefs.Preferences</code> class. The internals of this class are complicated, but the class itself is very easy to use.</p>
<p>For example, the following code obtains the exact windows distribution <strong>from the registry</strong>:</p>
<pre><code>String value = WinRegistry.readString (
WinRegistry.HKEY_LOCAL_MACHINE, //HKEY
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", //Key
"ProductName"); //ValueName
System.out.println("Windows Distribution = " + value);
</code></pre>
<p>Here is the original class. Just copy paste it and it should work:</p>
<pre><code>import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;
public class WinRegistry {
public static final int HKEY_CURRENT_USER = 0x80000001;
public static final int HKEY_LOCAL_MACHINE = 0x80000002;
public static final int REG_SUCCESS = 0;
public static final int REG_NOTFOUND = 2;
public static final int REG_ACCESSDENIED = 5;
private static final int KEY_ALL_ACCESS = 0xf003f;
private static final int KEY_READ = 0x20019;
private static final Preferences userRoot = Preferences.userRoot();
private static final Preferences systemRoot = Preferences.systemRoot();
private static final Class<? extends Preferences> userClass = userRoot.getClass();
private static final Method regOpenKey;
private static final Method regCloseKey;
private static final Method regQueryValueEx;
private static final Method regEnumValue;
private static final Method regQueryInfoKey;
private static final Method regEnumKeyEx;
private static final Method regCreateKeyEx;
private static final Method regSetValueEx;
private static final Method regDeleteKey;
private static final Method regDeleteValue;
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class,
int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class,
byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
"WindowsRegSetValueEx", new Class[] { int.class,
byte[].class, byte[].class });
regSetValueEx.setAccessible(true);
regDeleteValue = userClass.getDeclaredMethod(
"WindowsRegDeleteValue", new Class[] { int.class,
byte[].class });
regDeleteValue.setAccessible(true);
regDeleteKey = userClass.getDeclaredMethod(
"WindowsRegDeleteKey", new Class[] { int.class,
byte[].class });
regDeleteKey.setAccessible(true);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private WinRegistry() { }
/**
* Read a value from key and value name
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @param valueName
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String readString(int hkey, String key, String valueName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readString(systemRoot, hkey, key, valueName);
}
else if (hkey == HKEY_CURRENT_USER) {
return readString(userRoot, hkey, key, valueName);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read value(s) and value name(s) form given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, String> readStringValues(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringValues(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringValues(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read the value name(s) from a given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List<String> readStringSubKeys(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringSubKeys(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringSubKeys(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Create a key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void createKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int [] ret;
if (hkey == HKEY_LOCAL_MACHINE) {
ret = createKey(systemRoot, hkey, key);
regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
}
else if (hkey == HKEY_CURRENT_USER) {
ret = createKey(userRoot, hkey, key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);
}
}
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
writeStringValue(systemRoot, hkey, key, valueName, value);
}
else if (hkey == HKEY_CURRENT_USER) {
writeStringValue(userRoot, hkey, key, valueName, value);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Delete a given key
* @param hkey
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteKey(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteKey(userRoot, hkey, key);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key);
}
}
/**
* delete a value from a given key/value name
* @param hkey
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteValue(int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = -1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteValue(systemRoot, hkey, key, value);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteValue(userRoot, hkey, key, value);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key + " value=" + value);
}
}
// =====================
private static int deleteValue
(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
if (handles[1] != REG_SUCCESS) {
return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED
}
int rc =((Integer) regDeleteValue.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(value)
})).intValue();
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return rc;
}
private static int deleteKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc =((Integer) regDeleteKey.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) })).intValue();
return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
}
private static String readString(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
private static Map<String,String> readStringValues
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
HashMap<String, String> results = new HashMap<String,String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
new Object[] { new Integer(handles[0]) });
int count = info[0]; // count
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumValue.invoke(root, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)});
String value = readString(hkey, key, new String(name));
results.put(new String(name).trim(), value);
}
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return results;
}
private static List<String> readStringSubKeys
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
List<String> results = new ArrayList<String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ)
});
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
new Object[] { new Integer(handles[0]) });
int count = info[0]; // Fix: info[2] was being used here with wrong results. Suggested by davenpcj, confirmed by Petrucio
int maxlen = info[3]; // value length max
for(int index=0; index<count; index++) {
byte[] name = (byte[]) regEnumKeyEx.invoke(root, new Object[] {
new Integer
(handles[0]), new Integer(index), new Integer(maxlen + 1)
});
results.add(new String(name).trim());
}
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return results;
}
private static int [] createKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
return (int[]) regCreateKeyEx.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) });
}
private static void writeStringValue
(Preferences root, int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
regSetValueEx.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(valueName), toCstr(value)
});
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
}
// utility
private static byte[] toCstr(String str) {
byte[] result = new byte[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
result[i] = (byte) str.charAt(i);
}
result[str.length()] = 0;
return result;
}
}
</code></pre>
<p>Original Author: Apache.</p>
<p>Library Source: <a href="https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry" rel="noreferrer">https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry</a></p>
|
<p>I prefer using <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html" rel="nofollow">java.util.prefs.Preferences</a> class.</p>
<p>A simple example would be </p>
<pre><code>// Write Operation
Preferences p = Preferences.userRoot();
p.put("key","value");
// also there are various other methods such as putByteArray(), putDouble() etc.
p.flush();
//Read Operation
Preferences p = Preferences.userRoot();
String value = p.get("key");
</code></pre>
| 8,766
|
<p>I have a "span" element inside a "table" "td" element. The span tag has a Title.</p>
<p>I want to get the title of that span tag and pull it out to make it the "mouseover" tip for the "td" element.</p>
<p>For example:</p>
<p>I want to turn this:</p>
<pre><code><td>
<a href="#"><span id="test" title="Acres for each province">Acres</span></a>
</td>
</code></pre>
<p>Into this:</p>
<pre><code><td onmouseover="tip(Acres for each province)">
<a href="#"><span id="test">Acres</span></a>
</td>
</code></pre>
<p><strong>EDIT:</strong> I don't think you guys understand. I am trying to put the onmouseover function into the "td" tag. I am NOT trying to put it into the "span" tag.</p>
|
<p>Based on your edit, you might check out jQuery's DOM traversal methods: <a href="http://docs.jquery.com/Traversing" rel="noreferrer">http://docs.jquery.com/Traversing</a></p>
<p>Something along these lines (not tested, I don't claim it's syntactically correct, just general ideas here)...</p>
<pre><code>$("td").each(function()
{
$(this).mouseover(function()
{
tip($(this).children("span").attr("title"));
});
});
</code></pre>
|
<p>With jQuery:</p>
<pre><code>$('#test').attr('title')
</code></pre>
| 19,984
|
<p>Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,</p>
<pre><code>set[obj] = true;
</code></pre>
<p>This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?</p>
|
<p>JavaScript objects can only use strings as keys (anything else is converted to a string).</p>
<p>You could, alternatively, maintain an array which indexes the objects in question, and use its index string as a reference to the object. Something like this:</p>
<pre><code>var ObjectReference = [];
ObjectReference.push(obj);
set['ObjectReference.' + ObjectReference.indexOf(obj)] = true;
</code></pre>
<p>Obviously it's a little verbose, but you could write a couple of methods that handle it and get and set all willy nilly.</p>
<p>Edit:</p>
<blockquote>
<p>Your guess is fact -- this is defined behaviour in JavaScript -- specifically a toString conversion occurs meaning that you can can define your own toString function on the object that will be used as the property name. - olliej</p>
</blockquote>
<p>This brings up another interesting point; you can define a toString method on the objects you want to hash, and that can form their hash identifier.</p>
|
<p>If you truly want set behavior (I'm going by Java knowledge), then you will be hard pressed to find a solution in JavaScript. Most developers will recommend a unique key to represent each object, but this is unlike set, in that you can get two identical objects each with a unique key. The Java API does the work of checking for duplicate values by comparing hash code values, not keys, and since there is no hash code value representation of objects in JavaScript, it becomes almost impossible to do the same. Even the Prototype JS library admits this shortcoming, when it says:</p>
<blockquote>
<p>"Hash can be thought of as an
associative array, binding unique keys
to values (which are not necessarily
unique)..."</p>
</blockquote>
<p><a href="http://www.prototypejs.org/api/hash" rel="nofollow noreferrer">http://www.prototypejs.org/api/hash</a></p>
| 23,676
|
<p>I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx" rel="noreferrer" title="MSDN">System.Text.RegularExpressions.Regex.Replace()</a> is what you seek - IF your tokens are odd enough that you need a regex to find them.</p>
<p><a href="http://blogs.msdn.com/debuggingtoolbox/archive/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance.aspx" rel="noreferrer">Some kind soul did some performance testing</a>, and between Regex.Replace(), String.Replace(), and StringBuilder.Replace(), String.Replace() actually came out on top.</p>
|
<p>This is an ideal use of Regular Expressions. Check out <a href="http://regular-expressions.info" rel="nofollow noreferrer">this helpful website</a>, the <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx" rel="nofollow noreferrer">.Net Regular Expressions class</a>, and this very helpful book <a href="http://books.google.com/books?id=ucwR4KIvExMC" rel="nofollow noreferrer">Mastering Regular Expressions</a>.</p>
| 4,063
|
<p>The problem is following: I want to automate the way my emacs starts.
It has to be split in two buffers and the slime-repl has to be started in the smallest (bottom) buffer. Plus, I want my file to be opened in the bigger (upper) buffer.
In my .emacs there are lines:</p>
<pre><code>(slime)
...
(split-window-vertically -6)
(switch-to-buffer (other-buffer))
(find-file "g:/Private/pa/pa2.lsp")
</code></pre>
<p>SLIME opens o.k. in the bottom buffer, but the file is opened in one of the background buffers, while I want it to be in front.</p>
<p>How to fix this?</p>
|
<p>Instead of <code>switch-to-buffer</code>, use function <code>pop-to-buffer</code>.</p>
<blockquote>
<p><code>(pop-to-buffer BUFFER-OR-NAME &optional OTHER-WINDOW NORECORD)</code></p>
<p>Select buffer <code>BUFFER-OR-NAME</code> in some window, preferably a different one.</p>
</blockquote>
|
<p>Try:</p>
<pre><code>(other-window 1)
(find-file "g:/Private/pa/pa2.lsp")
</code></pre>
<p>instead of your last two lines.</p>
| 22,855
|
<p>I have a generic list, i.e. <code>List<myclass></code>. Here <code>myclass</code> contains two string properties. </p>
<p>How can I assign a datasource to the list collection?</p>
|
<p>Mirmal, I guess English is not your first language, this question is not very clear. I think that what you are asking is given a list of your class how do you then bind that list to something (a listbox or combobox etc)</p>
<p>Here is a simple code snippet of how to do this...</p>
<pre><code>private void button2_Click(object sender, EventArgs e)
{
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass() { FirstName = "Tim", Lastname = "Jarvis"});
list.Add(new MyClass() { FirstName = "John", Lastname = "Doe" });
listBox1.DataSource = list;
listBox1.DisplayMember = "FirstName"; // or override MyClass's ToString() method.
}
</code></pre>
<p>I hope this has answered your question.</p>
|
<p>You got it the other way around. Databound objects like grids and the like could set generic lists as their data source.</p>
<p>You have to either manually populate your list or use a technology that populates it for you (e.g., LINQ to SQL, NHibernate)</p>
| 17,785
|
<p>I know the rule-of-thumb to read declarations right-to-left and I was fairly sure I knew what was going on until a colleague told me that:</p>
<pre><code>const MyStructure** ppMyStruct;
</code></pre>
<p>means "ppMyStruct is <strong>a pointer to a const pointer to a (mutable) MyStructure</strong>" (in C++).</p>
<p>I would have thought it meant "ppMyStruct is <strong>a pointer to a pointer to a const MyStructure</strong>".
I looked for an answer in the C++ spec, but apparently I'm not very good at that...</p>
<p>What does in mean in C++, and does it mean the same thing in C?</p>
|
<p>Your colleague is wrong. That is a (non-const) pointer to a (non-const) pointer to a const MyStructure. In both C and C++.</p>
|
<pre><code>void Foo( int * ptr,
int const * ptrToConst,
int * const constPtr,
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the pointee
ptr = 0; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the pointee
ptrToConst = 0; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the pointee
constPtr = 0; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the pointee
constPtrToConst = 0; // Error! Cannot modify the pointer
}
</code></pre>
| 43,659
|
<p>What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:</p>
<pre><code>String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
</code></pre>
<ol>
<li>Would that be possible?</li>
<li>Would that be beneficial?</li>
<li>Do any languages currently support both and how well does it work out?</li>
</ol>
<p>Here is a better example (generics can't be used but the program does know the type):</p>
<pre><code>var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
</code></pre>
|
<p>C# has a "var" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it.</p>
|
<p>Dynamic typed variables just have type <strong>Universal</strong>, such that every other type is a subtype of <strong>Universal</strong>. Any language where all types inherit from such a universal type (such as Java modulo unboxed values) already have this capability. As for usefulness - depends on what you're doing. I prefer a fully static type system where it's easy to create safe tagged unions so I can put whatever values I need into a variable, but in a more controlled way than <strong>Universal</strong>.</p>
| 12,454
|
<p>The LinearGradientBrush in .net (or even in GDI+ as a whole?) seems to have a severe bug: Sometimes, it introduces artifacts. (See <a href="http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2007-01/msg01592.html" rel="nofollow noreferrer">here</a> or <a href="http://www.experts-exchange.com/Microsoft/Development/.NET/Visual_CSharp/Q_23329115.html" rel="nofollow noreferrer">here</a> - essentially, the first line of a linear gradient is drawn in the endcolor, i.e. a gradient from White to Black will start with a Black line and then with the proper White to Black gradient)</p>
<p>I wonder if anyone found a working workaround for this? This is a really annoying bug :-(</p>
<p>Here is a picture of the Artifacts, note that there are 2 LinearGradientBrushes:</p>
<p><a href="http://img142.imageshack.us/img142/7711/gradientartifactmm6.jpg" rel="nofollow noreferrer">alt text http://img142.imageshack.us/img142/7711/gradientartifactmm6.jpg</a></p>
|
<p>I have noticed this as well when using gradient brushes. The only effective workaround I have is to always create the gradient brush rectangle 1 pixel bigger on all edges than the area that is going to be painted with it. That protects you against the issue on all four edges. The downside is that the colors used at the edges are a fraction off those you specify, but this is better than the drawing artifact problem!</p>
|
<p>I experienced artifacts too in my C++ code. What solved the problem is setting a non-default SmoothingMode for the Graphics object. Please note that all non-default smoothing modes use coordinate system, which is bound to the center of a pixel. Thus, you have to correctly convert your rectangle from GDI to GDI+ coordinates:</p>
<pre><code> Gdiplus::RectF brushRect;
graphics.SetSmoothingMode( Gdiplus::SmoothingModeHighQuality );
brushRect.X = rect.left - (Gdiplus::REAL)0.5;
brushRect.Y = rect.top - (Gdiplus::REAL)0.5;
brushRect.Width = (Gdiplus::REAL)( rect.right - rect.left );
brushRect.Height = (Gdiplus::REAL)( rect.bottom - rect.top );
</code></pre>
<p>It seems like LinearGradientBrush works correctly only in high-quality modes.</p>
| 13,532
|
<p>Total newbie question but this is driving me mad!
I'm trying this:</p>
<pre><code>myInt = [myFloat integerValue];
</code></pre>
<p>but I get an error saying essentially integerValue doesn't work on floats. </p>
<p>How do I do it?</p>
|
<p>I'm pretty sure C-style casting syntax works in Objective C, so try that, too:</p>
<pre><code>int myInt = (int) myFloat;
</code></pre>
<p>It might silence a compiler warning, at least.</p>
|
<p>In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.</p>
<p>Anything you can do in regular old ANSI C can be done in Objective-C.</p>
| 36,461
|
<p>For reference, this would be for Visual Studio 2008 with a fair amount of WinForms working with the VS Designer.</p>
<p>Given the same price bracket, would there be certain specs you look for in a development rig vs what one would get for a gaming machine?</p>
<p>Edit: The reason I ask is on my laptop that I can run low-mid end games decently on, there's still a fair amount of time redrawing when switching between apps sometimes.(I keep about 20 tabs open average on a browser and have like 10-15 apps open at a time), and working with the VS designer on things like a TableLayoutPanel takes up to 10-15 seconds for changes and so forth. I'd like a really smooth experience.</p>
|
<p>Any new video card you could buy today would be more than adequate for non-3D software development. In fact whatever integrated video came with your system is fine. The only exception would be for multiple monitor support, in that case you would need to get an extra $50 video card since most (all?) motherboards only have a single monitor output.</p>
<p>Edit: in response to the edit, the lag you're describing sounds like your machine is out of RAM and is swapping to disk, rather than you being video card limited. You'll want at least 2-3GB of ram in your system if you're running vs2008 plus 20 other applications. That's about the max. you can install if you're running a 32-bit operating system. If you want more than that you'll need to go to a 64-bit OS and you'll need to make sure all your hardware has 64-bit drivers. Also very few laptops out there support more than 4GB of RAM.</p>
|
<p>Any 100 buck graphics card will do fine for software development, although that's probably about what you'd need to see Aero graphics effects on Vista.</p>
| 32,528
|
<p>I am implementing a validation class in classic ASP. How should the validation class interface with my other classes? </p>
<p>My current setup:
The User class's set methods call the appropriate validation method in the validation class. Any errors that occur are stored in User.mError. For example, here's my set method for the Email member variable in ASP Classic:</p>
<pre><code>Class User
Property Let Email(EmailInput)
If (myValidation.isEmail(EmailInput)) then
mEmail = EmailInput
Else
mError = "Invalid Email Address format."
End If
</code></pre>
<p>I don't like how I'm going to need an error member variable for every object that calls my validation class. Suggestions on a better setup?</p>
<p>Any suggestions for a validation architecture I should review as a benchmark?</p>
|
<p>You should try the validation concept used in ajaxed (which is an AJAX library for classic ASP - <a href="http://www.webdevbros.net/ajaxed/" rel="nofollow noreferrer">www.webdevbros.net/ajaxed/</a>). Unfortunately the validator will be officialy released in version 2.0 but its already available in <a href="http://code.google.com/p/asp-ajaxed/source/browse/#svn/trunk/ajaxed/class_validator" rel="nofollow noreferrer">SVN</a> - you could easily use it without the whole library (standalone)</p>
<p>Ajaxed has a class called validator which you can use to validate your business objects. It requires the creation of an isValid() method which takes a Validator as an argument and returns if the instance is valid or not. The isValid() method is called before saving the instance. It performs all validations and fills the given validator if anything is invalid. </p>
<p>Example:</p>
<pre><code>class User
public firstname
public lastname
'validates the user instance
'- call before save()
public function isValid(byRef v)
isValid = true
if len(firstname) < 5 then
v.add "firstname", "Firstname must be at least 5 chars long."
isValid = false
end if
if len(lastname) < 5 then
v.add "lastname", "Lastname must be at least 5 chars long."
isValid = false
end if
end function
public sub save()
'do some DB stuff
end sub
end class
'usage scenario 1 (simple - we just know if valid or not)
set u = new User
if u.isValid(new Validator) then
u.save()
else
response.write("User is invalid. some error happend")
end if
'usage scenario 2 (detailed - we have an error summary)
set u = new User
u.firstname = "Michal"
set v = new Validator
if u.isValid(v) then
u.save()
else
'the validator offers a helper to create a validation summary
response.write(v.getErrorSummary("<div><ul>", "<ul/></div>", "<li>", "</li>"))
end if
'usage scenario 3 (we can even validator more users in one go)
set u1 = new User
set u2 = new User
set v = new Validator
u1.isValid(v)
u2.isValid(v)
if v then
u1.save()
u2.save()
else
response.write("something is invalid")
end if
</code></pre>
<p>I am using this aproach for years already and its very flexible. You can use the Validator class as standalone but I would recommend you use the ajaxed library as a whole. It lets you develop ASP more easier.</p>
|
<p>I would suggest looking at Validator related classes provided by .net framework.</p>
<p>In your case, you can have a Validator Class (EmailValidator to be specific), which could have a method named Validate which takes a string, returns a boolean</p>
<p>You could also pass ErrorMessage as one of the parameters of the Validate function
e.g. </p>
<pre>
<code>
Psuedo Code.
class EmailValidator
...
function Validate(byval EmailAddress as string, optional byval Result as string) as boolean)
..
if (condition success)
result = success
elseif (emailafddress doesnt have @)
result = "invalid email address. missing @"
endif
end function
end class
</code>
</pre>
<p>You can take error message out, if you want to have control over it.</p>
<p>I invite fellow SO guys to suggest any shortcomings in this.</p>
| 39,447
|
<p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost" rel="noreferrer">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p>
<pre><code>Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
</code></pre>
<p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p>
<p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="noreferrer">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/" rel="noreferrer">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy" rel="noreferrer">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
|
<p><strong>How WSGI, CGI, and the frameworks are all connected?</strong></p>
<p>Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. </p>
<p>In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.</p>
<p>CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.</p>
<p>WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be.</p>
<p>WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.</p>
<p><strong>What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration?</strong></p>
<p>Recall that forking a subprocess is expensive. There are two ways to work around this.</p>
<ol>
<li><p><strong>Embedded</strong> <code>mod_wsgi</code> or <code>mod_python</code> embeds Python inside Apache; no process is forked. Apache runs the Django application directly.</p></li>
<li><p><strong>Daemon</strong> <code>mod_wsgi</code> or <code>mod_fastcgi</code> allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod_fastcgi to communicate with this process.</p></li>
</ol>
<p>Note that <code>mod_wsgi</code> can work in either mode: embedded or daemon.</p>
<p>When you read up on mod_fastcgi, you'll see that Django uses <a href="http://pypi.python.org/pypi/flup/" rel="noreferrer">flup</a> to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this.</p>
<pre><code>Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)
</code></pre>
<p>Django has several "django.core.handlers" for the various interfaces.</p>
<p>For mod_fastcgi, Django provides a <code>manage.py runfcgi</code> that integrates FLUP and the handler.</p>
<p>For mod_wsgi, there's a core handler for this.</p>
<p><strong>How to install WSGI support?</strong></p>
<p>Follow these instructions.</p>
<p><a href="https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki" rel="noreferrer">https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki</a></p>
<p>For background see this</p>
<p><a href="http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index" rel="noreferrer">http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index</a></p>
|
<p>It's a simple abstraction layer for Python, akin to what the Servlet spec is for Java. Whereas CGI is really low level and just dumps stuff into the process environment and standard in/out, the above two specs model the http request and response as constructs in the language. My impression however is that in Python folks have not quite settled on de-facto implementations so you have a mix of reference implementations, and other utility-type libraries that provide other things along with WSGI support (e.g. Paste). Of course I could be wrong, I'm a newcomer to Python. The "web scripting" community is coming at the problem from a different direction (shared hosting, CGI legacy, privilege separation concerns) than Java folks had the luxury of starting with (running a single enterprise container in a dedicated environment against statically compiled and deployed code).</p>
| 26,965
|
<p>Having the window handle for an open application, I'm able to use the GetWindowText function to retrieve the text from the title bar of the app. I would like to take this a step farther and retrieve the icon associated with the same app. </p>
<p>How might I go about doing this? I looked through what I thought would be the relevant Win32 API sections, but nothing jumped out at me.</p>
<p>Any pointers would be appreciated.</p>
<p>Thanks in advance!</p>
|
<pre><code>Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);
</code></pre>
<p><a href="https://stackoverflow.com/questions/203456/how-can-i-get-the-icon-from-the-executable-file-only-having-an-instance-of-its#203490">From TheSoftwareJedi</a></p>
<p>Initially this appears to be an exact duplicate of <a href="https://stackoverflow.com/questions/203456/how-can-i-get-the-icon-from-the-executable-file-only-having-an-instance-of-its">How can I get the icon from the executable file only having an instance of it's Process in C#</a> but that one seems to focus largely on how to get it from within it's own self, whereas you may be asking how to get the icon using a program separate from the running process.</p>
<p>-Adam</p>
|
<p>You could do the following:</p>
<pre><code>[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern IntPtr LoadIcon(IntPtr hInstance, IntPtr lpIconName);
[DllImport("user32.dll", EntryPoint = "GetClassLong")]
static extern uint GetClassLong32(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", EntryPoint = "GetClassLongPtr")]
static extern IntPtr GetClassLong64(IntPtr hWnd, int nIndex);
/// <summary>
/// 64 bit version maybe loses significant 64-bit specific information
/// </summary>
static IntPtr GetClassLongPtr(IntPtr hWnd, int nIndex)
{
if (IntPtr.Size == 4)
return new IntPtr((long)GetClassLong32(hWnd, nIndex));
else
return GetClassLong64(hWnd, nIndex);
}
uint WM_GETICON = 0x007f;
IntPtr ICON_SMALL2 = new IntPtr(2);
IntPtr IDI_APPLICATION = new IntPtr(0x7F00);
int GCL_HICON = -14;
public static Image GetSmallWindowIcon(IntPtr hWnd)
{
try
{
IntPtr hIcon = default(IntPtr);
hIcon = SendMessage(hWnd, WM_GETICON, ICON_SMALL2, IntPtr.Zero);
if (hIcon == IntPtr.Zero)
hIcon = GetClassLongPtr(hWnd, GCL_HICON);
if (hIcon == IntPtr.Zero)
hIcon = LoadIcon(IntPtr.Zero, (IntPtr)0x7F00/*IDI_APPLICATION*/);
if (hIcon != IntPtr.Zero)
return new Bitmap(Icon.FromHandle(hIcon).ToBitmap(), 16, 16);
else
return null;
}
catch (Exception)
{
return null;
}
}
</code></pre>
<p>This code retrieves the small window icon, which is shown next to the window text in the titlebar.</p>
| 39,073
|
<p>One of those classic programming interview questions...</p>
<p>You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible.</p>
<p>Extra info</p>
<ul>
<li>You must find the correct floor (not a possible range)</li>
<li>The marbles are both guaranteed to break at the same floor</li>
<li>Assume it takes zero time for you to change floors - only the number of marble drops counts</li>
<li>Assume the correct floor is randomly distributed in the building</li>
</ul>
|
<p>The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3....<br>
and n+(n-1)+(n-2)+...1 <=100<br>
<strong>n=14 Is the maximum drops required</strong></p>
|
<p>First thing I would do is use the dead simple algorithm that starts at floor 1 drops the marble one floor at a time until it reaches 100 or the marble breaks.</p>
<p>Then I'd ask why should I spend time optimizing it until somone can show that it will be a problem. Too many times people get all hung up on finding the perfect complicated algorithm when a much simpler one will solve the problem. In other words don't optimize things until it's needed. </p>
<p>This might be trick question to see if you are one of those people who can make a mountain out of a mole hill.</p>
| 2,826
|
<p>Is there a programatic way from java to force a file deletion on windows even if the file is locked by some process? I cannot kill the process that locks the file.</p>
|
<p>you can go through JNI. But the whole point of locking was NOT to allow for deletion from another process.</p>
<p>So, unless you're running Windows 9x, this might be impossible to do.</p>
<p>That said, if you're aware of a way to do it using WIN32, then you might be able to do it in java using JNI.</p>
|
<p>I am not an expert on windows, but I do not know of a way in OR OUT of Java to reliably force the deletion of a file that is currently open to a process while the process continues to run.</p>
| 21,238
|
<p><em>Please note: In each step I describe below I'm logged in as the same domain user account.</em></p>
<p>I have a web application that controls a service on a remote machine (via <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx" rel="nofollow noreferrer">ServiceController</a>). When I connect to the website remotely and attempt to control the service, I get an InvalidOperationException: Access is denied.</p>
<p>I know it <strong>CAN</strong> work, because when I connect to the website from the web server (remote desktop in, login as my domain user, then open the webpage), it works as expected.</p>
<p>I have configured IIS and ASP.NET to require windows authentication and impersonation. I log the current thread's principal when this fails, and I see that the thread is running under my identity whether I'm connecting remotely or from the server itself.</p>
<p>I have tried forcing IIS to use Kerberos authentication, NTLM authentication and both at the same time; whether my principal reports its AuthenticationType as "Negotiate" or "NTLM" it doesn't matter. None of them work when I connect remotely (from my local machine)</p>
<p>ANOTHER weird thing about this is that if I'm <strong>debugging</strong> from my local machine/connecting to the remote server, it works every time! But I'm NOT debugging, it fails every time!</p>
<p>What in the heck could be going on here?</p>
|
<p>Your scenario is delegation and not impersonation. Delegation is hard to achieve and it depends on many thing that are done right.</p>
<p>A place to start would be <a href="http://support.microsoft.com/kb/907272" rel="nofollow noreferrer">Kerberos authentication and troubleshooting delegation issues</a></p>
<p><a href="http://blogs.msdn.com/david.wang/" rel="nofollow noreferrer">David Wang blog</a> is a very useful resource on thous issues.</p>
|
<p>"ANOTHER weird thing about this is that if I'm debugging from my local machine/connecting to the remote server, it works every time! But I'm NOT debugging, it fails every time!"</p>
<p>That's a clear indication that you have permission issues. When you run in the debugger you're running as the logged on user, when you're not debugging it runs as whatever IIS is set to use (NETWORK SERVICE by default). Try setting (temporarily!) the Enable anonymous access using your domain account as the user and see if that works. If it does then it means your IIS is not setup properly to impersonate (and it's probably running as NETWORK SERVICE).</p>
<p>Permissions in IIS can be a bit<em>c</em>h to fine tune properly...
Good luck!</p>
<p>P/S: This looks more like a network administration question than a programming one (see <a href="https://stackoverflow.com/questions/321618/stackoverflow-is-for-programming-questions-here-are-some-better-forums-for-your#321756">https://stackoverflow.com/questions/321618/stackoverflow-is-for-programming-questions-here-are-some-better-forums-for-your#321756</a>)</p>
| 41,674
|
<p>In what order are the following parameters tested (in C++)?</p>
<pre><code>if (a || b && c)
{
}
</code></pre>
<p>I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.</p>
<p><strong><em>Edit: Accepted Answer & Follow Up</em></strong></p>
<p>This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/126fe14k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/126fe14k.aspx</a></p>
|
<p>From <a href="http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm" rel="nofollow noreferrer">here</a>:</p>
<pre><code>a || (b && c)
</code></pre>
<p>This is the default precedence.</p>
|
<p>I'm not sure but it should be easy for you to find out.</p>
<p>Just create a small program with a statement that prints out the truth value of:
(true || false && true)</p>
<p>If the result is true, then the || has higher precedence than &&, if it is falase, it's the other way around.</p>
| 13,920
|
<p>I created an html helper </p>
<pre><code>Html.BreadCrumb(IDictionary<string, string> crumbs)
</code></pre>
<p>Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.</p>
<p>I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?</p>
<p>Or any other issues/improvements you have?</p>
|
<p>BTW we have a naming pattern in ASP.NET MVC for the various rendering techniques.</p>
<p>Helpers that return a string of what they are should be named what they are. For example, Url.Action() and Html.TextBox() return those exact items. Thus, these helpers should be used with the <%= %> syntax.</p>
<p>Helpers that render directly to the output stream should start with Render. For example, Html.RenderPartial(). These are used with the <% %> syntax.</p>
<p>Helpers that use the IDisposable pattern should be named with Begin/End. For example, Html.BeginForm() and Html.EndForm(). These should also be used with the <% %> syntax.</p>
<p>Thanks,
Eilon</p>
|
<p>I don't think you will have any performance problems as long as the size of the HTML pages you produce is reasonable. And when you really start to create pages of megabytes in size, then you should ask yourself, why are you creating such huge HTML files?</p>
| 32,238
|
<p>Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?)</p>
<p>Anyways I want to write:</p>
<pre><code>myIter = mySet.erase(myIter);
</code></pre>
<p>But GCC doesn't like it...
So Is it safe to write this instead?</p>
<pre><code>mySet.erase(myIter++);
</code></pre>
<p>Edit: And yes I'm checking against mySet.end();</p>
|
<p>There is no problem with </p>
<pre><code>mySet.erase(myIter++);
</code></pre>
<p>The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method.</p>
<p><strong>For Greg and Mark</strong>: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.</p>
|
<p>First, reread the standard and you'll see that the prototype of the set::erase method is:</p>
<pre><code>void erase(iterator position);
</code></pre>
<p>However, the associative containers in the STL are "stable", as erasing an element do not affect the iterators on the other elements. This means that the following line is valid:</p>
<pre><code>iterator to_erase = myIter++;
mySet.erase(to_erase);
// Now myIter is still on the next element
</code></pre>
| 19,478
|
<p>We have a button that saves asynchronously using AjaxToolKit/C#/.NET. I'm getting this in my Error Console:</p>
<pre><code>Error: [Exception... "'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException:
An unknown error occurred while processing the request on the server. The status code returned from the server was: 500' when calling method:
[nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "<unknown>" data: no]
</code></pre>
<p>The strangest thing about this is that it's only happening on some machines (but not all). Everyone in the office checked this out in FF 3.0.4 and IE 7, and the save works fine for most people. For the handful of people that it doesn't work for, it fails in both browsers.</p>
<p>Any ideas of where to start troubleshooting this?</p>
<ol>
<li>I'd say it was a server/code error,
but it works for most people.</li>
<li>I'd say it was a javascript error, but
we're all using the same browser.</li>
<li>I might even say it was an OS
difference, but it happens to both
XP and Vista users.</li>
<li>User Permissions are the same for all of us</li>
</ol>
<p>The application was working correctly until this weekend's update, where we updated a UserControl on the page. If I remove that control, the save works fine on all computers. When I add the control, we have the above situation where it fails on random computers.</p>
<p><strong>Answer</strong></p>
<p>Unfortunately, this was hard to track down due to the mysteriousness of how AjaxToolKit returns errors. The real culprit was that there was HTML in some of our fields in the UserControl. We added ValidateRequest="false" to the top of our page, and our problems disappeared.</p>
<p>The way we ultimately found the problem was to <strong>remove the UpdatePanel</strong> from around our Save button.</p>
<p>Sorry I didn't think of this sooner, because it was pretty straightforward from there. I'm giving Michael the accepted answer for his hard work and exhaustive troubleshooting list.</p>
|
<p>Things to check:</p>
<ol>
<li>Reboot (oldie but goodie, and doesn't always go without saying)</li>
<li>OS version (you did this)</li>
<li>Web browser (you did this)</li>
<li>Web browser settings (you covered this by trying multiple browsers)</li>
<li>Network connectivity and <a href="http://en.wikipedia.org/wiki/Hosts_file" rel="nofollow noreferrer">Hosts file</a> rules</li>
<li>User permissions (you covered this)</li>
<li>Application permissions (you covered this)</li>
<li>OS locale settings (control panel: Regional and Language Options)</li>
<li>Try and capture more information.
<ul>
<li><a href="http://www.communitymx.com/content/article.cfm?cid=A66B8" rel="nofollow noreferrer">http://www.communitymx.com/content/article.cfm?cid=A66B8</a></li>
<li><a href="http://forums.asp.net/p/1163435/2673051.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1163435/2673051.aspx</a></li>
<li><a href="http://projects.nikhilk.net/WebDevHelper/Default.aspx" rel="nofollow noreferrer">http://projects.nikhilk.net/WebDevHelper/Default.aspx</a></li>
<li><a href="http://www.fiddlertool.com/fiddler/" rel="nofollow noreferrer">http://www.fiddlertool.com/fiddler/</a></li>
<li>IIS logs; Server Event Log</li>
</ul></li>
</ol>
<p>In this situation, I'd probably download a virgin browser to try to rule out browser settings. I'd throw Google Chrome onto a known good machine and a known bad machine to see what happens. If it works in both cases, then I'd look further at browser settings. I know that this isn't likely the case since it fails in both FF and IE, but IE this simple test could help provide a little more info nonetheless.</p>
<p>It's a weird one. Since it affects both IE and FF, I'd also look at the connectivity angle, the hosts file, and permissions.</p>
|
<p>It is not the error of Ajax, Somewhere your code has error.remove Ajax and then check,u will come to know What is exact error.</p>
<p>Ajit</p>
| 48,174
|
<p>In Perl, a conditional can be expressed either as</p>
<pre><code>if (condition) { do something }
</code></pre>
<p>or as</p>
<pre><code>(condition) and do { do something }
</code></pre>
<p>Interestingly, the second way seems to be about 10% faster. Does anyone know why?</p>
|
<p>I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is</p>
<pre><code>LISTOP (0x8177a18) leave [1]
OP (0x8176590) enter
COP (0x8177a40) nextstate
LISTOP (0x8177b20) scope
OP (0x81779b8) null [174]
UNOP (0x8177c40) dofile
SVOP (0x8177b58) const [1] PV (0x81546e4) "something"
</code></pre>
<p>The opcode tree for the second is </p>
<pre><code>LISTOP (0x8177b28) leave [1]
OP (0x8176598) enter
COP (0x8177a48) nextstate
UNOP (0x8177980) null
LISTOP (0x8177ca0) scope
OP (0x81779c0) null [174]
UNOP (0x8177c48) dofile
SVOP (0x8177b60) const [1] PV (0x81546e4) "something"
</code></pre>
<p>I really don't see how the latter could be faster. It does an opcode more!</p>
|
<p>It also could depend on the version of Perl. Which you haven't mentioned. And the difference is not enough to worry about anyway. So use whatever makes more sense.</p>
| 11,419
|
<p><strong>Short version</strong></p>
<p>If I split my users into shards, how do I offer a "user search"? Obviously, I don't want every search to hit every shard.</p>
<p><strong>Long version</strong></p>
<p>By shard, I mean have multiple databases where each contains a fraction of the total data. For (a naive) example, the databases UserA, UserB, etc. might contain users whose names begin with "A", "B", etc. When a new user signs up, I simple examine his name and put him into the correct database. When a returning user signs in, I again look at his name to determine the correct database to pull his information from.</p>
<p>The advantage of sharding vs read replication is that read replication does not scale your writes. All the writes that go to the master have to go to each slave. In a sense, they all carry the same write load, even though the read load is distributed.</p>
<p>Meanwhile, shards do not care about each other's writes. If Brian signs up on the UserB shard, the UserA shard does not need to hear about it. If Brian sends a message to Alex, I can record that fact on both the UserA and UserB shards. In this way, when either Alex or Brian logs in, he can retrieve all his sent and received messages from his own shard without querying all shards.</p>
<p>So far, so good. What about searches? In this example, if Brian searches for "Alex" I can check UserA. But what if he searches for Alex by his last name, "Smith"? There are Smiths in every shard. From here, I see two options:</p>
<ol>
<li>Have the application search for Smiths on each shard. This can be done slowly (querying each shard in succession) or quickly (querying each shard in parallel), but either way, every shard needs to be involved in every search. In the same way that read replication does not scale writes, having searches hit every shard does not scale your searches. You may reach a time when your search volume is high enough to overwhelm each shard, and adding shards does not help you, since they all get the same volume.</li>
<li>Some kind of indexing that itself is tolerant of sharding. For example, let's say I have a constant number of fields by which I want to search: first name and last name. In addition to UserA, UserB, etc. I also have IndexA, IndexB, etc. When a new user registers, I attach him to each index I want him to be found on. So I put Alex Smith into both IndexA and IndexS, and he can be found on either "Alex" or "Smith", but no substrings. In this way, you don't need to query each shard, so search might be scalable.</li>
</ol>
<p>So can search be scaled? If so, is this indexing approach the right one? Is there any other?</p>
|
<p>There is no magic bullet. </p>
<p>Searching each shard in succession is out of the question, obviously, due to the incredibly high latency you will incur.</p>
<p>So you want to search in parallel, if you have to.</p>
<p>There are two realistic options, and you already listed them -- indexing, and parallelized search. Allow me to go into a little more detail on how you would go about designing them.</p>
<p>The key insight you can use is that in search, you rarely need the complete set of results. You only need the first (or nth) page of results. So there is quite a bit of wiggle room you can use to decrease response time.</p>
<p><strong>Indexing</strong></p>
<p>If you know the attributes on which the users will be searched, you can create custom, separate indexes for them. You can build your own <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="noreferrer">inverted index</a>, which will point to the (shard, recordId) tuple for each search term, or you can store it in the database. Update it lazily, and asynchronously. I do not know your application requirements, it might even be possible to just rebuild the index every night (meaning you will not have the most recent entries on any given day -- but that might be ok for you). Make sure to optimize this index for size so it can fit in memory; note that you can shard this index, if you need to.</p>
<p>Naturally, if people can search for something like <code>"lastname='Smith' OR lastname='Jones'"</code>, you can read the index for Smith, read the index for Jones, and compute the union -- you do not need to store all possible queries, just their building parts.</p>
<p><strong>Parallel Search</strong></p>
<p>For every query, send off requests to every shard unless you know which shard to look for because the search happens to be on the distribution key. Make the requests asynchronous. Reply to the user as soon as you get the first page-worth of results; collect the rest and cache locally, so that if the user hits "next" you will have the results ready and do not need to re-query the servers. This way, if some of the servers are taking longer than others, you do not need to wait on them to service the request.</p>
<p>While you are at it, log the response times of the sharded servers to observe potential problems with uneven data and/or load distribution.</p>
|
<p>RDBMs are not good tool for textual search. You will be much better off looking at <a href="http://lucene.apache.org/solr/" rel="nofollow">Solr</a>. Performance difference between Solr and database will be in the order of magnitude of 100X. </p>
| 32,548
|
<p>This question has been discussed in two blog posts (<a href="http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/27/when-systemcurrenttimemillis-is-too-slow/</a>, <a href="http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/" rel="nofollow noreferrer">http://dow.ngra.de/2008/10/28/what-do-we-really-know-about-non-blocking-concurrency-in-java/</a>), but I haven't heard a definitive answer yet. If we have one thread that does this:</p>
<pre><code>public class HeartBeatThread extends Thread {
public static int counter = 0;
public static volatile int cacheFlush = 0;
public HeartBeatThread() {
setDaemon(true);
}
static {
new HeartBeatThread().start();
}
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
counter++;
cacheFlush++;
}
}
}
</code></pre>
<p>And many clients that run the following:</p>
<pre><code>if (counter == HeartBeatThread.counter) return;
counter = HeartBeatThread.cacheFlush;
</code></pre>
<p>is it threadsafe or not?</p>
|
<p>Within the java memory model? No, you are not ok. </p>
<p>I've seen a number of attempts to head towards a very 'soft flush' approach like this, but without an explicit fence, you're definitely playing with fire.</p>
<p>The 'happens before' semantics in </p>
<p><a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7" rel="nofollow noreferrer">http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.7</a></p>
<p>start to referring to purely inter-thread actions as 'actions' at the end of 17.4.2. This drives a lot of confusion since prior to that point they distinguish between inter- and intra- thread actions. Consequently, the intra-thread action of manipulating counter isn't explicitly synchronized across the volatile action by the happens-before relationship. You have two threads of reasoning to follow about synchronization, one governs local consistency and is subject to all the nice tricks of alias analysis, etc to shuffle operations The other is about global consistency and is only defined for inter-thread operations.</p>
<p>One for the intra-thread logic that says within the thread the reads and writes are consistently reordered and one for the inter-thread logic that says things like volatile reads/writes and that synchronization starts/ends are appropriately fenced. </p>
<p>The problem is the visibility of the non-volatile write is undefined as it is an intra-thread operation and therefore not covered by the specification. The processor its running on should be able to see it as it you executed those statements serially, but its sequentialization for inter-thread purposes is potentially undefined.</p>
<p>Now, the reality of whether or not this can affect you is another matter entirely.</p>
<p>While running java on x86 and x86-64 platforms? Technically you're in murky territory, but practically the very strong guarantees x86 places on reads and writes including the total order on the read/write across the access to cacheflush and the local ordering on the two writes and the two reads should enable this code to execute correctly provided it makes it through the compiler unmolested. That assumes the compiler doesn't step in and try to use the freedom it is permitted under the standard to reorder operations on you due to the provable lack of aliasing between the two intra-thread operations.</p>
<p>If you move to a memory with weaker release semantics like an ia64? Then you're back on your own. </p>
<p>A compiler could in perfectly good faith break this program in java on any platform, however. That it functions right now is an artifact of current implementations of the standard, not of the standard.</p>
<p>As an aside, in the CLR, the runtime model is stronger, and this sort of trick is legal because the individual writes from each thread have ordered visibility, so be careful trying to translate any examples from there.</p>
|
<p>Well, I don't think it is.</p>
<p>The first if-statement: </p>
<pre><code>if (counter == HeartBeatThread.counter)
return;
</code></pre>
<p>Does not access any volatile field and is not synchronized. So you might read stale data forever and never get to the point of accessing the volatile field.</p>
<p>Quoting from one of the comments in the second blog entry: "anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f."
But in your case B (the client) never reads f (=cacheFlush). So changes to HeartBeatThread.counter do not have to become visible to the client.</p>
| 34,477
|
<p>I have a huge dictionary of blank values in a variable called current like so:</p>
<pre><code>struct movieuser {blah blah blah}
Dictionary<movieuser, float> questions = new Dictionary<movieuser, float>();
</code></pre>
<p>So I am looping through this dictionary and need to fill in the "answers", like so:</p>
<pre><code>for(var k = questions.Keys.GetEnumerator();k.MoveNext(); )
{
questions[k.Current] = retrieveGuess(k.Current.userID, k.Current.movieID);
}
</code></pre>
<p>Now, this doesn't work, because I get an InvalidOperationException from trying to modify the dictionary I am looping through. However, you can see that the code should work fine - since I am not adding or deleting any values, just modifying the value. I understand, however, why it is afraid of my attempting this.</p>
<p>What is the preferred way of doing this? I can't figure out a way to loop through a dictionary WITHOUT using iterators.</p>
<p>I don't really want to create a copy of the whole array, since it is a lot of data and will eat up my ram like its still Thanksgiving.</p>
<p>Thanks,
Dave</p>
|
<p>Matt's answer, getting the keys first, separately is the right way to go. Yes, there'll be some redundancy - but it will work. I'd take a working program which is easy to debug and maintain over an efficient program which either won't work or is hard to maintain any day. </p>
<p>Don't forget that if you make <code>MovieUser</code> a reference type, the array will only be the size of as many references as you've got users - that's pretty small. A million users will only take up 4MB or 8MB on x64. How many users have you really got?</p>
<p>Your code should therefore be something like:</p>
<pre><code>IEnumerable<MovieUser> users = RetrieveUsers();
IDictionary<MovieUser, float> questions = new Dictionary<MovieUser, float>();
foreach (MovieUser user in users)
{
questions[user] = RetrieveGuess(user);
}
</code></pre>
<p>If you're using .NET 3.5 (and can therefore use LINQ), it's even easier:</p>
<pre><code>IDictionary<MovieUser, float> questions =
RetrieveUsers.ToDictionary(user => user, user => RetrieveGuess(user));
</code></pre>
<p>Note that if <code>RetrieveUsers()</code> can stream the list of users from its source (e.g. a file) then it will be efficient anyway, as you never need to know about more than one of them at a time while you're populating the dictionary.</p>
<p>A few comments on the rest of your code:</p>
<ul>
<li>Code conventions matter. Capitalise the names of your types and methods to fit in with other .NET code.</li>
<li>You're not calling <code>Dispose</code> on the <code>IEnumerator<T></code> produced by the call to <code>GetEnumerator</code>. If you just use <code>foreach</code> your code will be simpler <em>and</em> safer.</li>
<li><code>MovieUser</code> should almost certainly be a class. Do you have a genuinely good reason for making it a struct?</li>
</ul>
|
<p>store the dictionary keys in a temporary collection then loop over the temp collection and use the key value as your indexer parameter. This should get you around the exception.</p>
| 42,407
|
<p>I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).</p>
<p>What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?</p>
<p><a href="https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data">This</a> question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?</p>
|
<p>You should regard .h files as <strong>interface files</strong> of your .c file. Every .c file represents a module with a certain amount of functionality. If functions in a .c file are used by other modules (i.e. other .c files) put the function prototype in the .h interface file. By including the interface file in your original modules .c file and every other .c file you need the function in, you make this function available to other modules. </p>
<p>If you only need a function in a certain .c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. </p>
<p>Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'.</p>
<p>The inclusion guards in header files help to not include the same header file multiple times.</p>
<p>For example:</p>
<p>Module1.c:</p>
<pre>
#include "Module1.h"
static void MyLocalFunction(void);
static unsigned int MyLocalVariable;
unsigned int MyExternVariable;
void MyExternFunction(void)
{
MyLocalVariable = 1u;
/* Do something */
MyLocalFunction();
}
static void MyLocalFunction(void)
{
/* Do something */
MyExternVariable = 2u;
}
</pre>
<p>Module1.h:</p>
<pre>
#ifndef __MODULE1.H
#define __MODULE1.H
extern unsigned int MyExternVariable;
void MyExternFunction(void);
#endif
</pre>
<p>Module2.c</p>
<pre>
#include "Module.1.h"
static void MyLocalFunction(void);
static void MyLocalFunction(void)
{
MyExternVariable = 1u;
MyExternFunction();
}
</pre>
|
<p>The .h files should be used to define the prototypes for your functions. This is necessary so you can include the prototypes that you need in your C-file without declaring every function that you need all in one file. </p>
<p>For instance, when you <code>#include <stdio.h></code>, this provides the prototypes for printf and other IO functions. The symbols for these functions are normally loaded by the compiler by default. You can look at the system's .h files under /usr/include if you're interested in the normal idioms involved with these files. </p>
<p>If you're only writing trivial applications with not many functions, it's not really necessary to modularize everything out into logical groupings of procedures. However, if you have the need to develop a large system, then you'll need to pay some consideration as to where to define each of your functions. </p>
| 7,026
|
<p>I know that the JBoss Application Server has the JMX-Console as a GUI for administration. My question is, is there a similar admin tool using the command line? Does this tool come with the application server, and can it report on the status of various services under the control of the server?</p>
|
<p>You might want to have a look at twiddle.sh 'A JMX client to 'twiddle' with a remote JBoss server.' </p>
|
<p>If you are using JBoss Application Server 6, you can find a command line tool called Twiddle in the <em>bin</em> folder of your installation. You can find more information in JBoss wiki: <a href="http://community.jboss.org/wiki/Twiddle" rel="nofollow">http://community.jboss.org/wiki/Twiddle</a></p>
| 24,615
|
<p>SVN keyword substition gives is not pretty. E.g.,</p>
<blockquote>
<p>Last updated: $Date$ by $Author$</p>
</blockquote>
<p>yields</p>
<blockquote>
<p>Last updated: $Date: 2008-09-22
14:38:43 -0400 (Mon, 22 Sep 2008) $ by
$Author: cconway $"</p>
</blockquote>
<p>Does anybody have a Javascript snippet that prettifies things and outputs some HTML? The result should be more like:</p>
<blockquote>
<p>Last update: 22 Sep 2008 by cconway</p>
</blockquote>
<p>P.S. Is there a way to replace "cconway" with a display name?</p>
|
<p>Errr.. This feels a bit like me doing your job for you :), but here goes:</p>
<pre><code>function formatSvnString(string){
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var re = /\$Date: (\d{4})-(\d\d)-(\d\d).*?\$Author: (\S+) \$/
return string.replace(re, function(match, year, month, day, author){
var date = new Date([year, month, day].join('/'))
return date.getDate()
+ ' ' + months[date.getMonth()]
+ ' ' + date.getFullYear()
+ ' by ' + author
})
}
</code></pre>
<p>Usage:</p>
<pre><code>formatSvnString("$Date: 2008-09-22 14:38:43 -0400 (Mon, 22 Sep 2008) $ by $Author: cconway $")
// returns: 22 Sep 2008 by cconway
</code></pre>
<p>I'll leave it up to you to work out how to find these SVN string and apply the above code automatically :)</p>
<p>To do the user's display name, you'll either have to convince SVN to insert it (I don't think it can do that, but I might be wrong), or somehow provide a means for JS to either fetch it, or to have access to a table full of usernames and associated display name (might be a bit too much like a security risk though. Hey kids, see if you can break into my server using one of these usernames!)</p>
|
<p>Some JavaScript libraries provide templating functionality.</p>
<p>Prototype - <a href="http://www.prototypejs.org/api/template" rel="nofollow noreferrer">http://www.prototypejs.org/api/template</a><br>
Ext JS - <a href="http://extjs.com/deploy/dev/docs/?class=Ext.DomHelper" rel="nofollow noreferrer">http://extjs.com/deploy/dev/docs/?class=Ext.DomHelper</a></p>
<p>I'm sure you could find a plugin for JQuery.</p>
| 14,219
|
<p>I'm developing my first Word 2007 addin, and I've added an OfficeRibbon to my project. In a button-click handler, I'd like a reference to either the current <code>Word.Document</code> or <code>Word.Application</code>.</p>
<p>I'm trying to get a reference via the <code>OfficeRibbon.Context</code> property, which the documentation says should refer to the current <code>Application</code> object. However, it is always <code>null</code>.</p>
<p>Does anyone know either</p>
<p>a) if there is something I need to do to make <code>OfficeRibbon.Context</code> appear correctly populated?<br>
b) if there is some other way I can get a reference to the Word Application or active Word Document?</p>
<p>Notes:</p>
<ul>
<li><p>I'm using VS2008 SP1</p></li>
<li><p>The ribbon looks like it has initialized fine: The ribbon renders correctly in Word; I can step the debugger through both the constructor and the OnLoad members; Button click handlers execute correctly. </p></li>
<li><p>Here's <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.officeribbon.context.aspx?ppud=4" rel="nofollow noreferrer">the online help for this property</a>; </p></li>
</ul>
<blockquote>
<p><strong>OfficeRibbon.Context Property</strong></p>
<p><code>C#</code><br>
<code>public Object Context { get; internal set; }</code></p>
<p>An Object that represents the Inspector window or application instance that is associated with this OfficeRibbon object. </p>
<p><strong>Remarks</strong></p>
<p>In Outlook, this property refers to the Inspector window in which this OfficeRibbon is displayed.</p>
<p>In Excel, Word, and PowerPoint, this property returns the application instance in which this OfficeRibbon is displayed. </p>
</blockquote>
|
<p>I also encountered this problem while creating an Excel 2007 AddIn using VS2008 SP1. The workaround I used was to store the Application in an <code>internal static</code> property in the main AddIn class and then reference it in the event handler in my ribbon:</p>
<pre><code>public partial class ThisAddIn
{
internal static Application Context { get; private set; }
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Context = Application;
}
...
}
public partial class MyRibbon : OfficeRibbon
{
private void button1_Click(object sender, RibbonControlEventArgs e)
{
DoStuffWithApplication(ThisAddIn.Context);
}
...
}
</code></pre>
|
<p>While I dont know much about changes in Office 2007 word object model, here is my explanation using VBA knowledge.</p>
<p>Application is a globally available object.
Also, Application.ActiveDocument should get you handle to the current document.</p>
<p>Speculating: How are you trying to add the ribbon?</p>
| 31,555
|
<p>Hi I get an System.InvalidProgramException while trying to run the Example Project called "C# Example.WorkItemBrowser".
The Exception also apears when I try to execute these lines:</p>
<pre><code>TeamFoundationServer tfserver = new TeamFoundationServer("http://localhost:8085");
tfserver.EnsureAuthenticated();
WorkItemStore store = new WorkItemStore(tfserver);
Console.WriteLine(store.Projects.Count);
</code></pre>
<p>I'm using the 2008 Visual Studio SDK for that.</p>
<p>PEverify for the assembly Microsoft.TeamFoundation.WorkItemTracking.Client.dll</p>
<p>got this otuput:</p>
<pre><code>[MD]: Error: Value class has neither fields nor size parameter. [token:0x020000B3]
[MD]: Error: Value class has neither fields nor size parameter. [token:0x020000BF]
[MD]: Error: Value class has neither fields nor size parameter. [token:0x020000C4]
3 Error(s) Verifying Microsoft.TeamFoundation.WorkItemTracking.Client.dll
</code></pre>
<p>A fresh download and install of the SDK as well as deinstall and install as well as installing .net 3.5 sp1 again didn't help.</p>
<p>Is something wrong with the description of my problem or did it just not happen anywhere else?</p>
|
<p>This solved my problem: <a href="http://blogs.msdn.com/b/jianges/archive/2008/03/28/tfs-sdk-will-cause-invalidprogramexception-while-running-as-64-bit.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/jianges/archive/2008/03/28/tfs-sdk-will-cause-invalidprogramexception-while-running-as-64-bit.aspx</a></p>
|
<p>I just a very similar question <a href="https://stackoverflow.com/questions/1015648/how-do-i-distribute-a-service-that-uses-the-team-foundation-server-api">here</a>. </p>
<p>Turns out, you have to have Team Explorer installed on the machine you are executing this code on. Are you deploying this to another machine or trying this on a machine that doesn't have Team Explorer installed on it?</p>
| 21,529
|
<p>I've been given a prototype/mockup of a grid written in html and javascript (via ExtJS) that I now need to implement within an ASP.net web application. Does anyone have any pointers as to how to pass data to the grid (to a GroupingStore, specifically). </p>
<p>I'd rather not have a proliferation of web services or helper pages returning XML/JSON so if there's a way to use Client callbacks or Page Methods (Can't you tell I'm not particularly familiar with either - buzzword bingo!) or somesuch, that would be preferred.</p>
<p>Please, no recommendations that I use jQuery, the built-in ASP.net grid, or any other UI framework. The use of the ExtJS grid has been mandated by the powers that be, so that's the grid I'm using, for better or worse :)</p>
|
<p>I believe a service that simply returns json structures for your pages is the best option, nicely abstracted and reusable across the application rather than page methods.</p>
|
<p>I believe a service that simply returns json structures for your pages is the best option, nicely abstracted and reusable across the application rather than page methods.</p>
| 27,260
|
<p><strong>Scenario:</strong> C# apps uses SQL2000. It excecute 3 stored procs within a try catch in the app. In the catch the error is suppressed. Due to some legalities, the c# code cannot be changed and implemented. </p>
<p><strong>Q:</strong> How do I trap the actual SQL error in the stored proc into a log file or other table? @@Error returns an error message to the app but when evaluated in query analyzer it is always 0 although the 'If @@Error <> 0' does fire. I try to store the @@Error number, but it is always 0.</p>
<p>Please help.</p>
|
<p><code>@@ERROR</code> is reset to 0 when you check it. Why? Because it reflects the status of the last statement executed.</p>
<pre><code>IF @@ERROR <> 0 ...
</code></pre>
<p>is a statement, and that statement succeeds, causing <code>@@ERROR</code> to be set to 0.</p>
<p>The proper way to examine and operate on <code>@@ERROR</code> values is as follows:</p>
<pre><code>DECLARE @ErrorCode INT
INSERT INTO Table ...
SET @ErrorCode = @@ERROR
IF @ErrorCode <> 0
BEGIN
INSERT INTO ErrorLog (ErrorCode, Message)
VALUES (@ErrorCode, 'The INSERT operation failed.')
END
</code></pre>
|
<p>Didn't try it myself but I guess you can monitor the errors with <strong>Sql Server Profiler</strong>.</p>
| 16,703
|
<p>I have not seen much support for Grails to develop facebook apps.I was just wondering if people around are developing facebook apps on grails </p>
|
<p>Jozef Dransfield:
<a href="http://www.grassr.com/wordpress/?cat=8" rel="nofollow noreferrer">http://www.grassr.com/wordpress/?cat=8</a></p>
|
<p>I helped out a startup in San Francisco that are using Grails with facebook apps.
So yes, it's happening. There is even a grails plugin for facebook integration (at the time I'm writing this is woefully incomplete, but looks like it's having work done so check up on it again soon).</p>
| 10,751
|
<p>I'm making modifications to a members-based site whose owner wants to be able to track time spent on site (login/logout) for all users in a DB backend. Login is easy; there's one point of entry (the login form) and as a result, logins can be thrown in the database as soon as they happen.</p>
<p>Logouts, however, are a bit trickier, as unless the user clicks 'logout' to explicitly let us know they're leaving the solution gets hairier (and how often do users <em>really</em> click logout?). One possibility (just in terms of tracking total time on the site) would be to register each pageload in the database and associate it with the user that loaded it; the problem with that is that the site is a membership-based video delivery site (not what you're thinking!) and their last pageview is likely going to be a twenty or thirty minute video. We need to capture that time spent on that last page, as well--not just the time it was loaded.</p>
<p>I've thought of two possible solutions, neither of which is all that elegant. The first would be to trap all 'unload' events via javascript and register a call to 'logout.php' (this assuming the XMLHttpRequest or whatever doesn't die as soon as the page is unloaded); the problem there is that internal links also register as unload events, so clicking any link would log the user out (you could to check a flag in the 'unload' handler, and have all internal links set that flag--not hard to do dynamically, but a bit kludgy). The other approach would involve setting an interval to ping the DB every 60 s or so, which lets us know that the user is still on the site, and then doing some math when pulling the user's history to figure out the total length of that session; that also seems kind of hackish. Also, neither of these solutions work for users with JS disabled.</p>
<p>It seems that this problem isn't that unusual, and there's got to be a better way; is there a best-practices approach to solving this? If not, do you see any way to improve either of these solutions?</p>
|
<p>The web is not built to allow accurate tracking of logout events. You just aren't guaranteed to get notice from the browser when the user quits, so under normal circumstances the best you can hope for is to trap the session timeout event, and that event might not fire until 20 minutes after the user abandoned the page.</p>
<p>Now you could improve on this a little by putting an ajax request in a timer on each page (perhaps once or twice per minute) to provide a "heartbeat", but this has some caveats as well: You need to make sure the session will still eventually time out and you still aren't guaranteed that the user won't block these requests, perhaps by disabling javascript.</p>
|
<p>I've had good success with using timer in javascript to ping the server. In my case the site requires javascript so this is not an issue. I also use this mechanism to perform a check which prevents a single account from being logged in from two different machines so there is more compelling reasons to do this hack.</p>
<p>One thing to keep in mind with unload is your still not guarenteed that the unload event will always be fired. You will have people on laptops who for example just close the laptop, so the timer approach will probally be a bit more accurate.</p>
| 43,315
|
<p>I'm making a simple tool that will get a string of MySQL commands and run it (on several DB servers sequentially). I trust the users to be sensible, but mistakes happen, and I'm looking for a way to prevent basic typos:</p>
<p>Is there a way to validate, at runtime, (relatively simple) MySQL queries to see if they're syntactically correct?</p>
<p>I'm not looking for semantic correctness, e.g. table names or join applicability; just something like a spellcheck for SQL queries.</p>
<p>In other words, </p>
<pre><code>SELECT * FROM x;
</code></pre>
<p>or</p>
<pre><code>INSERT INTO x SET id=1,bar="foo";
</code></pre>
<p>would be marked valid, whereas any of those would not:</p>
<pre><code>SELECT FROM x;
SECLET * RFOM x;
ISNETR INTO x SET id=1;
HJBGYGCRYTCY;
</code></pre>
<p>For <code>SELECT</code>s, I could bend <code>EXPLAIN</code> to my needs - run <code>EXPLAIN SELECT (...)</code> and watch for errors, but is there a way to check for other commands as well? </p>
|
<p>Not without knowledge of the schema (for example, is 'x' a table?) and writing a SQL parser. Your MySQL query tool should be able to do that kind of validation (intellisense if you like) but I know from first hand experience, most of the (free) MySQL tools are abysmal.</p>
<p>'Preparing' the query would do what you want, but is a runtime check, not a compile time check - you seem to be looking for a compile time/offline solution.</p>
|
<p>You can temporarily create a stored procedure with your code and unique name.
Then you can drop it immediately. Transactions can't rollback SP creation.
But be careful, because it just syntax validation, so it doesn't check if an object (in your query) exists or not.</p>
| 49,490
|
<p>Well basically I'm finishing school in mid December so I'm just brushing up my resume and I'm wondering if there's a way to use custom fonts (in this case Calibri and Cambria) in a PDF file and make them render correctly on all computers.</p>
<p>Thanks in advance!</p>
<p><strong>EDIT:</strong> I'm using MS Word 2007, but am open to suggestions</p>
|
<p>PDFs don't store text and fonts like other documents, they actually convert the font to vectors, that way no matter what font you use, the document displays exactly as expected. This is why searching for text inside the PDF is such a problem for 3rd party PDF Readers and why even Adobe themselves use to distribute 2 versions of Acrobat (one with text search, one without).</p>
<p>Another thing to keep in mind is, PDF isn't pixel exact, it's ratio exact. PDF readers generally do not use a 100% zoom level, instead most people read them at "fit to screen" or "fit to page". I point this out because I'm guessing the reason you are trying to use those new Vista/Office 2007 fonts is because of their LCD subpixel support (improves readability on LCD screens). This feature will not translate into the PDF, since the letter becomes a vector, subpixel information is lost, and even if it wasn't, becomes useless because the vector will be sized to something other than you intended at view time.</p>
|
<p>theoretically speaking, on technical side, embedding/not embedding ability, regarding the fonts, is settled with a special flag in font file (ttf or opentype or type1)</p>
<p>you can view this special embedding flag with any font <strong>editor</strong> program (I recommend</p>
<p><strong>FontCreator</strong> (by High-logic)</p>
<ul>
<li><a href="http://www.high-logic.com/font-editor/fontcreator.html" rel="nofollow">http://www.high-logic.com/font-editor/fontcreator.html</a></li>
</ul>
<p>with a free trial fully operative and without limitations</p>
<p>you can also change embedding/not embedding flag, but legally speaking, for the 99% of fonts commercially distributed, this breaks the license of font</p>
| 34,023
|
<p>I'm currently trying to read text from a file and append it to a element in my html page using the DOM and Javascript. I can't get the text to format though. I've tried using innerHtml but isn't formating at all( no line breaks ).</p>
<p>Here is the javascript:</p>
<pre><code>http = new XMLHttpRequest();
http.open("GET",FILE,false);
http.send();
document.getElementById("tbody").innerHTML = http.responseText
</code></pre>
<p>Like I said the text gets added to the tbody element but isn't formatted what so ever.</p>
<hr>
<p>I got it working with this code( with the pre tag ), but like I said it works on my pc but not on the server which doesn't help.</p>
<pre><code> http.open("GET",FILE ,false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
</code></pre>
<hr>
<p>Here is all my javascript code:</p>
<p>function getHTTPObject()
{
var http = false;</p>
<pre><code>/*@cc_on
@if (@_jscript_version >= 5)
try
{
http = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
http = false;
}
}
@else
{
http = false;
}
@end @*/
if (!http && typeof XMLHttpRequest != 'undefined')
{
try
{
http = new XMLHttpRequest();
}
catch (e)
{
http = false;
}
}
return http
</code></pre>
<p>}</p>
<pre><code> function loadData()
{
http = getHTTPObject();
if (http)
{
http.open("GET","my file name",false);
http.send();
var newtext = document.createTextNode(http.responseText);
var para = document.getElementById("tbody");
para.appendChild(newtext);
}
}
</code></pre>
|
<p>You might have luck wrapping the text in a <code><pre></code> tag. What's in the response? If it's XML, you might want to use <code>responseXML</code>.</p>
<pre><code>http = new XMLHttpRequest();
http.open("GET",FILE,false);
http.send();
document.getElementById("tbody").appendChild(http.responseXML);
</code></pre>
|
<p>innerHTML takes (and parses) and html string, so what should result is a DOM tree similar to</p>
<p>(assuming )</p>
<pre><code><tbody>{responseText}</tbody>
</code></pre>
<p>But without knowing what type of content is in the response text it's difficult to know the exact cause of your problem.</p>
| 45,327
|
<p>In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.</p>
<p>I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.</p>
<p>Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?</p>
|
<p>Well, you could argue with the object oriented aspect, the prepared statements, the fact that it becomes a standard, etc. But I know that most of the time, convincing somebody works better with a killer feature. So there it is:</p>
<p>A really nice thing with PDO is you can fetch the data, injecting it automatically in an object. If you don't want to use an <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="noreferrer">ORM</a> (cause it's a just a quick script) but you do like object mapping, it's REALLY cool :</p>
<pre><code>class Student {
public $id;
public $first_name;
public $last_name
public function getFullName() {
return $this->first_name.' '.$this->last_name
}
}
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=school", $username, $password)
$stmt = $dbh->query("SELECT * FROM students");
/* MAGIC HAPPENS HERE */
$stmt->setFetchMode(PDO::FETCH_INTO, new Student);
foreach($stmt as $student)
{
echo $student->getFullName().'<br />';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
</code></pre>
|
<p>There's one thing to keep in mind.</p>
<p>Mysqli does not support fetch_assoc() function which would return the columns with keys representing column names. Of course it's possible to write your own function to do that, it's not even very long, but I had <strong>really</strong> hard time writing it (for non-believers: if it seems easy to you, try it on your own some time and don't cheat :) )</p>
| 3,450
|
<p>We're seeing the error message ORA-00936 Missing Expression for the following SQL:</p>
<p>Note that this is just a cut-down version of a much bigger SQL so rewriting it to a inner join or similar is not really in the scope of this:</p>
<p>This is the SQL that fails:</p>
<pre><code>select (select count(*) from gt_roster where ROS_ROSTERPLAN_ID = RPL_ID)
from gt_rosterplan
where RPL_ID = 432065061
</code></pre>
<p>What I've tried:
* Extracting the innermost SQL and substituting the ID from the outer SQL gives me the number 12.
* Aliasing both the sub-query, and the count(*) individually and both at the same time does not change the outcome (ie. still an error)</p>
<p>What else do I need to look at?</p>
<p>The above are only tables, no views, RPL_ID is primary key of gt_rosterplan, and ROS_ROSTERPLAN_ID is a foreign key to this column, there is basically no magic or hidden information here.</p>
<hr>
<p><strong>Edit:</strong> In response to answer, no, you do not need the aliases here as the columns are uniquely named across the tables.</p>
<hr>
<p><strong>Solved:</strong> The problem was that the client was running the wrong client driver version, 9.2.0.1, and there are known problems with that version.</p>
|
<p>That should work, assuming the column names are not ambiguous (and even if they were that would lead to a different error). I ran an equivalent statement and got a result without error:</p>
<pre><code>SQL> select (select count(*) from emp2 where empdeptno = deptno)
2 from dept
3 where deptno=10
4 /
(SELECTCOUNT(*)FROMEMP2WHEREEMPDEPTNO=DEPTNO)
---------------------------------------------
3
</code></pre>
<p>Googling it appears that there are or have been Oracle bugs leading to ORA-00936 errors - see <a href="http://oracle-error.blogspot.com/2008/04/ora-00936missing-expression.html" rel="nofollow noreferrer">this for example</a>.</p>
|
<p>That should work, assuming the column names are not ambiguous (and even if they were that would lead to a different error). I ran an equivalent statement and got a result without error:</p>
<pre><code>SQL> select (select count(*) from emp2 where empdeptno = deptno)
2 from dept
3 where deptno=10
4 /
(SELECTCOUNT(*)FROMEMP2WHEREEMPDEPTNO=DEPTNO)
---------------------------------------------
3
</code></pre>
<p>Googling it appears that there are or have been Oracle bugs leading to ORA-00936 errors - see <a href="http://oracle-error.blogspot.com/2008/04/ora-00936missing-expression.html" rel="nofollow noreferrer">this for example</a>.</p>
| 31,078
|
<p>I am using a nested html unordered list styled as a drop down. When the a tag within the inner lists list item is clicked it trigger some javascript which is supposed to set the value of a hidden field to the text for the link that was clicked.</p>
<p>The javascript seems to work - I used an alert to read the value from the hidden field but then when I try to put that value in the querystring in my asp.net c# code behind - it pulls the initial value - not the javascript set value.</p>
<p>I guess this is because the javascript is client side not server side but has anyone any idea how i can get this working</p>
<p><strong>HTML</strong></p>
<pre><code> <div class="dropDown accomodation">
<label for="accomodationList">Type of accomodation</label>
<ul class="quicklinks" id="accomodationList">
<li><a href="#" title="Quicklinks" id="accomodationSelectList">All types
<!--[if IE 7]><!--></a><!--<![endif]-->
<!--[if lte IE 6]><table><tr><td><![endif]-->
<ul id="sub" onclick="dropDownSelected(event,'accomodation');">
<li><a href="#" id="val=-1$#$All types" >All types</a></li>
<li><a href="#" id="val=1$#$Villa" >Villa</a></li>
<li><a href="#" id="val=2$#$Studio" >Studio</a></li>
<li><a href="#" id="val=3$#$Apartment" >Apartment</a></li>
<li><a class="last" href="#" id="val=4$#$Rustic Properties" >Rustic Properties</a></li>
</ul>
<!--[if lte IE 6]></td></tr></table></a><![endif]-->
</li></ul>
</div>
<input type="hidden" ID="accomodationAnswer" runat="server" />
</code></pre>
<p><strong>javascript</strong></p>
<pre><code> if(isChildOf(document.getElementById(parentList),document.getElementById(targ.id)) == true)
{
document.getElementById(parentLi).innerHTML = tname;
document.getElementById(hiddenFormFieldName).Value = targ.id;
alert('selected id is ' + targ.id + ' value in hidden field is ' + document.getElementById(hiddenFormFieldName).Value);
}
</code></pre>
<p><strong>C# code</strong></p>
<pre><code>String qstr = "accom=" + getValFromLiId(accomodationAnswer.Value) + "&sleeps=" + getValFromLiId(sleepsAnswer.Value) + "&nights=" + getValFromLiId(nightsAnswer.Value) + "&region=" +
getValFromLiId(regionAnswer.Value) + "&price=" + Utilities.removeCurrencyFormatting(priceAnswer.Value);
</code></pre>
|
<p>I would do this: First, remove the <code>runat='server'</code> attribute from the hidden field (inside body):</p>
<pre><code><input type="hidden" id="accomodationAnswer" />
</code></pre>
<p>Now, on the server, where you want to read that value, do this:</p>
<pre><code>string accomodationAnswer = Request.Form["accomodationAnswer"];
// now use accomodationAnswer instead of accomodationAnswer.Value
// in the C# code that you indicated you are using
</code></pre>
<p>That should do it.</p>
|
<p>Try this</p>
<p>if you are using .net 4.0 then in page header.</p>
<p>Language="C#" AutoEventWireup="true" CodeFile="Page.cs" Inherits="Page"</p>
<p>Alongwith this write:</p>
<pre><code>ClientIDMode="Static"
</code></pre>
<p>It helps in not changing the server side control id at runtime</p>
<p>Now</p>
<p></p>
<p>Set the value in javascript as </p>
<p>document.getElementById("hiddenField").value = "Vallue";</p>
<p>And access in codebehind like below.</p>
<p>string hiddenVallue=hiddenField.Value.ToString();</p>
| 42,964
|
<p>What is the best way to implement connection pooling in hsqldb, without compromising on the speed?</p>
|
<p>Hibernate gets connections from a <code>DataSource</code>, uses them and closes them. You need a connection pool or it will be very inefficient, consuming a lot of resources both on your app and on the DBMS, regardless of the database server you use.</p>
<p>You should try out <em>commons-dbcp</em> from Apache-Jakarta, it's very efficient and really simple to set up. It depends on <em>commons-pool</em>.
You just define a <code>BasicDataSource</code> with DBCP and it will manage the connections from whatever JDBC driver you tell it to use. It has connection validation and lots of other stuff.
Of, if you're writing a web app, configure a connection pool on the container you will be using and use that, instead of defining your own pool.</p>
|
<p>If you used Hibernate's own connection pooler, you could consider using <a href="http://sourceforge.net/projects/c3p0" rel="nofollow noreferrer">c3p0</a>? (If you're already using c3p0, I can't help further) I haven't used HSQLDB myself but I think that could be worth trying.</p>
| 33,221
|
<p>How do I make it so <code>mailto:</code> links will be registered with my program?</p>
<p>How would I then handle that event in my program?</p>
<p>Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client".</p>
<p>#Edit:
Removed reference to Delphi, because the answer is independent of your language.</p>
|
<p><em>@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this.</em></p>
<p>The solution to this question really doesn't depend on what programming language you're using, as long as there's some way to modify Windows registry settings.</p>
<p>Finally, here's the answer:</p>
<ul>
<li>To associate a program with the mailto protocol for <strong>all users</strong> on a computer, change the HKEY_CLASSES_ROOT\mailto\shell\open\command Default value to:<br />
"<em>Your program's executable</em>" "%1"</li>
<li>To <a href="http://windowsxp.mvps.org/permail.htm" rel="nofollow noreferrer">associate a program with the mailto protocol for the <strong>current user</strong></a>, change the HKEY_CURRENT_USER\Software\Classes\mailto\shell\open\command Default value to:<br />
"<em>Your program's executable</em>" "%1"</li>
</ul>
<p>The %1 will be replaced with the entire mailto URL. For example, given the link:</p>
<pre><code><a href="mailto:user@example.com">Email me</a>
</code></pre>
<p>The following will be executed:<br />
"<em>Your program's executable</em>" "mailto:user@example.com"</p>
<p>Update (via comment by shellscape):<br />
As of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\URLAssociations\MAILTO\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA.</p>
|
<p>From what I've seen, there are a few registry keys that set the default mail client. One of them is:</p>
<p>System Key: <code>[HKEY_CLASSES_ROOT\mailto\shell\open\command]</code></p>
<p>Value Name: <code>(Default)</code></p>
<p>Data Type: <code>REG_SZ</code> (String Value)</p>
<p>Value Data: <code>Mail program command-line</code>.</p>
<p>I'm not familiar with <code>Delphi 7</code>, but I'm sure there are some <em>registry editing libraries</em> there that you could use to modify this value.</p>
<p>Some places list more than this <em>key</em>, others just this key, so you may need to test a little bit to find the proper one(s).</p>
| 2,272
|
<p>Background: In my job, we use SVN, C# and VisualStudio. Part of my task regularly involves global renames. Often I end up with a broken build after renaming something and then merging in changes.</p>
<p>The question: is there a solution out there that can look at my changes, notice the global rename and then apply that to the edit that others have made while merging them in?</p>
<p>Another way to get much the same effect would be some sort of refactor log and then apply that to the incoming edits.</p>
<p>The tool need not be perfect, even if it just noted any references in their edits that referred to something that I have edited would be valuable.</p>
<p><strong>Edit</strong> I'm aware of VS's refactor tools. What I'm looking for is something that will allow me to, after I have refactored my working copy, apply the same refactorings to other peoples edits that I now need to merge in.</p>
<p>The ideal solution would be to make sure there are no outstanding edits when I do the refactoring, but that would prevent anyone else from getting anything done for the next week or more. (Because they would have to sync every half hour or so for the next week)</p>
|
<p>There is a commercial tool for exactly that use case called <a href="https://www.semanticmerge.com/" rel="nofollow noreferrer">Semantic Merge</a>. They provide a 15-day free trial, open source projects may use it for free (<a href="https://users.semanticmerge.com/Checkout" rel="nofollow noreferrer">contact the support</a>). </p>
<p>The company behind semantic merge also has <a href="https://gmaster.io/" rel="nofollow noreferrer">a git client with integrated Sematic Merge</a> which is currently beta (here, have some <a href="https://gmaster.io/installer/pc75e0090f5c14ddf8b448d0c1ea4a0b6" rel="nofollow noreferrer">short intro videos</a>).</p>
|
<p>Assuming at least VS 2005 and the global rename is a variable/property/function, there is a Refactor - Rename right-click menu option you could use. By design it propagates the name change in your entire solution.</p>
| 16,368
|
<p>Many languages have standard repositories where people donate useful libraries that they want others to have access to. For instance Perl has CPAN, PHP has PEAR, Ruby has RubyGems, and so on. What is the best option for JavaScript?</p>
<p>I ask because a few months ago I ported <a href="http://search.cpan.org/~mikek/Statistics-Distributions-1.02/Distributions.pm" rel="noreferrer">Statistics::Distributions</a> from Perl to JavaScript. (When I say ported I mean, "Ran text substitutions, fixed a few things by hand." I did <em>not</em> rewrite it.) Since I've used this module a number of times in Perl, I figure that <a href="http://elem.com/~btilly/effective-ab-testing/statistics-distributions.js" rel="noreferrer">statistics-distributions.js</a> is likely to be useful to someone. So I've put it under the same open source license as the original (your choice of the GPL or the Artistic License). But I have no idea where to put it so that people who might want it are likely to find it.</p>
<p>It doesn't fit into any sort of framework. It is just a standalone library that gives you the ability to calculate a number of useful statistics distributions to 5 digits of accuracy. In JavaScript.</p>
|
<p>AFAIK, there is no central JavaScript repository, but you might have success promoting it on <a href="http://snipplr.com/" rel="nofollow noreferrer">Snipplr</a> or as a project on <a href="http://code.google.com/" rel="nofollow noreferrer">Google Code</a>.</p>
|
<p>You could start a project on SourceForge to contain useful snippets of code like this (or google for snippets to find one).</p>
| 12,498
|
<p>I need to pause for maybe 500 miliseconds before I submit a form. Here is what I have so far:</p>
<pre><code> $(".rowqty input").bind("keyup", function() { $("#ViewCartPage form").animate({ opacity: 1.0 }, 3000).submit() });
</code></pre>
<p>so when someone changes the quantity of the input field it submits the form, but I want it to wait for a slight amount of time incase they need a moment to type 2 or 3 numbers. </p>
<p>As you can see I tried the animate function to try and delay things but with no luck.</p>
<p>I know I could use this: <a href="http://blog.mythin.net/projects/jquery.php" rel="nofollow noreferrer">http://blog.mythin.net/projects/jquery.php</a></p>
<p>I'd rather not add another JS to my site if there is a way around it.</p>
<p>EDIT: Actually the pause plugin above is not working for me either.</p>
|
<p>Give this a shot:</p>
<pre><code>$(".rowqty input").bind("keyup", function() { setTimeout("$('#ViewCartPage form').submit()", 500 });
</code></pre>
|
<pre><code>setTimeout(function () {$("#formID").submit()},1000);
</code></pre>
<p>it works for me (no quotes)</p>
| 33,228
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.