instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>In php, how can I get the number of apache children that are currently available <br>(<code>status = SERVER_READY</code> in the apache scoreboard)?</p>
<p>I'm really hoping there is a simple way to do this in php that I am missing.</p>
|
<p>You could execute a shell command of <code>ps aux | grep httpd</code> or <code>ps aux | grep apache</code> and count the number of lines in the output.</p>
<pre><code>exec('ps aux | grep apache', $output);
$processes = count($output);
</code></pre>
<p>I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.</p>
|
<p>If you have access to the Apache server status page, try using the ?auto flag:</p>
<p><a href="http://yourserver/server-status?auto" rel="nofollow noreferrer">http://yourserver/server-status?auto</a></p>
<p>The output is a machine-readable version of the status page. I <em>believe</em> you are looking for "IdleWorkers". Here's some simple PHP5 code to get you started. In real life you'd probably want to use cURL or a socket connection to initiate a timeout in case the server is offline.</p>
<pre><code><?php
$status = file('http://yourserver/server-status?auto');
foreach ($status as $line) {
if (substr($line, 0, 10) == 'IdleWorkers') {
$idle_workers = trim(substr($line, 12));
print $idle_workers;
break;
}
}
?>
</code></pre>
| 9,338
|
<p>In our game project we did have a timer loop set to fire about 20 times a second (the same as the application framerate). We use this to move some sprites around.
I'm wondering if this could cause problems and we should instead do our updates using an EnterFrame event handler?
I get the impression that having a timer loop run faster than the application framerate is likely to cause problems... is this the case?</p>
<p>As an update, trying to do it on EnterFrame caused very weird problems. Instead of a frame every 75ms, suddenly it jumped to 25ms. Note, it wasn't just our calculation <em>claimed</em> the framerate was different, suddenly the animations sped up to a crazy rate.</p>
|
<p>I'd go for the Enter frame, in some special cases it can be useful to have two "loops" one for logic and one for the visuals, but for most games I make I stick to the Enter frame-event listener. Having a separate timer for moving your stuff around is a bit unnecessary since having it set to anything except the framerate would make the motion either jerky or just not visible (since the frame is not redrawn). </p>
<p>One thing to consider however is to decouple your logic from the framerate, this is most easily accomplished by using getTimer (available in both as2 and as3) to calculate the time that has expired since the last frame and adjusting the motions or whatever accordingly. </p>
<p>A timer is no more reliable than the enter frame event, flash will try to keep up with whatever rate you've set, but if you're doing heavy processing or complex graphics it will slow down, both timers and framerate. </p>
|
<p>I think timerEvent and Enter Frame are both good options, I have used both of them in my games. ( Did you mean timerEvent by timer loop? )</p>
<p>PS: notice that in slow machines the timer may not refresh quick enough, so you may need to adjust your code to make game work "faster" in slow machines.</p>
| 15,375
|
<p>I have a pretty simple app on the web (written in Flex) which is very straightforward to use once it has data inside it. The steps to get data inside it are themselves also pretty simple, but not at all obvious to my audience when they first log into my app. </p>
<p>I have been wrestling with how to communicate the data setup process to my users without referring them to a separate help. I also don't want to clog my lovely, elegant UI (which has uniformly been praised for its clarity from my current users and matches their processes very well) with wizards, or worse still an annoying animated paperclip.</p>
<p>I have a very rich set of tools available for the web UI but I am looking for inspiration and wondered if anyone had experienced good web-based, intuitive, unobtrusive, genuinely helpful process/usage instructions embedded in an application and could point me to a link so I can take a look for myself.</p>
<p>Failing that anyone got any bright ideas? There are about 5 steps involved each one visiting a different page of the existing app to enter/upload data.</p>
|
<p>Have you taken a look at:
<a href="http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html" rel="nofollow noreferrer">http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html</a></p>
<p>I believe there is a jquery or prototype or mootools or whatever framework that goes a couple steps beyond the above and walks a user through what to do. My google-fu isn't coming through right now so I can't seem to find it.</p>
|
<p>You could display the links to the data setup pages in a small strip on your main page like this (pardon the ugliness - this is just a usability idea):</p>
<p><a href="http://www.freeimagehosting.net/uploads/052b13acb7.jpg" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/052b13acb7.jpg</a></p>
<p>The steps they've already completed are greyed out (I assume they don't have to complete these steps in sequence). When they mouse over a step they get a brief description, and then full details when they click through to the actual step page. You could have descriptive icons for each step instead of hyperlinks, of course.</p>
| 41,227
|
<p>I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so.</p>
<p>If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0.</p>
<p>Is there a way to bypass this behaviour and get true Windows version?</p>
|
<p>The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports <a href="http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx" rel="noreferrer">GetLocaleInfoEx</a> from kernel32.dll while previous Windowses didn't.</p>
<p>To cut the long story short, here is one such list containing only exports from kernel32.dll.</p>
<pre>
> *function: implemented in*
> GetLocaleInfoEx: Vista
> GetLargePageMinimum: Vista, Server 2003
GetDLLDirectory: Vista, Server 2003, XP SP1
GetNativeSystemInfo: Vista, Server 2003, XP SP1, XP
ReplaceFile: Vista, Server 2003, XP SP1, XP, 2000
OpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME
GetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4
IsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98
GetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2
ConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3
Beep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95
</pre>
<p>Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use <a href="http://msdn.microsoft.com/en-us/library/ms683212.aspx" rel="noreferrer">GetProcAddress</a> to check exported APIs. Implementing this in any language should be trivial.</p>
<p>The following code in Delphi was extracted from the free <a href="http://gp.17slon.com/gp/dsiwin32.htm" rel="noreferrer">DSiWin32</a> library):</p>
<pre><code>TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98,
wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP,
wvWinNT, wvWinServer2003, wvWinVista);
function DSiGetWindowsVersion: TDSiWindowsVersion;
var
versionInfo: TOSVersionInfo;
begin
versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo);
GetVersionEx(versionInfo);
Result := wvUnknown;
case versionInfo.dwPlatformID of
VER_PLATFORM_WIN32s: Result := wvWin31;
VER_PLATFORM_WIN32_WINDOWS:
case versionInfo.dwMinorVersion of
0:
if Trim(versionInfo.szCSDVersion[1]) = 'B' then
Result := wvWin95OSR2
else
Result := wvWin95;
10:
if Trim(versionInfo.szCSDVersion[1]) = 'A' then
Result := wvWin98SE
else
Result := wvWin98;
90:
if (versionInfo.dwBuildNumber = 73010104) then
Result := wvWinME;
else
Result := wvWin9x;
end; //case versionInfo.dwMinorVersion
VER_PLATFORM_WIN32_NT:
case versionInfo.dwMajorVersion of
3: Result := wvWinNT3;
4: Result := wvWinNT4;
5:
case versionInfo.dwMinorVersion of
0: Result := wvWin2000;
1: Result := wvWinXP;
2: Result := wvWinServer2003;
else Result := wvWinNT
end; //case versionInfo.dwMinorVersion
6: Result := wvWinVista;
end; //case versionInfo.dwMajorVersion
end; //versionInfo.dwPlatformID
end; { DSiGetWindowsVersion }
function DSiGetTrueWindowsVersion: TDSiWindowsVersion;
function ExportsAPI(module: HMODULE; const apiName: string): boolean;
begin
Result := GetProcAddress(module, PChar(apiName)) <> nil;
end; { ExportsAPI }
var
hKernel32: HMODULE;
begin { DSiGetTrueWindowsVersion }
hKernel32 := GetModuleHandle('kernel32');
Win32Check(hKernel32 <> 0);
if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then
Result := wvWinVista
else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then
Result := wvWinServer2003
else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then
Result := wvWinXP
else if ExportsAPI(hKernel32, 'ReplaceFile') then
Result := wvWin2000
else if ExportsAPI(hKernel32, 'OpenThread') then
Result := wvWinME
else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then
Result := wvWinNT4
else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4!
Result := wvWin98
else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4!
Result := wvWin95OSR2
else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then
Result := wvWinNT3
else if ExportsAPI(hKernel32, 'Beep') then
Result := wvWin95
else // we have no idea
Result := DSiGetWindowsVersion;
end; { DSiGetTrueWindowsVersion }
</code></pre>
<p>--- updated 2009-10-09</p>
<p>It turns out that it gets very hard to do an "undocumented" OS detection on Vista SP1 and higher. A look at the <a href="http://msdn.microsoft.com/en-us/library/aa383687(VS.85).aspx" rel="noreferrer">API changes</a> shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :(</p>
<p>--- end of update</p>
<p>FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.)</p>
<p>We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article!</p>
<p>If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ...</p>
|
<p><strong>Note:</strong> Gabr is asking about an approach that can bypass the limitations of <code>GetVersionEx</code>. JCL code uses GetVersionEx, and is thus subject to compatibility layer. This information is for people who don't need to bypass the compatibility layer, only.</p>
<p>Using the Jedi JCL, you can add unit JclSysInfo, and call function <code>GetWindowsVersion</code>. It returns an enumerated type TWindowsVersion.</p>
<p>Currently JCL contains all shipped windows versions, and gets changed each time Microsoft ships a new version of Windows in a box:</p>
<pre><code> TWindowsVersion =
(wvUnknown, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME,
wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4, wvWin2000, wvWinXP,
wvWin2003, wvWinXP64, wvWin2003R2, wvWinVista, wvWinServer2008,
wvWin7, wvWinServer2008R2);
</code></pre>
<p>If you want to know if you're running 64-bit windows 7 instead of 32-bit, then call <code>JclSysInfo.IsWindows64</code>.</p>
<p>Note that JCL allso handles Editions, like Pro, Ultimate, etc. For that call GetWindowsEdition, and it returns one of these:</p>
<pre><code>TWindowsEdition =
(weUnknown, weWinXPHome, weWinXPPro, weWinXPHomeN, weWinXPProN, weWinXPHomeK,
weWinXPProK, weWinXPHomeKN, weWinXPProKN, weWinXPStarter, weWinXPMediaCenter,
weWinXPTablet, weWinVistaStarter, weWinVistaHomeBasic, weWinVistaHomeBasicN,
weWinVistaHomePremium, weWinVistaBusiness, weWinVistaBusinessN,
weWinVistaEnterprise, weWinVistaUltimate, weWin7Starter, weWin7HomeBasic,
weWin7HomePremium, weWin7Professional, weWin7Enterprise, weWin7Ultimate);
</code></pre>
<p>For historical interest, you can check the NT-level edition too with the NtProductType function, it returns:</p>
<pre><code> TNtProductType = (ptUnknown, ptWorkStation, ptServer, ptAdvancedServer,
ptPersonal, ptProfessional, ptDatacenterServer,
ptEnterprise, ptWebEdition);
</code></pre>
<p>Note that "N editions" are detected above. That's an EU (Europe) version of Windows, created due to EU anti-trust regulations. That's a pretty fine gradation of detection inside the JCL.</p>
<p>Here's a sample function that will help you detect Vista, and do something special when on Vista.</p>
<pre><code>function IsSupported:Boolean;
begin
case GetWindowsVersion of
wvVista: result := false;
else
result := true;
end;
end;
</code></pre>
<p>Note that if you want to do "greater than" checking, then you should just use other techniques. Also note that version checking can often be a source of future breakage. I have usually chosen to warn users and continue, so that my binary code doesn't become the actual source of breakage in the future.</p>
<p>Recently I tried to install an app, and the installer checked my drive free space, and would not install, because I had more than 2 gigabytes of free space. The 32 bit integer signed value in the installer became negative, breaking the installer. I had to install it into a VM to get it to work. Adding "smart code" often makes your app "stupider". Be wary.</p>
<p>Incidentally, I found that from the command line, you can run WMIC.exe, and type <code>path Win32_OperatingSystem</code> (The "Select * from Win32_OperatingSystem" didn't work for me). In future perhaps JCL could be extended to use the WMI information.</p>
| 8,131
|
<p>So i have a piece of assembly that needs to call a function with the fastcall calling convention on windows, but gcc doesn't (afaict) support it. GCC does provide the regparm attribute but that expects the first 3 parameters to be passed in eax, edx and ecx, whereas fastcall expects the first two parameters to be passed in ecx and edx.</p>
<p>I'm merely trying to avoid effectively duplicating a few code paths, so this isn't exactly critical, but it would be great if it were avoidable.</p>
|
<p>GCC does support <code>fastcall</code>, via <code>__attribute__((fastcall))</code>. It appears to have been introduced in GCC 3.4.</p>
|
<p>If you're calling the function from asm then surely you have complete control over how you call the function. What's stopping you from just loading up the registers and issuing a <code>CALL</code>?</p>
| 19,993
|
<p>We may tag a question with multiple tags in StackOverflow website, I'm wondering how to find out the most related questions with common tags.</p>
<p>Assume we have 100 questions in a database, each question has several tags. Let's say user is browsing a specific question, and we want to make the system to display the related questions on the page. The criteria for related question is they have most common tags.</p>
<p>For example:
Question 1 is tagged with AAA, BBB, CCC, DDD, EEE.</p>
<p>Question 2 is top 1 related because it also has all those 5 tags.
Question 3 is top 2 related because it has only 4 or 3 tags that Questio1 has.
......</p>
<p>So my question is how to design the database and find out the questions that's related to Question 1 quickly. Thank you very much.</p>
|
<p>Perhaps something like:</p>
<pre><code>select qt.question_id, count(*)
from question_tags qt
where qt.tag in
( select qt2.tag
from question_tags qt2
where qt2.question_id = 123
)
group by qt.question_id
order by 2 desc
</code></pre>
|
<p>Not entirely sure what you mean, but <a href="https://stackoverflow.com/tags">the Tags page</a> lists tags in order of popularity (as in amount tagged).</p>
<p><strong>Edit:</strong> is this about SO or about your own application? If it is about your own app, remove the SO tag as it's kind of misleading.</p>
<p><strong>Edit2:</strong> I'd say something like:</p>
<pre><code>SELECT * FROM `questions` WHERE `tag` LIKE '%tagname%' OR (looped for each tag) LIMIT 5,0
</code></pre>
<p>Where 5 is the maximum results you want to return (for at least some optimisation). Probably not the best solution, but I could see it working. </p>
<p>You might also want to try a <code>LIKE</code> match using the title.</p>
| 30,645
|
<p>I tried the following code in LINQPad and got the results given below:</p>
<pre><code>List<string> listFromSplit = new List<string>("a, b".Split(",".ToCharArray())).Dump();
listFromSplit.ForEach(delegate(string s)
{
s.Trim();
});
listFromSplit.Dump();
</code></pre>
<blockquote>
<p>"a" and " b"</p>
</blockquote>
<p>so the letter b didn't get the white-space removed as I was expecting...?</p>
<p>Anyone have any ideas</p>
<p>[NOTE: the .Dump() method is an extension menthod in LINQPad that prints out the contents of any object in a nice intelligently formatted way]</p>
|
<p>you're just creating a trimmed string, not assigning anything to it.</p>
<pre><code>var s = " asd ";
s.Trim();
</code></pre>
<p>won't update s, while..</p>
<pre><code>var s = " asd ";
s = s.Trim();
</code></pre>
<p>will.. </p>
<pre><code>var listFromSplit = "a, b".Split(',').Select(s=>s.Trim());
</code></pre>
<p>would, i suppose, be how i'd go about it.</p>
|
<p>Split on both spaces and commas and remove any empty entries. All nice and trimmed. Assumes that your strings don't contain spaces, though.</p>
<pre><code>List<string> listFromSplit =
new List<string>( "a , b ".Split( new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries ));
</code></pre>
| 25,154
|
<p>Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.</p>
<p>Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky...</p>
|
<p>I've never come across a tool that would do the job. Instead I've used individual files, numbered so that I know which order to run them: essentially, a manual version of Rails migrations, but without the rollback.</p>
<p>Here's the sort of thing I'm talking about:</p>
<pre><code>000-clean.sql # wipe out everything in the DB
001-schema.sql # create the initial DB objects
002-fk.sql # apply referential integrity (simple if kept separate)
003-reference-pop.sql # populate reference data
004-release-pop.sql # populate release data
005-add-new-table.sql # modification
006-rename-table.sql # another modification...
</code></pre>
<p>I've never actually run into any problems doing this, but it's not very elegant. It's up to you to track which scripts need to run for a given update (a smarter numbering scheme could help). It also works fine with source control.</p>
<p>Dealing with surrogate key values (from autonumber columns) can be a pain, since the production database will likely have different values than the development DB. So, I try never to reference a literal surrogate key value in any of my modification scripts if at all possible.</p>
|
<p>I've always preferred to keep my development site pointing to the same DB as the live site. This may sound risky at first but in reality it solves many problems. If you have two sites on the same server pointing to the same DB, you get a real time and accurate view of what your users will see when it goes live. </p>
<p>You will only ever have 1 database and so long as you make it a policy to never delete a column from a table, you know your new code will match up with the database you are using.</p>
<p>There is also significantly less havoc when migrating. You only need to move over the PHP scripts and they are already tested using the same DB.</p>
<p>I also tend to create a symlink to any folder that is a target for user uploads. This means there is no confusion on which user files have been updated.</p>
<p>Another side affect is the option of porting over a small group of 'beta-testers' to use the site in everyday use. This can lead to a lot of feedback that you can implement <em>before</em> the public launch.</p>
<p>This may not work in all cases but I've started moving all my updates to this model. It's caused much smoother development and launches.</p>
| 5,548
|
<p>I have a requirement to produce a Web User Control (in C#) which will exhibit different behaviour when clicked depending on whether the shift (or control) key is pressed at the time. The control itself will contain an ImageButton and/or Hyperlink.</p>
<p>Is this possible?</p>
<p>Basically, if the logged in user is an Admin then I need to allow them access to update the associated URL. I don't want to have a separate page for this admin as it will cause confusion.</p>
<p>Thanks in advance</p>
|
<p>How about <a href="http://www.javascripter.net/faq/ctrl_alt.htm" rel="nofollow noreferrer">here</a>?</p>
<p>To implement the <kbd>Ctrl</kbd> / <kbd>Alt</kbd> / <kbd>Shift</kbd> detection, you can use the properties <code>event.ctrlKey</code>, <code>event.altKey</code>, <code>event.shiftKey</code> and the deprecated Navigator-specific property <code>event.modifiers</code>.</p>
|
<p>Well the 'powers' have decided that the Shift/Ctrl + Click approach was too clunky. </p>
<p>After a brainstorming session we have decided to go down the route of displaying a small 'Edit' button next to the control. This will only be visible for Administrator users and I've pulled it together in about two hours.</p>
<p>Thanks for taking the time to provide your input.</p>
<p>Can someone with a high rep please close this question for me - thanks.</p>
| 31,350
|
<p>Is there a way to enable STRICT_ALL_TABLES for a single MySQL database?</p>
|
<p>set sql_mode = 'STRICT_ALL_TABLES'; will do it.</p>
|
<p>Don't think you can do this directly but you might get close with setting Strict for the current session when working on a particular database. Could do this in the config files of specific users. </p>
| 19,932
|
<p>Essentially i want to have a generic function which accepts a LINQ anonymous list and returns an array back. I was hoping to use generics but i just can seem to get it to work.</p>
<p>hopefully the example below helps</p>
<p>say i have a person object with id, fname, lname and dob.
i have a generic class with contains a list of objects.</p>
<p>i return an array of persons back</p>
<p>my code snippet will be something like</p>
<pre><code>dim v = from p in persons.. select p.fname,p.lname
</code></pre>
<p>i now have an anonymous type from system.collections.generic.ineumerable(of t)</p>
<p>to bind this to a grid i would have to iterate and add to an array
e.g.</p>
<pre><code>dim ar() as array
for each x in v
ar.add(x)
next
grid.datasource = ar
</code></pre>
<p>i dont want to do the iteration continually as i might have different objects</p>
<p>i would like a function which does something like below:</p>
<pre><code>function getArrayList(of T)(dim x as T) as array()
dim ar() as array
for each x in t
ar.add(x)
next
return ar
end
</code></pre>
<p>hope that clarifies. how can i get a generic function with accepts an anonymous list of ienumearable and returns an array back.
unfortunately, the one i have does not work.</p>
<p>many thanks in advance as any and all pointers/help will be VASTLY appreciated.</p>
<p>regards</p>
<p>azad</p>
|
<p>You'd just call <a href="http://msdn.microsoft.com/en-us/library/bb298736.aspx" rel="nofollow noreferrer">ToArray</a>. Sure, the type is anonymous... but because of type inference, you don't have to say the type's name.</p>
<p>From the example code:</p>
<pre><code> packages _
.Select(Function(pkg) pkg.Company) _
.ToArray()
</code></pre>
<p>Company happens to be string, but there's no reason it couldn't be anything else.</p>
|
<p>I'm not sure that you can easily pass anonymous objects as parameters, anymore than you can have them as return values.</p>
<p>I say easily, because:</p>
<ul>
<li><a href="http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx" rel="nofollow noreferrer">http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx</a></li>
<li><a href="http://blog.decarufel.net/2007/11/passing-anonymous-to-and-from-methods.html" rel="nofollow noreferrer">http://blog.decarufel.net/2007/11/passing-anonymous-to-and-from-methods.html</a></li>
</ul>
<p><em>[Try the code formatting option on your question (the " button in the editor), it would make it easier to read the parts of your question which are code snippets.]</em></p>
| 42,136
|
<p>I would like to execute the jQuery $(document).ready() in a drupal site. While i know that i can just stick it in the index page , this is really messy and a hack. </p>
<p>What i want to know is where is the correct location to put this, it would also need to be theme specific as i dont want all themes to use it.</p>
<p>Thanks in advance for the help. </p>
<hr>
<p>Sweet success , thanks both of you for the help , i just have one last amend to this question. Now that i have got this far , i need to execute the jQuery code to update the document , can i use the context to modify the document ? </p>
|
<p>Not a Drupal specialist, but this <a href="http://raincitystudios.com/blogs-and-pods/katherine-bailey/the-lowdown-jquery-drupal-part-two" rel="noreferrer">blog entry</a> suggest that, as of Drupal 6, you don't need to include the <code>$(document).ready()</code> function in our jQuery code at all. </p>
<p>Instead you could put all the code inside a function that you assign as a property of <code>Drupal.behaviors</code>.</p>
<blockquote>
<p>In the <code>misc/ directory</code> of the Drupal install, we not only have the jquery.js file but we also have drupal.js (and several other js files, controlling functionality specific to certain pages or admin features, e.g. upload.js), which governs the general use of jQuery in Drupal. </p>
<p>It declares the Drupal JavaScript object for the purpose of containing properties that need to be accessed and used by other js files. For example, the Drupal.settings property is used for passing an array of module settings to the js code for that module. You do this simply by calling drupal_add_js() in your php code and making sure the second parameter is passed in as "setting", e.g.: </p>
</blockquote>
<pre><code>drupal_add_js(array('mymodule' => $array_of_settings), 'setting');
</code></pre>
<blockquote>
<p>In your js file, then, you can access these settings at Drupal.settings.mymodule. You have thus extended the Drupal.settings object with the mymodule property, which is itself an object containing all your settings.</p>
<p>Another property of the Drupal object is the behaviors object, i.e. <code>Drupal.behaviors</code>, and when we want our module to add new jQuery behaviours, we simply extend this object. The entire jQuery code for your module could be structured like this: </p>
</blockquote>
<pre><code>Drupal.behaviors.myModuleBehavior = function (context)
{
//do some fancy stuff
};
</code></pre>
<blockquote>
<p>But, you may wonder, all that does is declare a function - how does it even get called? Well, <strong>that's all looked after in drupal.js. It has a <code>$(document).ready</code> function which calls the <code>Drupal.attachBehaviors</code> function, which in turn cycles through the <code>Drupal.behaviors</code> object calling every one of its properties, these all being functions declared by various modules as above, and passing in the document as the context</strong>. </p>
<p>The reason for doing it this way is that if your jQuery code makes AJAX calls which result in new DOM elements being added to the page, you might want your behaviors (e.g. hiding all h3 elements or whatever) to be attached to that new content as well. But since it didn't exist when the DOM was loaded and <code>Drupal.attachBehaviors</code> ran it doesn't have any behaviors attached. With the above set-up, though, all you need to do is call <code>Drupal.behaviors.myModuleBehavior(newcontext)</code>, where <code>newcontext</code> would be the new, AJAX-delivered content, thus ensuring that the behaviors don't get attached to the whole document all over again. See here for the full example of how to use this code</p>
</blockquote>
|
<p>Not a Drupal specialist, but this <a href="http://raincitystudios.com/blogs-and-pods/katherine-bailey/the-lowdown-jquery-drupal-part-two" rel="noreferrer">blog entry</a> suggest that, as of Drupal 6, you don't need to include the <code>$(document).ready()</code> function in our jQuery code at all. </p>
<p>Instead you could put all the code inside a function that you assign as a property of <code>Drupal.behaviors</code>.</p>
<blockquote>
<p>In the <code>misc/ directory</code> of the Drupal install, we not only have the jquery.js file but we also have drupal.js (and several other js files, controlling functionality specific to certain pages or admin features, e.g. upload.js), which governs the general use of jQuery in Drupal. </p>
<p>It declares the Drupal JavaScript object for the purpose of containing properties that need to be accessed and used by other js files. For example, the Drupal.settings property is used for passing an array of module settings to the js code for that module. You do this simply by calling drupal_add_js() in your php code and making sure the second parameter is passed in as "setting", e.g.: </p>
</blockquote>
<pre><code>drupal_add_js(array('mymodule' => $array_of_settings), 'setting');
</code></pre>
<blockquote>
<p>In your js file, then, you can access these settings at Drupal.settings.mymodule. You have thus extended the Drupal.settings object with the mymodule property, which is itself an object containing all your settings.</p>
<p>Another property of the Drupal object is the behaviors object, i.e. <code>Drupal.behaviors</code>, and when we want our module to add new jQuery behaviours, we simply extend this object. The entire jQuery code for your module could be structured like this: </p>
</blockquote>
<pre><code>Drupal.behaviors.myModuleBehavior = function (context)
{
//do some fancy stuff
};
</code></pre>
<blockquote>
<p>But, you may wonder, all that does is declare a function - how does it even get called? Well, <strong>that's all looked after in drupal.js. It has a <code>$(document).ready</code> function which calls the <code>Drupal.attachBehaviors</code> function, which in turn cycles through the <code>Drupal.behaviors</code> object calling every one of its properties, these all being functions declared by various modules as above, and passing in the document as the context</strong>. </p>
<p>The reason for doing it this way is that if your jQuery code makes AJAX calls which result in new DOM elements being added to the page, you might want your behaviors (e.g. hiding all h3 elements or whatever) to be attached to that new content as well. But since it didn't exist when the DOM was loaded and <code>Drupal.attachBehaviors</code> ran it doesn't have any behaviors attached. With the above set-up, though, all you need to do is call <code>Drupal.behaviors.myModuleBehavior(newcontext)</code>, where <code>newcontext</code> would be the new, AJAX-delivered content, thus ensuring that the behaviors don't get attached to the whole document all over again. See here for the full example of how to use this code</p>
</blockquote>
| 47,992
|
<p>What implementations of the <a href="http://en.wikipedia.org/wiki/Prototype_pattern" rel="nofollow noreferrer">Prototype</a> Pattern exist on the Java platform?</p>
<blockquote>
<p>A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. </p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="nofollow noreferrer">Prototype based programming</a>:</p>
<blockquote>
<p>Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. </p>
</blockquote>
<p>The implementation should be aware that some Java objects are mutable, and some are immutable (see <a href="https://stackoverflow.com/questions/214714/mutable-vs-immutable-objects">Mutable vs Immutable objects</a>).</p>
|
<p>According to Josh Bloch and Doug Lea, <a href="http://www.artima.com/intv/bloch13.html" rel="nofollow noreferrer">Cloneable is broken</a>. In that case, you can use a <a href="http://www.javapractices.com/topic/TopicAction.do?Id=12" rel="nofollow noreferrer">copy constructor</a>.</p>
|
<p>Java defines the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html" rel="nofollow noreferrer">Cloneable</a> interface, described here at <a href="http://www.jguru.com/faq/view.jsp?EID=255004" rel="nofollow noreferrer">JGuru</a></p>
<blockquote>
<p>Java provides a simple interface named Cloneable that provides an implementation of the Prototype pattern. If you have an object that is Cloneable, you can call its clone() method to create a new instance of the object with the same values.</p>
</blockquote>
<p>Warning: see <a href="http://www.artima.com/intv/bloch13.html" rel="nofollow noreferrer">Cloneable is broken</a></p>
| 28,358
|
<p>I'd like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or explicitly by parameters, either way is good) and saves me looking up constructors every time I want to do this. All of the above is preferably in C, although I could translate it from C++ at need.</p>
<p>Does anyone on SO have something like this that they can share?</p>
|
<p>We just code utility methods for each of the types of exceptions we want to throw. Here are some examples:</p>
<pre><code>jint throwNoClassDefError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/NoClassDefFoundError";
exClass = (*env)->FindClass( env, className);
if (exClass == NULL) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
jint throwNoSuchMethodError(
JNIEnv *env, char *className, char *methodName, char *signature )
{
jclass exClass;
char *exClassName = "java/lang/NoSuchMethodError" ;
LPTSTR msgBuf;
jint retCode;
size_t nMallocSize;
exClass = (*env)->FindClass( env, exClassName );
if ( exClass == NULL ) {
return throwNoClassDefError( env, exClassName );
}
nMallocSize = strlen(className)
+ strlen(methodName)
+ strlen(signature) + 8;
msgBuf = malloc( nMallocSize );
if ( msgBuf == NULL ) {
return throwOutOfMemoryError
( env, "throwNoSuchMethodError: allocating msgBuf" );
}
memset( msgBuf, 0, nMallocSize );
strcpy( msgBuf, className );
strcat( msgBuf, "." );
strcat( msgBuf, methodName );
strcat( msgBuf, "." );
strcat( msgBuf, signature );
retCode = (*env)->ThrowNew( env, exClass, msgBuf );
free ( msgBuf );
return retCode;
}
jint throwNoSuchFieldError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/NoSuchFieldError" ;
exClass = (*env)->FindClass( env, className );
if ( exClass == NULL ) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
jint throwOutOfMemoryError( JNIEnv *env, char *message )
{
jclass exClass;
char *className = "java/lang/OutOfMemoryError" ;
exClass = (*env)->FindClass( env, className );
if ( exClass == NULL ) {
return throwNoClassDefError( env, className );
}
return (*env)->ThrowNew( env, exClass, message );
}
</code></pre>
<p>That way, it's easy to find them, your code-completion editor will help you to type them in, and you can pass simple parameters.</p>
<p>I'm sure you could expand this to handle chained exceptions, or other more complicated approaches. This was enough to meet our needs.</p>
|
<p>I will put a more complete and general answer for who need a little bit more explanations like I need before.</p>
<p>First is nice to set your method with a <code>Throw Exception</code> so the IDE will ask for try/catch.</p>
<pre><code>public native int func(Param1, Param2, Param3) throws IOException;
</code></pre>
<p>I decide for <code>IOException</code> over <code>Exception</code> because of <a href="https://stackoverflow.com/a/5899901/3117650">this</a>.</p>
<pre><code>JNIEXPORT int JNICALL Java_YourClass_func
(int Param1, int Param2, int Param3) {
if (Param3 == 0) { //something wrong
jclass Exception = env->FindClass("java/lang/Exception");
env->ThrowNew(Exception, "Can't divide by zero."); // Error Message
}
return (Param1+Param2)/Param3;
}
</code></pre>
| 28,556
|
<p>All my applications are developed in Native Code. I am hesitant to move to .Net because of all the negatives that I hear, such as:</p>
<ol>
<li>Slow response time</li>
<li>Lock-In into Windows</li>
<li>Dependance on huge .Net run-time that makes installation a pain and slow as well.</li>
</ol>
<p>etc. etc.</p>
<p>Your advice will be much appreciated.</p>
|
<p>Don't do that just for the sake of converting.</p>
<p>If you have some other technical reason to convert, then you should consider it, but be aware that it is not a small change, especially for larger projects.</p>
<p>EDIT: I also want to add that it would be better if you start some small project in .NET, just to know what to expect, and later decide is the conversion of existing projects valid option.</p>
|
<p>It depends on several factors.</p>
<p>Does your application NEED to be rewritten? How long will the advantages of .Net take to offset the cost of rewriting? Is Windows lock-in a problem for you?</p>
<p>.Net is a great platform, but it's not for everyone or every project. I will say that the run-time issue was a bigger deal when .Net was new, at this point that has become rather trivial IHO.</p>
| 40,487
|
<p>Can someone tell me how can I extract a public keu in .pem format from a .cer file ?
I'm trying to configure webservice over https with nusoap.</p>
<p>Tks,
ED</p>
|
<p>Any time I need to convert certificate formats I like to hop on my Linux shell and use the openssl CLI.</p>
<p>Take a look at <a href="http://shib.kuleuven.be/docs/ssl_commands.shtml" rel="nofollow noreferrer">this page</a> for common openssl commands. You will be most interested in the one titled "Convert DER (.crt .cer .der) to PEM".</p>
|
<p>Any time I need to convert certificate formats I like to hop on my Linux shell and use the openssl CLI.</p>
<p>Take a look at <a href="http://shib.kuleuven.be/docs/ssl_commands.shtml" rel="nofollow noreferrer">this page</a> for common openssl commands. You will be most interested in the one titled "Convert DER (.crt .cer .der) to PEM".</p>
| 49,596
|
<p>In our MOSS '07 site we have a page that contains just a Page Viewer web part in it that points to a site on another server. However, I've noticed that on that page (and any others that have a Page Viewer web part on it) our drop down menus and hover effects are <strong>super slow</strong> and completely max out the CPU on the visitor's computer (process is <strong>IExplorer</strong>.)</p>
<p>Through testing, I was able to determine that it doesn't matter what URL the web part is pointed to...just having the Iframe on the page seems to cause it (just setting the viewer to load Google's homepage--which is probably the simplest site I know--still causes the problem). If I go and remove the web part, the menus start functioning just fine again.</p>
<p>I attached a debugger to the process and stepped through the <code>Menu_HoverStatic</code> and called functions and it seems to have a hard time when assigning <code>panel.scrollTop</code> to zero in the <code>PopOut_Show</code> function.</p>
<p>Has anyone else noticed this? ...perhaps found a solution to it? I can't find where to edit <code>PopOut_Show</code> function on our server (I think it's a resource in one of the .NET DLLs) or else I'd just comment out that line as I don't think it's really important anyway...at least on our site.</p>
<p>I really like the ability to have web pages from another server hosted in our SharePoint site, but the performance on the hovers is agonizing... and, honestly, unacceptable. Depending on the resources of the user's computer, the hover effects can take 15 seconds to complete at times!!!!</p>
<p>Any suggestions would be really appreciated!</p>
|
<pre><code>function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
</code></pre>
<p>And to use (I used swfObject as an example):</p>
<pre><code>var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
callbackMethod();
</code></pre>
|
<p>you can load script dynamically by adding <code><script src="..."></code> tag to DOM tree.</p>
| 40,020
|
<p>I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?</p>
<p>Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related?</p>
|
<p><strong>Using this setup, everything worked.</strong> </p>
<p><em>1) LINQ to SQL Query, 2) DB Tables, 3) LINQ to SQL Data Model in VS.NET 2008</em></p>
<p><strong>1 - LINQ to SQL Query</strong></p>
<pre><code>DataClasses1DataContext db = new DataClasses1DataContext();
var results = from threes in db.tableThrees
join twos in db.tableTwos on threes.fk_tableTwo equals twos.id
join ones in db.tableOnes on twos.fk_tableOne equals ones.id
select new { ones, twos, threes };
</code></pre>
<p><strong>2 - Database Scripts</strong></p>
<pre><code>--Table One
CREATE TABLE tableOne(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
--Table Two
CREATE TABLE tableTwo(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableOne] [int] NOT NULL,
CONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableTwo WITH CHECK
ADD CONSTRAINT [FK_tableTwo_tableOne]
FOREIGN KEY([fk_tableOne])
REFERENCES tableOne ([id]);
ALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];
--Table Three
CREATE TABLE tableThree(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableTwo] [int] NOT NULL,
CONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED
([id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableThree WITH CHECK
ADD CONSTRAINT [FK_tableThree_tableTwo]
FOREIGN KEY([fk_tableTwo])
REFERENCES tableTwo ([id]);
ALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];
</code></pre>
<p><strong>3 - LINQ to SQL Data Model in Visual Studio</strong> </p>
<p><a href="http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png" rel="nofollow noreferrer">alt text http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png</a> </p>
|
<p>the FK_Contraints are set up like this:</p>
<p>ALTER TABLE [dbo].[e2] WITH CHECK ADD CONSTRAINT [FK_e2_e1] FOREIGN KEY([E1Id]) REFERENCES [dbo].[e1] ([Id])</p>
<p>ALTER TABLE [dbo].[e3] WITH CHECK ADD CONSTRAINT [FK_e3_e2] FOREIGN KEY([E2Id]) REFERENCES [dbo].[e2] ([Id])</p>
<p>is this what you were asking for?</p>
| 7,369
|
<p>My Y-axis on my Monoprice maker select running ramps 1.4 and Marlin makes a thud noise when moving every now and then. I have noticed a 1 to 2 mm shift in the print when this occurs. I tighten the belts and alas no joy. I ordered new bearings which should be coming Monday. I also tried slowing the print down and still get the same result. Anyone have any ideas.</p>
|
<p>The issue was the X-axis top smooth rod came out. this caused the extruder to bang around and shift on the Y-axis when it shifted forward. thank everyone for their help. </p>
|
<p>A thudding noise is usually a belt slipping through its end-restraints. A clicking noise is usually a stepper motor missing a step. Seized bearings could be the cause.</p>
| 734
|
<p>Which would be faster for say 500 elements.</p>
<p>Or what's the faster data structure/collection for retrieving elements?</p>
<pre><code> List<MyObj> myObjs = new List<MyObj>();
int i = myObjs.BinarySearch(myObjsToFind);
MyObj obj = myObjs[i];
</code></pre>
<p>Or</p>
<pre><code> Dictionary<MyObj, MyObj> myObjss = new Dictionary<MyObj, MyObj>();
MyObj value;
myObjss.TryGetValue(myObjsToFind, out value);
</code></pre>
|
<p>I assume in your real code you'd actually <em>populate</em> myObjs - and sort it.</p>
<p>Have you just tried it? It will depend on several factors:</p>
<ul>
<li>Do you need to sort the list for any other reason?</li>
<li>How fast is MyObj.CompareTo(MyObj)?</li>
<li>How fast is MyObj.GetHashCode()?</li>
<li>How fast is MyObj.Equals()?</li>
<li>How likely are you to get hash collisions?</li>
<li>Does it actually make a significant difference to you?</li>
</ul>
<p>It'll take around 8 or 9 comparisons in the binary search case, against a single call to GetHashCode and some number of calls to Equals (depending on hash collisions) in the dictionary case. Then there's the intrinsic calculations (accessing arrays etc) involved in both cases.</p>
<p>Is this really a bottleneck for you though?</p>
<p>I'd expect Dictionary to be a bit faster at 500 elements, but not <em>very</em> much faster. As the collection grows, the difference will obviously grow.</p>
|
<p>BinarySearch requires the list to already be sorted. [edit: Forgot that dictionary is a hashtable. So lookup is O(1)]. The 2 are not really the same either. The first one is really just checking if it exists in the list and where it is. If you want to just check existance in a dictionary use the contain method.</p>
| 46,828
|
<p>I use the jQuery <a href="http://docs.jquery.com/Utilities/jQuery.extend" rel="nofollow noreferrer">extend</a> function to extend a class prototype.</p>
<p>For example:</p>
<pre><code>MyWidget = function(name_var) {
this.init(name_var);
}
$.extend(MyWidget.prototype, {
// object variables
widget_name: '',
init: function(widget_name) {
// do initialization here
this.widget_name = widget_name;
},
doSomething: function() {
// an example object method
alert('my name is '+this.widget_name);
}
});
// example of using the class built above
var widget1 = new MyWidget('widget one');
widget1.doSomething();
</code></pre>
<p>Is there a better way to do this? Is there a cleaner way to create the class above with only one statement instead of two?</p>
|
<p>I quite like John Resig's <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="noreferrer">Simple JavaScript Inheritance</a>.</p>
<pre><code>var MyWidget = Class.extend({
init: function(widget_name){
this.widget_name = widget_name;
},
doSomething: function() {
alert('my name is ' + this.widget_name);
}
});
</code></pre>
<p>NB: The "Class" object demonstrated above isn't included in jQuery itself - it's a 25 line snippet from Mr. jQuery himself, provided in the article above.</p>
|
<p>This is long gone dead, but if anyone else searches for jQuery creating class - check this plugin:
<a href="http://plugins.jquery.com/project/HJS" rel="nofollow noreferrer">http://plugins.jquery.com/project/HJS</a></p>
| 11,020
|
<p>I recently got a Creality Ender-3, and tried printing a few things for some tests. I’ve printed a cube and just printed a cylindrical tube today, and I notice each time, it adds this random line on the left and a sort of outline around the actual print. Neither of these were there in my Cura file, but they’re always printed and I’m not sure why?</p>
<p><a href="https://i.stack.imgur.com/SyhGh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SyhGh.jpg" alt="enter image description here"></a></p>
|
<p>If the printer is printing, it is instructed to do so by the <a href="https://reprap.org/wiki/G-code" rel="nofollow noreferrer">G-code</a> file unless you are printing through an external software program that has extra G-code to print before your print starts. E.g. in OctoPrint print server it is possible to execute G-code before the print starts.</p>
<h2>Left line = Priming</h2>
<p>The <strong>straight line on the left</strong> is typically <strong>used to prime the printer nozzle to get the filament flow starting</strong>, this is typically seen in <a href="https://github.com/prusa3d/PrusaSlicer" rel="nofollow noreferrer">PrusaSlicer</a> (Prusa's fork of Open Source toolpath generator for 3D printers <a href="https://github.com/slic3r" rel="nofollow noreferrer">Slic3r</a>). <em><strong>This straight line is called priming line, purge line or intro line</strong></em>, and is typically (but not necessarily) printed outside or at the edge of the bed area. Furthermore, a prime line print routine will catch errant nozzle ooze, test extrusion (it is the first indication if the nozzle to bed distance is correct; if not you can abort with minimal material loss) and perform a final wipe action to avoid stringing between the prime line and start of the print. Note that this straight prime line is not a standard option in a <em>custom</em> profile of Cura, so this was part of the Ender-3 Preset you imported or possibly you have copied a starting G-code that includes this prime line.</p>
<p>A typical set of G-code lines to create a prime/purge/intro line is found in your start G-code and could look similar to:</p>
<pre>
G1 Y-3.0 F1000.0 ; go outside print area
G92 E0.0
G1 X60.0 E9.0 F1000.0 ; intro line
G1 X100.0 E12.5 F1000.0 ; intro line
G92 E0.0
</pre>
<p>After slicing your object, you will find such lines in the generated G-code file, but they are not displayed in the preview. Further information can be found in <a href="https://3dprinting.stackexchange.com/questions/6355/writing-g-code-swiping-at-start-of-print">Writing G-code : swiping at start of print</a></p>
<h2>Equidistant line = Skirt</h2>
<p>The <strong>lines at distance from the print</strong> object <strong>is called the "skirt"</strong>, the skirt is an option found under the "Build Plate Adhesion" options in your slicer. The function of the skirt is similar as described for the straight prime line, but it has additional effects that can be wanted. It also shows fairly fast if the bed is unleveled as a whole or if the bed is greasy. Please look into: <a href="/q/20">"What are main differences between rafts, skirts and brims?
"</a>.</p>
<p>Note that it is usually superfluous to use both the prime/purge/intro line and the skirt, both have a similar function. The benefit of the skirt is that you can configure it within the slicer (e.g. length of the printed skirt, height to use as a shield for draft or ooze and distance to product). The downside is, that a skirt limits the useable build area by the distance and width of the skirt.</p>
|
<p>These are features, not bugs. </p>
<p>The line off to the left is the "priming line"; the printer is extruding a bead of material to ensure that any oozing is cleaned off of the filament tip, and that the filament is properly pressed into the hotend and flowing consistently from the nozzle, before beginning your print. Notice how plastic didn't start extruding on the "backstroke" until the extruder had almost reached the back of the plate? If you didn't have that priming line, that material would have been missing from your print's first layer.</p>
<p>The ring around your print is the "skirt". The skirt also helps to prime the extruder, and allows you a quick look at your first layer printing behavior before the printer begins printing your actual part. Is your build plate level? Is the nozzle clearance correct? Is the filament adhering well to your bed prep? Are your build plate size and offsets set up properly in the slicer (or are you about to try to print off the edge of your plate)? A skirt can help you determine all these things very quickly, like before the printer starts working over the actual print area, giving you a chance to correct them on-the-fly or at least quickly cancel the print, and it uses a minimum of material to do so compared to a more substantial plate adhesion aid like a brim or raft.</p>
<p>You can disable or alter the behavior of both of these in your slicer software; exactly how depends on the slicer software. </p>
<p>In Ultimaker's Cura, which comes fairly highly recommended for use with Creality printers like the Ender 3, the priming line is part of the pre-print configuration script in the printer settings, and you'll need to have a working knowledge of GCode to mess with that. GCode isn't terribly difficult, but it was designed for computers to generate more than for humans to comprehend, and incorrect GCode commands in this section can cause printer firmware errors, failed prints and can even damage your printer.</p>
<p>The skirt settings are part of the slicer settings for your specific print, under the "Platform Adhesion" section. You can typically choose to print a skirt, a brim (similar concept but it extends all the way in to the outline of the part's first layer, and helps hold the part on the plate while it prints), a raft (a more complex adhesion aid where the printer will lay down several layers of material as a foundation for the actual print), or nothing at all. You can also customize the settings of each of these to create a larger or smaller skirt or brim.</p>
<p>Personally, I keep both of these print features enabled for almost all prints on my Ender 3 Pro; the only time I disable the skirt is either when I want a brim (small parts like <a href="http://www.3dbenchy.com/download/" rel="nofollow noreferrer">3DBenchies</a> print more reliably with a brim) or when the skirt just won't fit on the build plate (which usually means the part has a large enough footprint not to go anywhere during the print), and the only time I mess with the priming line is when I need that area of the build plate for the actual print. These features cost you maybe a penny or two in filament and can save you far more than that in frustration and wasted plastic on failed or imperfect prints.</p>
| 1,504
|
<p>Forgive me for being a complete newbie with Windows DDK.</p>
<p>I have create a simple file named <code>test.cpp</code>:</p>
<pre><code>#include <windows.h>
#define BAD_ADDRESS 0xBAADF00D
int __cdecl main(int argc, char* args[])
{
char* p =(char*)BAD_ADDRESS;
*p='A';
return 0;
}
</code></pre>
<p>In the same directory I created a <code>sources</code> file like this:</p>
<pre>
TARGETNAME=test
TARGETTYPE=PROGRAM
TARGETPATH=obj
TARGETLIBS=$(SDK_LIB_PATH)\kernel32.lib
SOURCES= test.cpp
</pre>
<p>And a <code>makefile</code> like this:</p>
<pre>
#
# DO NOT EDIT THIS FILE!!! Edit .\sources. if you want to add a new source
# file to this component. This file merely indirects to the real make file
# that is shared by all the components of Windows
#
!INCLUDE $(NTMAKEENV)\makefile.def
</pre>
<p>After launching the Windows XP Free Build Environment I browse to the directory with the three files (test.cpp, makefile and sources) and run the following command:</p>
<pre>F:\temp\debug\dir1>build -cZg</pre>
<p>Which outputs:</p>
<pre>
BUILD: Adding /Y to COPYCMD so xcopy ops won't hang.
BUILD: Using 2 child processes
BUILD: Object root set to: ==> objfre_wxp_x86
BUILD: Compile and Link for i386
BUILD: Examining f:\temp\debug\dir1 directory for files to compile.
BUILD: Compiling (NoSync) f:\temp\debug\dir1 directory
1>Compiling - test.cpp for i386
BUILD: Compiling f:\temp\debug\dir1 directory
BUILD: Linking f:\temp\debug\dir1 directory
1>Linking Executable - objfre_wxp_x86\i386\test.exe for i386
BUILD: Done
2 files compiled
1 executable built
</pre>
<p>The problem is that when I run the created executable <code>test.exe</code> it says:</p>
<pre>
F:\temp\debug\dir1\objfre_wxp_x86\i386>test
The F:\temp\debug\dir1\objfre_wxp_x86\i386\test.exe application cannot be run in Win32 mode.
</pre>
<p><strong>What am I missing here?</strong></p>
|
<p><a href="https://stackoverflow.com/questions/226790/error-when-compiling-with-windows-ddk#226952">Rob Walker</a> explains the why but <a href="http://blogs.msmvps.com/kernelmustard/2005/11/04/building-win32-apps-with-build-exe-and-the-ddk/" rel="nofollow noreferrer">Kernel Mustard</a> explains the how.</p>
|
<p>You have compiled a 'native application' rather than a win32 one. The TARGET_TYPE definition controls this.</p>
<p>See '<a href="http://technet.microsoft.com/en-us/sysinternals/bb897447.aspx" rel="nofollow noreferrer">Inside Native Applications</a>' for a discussion of using the DDK to generate a native application.</p>
| 28,049
|
<p>I have a line (actually a cube) going from (x1,y1,z1) to (x2,y2,z2). I would like to rotate it so that it is aligned along another line going from (x3,y3,z3) to (x4,y4,z4). Presently I am using <code>Math::Atan2</code> along with <code>Matrix::RotateYawPitchRoll</code>. Any better ways to do this?</p>
<p>Edit: I think I've worded this post very badly. What I am actually looking for is a Rotation Matrix from two Vectors.</p>
|
<p>Yes you can do this without needing to think in terms of angles at all.</p>
<p>Since you have a cube, suppose you pick one corner and then define the 3 edges radiating out from it as vectors f0, f1, f2 (these are direction vectors, relative to the corner you've picked). Normalise those and write them as columns in a matrix F</p>
<pre><code>(f0x f1x f2x)
(f0y f1y f2y)
(f0z f1z f2z)
</code></pre>
<p>Now do the same thing for the vectors t0, t1, t2 of the cube you want to rotate to and call it matrix T.</p>
<p>Now the matrix R = T * Inverse(F) is the matrix which rotates from the orientation of the first cube to the orientation of the second (because inverse F maps e.g f0 to (1 0 0)', and then T maps (1 0 0)' to t0).</p>
<p>If you want to know why this works, think in terms of coordinate system basis vectors: if you want to rotate the X Y and Z axes to a new coordinate system, well the columns of the rotation matrix are just the vectors you want (1 0 0)', (0 1 0)' & (0 0 1)' to be mapped to. T*Inverse(F) is effectively rotating your cube from its original orientation to axis aligned, and then to the desired orientation.</p>
<p>(Sorry, above is for column vectors and transforms on the left, OpenGL style. I seem to remember Direct3D is row vectors and transforms on the right, but it should be obvious how to switch it around).</p>
<p>It also applies equally well to 4x4 matrices with a translation component too.</p>
|
<p>You might want to add how to actually interpolate the matrices. Source and destination matrices are fine in your answer, but computing the inverse is pointless. Quaternions will give you the shortest rotational path, so take the rotational 3x3 matrices on both matrices, convert to quaternions and lerp those. Do a separate lerp for the translation and recompose. Google for quaternion - matrix and back conversions and quaternion lerp. </p>
<p>Edit: A rotation matrix from a forward and an up vector is trivial. The missing column is the cross product of the other two vectors. (don't forget to normalize columns). </p>
| 31,607
|
<p>Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003?</p>
<p>I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to a particular worksheet (for example, all July data from a SharePoint worksheet to the Jul worksheet, all June data from a SharePoint worksheet to Jun worksheet, etc.).</p>
<p><strong>Sample data</strong></p>
<pre><code>Date - Project - ID - Engineer
8/2/08 - XYZ - T0908-5555 - JS
9/4/08 - ABC - T0908-6666 - DF
9/5/08 - ZZZ - T0908-7777 - TS
</code></pre>
<p>It's not a one-off exercise. I'm trying to put together a dashboard that my boss can pull the latest data from SharePoint and see the monthly results, so it needs to be able to do it all the time and organize it cleanly.</p>
|
<p>This works: The way it's set up I called it from the immediate pane, but you can easily create a sub() that will call MoveData once for each month, then just invoke the sub.</p>
<p>You may want to add logic to sort your monthly data after it's all been copied</p>
<pre><code>Public Sub MoveData(MonthNumber As Integer, SheetName As String)
Dim sharePoint As Worksheet
Dim Month As Worksheet
Dim spRange As Range
Dim cell As Range
Set sharePoint = Sheets("Sharepoint")
Set Month = Sheets(SheetName)
Set spRange = sharePoint.Range("A2")
Set spRange = sharePoint.Range("A2:" & spRange.End(xlDown).Address)
For Each cell In spRange
If Format(cell.Value, "MM") = MonthNumber Then
copyRowTo sharePoint.Range(cell.Row & ":" & cell.Row), Month
End If
Next cell
End Sub
Sub copyRowTo(rng As Range, ws As Worksheet)
Dim newRange As Range
Set newRange = ws.Range("A1")
If newRange.Offset(1).Value <> "" Then
Set newRange = newRange.End(xlDown).Offset(1)
Else
Set newRange = newRange.Offset(1)
End If
rng.Copy
newRange.PasteSpecial (xlPasteAll)
End Sub
</code></pre>
|
<p>If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?</p>
| 10,992
|
<p>Reading <a href="http://msdn.microsoft.com/en-us/library/ms345265.aspx" rel="nofollow noreferrer">MSDN</a> (and other sources) about custom report items (CRI) for reporting services 2005. It looks like I'm limited to generating a bitmap. Not even with some mapping overlay for detecting mouse clicks on it. Is there away to go around this? There are two things I would like to do:</p>
<ul>
<li>Embed HTML directly into the report, to format dynamic text.</li>
<li>Embed flash (swf) control in the report. This could be done with HTML if the previous point is possible. But maybe there is another way</li>
</ul>
<p>Any suggestions? What am I missing?</p>
|
<p>You didn't missing anything.</p>
<p>For me, like you mentioned, the main disadvantage is, that with a CRI you can only render images. You don't get any scalable text or something similar.
If you want include swf, you need to render it as static image.</p>
|
<p>You can render the report as HTML and include the report using a floating frame in a page with the swf file. You can use functions to format dynamic text. SSRS 2008 solves some of these problems with the "richly" formated textbox (not RTF). it may worth a look, if it's an option. </p>
| 4,118
|
<p>I am a recent college graduate working for a large corporation that has an aging workforce. I am curious for peoples experiences on working with an age gap preferably from both sides. </p>
<p>Examples Issues I have encountered so far: </p>
<ul>
<li>Agile practices vs Waterfall</li>
<li>Collaboration between programmers vs individuality</li>
<li>Working early in the morning vs late at night </li>
</ul>
<p>I learned primarily agile programming in school while the project I am on (and most of the developers are used to waterfall)</p>
<p>I am used to collaborating with classmates and friends on projects while I tend to see older programmers like to do their own thing. I feel like I pester them asking them questions.</p>
<p>I find myself more of a night programmer, but most of my older colleagues are early morning (5am)</p>
<p>Any experiences on the age gap in the technology work is relevant.</p>
|
<p>I have been on both sides of the fence, so to speak.</p>
<p>The problem with agile programming is that, like any tool, it isn't always appropriate for the task. In some environments a waterfall methodology is still effective.</p>
<p>I don't think the collaboration differences come from an age difference, but rather that is the style that has been fostered by that company and the work environment. I worked at a defense contractor for a while just out of school where almost everyone on the project was considerably older than I was but there was a very high amount of collaboration. On the flip side, I have worked for companies where everyone was around the same age and there was almost no collaboration. </p>
<p>People will either like answering questions/mentoring or they won't. Age doesn't necessarily make much of a difference. I have worked with people that are older and younger than I am but there have only been a few people that genuinely like answering questions (whether they were project related or not).</p>
|
<p>I'm a recent college graduate as well. I work with aging developers, but for the most part they embrace agile methodology and understand why it is a necessary for our purposes to use that instead of waterfall. I'll admit that their execution of it sometimes isn't correct, but at least they try.</p>
<p>I find that corporate interests put a much bigger strain on trying to correctly use agile methods. Try using agile when you got a corporate executive on you telling you to plan all the tasks and estimate the hours for 10 sprints at once. Trying to tell them that it will probably change and there's no point will cause spouts of anger. Problems like that make age differences seem trivial.</p>
| 38,919
|
<p>I'm using MBUnit Framework for unit testing and looking for a good test runner.</p>
<p>MbUnit's runner is fast however lacking lots of stuff such as </p>
<ul>
<li>You can't set execution path</li>
<li>It's collapsing all trees in every run which drives me crazy</li>
<li>And almost all other test runner provides so many extra quite and lovely features</li>
</ul>
<p>I used Zanebug, but:</p>
<ul>
<li>Not properly supported any more, kind of a dead project</li>
<li>I think it's not compatible with latest MBUnit because it keeps crashing on me</li>
<li>Got so many weird bugs</li>
</ul>
<p>Gallio</p>
<ul>
<li>Don't know why keeps crashing on startup, (Vista x64)</li>
<li>I've got it run in another setup, it's about 6 times slower than MBUnit GUI and I've got so many test,</li>
</ul>
<p>Test Driven .NET addon</p>
<ul>
<li>This is great little tool but just for testing one or unit test, doesn't provide a good or VS.NET independent GUI</li>
</ul>
<p>I'm open to any other free test runner which works with or independent from VS 2008</p>
|
<p>I really enjoy NUnit. Now I enjoy even more since I can use it inside the IDE with ReSharper that let me do quick test for a method very fast.</p>
|
<p>I'm using resharper to run individual tests in IDE, but nunit-console to run all tests for speed.</p>
| 39,554
|
<p>I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:</p>
<blockquote>
<p>warning: deprecated conversion from string constant to ‘char*’</p>
</blockquote>
<p>Obviously, the correct way to fix this is to find every declaration like</p>
<pre><code>char *s = "constant string";
</code></pre>
<p>or function call like:</p>
<pre><code>void foo(char *s);
foo("constant string");
</code></pre>
<p>and make them <code>const char</code> pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror" rel="nofollow noreferrer">-Werror</a>, so I need some way to stifle these warnings. How can I do that?</p>
|
<p>I believe passing <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings" rel="nofollow noreferrer">-Wno-write-strings</a> to GCC will suppress this warning.</p>
|
<blockquote>
<p>The problem right now is that I'm running with -Werror</p>
</blockquote>
<p>This is your real problem, IMO. You can try some automated ways of moving from (char *) to (const char *) but I would put money on them not just working. You will have to have a human involved for at least some of the work.
For the short term, just ignore the warning (but IMO leave it on, or it'll never get fixed) and just remove the -Werror.</p>
| 8,434
|
<p>I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the <a href="http://www.secdev.org/projects/scapy/build_your_own_tools.html" rel="noreferrer">scapy site</a>, they give a sample program which I'm not able to run on my own machine:</p>
<pre><code>#! /usr/bin/env python
import sys
from scapy import sr1,IP,ICMP
p=sr1(IP(dst=sys.argv[1])/ICMP())
if p:
p.show()
</code></pre>
<p>To which I get:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 4, in <module>
from scapy import sr1,IP,ICMP
ImportError: cannot import name sr1
</code></pre>
<p>So my question then is: when installing Python libraries, do I need to change my path or anything similar? Also, is there something I can run in the interpreter to tell me the contents of the scapy package? I can run <code>from scapy import *</code> just fine, but since I have no idea what's inside it, it's hard to use it.</p>
|
<p>With the caveat from Federico Ramponi "You should use scapy as an interpreter by its own, not as a library", I want to answer the non-scapy-specific parts of the question.</p>
<p><strong>Q:</strong> when installing Python libraries, do I need to change my path or anything similar?</p>
<p><strong>A:</strong> I think you are talking about changing <code>PYTHONPATH</code> system-wide. This is usually not required or a good idea.</p>
<p>Third party Python libraries should either be installed in system directories, such as <code>/usr/lib/python2.5/site-packages</code>, or installed locally, in which case you might want to set <code>PYTHONPATH</code> in your Makefile or a in driver shell script.</p>
<p><strong>Q:</strong> Also, is there something I can run in the interpreter to tell me the contents of the scapy package?</p>
<p><strong>A:</strong> You can do something like this:</p>
<pre><code>>>> import scapy
>>> dir(scapy)
</code></pre>
<p>Or even better:</p>
<pre><code>>>> import scapy
>>> help(scapy)
</code></pre>
<p>Bonus question asked in a comment.</p>
<p><strong>Q:</strong> Is 'import scapy' the same as 'from scapy import *'?</p>
<p><strong>A:</strong> <code>import scapy</code> binds the scapy name in the local namespace to the scapy module object. OTOH, <code>from scapy import *</code> does not bind the module name, but all public names defined in the scapy module are bound in the local namespace.</p>
<p>See paragraphs 6 and 7 of the Python Reference Manual, <a href="http://www.python.org/doc/2.5.2/ref/import.html" rel="nofollow noreferrer">6.12 The import statement</a>.</p>
|
<p>The <a href="http://www.secdev.org/projects/scapy/index.html" rel="nofollow noreferrer">scapy</a> package is a tool for network manipulation and monitoring. I'm curious as to what you're trying to do with it. It's rude to spy on your friends. :-)</p>
<pre><code>coventry@metta:~/src$ wget -q http://www.secdev.org/projects/scapy/files/scapy-latest.zip
coventry@metta:~/src$ unzip -qq scapy-latest.zip
warning [scapy-latest.zip]: 61 extra bytes at beginning or within zipfile
(attempting to process anyway)
coventry@metta:~/src$ find scapy-2.0.0.10 -name \*.py | xargs grep sr1
scapy-2.0.0.10/scapy/layers/dns.py: r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5,
scapy-2.0.0.10/scapy/layers/dns.py: r=sr1(IP(dst=nameserver)/UDP()/DNS(opcode=5,
scapy-2.0.0.10/scapy/layers/inet6.py:from scapy.sendrecv import sr,sr1,srp1
scapy-2.0.0.10/scapy/layers/snmp.py: r = sr1(IP(dst=dst)/UDP(sport=RandShort())/SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])),timeout=2, chainCC=1, verbose=0, retry=2)
scapy-2.0.0.10/scapy/layers/inet.py:from scapy.sendrecv import sr,sr1,srp1
scapy-2.0.0.10/scapy/layers/inet.py: p = sr1(IP(dst=target, options="\x00"*40, proto=200)/"XXXXYYYYYYYYYYYY",timeout=timeout,verbose=0)
scapy-2.0.0.10/scapy/sendrecv.py:def sr1(x,filter=None,iface=None, nofilter=0, *args,**kargs):
</code></pre>
<p>According to the last line, <code>sr1</code> is a function defined in <code>scapy.sendrecv</code>. Someone should file a documentation bug with the author.</p>
| 28,440
|
<p>In Latex how can you make the background image to occupy the whole sheet on every page <i>except</i> a certain stripe on the inner side of each page? I can't figure it out.<br>
I have a background image I'd like to be seen in whole on each page after printing/binding.</p>
<p>Matyi</p>
|
<p>The beauty of two's complement is that at the binary level it's a matter of interpretation rather than algorithm - the hardware for adding two signed numbers is the same as for unsigned numbers (ignoring flag bits). </p>
<p>Your first example - "just add them" - is exactly the right answer. Your example numbers </p>
<ul>
<li>01001001 = 73</li>
<li>10101010 = -86</li>
</ul>
<p>So, the correct answer is indeed -13.</p>
<p>Subtracting is just the same, in that no special processing is required for two's complement numbers: you "just subtract them".</p>
<p>Note that where things get interesting is the handling of overflow/underflow bits. You can't represent the result of 73 - (-86) as an 8-bit two's complement number...</p>
|
<p>Adding in two's complement doesn't require any special processing when the signs of the two arguments are opposite. You just add them as you normally would in binary, and the sign of the result is the sign you keep.</p>
| 45,119
|
<p>I've got a DB table where we store a lot of MD5 hashes (and yes I know that they aren't 100% unique...) where we have a lot of comparison queries against those strings.
This table can become quite large with over 5M rows.</p>
<p>My question is this: Is it wise to keep the data as hexadecimal strings or should I convert the hex to binary or decimals for better querying?</p>
|
<p>Do it like this:</p>
<pre><code>char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
printf("token: %s\n", token);
token = strtok(NULL, " ");
}
</code></pre>
<p>Note: <code>strtok</code> modifies the string its tokenising, so it cannot be a <code>const char*</code>. </p>
|
<pre><code>int not_in_delimiter(char c, char *delim){
while(*delim != '\0'){
if(c == *delim) return 0;
delim++;
}
return 1;
}
char *token_separater(char *source, char *delimiter, char **last){
char *begin, *next_token;
char *sbegin;
/*Get the start of the token */
if(source)
begin = source;
else
begin = *last;
sbegin = begin;
/*Scan through the string till we find character in delimiter. */
while(*begin != '\0' && not_in_delimiter(*begin, delimiter)){
begin++;
}
/* Check if we have reached at of the string */
if(*begin == '\0') {
/* We dont need to come further, hence return NULL*/
*last = NULL;
return sbegin;
}
/* Scan the string till we find a character which is not in delimiter */
next_token = begin;
while(next_token != '\0' && !not_in_delimiter(*next_token, delimiter)) {
next_token++;
}
/* If we have not reached at the end of the string */
if(*next_token != '\0'){
*last = next_token--;
*next_token = '\0';
return sbegin;
}
}
void main(){
char string[10] = "abcb_dccc";
char delim[10] = "_";
char *token = NULL;
char *last = "" ;
token = token_separater(string, delim, &last);
printf("%s\n", token);
while(last){
token = token_separater(NULL, delim, &last);
printf("%s\n", token);
}
</code></pre>
<p>}</p>
<p>You can read detail analysis at blog mentioned in my profile :)</p>
| 33,396
|
<p>Is it possible to use stored procedures for designing Reports in Report builder?</p>
|
<p>If you're asking if it's possible to use sprocs in SSRS reports that you create, then yes. Just call the sproc in the query for your DataSet like you would normaly.</p>
|
<p>If you're using Oracle on the backend, you can query the results of a table function (a stored function that returns a TABLE of TYPE). The query string for your Dataset will look like:</p>
<pre><code>select * from table (f_foo(:p_bar))
</code></pre>
<p>...where f_foo is your table function stored in the database and p_bar is a report parameter to f_foo. More info on table functions here:</p>
<p><a href="http://www.databasejournal.com/features/oracle/article.php/2222781" rel="nofollow noreferrer">http://www.databasejournal.com/features/oracle/article.php/2222781</a></p>
| 12,429
|
<p>What is the keyboard short cut in Eclipse to jump to the closing brace of a scope?</p>
|
<p>Place the cursor next to an opening <em>or closing</em> brace and punch <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> to find the matching brace. If Eclipse can't find one you'll get a <em>"No matching bracket found"</em> message.</p>
<p><strong><em>edit:</em></strong> as <a href="https://stackoverflow.com/a/1637242/1030">mentioned by Romaintaz below</a>, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.</p>
|
<p>On the Macintosh, place the cursor after either the opening or closing curly brace <code>}</code> and use the keys: <kbd>Shift</kbd> + <kbd>Command</kbd> + <kbd>P</kbd>.</p>
| 36,843
|
<p>I'm writing some code to scale a 32 bit RGBA image in C/C++. I have written a few attempts that have been somewhat successful, but they're slow and most importantly the quality of the sized image is not acceptable. </p>
<p>I compared the same image scaled by OpenGL (i.e. my video card) and my routine and it's miles apart in quality. I've Google Code Searched, scoured source trees of anything I thought would shed some light (SDL, Allegro, wxWidgets, CxImage, GD, ImageMagick, etc.) but usually their code is either convoluted and scattered all over the place or riddled with assembler and little or no comments. I've also read multiple articles on Wikipedia and elsewhere, and I'm just not finding a clear explanation of what I need. I understand the basic concepts of interpolation and sampling, but I'm struggling to get the algorithm right. I do NOT want to rely on an external library for one routine and have to convert to their image format and back. Besides, I'd like to know how to do it myself anyway. :)</p>
<p>I have seen a similar question asked on stack overflow before, but it wasn't really answered in this way, but I'm hoping there's someone out there who can help nudge me in the right direction. Maybe point me to some articles or pseudo code... anything to help me learn and do.</p>
<p>Here's what I'm looking for:</p>
<ol>
<li>No assembler (I'm writing very portable code for multiple processor types).</li>
<li>No dependencies on external libraries.</li>
<li>I am primarily concerned with scaling DOWN, but will also need to write a scale up routine later.</li>
<li>Quality of the result and clarity of the algorithm is most important (I can optimize it later).</li>
</ol>
<p>My routine essentially takes the following form:</p>
<pre><code>DrawScaled(uint32 *src, uint32 *dst,
src_x, src_y, src_w, src_h,
dst_x, dst_y, dst_w, dst_h );
</code></pre>
<p>Thanks!</p>
<p><strong>UPDATE:</strong> To clarify, I need something more advanced than a box resample for downscaling which blurs the image too much. I suspect what I want is some kind of bicubic (or other) filter that is somewhat the reverse to a bicubic upscaling algorithm (i.e. each destination pixel is computed from all contributing source pixels combined with a weighting algorithm that keeps things sharp.</p>
<h2>Example</h2>
<p>Here's an example of what I'm getting from the wxWidgets BoxResample algorithm vs. what I want on a 256x256 bitmap scaled to 55x55.</p>
<ul>
<li>www.free_image_hosting.net/uploads/1a25434e0b.png</li>
</ul>
<p>And finally: </p>
<ul>
<li>www.free_image_hosting.net/uploads/eec3065e2f.png</li>
</ul>
<p>the original 256x256 image</p>
|
<p>I've found the wxWidgets implementation fairly straightforward to modify as required. It is all C++ so no problems with portability there. The only difference is that their implementation works with unsigned char arrays (which I find to be the easiest way to deal with images anyhow) with a byte order of RGB and the alpha component in a separate array.</p>
<p>If you refer to the "src/common/image.cpp" file in the wxWidgets source tree there is a down-sampler function which uses a box sampling method "wxImage::ResampleBox" and an up-scaler function called "wxImage::ResampleBicubic".</p>
|
<p>Take a look at <a href="http://www.imagemagick.org" rel="nofollow noreferrer">ImageMagick</a>, which does all kinds of rescaling filters.</p>
| 45,981
|
<p>My code:</p>
<pre><code> string input1;
input1 = Console.ReadLine();
Console.WriteLine("byte output");
byte[] bInput1 = Encoding.Unicode.GetBytes(input1);
for (int x = 0; x < bInput1.Length; x++)
Console.WriteLine("{0} = {1}", x, bInput1[x]);
</code></pre>
<p>outputs: </p>
<p>104
0
101
0
108
0
108
0
111
0</p>
<p>for the input "hello"</p>
<p>Is there a reference to the character map where I can make sense of this?</p>
|
<p>You should read "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" at <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/articles/Unicode.html</a></p>
<p>You can find a list of all Unicode characters at <a href="http://www.unicode.org" rel="nofollow noreferrer">http://www.unicode.org</a> but don't expect to be able to read the files there without learning a lot about text encoding issues.</p>
|
<p>At <a href="http://www.unicode.org/charts/" rel="nofollow noreferrer">http://www.unicode.org/charts/</a> you can find all the Unicode code charts. <a href="http://www.unicode.org/charts/PDF/U0000.pdf" rel="nofollow noreferrer">http://www.unicode.org/charts/PDF/U0000.pdf</a> shows that the code point for 'h' is U+0068. (Another great tool for viewing this data is <a href="http://www.babelstone.co.uk/Software/BabelMap.html" rel="nofollow noreferrer">BabelMap</a>.)</p>
<p>The exact details of UTF-16 encoding can be found at <a href="http://unicode.org/faq/utf_bom.html#6" rel="nofollow noreferrer">http://unicode.org/faq/utf_bom.html#6</a> and <a href="http://www.ietf.org/rfc/rfc2781.txt" rel="nofollow noreferrer">http://www.ietf.org/rfc/rfc2781.txt</a>. In short, U+0068 is encoded (in UTF-16LE) as 0x68 0x00. In decimal, this is the first two bytes you see: 104 0. </p>
<p>The other characters are encoded similarly.</p>
<p>Finally, a great reference (when trying to understand the various Unicode specifications), apart from the <a href="http://www.unicode.org/versions/Unicode5.1.0/" rel="nofollow noreferrer">Unicode Standard</a> itself, is the <a href="http://unicode.org/glossary/" rel="nofollow noreferrer">Unicode Glossary</a>.</p>
| 35,568
|
<p>I have been used to working with VS2005 and 2008 - using msbuild, etc, but I have inherited a set of projects that have to remain in vc6.0 for now. I don't like opening each project in the developer studio and building. I prefer to build form command line (I am automating the builds). Is this possible?</p>
<p>I have tried the nmake utility, but I still need to open up the projects and save/export the make file. This is tedious if the project changes - each time I have to save the make file. nmake seems to work, but it had a problem when I changed the location of the project in my directory tree (I checked out of svn into a new clean dir to try the build). It seemed to have hard coded paths in it, but I will have to check on that - it might have been a different problem.</p>
<p>Any alternatives out there?</p>
<p>Eventually I will migrate these to 2008, but for now that is not an option.</p>
|
<p>I think I found m answer here:
<a href="http://msdn.microsoft.com/en-us/library/aa699274.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa699274.aspx</a></p>
<p>thanks all</p>
|
<p>Another option which is less labor intensive is</p>
<p><BR> Pulldown Menu (BUILD)
<BR> Select (BATCHBUILD)
<BR> Push Button (REBUILDALL)</p>
| 17,155
|
<p>Here's my problem - I'd like to communicate between two websites and I'm looking for a clean solution. The current solution uses Javascript but there are nasty workarounds because of (understandable) cross-site scripting restrictions.</p>
<p>At the moment, <strong>website A</strong> opens a modal window containing <strong>website B</strong> using a <a href="http://jquery.com/" rel="noreferrer">jQuery</a> plug-in called <a href="http://dev.iceburg.net/jquery/jqModal/" rel="noreferrer">jqModal</a>. <strong>Website B</strong> does some work and returns some results to <strong>website A</strong>. To return that information we have to work around cross-site scripting restrictions - <strong>website B</strong> creates an iframe that refers to a page on <strong>website A</strong> and includes *fragment identifiers" containing the information to be returned. The iframe is polled by <strong>website A</strong> to detect the returned information. It's a <a href="http://tagneto.blogspot.com/2006/06/cross-domain-frame-communication-with.html" rel="noreferrer">common technique</a> but it's hacky.</p>
<p>There are variations such as <a href="http://www.julienlecomte.net/blog/2007/11/31/" rel="noreferrer">CrossSite</a> and I could perhaps use an HTTP POST from <strong>website B</strong> to <strong>website A</strong> but I'm trying to avoid page refreshes.</p>
<p>Does anyone have any alternatives?</p>
<p>EDIT: I'd like to avoid having to save state on <strong>website B</strong>.</p>
|
<p>My best suggestion would be to create a webservice on each site that the other could call with the information that needs to get passed. If security is necessary, it's easy to add an SSL-like authentication scheme (or actual SSL even, if you like) to this system to ensure that only the two servers are able to talk to their respective web services.</p>
<p>This would let you avoid the hackiness that's inherent in any scheme that involves one site opening windows on the other.</p>
|
<p>@jmein - you've described how to create a modal popup (which is exactly what jqModal does) however you've missed that the content of the modal window is served from another domain. The two domains involved belong to two separate companies so can't be combined in the way you describe.</p>
| 5,310
|
<p>When do you test against an <a href="http://martinfowler.com/bliki/InMemoryTestDatabase.html" rel="nofollow noreferrer">In-Memory Database</a> vs. a Development Database?</p>
<p>Also, as a related side question, when you do use a Development Database, do you use an Individual Development Database, an Integration Development Database, or both?</p>
<p>Also++, for unit testing, when do you use an In-Memory Database over mocking out your Repository/DAL, etc.?</p>
|
<p>In memory is an excellent choice for your <em>unit</em>-tests, when the data is easy to seed for your given test cases and a very particular operation is being tested. A real database is better for <em>integration</em> tests, where the data pre-requisites are more complex and there is value to having the base data remain after the tests complete.</p>
<p>For us, the only things we allow in our 'fast' test suite of JUnit tests are those that do not have any external dependencies (database, file, network, etc) so that the suite can be run quickly and efficiently by both developers and continuous integration on checkin. If there is a certain test that absolutely needs to go to the DB, then an in memory one is the only way to go.</p>
<p>A couple points to keep in mind:</p>
<ul>
<li>Think carefully if you need to use a
database at all in a unit test. It
may be indicative of a poor design
in that the data access layer is
coupled too tightly to the business
logic you are trying to test and
cannot be mocked out.</li>
<li>If using a real database for integration testing, ensure that the tests always restore the data to a pristine state when finished. I've seen a lot of wasted time and failed integration tests because some other test messed up the data.</li>
</ul>
<p>As for your other question, it really depends on your need. A good rule of thumb is one development database per code branch, since schema changes may be needed that are not relevant to another branch of code. Just <em>having</em> a dedicated development database is important; I'm surprised at how many development teams have to share a database with the QA team, etc. It is important to be able to make changes in a sandboxed environment that does not affect other teams or prevent others from doing their work, so if you've met those requirements you're doing well.</p>
|
<p>For my team, it's in-memory on developper machine, and the real-database on the continuous integration server.</p>
| 15,588
|
<p>I saw a link to find out if AD was running, but am not too sure if the same applies to AD/AM.
One caveat is that I should be able to check about any AD/AM instance (any domain) assuming I have permissions.</p>
|
<p>the same approach applies to AD or to AD LDS (lightweight directory services, new name for ADAM). .NET examples at <a href="http://msdn.microsoft.com/en-us/library/x8wxt72e(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/x8wxt72e(VS.71).aspx</a></p>
|
<p>the same approach applies to AD or to AD LDS (lightweight directory services, new name for ADAM). .NET examples at <a href="http://msdn.microsoft.com/en-us/library/x8wxt72e(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/x8wxt72e(VS.71).aspx</a></p>
| 45,143
|
<p>Ok, so after spending a good portion of a day debugging a stupid typing mistake inside a piece of code I am curious as to why the specific actions occured rather than an exception.</p>
<p>First of all the problem code.</p>
<pre><code>Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
Dim hl As New HyperLink
AddHandler hl.DataBinding, AddressOf Me.BindData
container.Controls.Add(container)
End Sub
</code></pre>
<p>The obvious problem is that we are trying to add the container to itself, which I would have expected to cause an exception. However, instead it caused the page to prompt the user for their login credentials (Windows authentication in the browser).</p>
<p>Does anyone have an idea why this is the case, and why an exception or something else didn't happen?</p>
<p><strong>EDIT</strong></p>
<p>The reason for the question is that due to this mistake, the page is rendered useless, and prompts for Windows Login, and NOT giving stack overflow exceptions or any other exception.</p>
|
<p>Google has a library for generating coredumps from inside a running process called <a href="http://code.google.com/p/google-coredumper/" rel="noreferrer">google-coredumper</a>. This should ignore ulimit and other mechanisms. </p>
<p>The documentation for the call that generates the core file is <a href="http://code.google.com/p/google-coredumper/wiki/WriteCoreDump" rel="noreferrer">here</a>. According to the documentation, it seems that it is feasible to generate a core file in a signal handler, though it is not guaranteed to always work.</p>
|
<p>system ("kill -6 ")</p>
<p>I'd give it a try if you are still looking for something</p>
| 41,187
|
<p>In postgresql you have a wealth of optimizations at hand to configure it for your performance needs. The settings for memory usage are still easy enough, but with other options like the cost factors for CPU and IO which are used for the query optimizer are quite a mystery for me. I wonder if there is <strong>a program</strong> available which would do lets say a benchmark of your hardware (CPU speed, memory performance, harddisk speed), analyze your database and come up with the optimal configuration for this specific environment?</p>
<p>EDIT:</p>
<p>Let me clarify this, I know how to tune my database with indexes and the basic memory settings. I also could find out which settings are to be tweaked to get better performance, <strong>but</strong>: I don't have the time, so I want to have a tool which finds this out for me.</p>
|
<p>Not that I know of, but the next best thing is the <a href="http://www.pgcon.org/2008/schedule/events/104.en.html" rel="nofollow noreferrer">GUCs: A Three Hour Tour</a> presentation. You can download a <a href="http://www.pgcon.org/2008/schedule/attachments/44_annotated_gucs_draft1.pdf" rel="nofollow noreferrer">PDF</a> from there which gives the recommended values for the settings depending on your system resources.</p>
|
<p>Understanding indexes is the where most people should start when trying to improve any databases performance.</p>
| 18,984
|
<p>So, I have a nice domain model built. Repositories handle the data access and what not. A new requirements has popped up that indicates that reasons need to be logged with deletes. Up until now, deletes have been fairly simple => Entity.Children.Remove(child). No internal change tracking was happening as my ORM tool was handling state management. However, I'm not sure exactyl how to handle this.</p>
<p>1) I could keep a deleted children collection in the parent entity and pull the change tracking out of nHibernate and handle it myself.</p>
<p>2) ??????</p>
|
<p>Ok, this sounds crazy and I'm going to take another shot at this -- even though I might be spanked for bad nHibernate usage. Before you delete, why don't you select the children that are going to be deleted (you already have their ids correct?) and do a transformation into whatever entity your going to be using to log your deletes to a table. Add the reason to the entities and save them -- then proceed with your deletes. Best part, you can use a generic entity i.e. "auditInfo" for the result of the transformation, and you can do it within a transaction so you can rollback everything if something fails! OK, maybe crazy but creative right?</p>
|
<p>Could you implement the <a href="http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html_single/#manipulatingdata-interceptors" rel="nofollow noreferrer">IInterceptor interface</a> and override the onDelete functionality to pull the information you need from the entity and send it to logger before you delete (using NHibernate of course)?</p>
<p><a href="http://www.lostechies.com/blogs/rhouston/archive/2008/03/27/creating-a-timestamp-interceptor-in-nhibernate.aspx" rel="nofollow noreferrer">example</a></p>
| 22,191
|
<p>I looked at the AdaCore site, as well as for A# (which now appears to be owned by AdaCore) and neither appear to be free (although I could have misread something). Any recommendations?</p>
|
<p>GNAT is available for download here: <a href="https://libre.adacore.com/" rel="noreferrer">https://libre.adacore.com/</a></p>
<p>Look for "GNAT GPL Edition". Not sure why it is so well hidden on that little known site.</p>
|
<p>Thomas, you can find the GPL edition of GNAT Adacore Ada framework in <a href="http://libre.adacore.com/libre/" rel="nofollow">http://libre.adacore.com/libre/</a> and download it from <a href="http://libre.adacore.com/libre/download/" rel="nofollow">http://libre.adacore.com/libre/download/</a>. Just select Free Software or Academic Development and Build Download Package. The compiler is the option gnat-gpl-2011-i686-pc-mingw32-bin.exe, but there are several additional libraries in the list.</p>
| 21,808
|
<p>Inspired by <a href="https://stackoverflow.com/questions/220044/which-sort-algorithm-works-best-on-mostly-sorted-data">this question</a></p>
<p>The choice of which algorithm to use to sort a collection can be made better if we know ahead of time how well sorted a collection is. Is there a way we can measure (or maintain a measurement) of how well sorted the collection is? Can we do this in such a way that the cost of maintaining or measuring how well sorted something doesn't outweigh the benefit of choosing the best sort algorithm?</p>
|
<p>You could use sampling: Check N elements spaced evenly in the list and see how many are in order. (Of course that only works in a random-access list, but usually that's the type you sort.)</p>
<p>Also have a threshold for small N. If N is small (e.g. <code>10</code>) insertion sort is good even if the list isn't sorted. Java makes this optimization for small N in what is otherwise a merge-sort.</p>
|
<p>Well, first check if the collection is sorted by definition, that will always save you a bunch of time :) For the most part, don't bother extending a collection to test if it is sorted during its insert/delete operations, if the collection needs to be sorted, use a collection that is sorted by definition.</p>
<p>If you are trying to extend a collections class to track for sorting, just keep a separate sorted list of pointers to elements in the collection...</p>
<p>Finally , for 99.99% of the time, why bother? Just use a quicksort. If your dataset is small enough that the constant portion of Big O sorting on quicksort is going to override timesavings from bubble sort, the sort will be so fast you shouldn't even waste time asking the question.</p>
<p>Are you really telling me your question is the .01% of sorting that this needs to be addressed?</p>
| 27,092
|
<p>How do i make the plus minus icons bigger in the tree view in C# .net with out making visual styles disable.</p>
|
<p>I don't think you have any control about it. The only thing you can do is override the DrawNode event and paint the nodes yourself.</p>
<p>First you need to change the DrawMode to OwnerDrawAll. Take a look at the relevant msdn page, it contains surprisingly much detail: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.drawnode.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.drawnode.aspx</a></p>
|
<p>Bigger than the default 10px or so? I think follow the answer above, but because I came across this while trying to determine how to restore the original size:</p>
<p>Turns out you have some control if you set the indent property - anything less than 10 px starts to shrink the +/- icons. I had a treeview that was being set with an indent of 5, and I found that by restoring it to 15 (or even 10) restored the icon size.</p>
<p>I hope that helps someone else looking for a solution in that area.</p>
| 27,777
|
<p>How can I check if a string ends with a particular character in JavaScript?</p>
<p>Example: I have a string </p>
<pre><code>var str = "mystring#";
</code></pre>
<p>I want to know if that string is ending with <code>#</code>. How can I check it?</p>
<ol>
<li><p>Is there a <code>endsWith()</code> method in JavaScript?</p></li>
<li><p>One solution I have is take the length of the string and get the last character and check it.</p></li>
</ol>
<p>Is this the best way or there is any other way?</p>
|
<p><strong>UPDATE (Nov 24th, 2015):</strong></p>
<p>This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:</p>
<ul>
<li><a href="https://stackoverflow.com/users/570040/shauna">Shauna</a> -</li>
</ul>
<blockquote>
<p>Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith" rel="nofollow noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith</a></p>
</blockquote>
<ul>
<li><a href="https://stackoverflow.com/users/157247/t-j-crowder">T.J. Crowder</a> -</li>
</ul>
<blockquote>
<p>Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple <code>this.substr(-suffix.length) === suffix</code> approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: <a href="https://jsben.ch/OJzlM" rel="nofollow noreferrer">https://jsben.ch/OJzlM</a> And faster across the board when the result is false: <a href="http://jsperf.com/endswith-stackoverflow-when-false" rel="nofollow noreferrer">jsperf.com/endswith-stackoverflow-when-false</a> <strong>Of course, with ES6 adding endsWith, the point is moot. :-)</strong></p>
</blockquote>
<hr />
<p><strong>ORIGINAL ANSWER:</strong></p>
<p>I know this is a year old question... but I need this too and I need it to work cross-browser so... <strong>combining everyone's answer and comments</strong> and simplifying it a bit:</p>
<pre><code>String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
</code></pre>
<ul>
<li>Doesn't create a substring</li>
<li>Uses native <code>indexOf</code> function for fastest results</li>
<li>Skip unnecessary comparisons using the second parameter of <code>indexOf</code> to skip ahead</li>
<li>Works in Internet Explorer</li>
<li>NO Regex complications</li>
</ul>
<hr />
<p>Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:</p>
<pre><code>function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
</code></pre>
<hr />
<p><strong>EDIT:</strong> As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a <code>typeof</code> check like so:</p>
<pre><code>if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
</code></pre>
|
<p>7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:</p>
<pre><code>function strEndsWith(str, endwith)
{
var lastIndex = url.lastIndexOf(endsWith);
var result = false;
if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
{
result = true;
}
return result;
}
</code></pre>
| 35,491
|
<p>In another question, <a href="https://stackoverflow.com/users/26310/mark">Mark</a> speaks highly of IDEs, saying "some people still just dont know "why" they should use one...". As someone who uses vim for programming, and works in an environment where most/all of my colleagues use either vim or emacs for all of their work, what are the advantages of IDEs? Why should I use one?</p>
<p>I'm sure this is a charged issue for some people, and I'm not interested in starting a flame war, so <strong>please only reply with the reasons you believe an IDE-based approach is superior</strong>. I'm not interested in hearing about why I shouldn't use an IDE; I already don't use one. I'm interested in hearing from "the other side of the fence", so to speak.</p>
<p>If you think that IDEs may be suitable for some types of work but not others, I'm also interested to hear why.</p>
|
<p>It really depends on what language you're using, but in C# and Java I find IDEs beneficial for:</p>
<ul>
<li>Quickly navigating to a type without needing to worry about namespace, project etc</li>
<li>Navigating to members by treating them as hyperlinks</li>
<li>Autocompletion when you can't remember the names of all members by heart</li>
<li>Automatic code generation</li>
<li>Refactoring (massive one)</li>
<li>Organise imports (automatically adding appropriate imports in Java, using directives in C#)</li>
<li>Warning-as-you-type (i.e. some errors don't even require a compile cycle)</li>
<li>Hovering over something to see the docs</li>
<li>Keeping a view of files, errors/warnings/console/unit tests etc and source code all on the screen at the same time in a useful way</li>
<li>Ease of running unit tests from the same window</li>
<li>Integrated debugging</li>
<li>Integrated source control</li>
<li>Navigating to where a compile-time error or run-time exception occurred directly from the error details.</li>
<li>Etc!</li>
</ul>
<p>All of these save time. They're things I could do manually, but with more pain: I'd rather be coding.</p>
|
<p>A very good reason for using IDEs is that they are the accepted way of producing modern software. If you do not use one, then you likely use "old fashioned" stuff like vi and emacs. This can lead people to conclude - possibly wrongly - that you are stuck in your ways and unable to adapt to new ways of working. In an industry such as software development - where ideas can be out of date in mere months - this is a dangerous state to get into. It could seriously damage your future job prospects...</p>
| 25,539
|
<p>Can I put the painter into the class variables? :</p>
<pre><code>protected:
QPainter *myPainter;
...
void MyWidget::paintEvent(QPaintEvent *event)
{
myPainter = new QPainter(this);
</code></pre>
|
<p>A new anser to address more reentrancy more specifically...</p>
<p><a href="https://stackoverflow.com/users/19884/danatel">danatel</a> left the following comment to <a href="https://stackoverflow.com/questions/193656/is-it-necessary-for-qtpaintevent-to-be-reentrant#195755">this message</a> (in part):</p>
<blockquote>
<p>By reentrancy I mean this specific situation: 1) paintEvent handler saves a QPainter to a class variable. 2) paintEvent handler calls subroutines to draw something 3) one of the subroutines calls a Qt method 4) this Qt method generates another paintEvent recursively</p>
</blockquote>
<p>The answer to this is that it should likely be acceptable, unless you do something really odd. (And if you do something that odd, Qt will likely warn you or abort.) I think there might still be some confusion over what you mean by reentrant, but generating a paintEvent won't stop the execution flow of the current action to immediately process that event. Instead (like all events), it will be queued up for later processing. As long as you aren't doing multi-threading or calling processEvents, the execution order of the code while you are in one of your own functions should be very straightforward.</p>
<p>As an example, let's follow your steps and examine them in more detail. </p>
<ol>
<li><code>Foo::paintEvent()</code> handler
creates a QPainter and sets
<code>Foo::m_painter_p</code> at it. </li>
<li><code>Foo::paintEvent()</code> calls
<code>Foo::paintAntarticaFlag()</code>.</li>
<li><code>Foo::paintAntarticaFlag()</code>: a) uses <code>Foo::m_painter_p</code>, then b) calls something that calls <code>Foo::update()</code>, then c) uses <code>Foo::m_painter_p</code> some more.</li>
<li><code>Foo::update()</code>, which is really a Qt method, generates a paintEvent for Foo.</li>
</ol>
<p>The above sequence is fine, since update creates <strong>an event</strong>, which means delayed processing. If instead you called Foo::repaint(), that would cause an immediate recursion into Foo::paintEvent(), which would either cause Qt to abort because you are creating more than 1 painter for the same object, or your program to abort because it eventually (you know, in a few hundred milliseconds) blew out the stack.</p>
<p>If you are doing multiple threads and just want to trigger a redraw, you can still do that from the other thread, since it will just put a paintEvent on the queue to be handled by the proper thread at the proper time. If you are doing multiple threads and want to draw those flags using the same painter, well, don't. Just don't. In that case, you might consider drawing each flag to a shared image, and drawing that image where you are using the QPainter now.</p>
|
<p>If you are trying to avoid passing the painter widget to a number of subroutine calls, you can probably get away with a pointer to the painter as a class variable. As mentioned, you should still create/destroy it in the paintEvent function. Personally, I would probably just pass it to the helper functions, but you could do it this way.</p>
<p>Also, I'm not sure how your question related to reentrancy. All of the painting of UI elements should only be in the UI thread, if you have multiple threads. You can do a painter on an image in a different thread, but in that case you'd probably want to only be painting that image in that thread, not in multiple threads. Either way, I don't think you'd run into problems with reentrancy in the Qt functions you would call on a painter as long as you kept to those conditions.</p>
| 23,534
|
<p>I have a User class which may or may not have an associated Department. This is referenced through the foreign key DepartmentId, and the relevant field in the User table is set to allow nulls.</p>
<p>When I set up my "Create User" form and select no Department, I get a conflict error on SubmitChanges():</p>
<pre><code>The INSERT statement conflicted with the FOREIGN KEY constraint "FK_User_Department".
</code></pre>
<p>How can I convince Linq to SQL to insert a NULL when the "Department" has been selected as the "blank" first option?</p>
<p>Or, perhaps, is there a keyword I am missing for the "optionLabel" parameter of the Html.DropDownList method that does this? I am currently using "None" because using null or "" cause no "blank option" to be displayed, and I suspect that this may be contributing to the problem. Thanks for any assistance.</p>
|
<p>I have found a less-than-desirable solution by putting the following in my <code>UsersController.Create</code> method:</p>
<pre><code>// Snipped UpdateModel call
if (form["User.DepartmentId"].Length == 0)
{
createdUser.DepartmentId = null;
}
Models.User.DataContext.SubmitChanges();
</code></pre>
<p>Of course, I would prefer something that is cleaner / automatic.</p>
|
<p>You could have an entry "N/A" in Department which you assign when no department is selected. Then you wouldn't get a foreign key conflict.</p>
| 22,197
|
<p>Does anyone have any examples or resources where i might find information on scrolling text which is too long to display in a button control? I'm thinking something along these lines.</p>
<ul>
<li>Display as much text will fit within the current rect with a '...' at the end to signify overflow.</li>
<li>Pause for say 1 second then slowly scroll the text to the right edge displaying the right part of the string.</li>
<li>Display as much text will fit within the current rect with a '...' at the beginning to signify overflow.</li>
<li>Start the whole thing over in reverse.</li>
</ul>
<p>Is there an easy way to do this using the "core" or built in "animation" frameworks on a certain mobile device?</p>
<p>[edit]
Iwanted to add some more details as i think people are more focused on wether or not what i'm trying to accomplish is appropriate. The button is for the answers on a trivia game. It does not perform any speciffic UI function but is for displaying the answer. Apple themselves is doing this in their iQuiz trivia game on the iPod Nano and i think its a pretty elegant solution to answers that are longer than the width of my button.</p>
<p>In case its the '...' that is the difficult part of this. Lets say i removed this requirement. Could i have the label for the button be full sized but clipped to the client rect of the button and use some animation methods to scroll it within the clipping rect? This would give me almost the same effect minus the ellipses.</p>
|
<p>Here's an idea: instead of ellipses (...), use a gradient on each side, so the extra text fades away into the background color. Then you could do this with three CALayers: one for the text and two for fade effect.</p>
<p>The fade masks would just be rectangles with a gradient that goes from transparent to the background color. They should be positioned above the text layer. The text would be drawn on the text layer, and then you just animate it sliding back and forth in the manner you describe. You can create a CGPath object describing the path and add it to a CAKeyframeAnimation object which you add to the text layer.</p>
<p>As for whether you think this is "easy" depends on how well you know Core Animation, but I think once you learn the API you'll find this isn't too bad and would be worth the trouble.</p>
|
<p>Pretty sure you can't do that using the standard API, certainly not with UILineBreakMode. In addition, the style guide says that an ellipsis indicates that the button when pressed will ask you for more information -for example Open File... will ask for the name of a file. Your proposed use of ellipsis violates this guideline.</p>
<p>You'd need some custom logic to implement the behaviour you describe, but I don't think it's the way to go anyway.</p>
| 17,715
|
<p>I Have following code:</p>
<p>Controller:</p>
<pre><code>public ActionResult Step1()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Step1(FormCollection form)
{
TempData["messageStatus"] = new Random().Next(1, 1000);
return RedirectToAction("Step1");
}
</code></pre>
<p>View:</p>
<pre><code><%=TempData["messageStatus"]%>
</code></pre>
<p>in first time in view im getting <strong>12345</strong> for example, but when i request second time of course i must get something else instead <strong>12345</strong> for example <strong>54321</strong> but not, im getting same result <strong>12345</strong>, how can u explain it? <strong>RedirectToAction</strong> cache pages?</p>
<p>where does it mean i must put Guid in my urls for resolving problems with cache? what do u think about this issue?</p>
|
<p>I'm guessing you're running into caching problems. It's not a problem with redirect to action. All RedirectToAction does is issues a redirect response to your browser telling it to request Step01. Then your browser makes a request for Step01.</p>
<p>In that case, your browser might have Step01 cached. So you need to add a Response header in STep01 indicating it should never be cached. You can do this like so:</p>
<pre><code>[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Step1()
{
return View();
}
</code></pre>
<p>Or you can add a random querystring to the redirect to action call by passing in an arbitrary value.</p>
|
<p>Try this:</p>
<pre><code>TempData["messageStatus"] = new Random(DateTime.Now.Millisecond).Next(1, 1000);
</code></pre>
| 49,227
|
<p>Can anyone point me to a good tutorial on creating a bootable Linux CD from scratch?</p>
<p>I need help with a fairly specialized problem: my firm sells an expansion card that requires custom firmware. Currently we use an extremely old live CD image of RH7.2 that we update with current firmware. Manufacturing puts the cards in a machine, boots off the CD, the CD writes the firmware, they power off and pull the cards. Because of this cycle, it's essential that the CD boot and shut down as quickly as possible.</p>
<p>The problem is that with the next generation of cards, I have to update the CD to a 2.6 kernel. It's easy enough to acquire a pre-existing live CD - but those all are designed for showing off Linux on the desktop - which means they take forever to boot.</p>
<p>Can anyone fix me up with a current How-To?</p>
<hr />
<h3>Update:</h3>
<p>So, just as a final update for anyone reading this later - the tool I ended up using was "livecd-creator".</p>
<p>My reason for choosing this tool was that it is available for RedHat-based distributions like CentOs, Fedora and RHEL - which are all distributions that my company supports already. In addition, while the project is very poorly documented it is extremely customizable. I was able to create a minimal LiveCD and edit the boot sequence so that it booted directly into the firmware updater instead of a bash shell.</p>
<p>The whole job would have only taken an hour or two if there had been a README explaining the configuration file!</p>
|
<p>One key piece of advice I can give is that most LiveCDs use a compressed filesystem called squashfs to cram as much data on the CD as possible. Since you don't need compression, you could run the mksquashfs step (present in most tutorials) with -noDataCompression and -noFragmentCompression to save on decompression time. You may even be able to drop the squashfs approach entirely, but this would require some restructuring. This may actually be slower depending on your CD-ROM read speed vs. CPU speed, but it's worth looking into.</p>
<p>This <a href="https://help.ubuntu.com/community/LiveCDCustomization" rel="nofollow noreferrer">Ubuntu tutorial</a> was effective enough for me to build a LiveCD based on 8.04. It may be useful for getting the feel of how a LiveCD is composed, but I would probably <strong>not</strong> recommend using an Ubuntu LiveCD. </p>
<p>If at all possible, find a minimal LiveCD and build up with only minimal stripping out, rather than stripping down a huge LiveCD like Ubuntu. There are some situations in which the smaller distros are using smaller/faster <em>alternatives</em> rather than just leaving something out. If you want to get seriously hardcore, you could look at <a href="http://www.linuxfromscratch.org/" rel="nofollow noreferrer">Linux From Scratch</a>, and include <em>only</em> what you want, but that's probably more time than you want to spend.</p>
|
<p>Depends on your distro. Here's a good article you can check out from <a href="http://lwn.net/Articles/172132/" rel="nofollow noreferrer">LWN.net</a></p>
<p>There is a book I used which covers a lot of distros, though it does not cover creating a flash-bootable image. The book is <a href="https://rads.stackoverflow.com/amzn/click/com/0132432749" rel="nofollow noreferrer" rel="nofollow noreferrer">Live Linux(R) CDs: Building and Customizing Bootables</a>. You can use it with supplemental information from your distro of choice.</p>
| 5,313
|
<p>I have a simple web service operation like this one:</p>
<pre><code> [WebMethod]
public string HelloWorld()
{
throw new Exception("HelloWorldException");
return "Hello World";
}
</code></pre>
<p>And then I have a client application that consumes the web service and then calls the operation. Obviously it will throw an exception :-)</p>
<pre><code> try
{
hwservicens.Service1 service1 = new hwservicens.Service1();
service1.HelloWorld();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
</code></pre>
<p>In my catch-block, what I would like to do is extract the Message of the actual exception to use it in my code. The exception caught is a <code>SoapException</code>, which is fine, but it's <code>Message</code> property is like this...</p>
<pre><code>System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Exception: HelloWorldException
at WebService1.Service1.HelloWorld() in C:\svnroot\Vordur\WebService1\Service1.asmx.cs:line 27
--- End of inner exception stack trace ---
</code></pre>
<p>...and the <code>InnerException</code> is <code>null</code>.</p>
<p>What I would like to do is extract the <code>Message</code> property of the <code>InnerException</code> (the <code>HelloWorldException</code> text in my sample), can anyone help with that? If you can avoid it, please don't suggest parsing the <code>Message</code> property of the <code>SoapException</code>.</p>
|
<p>Unfortunately I don't think this is possible.</p>
<p>The exception you are raising in your web service code is being encoded into a Soap Fault, which then being passed as a string back to your client code.</p>
<p>What you are seeing in the SoapException message is simply the text from the Soap fault, which is not being converted back to an exception, but merely stored as text.</p>
<p>If you want to return useful information in error conditions then I recommend returning a custom class from your web service which can have an "Error" property which contains your information.</p>
<pre><code>[WebMethod]
public ResponseClass HelloWorld()
{
ResponseClass c = new ResponseClass();
try
{
throw new Exception("Exception Text");
// The following would be returned on a success
c.WasError = false;
c.ReturnValue = "Hello World";
}
catch(Exception e)
{
c.WasError = true;
c.ErrorMessage = e.Message;
return c;
}
}
</code></pre>
|
<p>I ran into something similar a bit ago and <a href="http://theruntime.com/blogs/jacob/archive/2008/01/28/getting-at-the-details.aspx" rel="nofollow noreferrer">blogged about it</a>. I'm not certain if it is precisely applicable, but might be. The code is simple enough once you realize that you have to go through a MessageFault object. In my case, I knew that the detail contained a GUID I could use to re-query the SOAP service for details. The code looks like this:</p>
<pre><code>catch (FaultException soapEx)
{
MessageFault mf = soapEx.CreateMessageFault();
if (mf.HasDetail)
{
XmlDictionaryReader reader = mf.GetReaderAtDetailContents();
Guid g = reader.ReadContentAsGuid();
}
}
</code></pre>
| 5,201
|
<p>Does anyone have time to take a look at it? </p>
<p>I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot</p>
|
<p>I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on <a href="http://www2.webkit.org/perf/sunspider-0.9/sunspider.html" rel="noreferrer">SunSpider JavaScript Benchmark</a> with the following results:</p>
<ul>
<li>Firefox - total: 2900.0ms +/- 1.8%</li>
<li>Chrome - total: <strong>1549.2ms +/- 1.7%</strong></li>
</ul>
<p>and on <a href="http://code.google.com/apis/v8/benchmarks.html" rel="noreferrer">V8 Benchmark Suite</a> with the following results (higher score is better):</p>
<ul>
<li>Firefox - score: 212</li>
<li>Chrome - score: <strong>1842</strong></li>
</ul>
<p>and on <a href="http://celtickane.com/webdesign/jsspeedarchive.php" rel="noreferrer">Web Browser Javascript Benchmark</a> with the following results:</p>
<ul>
<li>Firefox - total duration: 362 ms</li>
<li>Chrome - total duration: <strong>349 ms</strong></li>
</ul>
<p><em>Machine:</em> Windows XP SP2, Intel Core2 DUO T7500 @ 2.2 Ghz, 2 GB RAM</p>
<p>All blog posts and articles that I've read so far also claim that V8 is clearly the fastest JavaScript engine out there. See for example - <a href="http://waynepan.com/2008/09/02/v8-tracemonkey-squirrelfish-ie8-benchmarks/" rel="noreferrer">V8, TraceMonkey, SquirrelFish, IE8 BenchMarks</a></p>
<blockquote>
<p>"... Needless to say, Chrome’s V8 blows away all the current builds of the next-generation of JavaScript VMs. Just to be clear, WebKit and FireFox engines haven’t even hit beta, but it looks like the performance bar has just been set to an astronomical height by the V8 Team."</p>
</blockquote>
|
<p>It's really speedy. Visibly so. I was pretty impressed with its performance compared with Firefox 3. Already made it my default browser.</p>
| 6,227
|
<p>Is there a way to have two columns, that match each other in height, without using table cells, fixed heights or Javascript?</p>
<p><strong>Using a TABLE</strong></p>
<pre><code><table>
<tr>
<td style="background:#F00;">
This is a column
</td>
<td style="background:#FF0;">
This is a column<br />
That isn't the same<br />
height at the other<br />
yet the background<br />
still works
</td>
</tr>
</table>
</code></pre>
<p><strong>Using DIVs</strong></p>
<pre><code><div style="float:left;background:#F00" >
This is a column
</div>
<div style="float:left;background:#FF0" >
This is a column<br />
That isn't the same<br />
height at the other<br />
yet the background<br />
still works
</div>
<div style="clear:both;" ></div>
</code></pre>
<p>The goal is to make both backgrounds extend the full height regardless of which side is taller.</p>
<p>Nesting one in the other wouldn't work because it doesn't guarantee both side are the correct height.</p>
<p><strong>Unfortunately, the preview showed the working HTML, but the actual post stripped it out. You should be able to paste this into an HTML file and see what I mean.</strong></p>
|
<p><a href="http://www.xs4all.nl/~peterned/examples/csslayout1.html" rel="nofollow noreferrer">http://www.xs4all.nl/~peterned/examples/csslayout1.html</a></p>
<p>this is the kind of thing you want, give them both a height of 100% (using this css trick) and they'll stretch out to the height of the containing div!</p>
<p>edit: forgot to mention, put them in a container div!</p>
<p>Edit: </p>
<pre><code><html>
<head>
<style>
html, body
{
margin: 0;
padding: 0;
height: 100%; /* needed for container min-height */
}
#container
{
background-color: #333333;
width: 500px;
height: auto !important; /* real browsers */
height: 100%; /* IE6: treaded as min-height*/
min-height: 100%; /* real browsers */
}
#colOne, #colTwo
{
width: 250px;
float: left;
height: auto !important; /* real browsers */
height: 100%; /* IE6: treaded as min-height*/
min-height: 100%; /* real browsers */
}
#colOne
{
background-color: #cccccc;
}
#colTwo
{
background-color: #f4f5f3;
}
</style>
</head>
<body>
<div id="container">
<div id="colOne">
this is something</div>
<div id="colTwo">
this is also something</div>
<div style="clear: both;">
</div>
</div>
</body>
</html>
</code></pre>
|
<p>Theres a simple way of achieving this with clever HTML and CSS.</p>
<p>First the HTML:</p>
<pre><code><div id="container">
<div id="col1">
this is column 1
</div>
<div id="col2">
this is column 2<br />
it is obviously longer than the first column <br />
YEP!
</div>
</div>
</code></pre>
<p>Please note the lack of clear:both unsemantic div.</p>
<p>Now the CSS:</p>
<pre><code>#container { background:#f0f; overflow:hidden; width:400px; }
#col1, #col2 { float:left; width:50%; }
#col2 { background:#ff0; }
</code></pre>
<p>The overflow hidden in the container rule makes sure that the container expands to the size of the contained floated divs (and gets rid of the unsematic clearing div that everyone loves so much).</p>
<p>The background of the container applies to the first column. The background of the col2 div applies only to the second div. This is what gives us the illusion that both divs are always the same height.</p>
<p>Simple, semantic solution in 3 lines of CSS. Enjoy</p>
<p><strong>EDIT: Please comment on reason to vote down, otherwise I have to guess why my answer is wrong. In this case I had forgot to add the width property to the container so that it plays nice with IE6/7. Please check the revised CSS above.</strong></p>
| 43,527
|
<p>I usually format my project directory like J-P Boodhoo. a main dir containing solution file, then a lib folder for all third-party lib, a src dir, a tools lib for third-party that wont be deployed.... <a href="http://blog.jpboodhoo.com/DirectoryStructureForProjects.aspx" rel="noreferrer">For more info look here</a></p>
<p>I set in my project the reference path for all the needed folder, but if a developper checkout the trunk, he have to set all the reference path. Is there a way to simplify this ?</p>
<p>And am I using Visual Studio 2008.</p>
<p>Thank you.</p>
|
<p>I'm not sure which Visual Studio language you use, but if it's C++, then then file paths are stored in the <code>.vcproj</code> project file which should also be under version control. (NOTE: the <code>.sln</code> solution file does NOT store path settings) If you are careful to use relative, rather than absolute paths, it should be easily sharable among multiple developers.</p>
<p>In Visual C++ 2008, <a href="http://msdn.microsoft.com/en-us/library/2208a1f2.aspx" rel="nofollow noreferrer">project files are XML</a> so you can edit them directly. If you want to get really fancy, you can use <a href="http://msdn.microsoft.com/en-us/library/a4xbdz1e.aspx" rel="nofollow noreferrer"><code>.vsprops</code> property sheets</a> for additional control.</p>
|
<p>I use a shared folder on the network for stuff like that. And give that folder full trust. on the PDC i just have a login script that maps approriately. Its might not be the best way, but its worked for me without any issues.</p>
<p>Another solution I have used in the past is a common folder on each machine where all dependancies go, and have it syncronize with some sort of tool. I use Backup Exec which comes with Desktop and Laptop option which has a syncing feature, but other things work as well.</p>
| 15,684
|
<p>I'm trying to retrieve numeric values from a <code>DataGridView</code>. So far, the only way I've found is to retrieve them as a string and convert them to numeric.</p>
<pre><code>Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());
</code></pre>
<p>There must be an easier way. The cell is originally populated from a <code>DataSet</code> with a numeric field value but since the <code>DataGridViewCell</code> object returns it as an object, I can't do a straight assignment. I must be missing something simple here.</p>
<p>Thanks.</p>
|
<p>With <code>DataGridViewCell</code> you can just cast the <code>.Value</code> to your known type; the following is a complete example that shows this happening (using double) from a <code>DataTable</code> (like your example).
Additionally, <code>Convert.To{blah}(...)</code> and <code>Convert.ChangeType(...)</code> might be helpful.</p>
<pre><code>using System.Data;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
DataTable table = new DataTable
{
Columns = {
{"Foo", typeof(double)},
{"Bar", typeof(string)}
},
Rows = {
{123.45, "abc"},
{678.90, "def"}
}
};
Form form = new Form();
DataGridView grid = new DataGridView {
Dock = DockStyle.Fill, DataSource = table};
form.Controls.Add(grid);
grid.CurrentCellChanged += delegate
{
form.Text = string.Format("{0}: {1}",
grid.CurrentCell.Value.GetType(),
grid.CurrentCell.Value);
if (grid.CurrentCell.Value is double)
{
double val = (double)grid.CurrentCell.Value;
form.Text += " is a double: " + val;
}
};
Application.Run(form);
}
}
</code></pre>
|
<p>What is the error you are getting? <code>Convert.ToDouble</code> has an overloaded method that takes an object, so you shouldn't need the <code>ToString()</code>? Unless you are doing a <code>TryParse</code>?</p>
| 18,702
|
<p>I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. </p>
<p>I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages "easy" questions in the private beta.</p>
<p>What can newbies like me do for the site at this stage besides voting questions and answers?</p>
|
<h1>Vote!</h1>
<p>Private Betas love, love, <em>love</em> votes. Without votes, it's difficult to attain privileges, get rewards, and help push us out to public beta.</p>
<h1>Ask Questions!</h1>
<p>I know you said this:</p>
<blockquote>
<p>I thought about asking about how to get started with 3D printing but SE explicitly discourages "easy" questions in the private beta.</p>
</blockquote>
<p>But here's the catch. "Easy" isn't defined. If you have an "easy" question, but it is specific, high-quality, and to the point, and you can show some effort in it, then, please, go ahead and ask it!</p>
<h1>Participate!</h1>
<p>You have a voice in our meta discussions as well. You also have the authority to suggest edits, to posts, tag wikis, and tag excerpts. They also get you +2 rep for each that is approved, which can help bring you more afloat. You can also give your opinion in scope, by casting close and reopen votes as well :)</p>
|
<p>I would suggest doing a bit of basic research on 3D printing (including reading questions and answers). From these you will learn more about it and hopefull you will have new questions about 3D printing that can be asked. </p>
<p>If you are looking at getting a 3D printer, you could ask about different features listed and why they make prints better.</p>
| 0
|
<p>I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this></p>
<p>I tried the following but this resulted in a blank file?</p>
<pre><code>
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "file:///ReportWiz.dtd");
xformer.transform(source, result);
OutputStream writer = new FileOutputStream(file);
Byte b = '\n';
writer.write(b);
writer.close();</code></pre>
|
<p>Simple... just add the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)" rel="noreferrer">append</a> option:</p>
<pre><code> new FileOutputStream(f, true /* append */);
</code></pre>
|
<p>I didn't know this Transformer class. But I see no connection between your writer/file variables and your xformer/source/result variables... Looks like you write only a newline.<br>
Unless you omitted some essential part.</p>
| 48,294
|
<p>I have a ListCtrl that displays a list of items for the user to select. This works fine except that when the ctrl is not large enough to show all the items, I want it to expand downwards with a vertical scoll bar rather than using a horizontal scroll bar as it expands to the right.</p>
<p>The ListCtrl's creation:</p>
<pre><code>self.subjectList = wx.ListCtrl(self, self.ID_SUBJECT, style = wx.LC_LIST | wx.LC_SINGLE_SEL | wx.LC_VRULES)
</code></pre>
<p>Items are inserted using wx.ListItem:</p>
<pre><code>item = wx.ListItem()
item.SetText(subject)
item.SetData(id)
item.SetWidth(200)
self.subjectList.InsertItem(item)
</code></pre>
|
<p>Use the <a href="http://docs.wxwidgets.org/stable/wx_wxlistctrl.html#wxlistctrl" rel="nofollow noreferrer">wxLC_REPORT</a> style.</p>
<pre><code>import wx
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.test = wx.ListCtrl(self, style = wx.LC_REPORT | wx.LC_NO_HEADER)
for i in range(5):
self.test.InsertColumn(i, 'Col %d' % (i + 1))
self.test.SetColumnWidth(i, 200)
for i in range(0, 100, 5):
index = self.test.InsertStringItem(self.test.GetItemCount(), "")
for j in range(5):
self.test.SetStringItem(index, j, str(i+j)*30)
self.Show()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
</code></pre>
|
<p>Try this:</p>
<pre><code>import wx
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.test = wx.ListCtrl(self, style = wx.LC_ICON | wx.LC_AUTOARRANGE)
for i in range(100):
self.test.InsertStringItem(self.test.GetItemCount(), str(i))
self.Show()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
</code></pre>
| 26,441
|
<p>I'm desperately searching for a tool allowing me to copy documents with their old versions from a SharePoint 2003 to a SharePoint 2007 site.<br />
Do you know about any simple (and preferably free) tool which does this?<br /></p>
|
<p>We recently did a migration from SPS 2003 to MOSS 2007, and I was trying to figure out how to do this. Sadly, there didn't seem to be a great way. What I ended up doing was using a back up of my SPS 2003 content database and a MOSS 2007 VM to do a database attach upgrade of the whole SPS 2003 portal. Then, I used the content migration commands (stsadm -o export, stsadm -o import) to move the lists with all of their versions to the "real" MOSS 2007 site collection. </p>
<p>This <a href="http://farhanfaiz.wordpress.com/2008/05/23/sharepoint-upgrade-database-migration/" rel="nofollow noreferrer">page</a> gave me the steps for doing the database migration.</p>
<p>There are also some nice commands you can potentially use for moving just a list <a href="http://stsadm.blogspot.com/" rel="nofollow noreferrer">here</a>. For the record, the migration commands (e.g. gl-exportlist, gl-importlist) only work between two MOSS 2007 installations.</p>
<p>I definitely had to try it both with the stsadm extensions and the built-in commands a couple of times before the results were acceptable. The real key was doing the database migration to a VM to get everything into MOSS so I could use those tools.</p>
<p>I know this seems like a crazy amount of work, but it's the only way I found to get it done without dropping thousands of dollars for something like AvePoint's DocAve Migrators. And it really wasn't <em>that</em> bad.</p>
<p>One thing to watch out for is that, if you include user security when you do the export and import, you will get a lot of SharePoint groups and users added to your production site collection.</p>
|
<p>the splistcp worked really well, but I was getting a time out error every once in a while when it was trying to move a file. I was getting a time out message, then a message that file couldn't be found, then the program just quit. I downloaded the source code, found in MBSPListItemsMap.cs where the program was trying to get the file.</p>
<p>I added a finally block below the the catch code around line 620 to write to consule to telling me what the system is doing:</p>
<pre><code> ` catch (Exception e)
{
Console.WriteLine(e.Message);
bDownloadError = true;
}
finally
{
if (bDownloadError)
{
Console.WriteLine("Error in downloading file: " + fileName);
Console.WriteLine("Moving to next file");
}
}
if (!bDownloadError)
{
if (Program.beVerbose)
{
Console.WriteLine("Attaching " + fileName);
}
byte[] fileContents = MBSPSiteMap.ByteArrayFromFilePath(downloadPath);
newItem.Attachments.Add(fileName, fileContents);
File.Delete(downloadPath);
} `
</code></pre>
<p>I also added some Console.WriteLine statements else where to let me know what the system is doing. Otherwise the system just chuggs along and you don't have a very good indicator of what it is doing.</p>
<p>This program was a great help as I had to move 770 records with about 20 columns of information and several attachments.</p>
<p>THANKS MICHAEL!!!!</p>
| 34,320
|
<p>I have a simple application, which should send a single byte to a serial port once a minute. But sometimes, from some strange reason, it freezes somewhere in the WriteFile() function. Both sw and hw flow controls are turned off. I've googled some stuff about pending read operations performed from another threads, but I believe this is not a problem, because my app has single thread. Also, handle from CreateFile looks valid, so the port should not be used by any other applications. Have anybody suffered this?</p>
|
<p>If you google for the words <em>writefile hangs</em>, you'll find a number of discussions on this problem. Some leads are buffer overruns, sizing your buffer correctly, a defective COM port, clearing the status on error... Seems like there are plenty of things to try.</p>
<p>Another thing I would suggest is to use a communications library instead of calling the API directly, something like Async Professional (<a href="http://sourceforge.net/projects/tpapro/" rel="nofollow noreferrer">http://sourceforge.net/projects/tpapro/</a>). Even if they add some overhead to your application, they might simplify your work and avoid a number of potential pitfalls...</p>
|
<p>Well, I'm using this library: <a href="http://lhdelphi.ic.cz/uploader/storage/ComDrv32.pas" rel="nofollow noreferrer">http://lhdelphi.ic.cz/uploader/storage/ComDrv32.pas</a> in Delphi 7, on Windows XP, but the component inside is just a wrapper around some Win API calls, CreateFile, WriteFile, etc.</p>
| 31,340
|
<p>Recently, the ticking sounds started to come from feeder of my UM2. Inspecting it I have noticed that once in a while stepper motor jumps back for few steps. I have an idea of what can be the reason, but I just want to hear what you can think of. That is the video of feeder during the printing :)
<a href="https://youtu.be/z6CzudMOeD0" rel="nofollow">https://youtu.be/z6CzudMOeD0</a> First tick at 10sec</p>
|
<p>Ultimately, your stepper motor is unsuccessful in driving the filament through the extruder. A couple potential reasons:</p>
<ul>
<li>extruder temperature isn't high enough. This could either be operator error from not setting the temperature correctly or your machine is getting a false reading. Typically, for ABS/PLA, you can get away with a low extruding temperature of about 210c.</li>
<li>filament tension is too high. This happens if, say, your spool of filament gets kinked or wrapped around the spool spindle.</li>
<li>your nozzle is clogged. I've encountered where I had back flow coming out of the nozzle (filaments oozed around from the hotend at the threads). This was a result of not putting the hotend back together correctly. There was a enough hardened plastic backed up in the hotend that when I threaded the nozzle back on, it technically didn't fit back on all the way.</li>
</ul>
|
<p>Oh yeah that is way too low for the ultimaker.</p>
<p>That temp is a general "this is what PLA melts at" so if you took plastic, heated it up to that temp it would melt.</p>
<p>However, you don't heat all the plastic at once. Your hotend it at that temp and if you let it sit it would heat up (fairly quickly). Printers like the ultimaker are fast, and well designed. They have a very small heat melt zone. So the plastic only has a fraction of time to heat up.</p>
<p>Solution? Higher temps!</p>
<p>(do not do this example. Not liable if you hurt yourself) You know how you can take a lighter and almost slowly wave your finger thought it without getting burned? You know if you let it stay even a full second you would regret it. Same thing here. It is going too fast to heat up.</p>
| 240
|
<p>Can anyone recommend a decent C image library?</p>
<p>I'm after loaders for bmp, gif, jpg, png and tga.</p>
<p>I want to use this for programming my <strong>Sony Playstation Portable</strong>, so opensource would be very handy.</p>
<p>After some googleing I've found FreeImage and CImg, but both feel rather heavy, and CImg is C++ not C.</p>
|
<p>If you control the images you're loading, the lightest loader I know is Sean Barrett's awesome <a href="http://nothings.org/stb_image.c" rel="noreferrer">stb_image.c</a> (direct link to single file source code!).</p>
<p>There are also other very worthwhile libraries on Sean's site such as a tiny TrueType rasterizer and Vorbis decompressor, btw.</p>
<p>If you need OpenGL image loading that uses stb_image, I'll humbly point you to <a href="http://bitbucket.org/akx/soilex" rel="noreferrer">SOILex</a>...</p>
|
<p><a href="http://code.google.com/p/kgui/source/browse/trunk/kguiimage.cpp" rel="nofollow noreferrer">Here</a> is some code I wrote for handling images. It is in c++ ( not c ) but you should be able to easily extract the BMP and GIF load code. It's licensed LGPL. </p>
<p>I use the libpng and jpeglib for decompressing those formats. </p>
| 7,269
|
<p>I am trying to build a working encrypted signature for the Amazon S3 web service, writing a connection library using Objective C. </p>
<p>I have run into HMAC SHA-1 digest problems with the ObjC code, so I'm putting that to the side and looking at existing, working Perl code, to try to troubleshoot digest creation.</p>
<p>I am testing HMAC SHA-1 digest output from the <code>s3ls</code> command of the <code>Net::Amazon::S3</code> package and comparing that against the <code>_encode</code> subroutine that I pulled out and put into its own perl script:</p>
<pre><code>#!/usr/bin/perl -w
use MIME::Base64 qw(encode_base64);
use Digest::HMAC_SHA1;
use String::Escape qw( printable unprintable );
sub _ascii_to_hex {
(my $str = shift) =~ s/(.|\n)/sprintf("%02lx", ord $1)/eg;
return $str;
}
sub _encode {
my ( $aws_secret_access_key, $str ) = @_;
print "secret key hex: "._ascii_to_hex($aws_secret_access_key)."\n";
my $hmac = Digest::HMAC_SHA1->new($aws_secret_access_key);
$hmac->add($str);
my $digest = $hmac->digest;
print "cleartext hex: "._ascii_to_hex($str)."\n";
print "digest hex: "._ascii_to_hex($digest)."\n";
my $b64 = encode_base64( $digest, '' );
print "encoded: ".$b64."\n";
}
my $secret = "abcd1234";
my $cleartext = "GET\n\n\nFri, 12 Dec 2008 10:08:51 GMT+00:00\n/";
_encode($secret, $cleartext);
</code></pre>
<p>Here is sample output from this script:</p>
<pre><code>$ ./testhmac.pl
secret key hex: 6162636431323334
cleartext hex: 4745540a0a0a4672692c2031322044656320323030382031303a30383a353120474d542b30303a30300a2f
digest hex: 63308f9b8a198440d6d8685a3f3f70d0aab02f68
encoded: YzCPm4oZhEDW2GhaPz9w0KqwL2g=
</code></pre>
<p>What I am testing is that, if I input the same secret key and cleartext into the same <code>_encode</code> function of the <code>Net::Amazon::S3</code> package, I should see the very same secret key, cleartext, and digest bytes.</p>
<p>Indeed, I get the same bytes for the secret key and cleartext.</p>
<p>But I get something different for the digest (and of course the base64 encoding), e.g.:</p>
<pre><code>$ s3ls --access-key=foobar --secret-key=abcd1234
...
secret key hex: 6162636431323334
cleartext hex: 4745540a0a0a4672692c2031322044656320323030382031303a30383a353120474d542b30303a30300a2f
digest hex: c0da50050c451847de7ed055c5286de584527a22
encoded: wNpQBQxFGEfeftBVxSht5YRSeiI=
</code></pre>
<p>I have verified that the secret key and clear text are the same input to both scripts. The encoding subroutine is virtually identical in both scripts (except for an unused argument passed to the subroutine, which I remove from my custom version).</p>
<p>What would cause the HMAC SHA-1 digest to be computed differently in both cases, if the input bytes and <code>_encode</code> subroutine are the same?</p>
<p>(I have also verified the two scripts against the test cases at <a href="http://www.faqs.org/rfcs/rfc2202.html" rel="nofollow noreferrer">RFC 2201</a>.)</p>
|
<p>I find the the main problems I have had with hashes in comparisons are:</p>
<ol>
<li>ensure the data and key are the same in both comparisons</li>
<li>ensure the data and key are in the same character encoding in both comparisons</li>
<li>ensure the key and text are being passed the same in both scripts, i.e. which one is key and which one is text (this has caught me more than once).</li>
</ol>
<p>Try using the Digest::SHA module to create the hash for you and compare the results with that.</p>
<pre><code>use Digest::SHA qw(hmac_sha1_hex);
my $hash = hmac_sha1_hex($data, $key);
</code></pre>
<p>See docs at <a href="http://perldoc.perl.org/Digest/SHA.pdf" rel="nofollow noreferrer">http://perldoc.perl.org/Digest/SHA.pdf</a></p>
|
<p>I'm afraid I can't help much here, but there's definitely something wrong with what you posted. Your example script produces different output for me and the output you posted really cannot be correct.</p>
<p>How could this </p>
<pre><code>secret key hex: abcd...1234
</code></pre>
<p>ever be the result of that</p>
<pre><code>_ascii_to_hex("blahblahblah")
</code></pre>
<p>Of course, the whole ascii_to_hex thing is completely irrelevant to your problem, but it shows that you should double-check your results.</p>
| 47,307
|
<p>I have an ASP.NET 1.1 application that uses the following code to write out a file in the response:</p>
<pre><code>Dim objStream As Object
objStream = Server.CreateObject("ADODB.Stream")
objStream.open()
objStream.type = 1
objStream.loadfromfile(localfile)
Response.BinaryWrite(objStream.read)
</code></pre>
<p>This code is called by a pop up window that displays this file or gives a open/save dialog in Internet Explorer. The problem is, that it seems to work fine in IE6 but in IE7 the pop up opens and then closes without displaying the file. Any one know whats wrong?</p>
|
<p>I have a code like this for download files from server:</p>
<pre><code>strFilename = Server.MapPath("/App_Upload/" & strFilename)
With Response
.AddHeader("Content-Type", "binary/octet-stream")
.AddHeader("Content-Disposition", "attachment; filename=" & strFilename & ";")
.WriteFile(strFilename)
.End()
End With
</code></pre>
<p>Try if work in your case.</p>
|
<p>So the images that are being served by Asp.Net are tiff files. And it says <a href="http://forums.asp.net/p/1113169/2332853.aspx#2332853" rel="nofollow noreferrer">here</a> that IE7 doesn't display files with 4 letter extensions for some reason. I think I'll try to change it to 3 letters and see what happens.</p>
| 35,982
|
<p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
|
<p>It depends on how long they are. I tend to structure them like so:</p>
<pre><code>[x.id for x
in self.db.query(schema.allPostsUuid).execute(timeout=20)
if x.type == 'post'
and x.deleted is not False
and ...
and ...]
</code></pre>
<p>That way every expression has its own line.</p>
<p>If any line becomes too big I like to extract it out in a lambda or expression:</p>
<pre><code>transform = lambda x: x.id
results = self.db.query(schema.allPostsUuid).execute(timeout=20)
condition = lambda x: x.deleted is not False and ... and ...
[transform(x) for x in results if condition(x)]
</code></pre>
<p>And then if a lambda becomes too long it gets promoted to a function.</p>
|
<pre><code> allUuids = [
x.id
for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)
if x.type == "post"
and x.deleted
]
</code></pre>
| 40,149
|
<p>I have a piece of code looking like this : </p>
<pre><code>TAxis *axis = 0;
if (dynamic_cast<MonitorObjectH1C*>(obj))
axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis();
</code></pre>
<p>Sometimes it crashes : </p>
<pre><code>Thread 1 (Thread -1208658240 (LWP 11400)):
#0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x048c67fb in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x04870649 in do_system () from /lib/tls/libc.so.6
#3 0x048709c1 in system () from /lib/tls/libc.so.6
#4 0x001848bd in system () from /lib/tls/libpthread.so.0
#5 0x0117a5bb in TUnixSystem::Exec () from /opt/root/lib/libCore.so.5.21
#6 0x01180045 in TUnixSystem::StackTrace () from /opt/root/lib/libCore.so.5.21
#7 0x0117cc8a in TUnixSystem::DispatchSignals ()
from /opt/root/lib/libCore.so.5.21
#8 0x0117cd18 in SigHandler () from /opt/root/lib/libCore.so.5.21
#9 0x0117bf5d in sighandler () from /opt/root/lib/libCore.so.5.21
#10 <signal handler called>
#11 0x0533ddf4 in __dynamic_cast () from /usr/lib/libstdc++.so.6
</code></pre>
<p>I have no clue why it crashes. <em>obj</em> is not null (and if it was it would not be a problem, would it ?). </p>
<p>What could be the reason for a dynamic cast to crash ? </p>
<p>If it can't cast, it should just return NULL no ?</p>
|
<p>Some possible reasons for the crash:</p>
<ul>
<li><code>obj</code> points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type).</li>
<li><code>obj</code> points to an object that has been freed.</li>
<li><code>obj</code> points to unmapped memory, or memory that has been mapped in such a way as to generate an exception when accessed (such as a guard page or inaccessible page).</li>
<li><code>obj</code> points to an object with a polymorphic type, but that type was defined in an external library that was compiled with RTTI disabled.</li>
</ul>
<p>Not all of these problems necessarily cause a crash in all situations.</p>
|
<p>Can the value of obj be changed by a different thread?</p>
| 35,161
|
<p>How can I enable Emacs key bindings in Microsoft Visual C# 2008 Express Edition?</p>
|
<p>It seems that the Emacs keybinding file (<strong>Emacs.vsk</strong>) it's not included on Visual Studio Express Editions, however you might be able to find it and use it :-)</p>
|
<p>Additionally, install Visual C++ Express Edition. It includes the emacs keybindings.</p>
| 42,384
|
<p>Can someone supply me with a regex to match a search term that is not preceded or followed by <code>[a-z]</code> and <code>[A-Z]</code>? (Other characters are OK.) I.e., when searching for <code>key</code>, I don't want <code>keyboard</code> in my search results, but <code>key.</code> is okay.</p>
|
<p><code>\bkey\b</code> should do what you want.</p>
<p><code>\b</code> is a word boundary</p>
|
<p>No need for the <code>OR</code>s if you do it like this:</p>
<pre><code>(^|[^A-Za-z])key([^A-Za-z]|$)
</code></pre>
| 34,191
|
<p>In a file called index.asp, which is set up in IIS as a default document for the directory, I'm trying to determine via .asp VBScript if the page was called as the default document versus directly by name, i.e. I'm trying to distinguish between these two cases server-side:</p>
<p><a href="http://someurl/" rel="nofollow noreferrer">http://someurl/</a></p>
<p><a href="http://someurl/index.asp" rel="nofollow noreferrer">http://someurl/index.asp</a></p>
<p>I know how to do this in ASP.NET, but the same "server variables" don't seem to be available. The server variables that do deal with the URL and script name (PATH_ INFO, SCRIPT_NAME, URL) all return "index.asp" regardless of which way the script is called. </p>
<p>A Google search falls short on this one. Any ideas?</p>
|
<p>The server won't know, but the client will. In JavaScript you can examine the <code>location.href</code>, then pass that value back to the server using an Ajax call to whatever logging mechanism you want.</p>
|
<p>How about this...<br />
Create a new file IndexDefault.asp and set it as the default document<br />
In IndexDefault.asp make it a redirect to Index.asp<br />
In IndexDefault.asp check the referrer for the IndexDefault.asp.</p>
| 49,296
|
<p>OK, So i have been watching some MVC vids and reading some bits.
I am new to the entire MVC pattern, and until now have been happily wrapped up in the web forms world!</p>
<p>Like with so many demos it all seems great and I'm sure I'll have lots I dont understand as I move along, but in the first instance...</p>
<p>I can see that you can have a strongly typed view, which gets data from the controller. What happens if I want data in a view from different object types?? Say i want to show a grid of cars and a grid of people, which are not related in anyway??</p>
<p>Thx
Steve</p>
|
<p>Setup your strongly typed ViewData class with two properties like this</p>
<pre><code>public class MyViewData
{
public IEnumerable<Car> Cars { get; set; }
public IEnumerable<People> People { get; set; }
}
</code></pre>
<p>and then fill them in the controller,
Sorry for the duplicate. In good MVC spirit try to use interfaces where possible to make your code more generic</p>
|
<p>You can either pass both objects inside the ViewData hashtable, or create a MyViewViewModel, add two properties, and set them both from your controller.</p>
| 40,997
|
<p>Looking through some code I came across the following code</p>
<pre><code>trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));
</code></pre>
<p>and I'd like to know if casting this way has any advantages over </p>
<pre><code>trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);
</code></pre>
<p>I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.</p>
|
<p>These statements are not identical. The cast method is a normal method invocation (<code>invokevirtual</code> JVM instruction) while the other is a language construct (<code>checkcast</code> instruction). In the case you show above, you should use the second form: <code>(TrTuDocPackTypeDto) packDto</code></p>
<p>The <code>cast</code> method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:</p>
<pre><code>public <T> Set<T> find(Class<T> clz, Filter criteria) {
List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */
Set<T> safe = new HashSet<T>();
for (Object o : raw)
safe.add(clz.cast(o));
return safe;
}
</code></pre>
<p>This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:</p>
<pre><code>/* DO NOT DO THIS! */
List raw = new ArrayList();
...
return (List<Widget>) raw;
</code></pre>
<p>The compiler will warn you, <code>Unchecked cast from List to List<Widget></code>, meaning that in the ellipsis, someone could have added a <code>Gadget</code> to the raw list, which will eventually cause a <code>ClassCastException</code> when the caller iterates over the returned list of (supposed) <code>Widget</code> instances.</p>
|
<p>Both of these statements are identical. Pick whichever one you find more readable. The second method is more common in my experience, and it is the once that I prefer.</p>
<p>I tend to use the cast method solely when I am working with reflection, and it reads nicer in that situation. All other times I find myself using the second way of casting.</p>
| 30,209
|
<p>I am wondering, what goes into the creation of a GUID. I don't mean what is used to create a GUID in a specific language (NewID() in SQL Server, Guid.NewGuid() in C#), I mean when you call those methods/functions, what do they do to make the GUID?</p>
|
<p>The details of GUIDs, including the algorithm used to generate them is described on <a href="http://en.wikipedia.org/wiki/Globally_Unique_Identifier" rel="nofollow noreferrer">wikipedia</a>.</p>
|
<p>Hash function. Its complicated.</p>
<p><a href="http://en.wikipedia.org/wiki/GUID#Algorithm" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/GUID#Algorithm</a> Knows more than I do.</p>
| 11,262
|
<p>Ok I am a total beginner with the Solaris Operating system and I need to install and configure samba on 3 boxes each has a different version of Solaris (8,9,10).</p>
<p>What I want to know location of samba configuration file i.e., <code>smb.conf</code> files in each version? So far all I have found is </p>
<ol>
<li><p>Solaris 8 </p>
<blockquote>
<p>/usr/local/samba/lib/smb.conf</p>
</blockquote></li>
<li><p>Solaris 9 and Solaris 10</p>
<blockquote>
<p>/etc/sfw/samba/smb.conf</p>
</blockquote></li>
</ol>
<p>Is this right? I need to know where these files go by default when samba is installed.</p>
|
<p>Samba configuration files can be set anywhere your administrator want you to have them.</p>
<ul>
<li><code>/usr/local/samba/</code> is the path where samba can be installed.</li>
<li>smb.conf is one of the configuration files, along with private/secrets.tdb or username.map</li>
</ul>
<p>You can launch your samba with a:</p>
<pre><code>smbd -D -s /myPath/smb.conf
</code></pre>
<p>The two locations (samba installation and samba configuration paths) can be completely separate.</p>
<p><code>-D</code> If specified, this parameter causes the server to operate as a daemon. That is, it detaches itself and runs in the background, fielding requests on the appropriate port. Operating the server as a daemon is the recommended way of running smbd for servers that provide more than casual use file and print services. This switch is assumed if smbd is executed on the command line of a shell.</p>
<p><code>-s <configuration file></code>
The file specified contains the configuration details required by the server. The information in this file includes server-specific information such as what printcap file to use, as well as descriptions of all the services that the server is to provide.</p>
|
<p>The FILES section of the manpage for `smbd' may give some hints. I don't have any Solaris box handy, so cannot unfortunately confirm.</p>
| 40,903
|
<p>As best-behaved as I try to be about keeping my unit tests disconnected from the database, etc. etc, it still seems inevitable that my day will be interrupted by small regular enforced breaks while I wait for my machine to do something boring.</p>
<p><img src="https://imgs.xkcd.com/comics/compiling.png" alt="xkcd comic: compiling"></p>
<p>I personally find swordfighting makes me lose my train of thought. I'm often 'in the zone' when I run a build or suite of tests, and I'd prefer something that keeps me in the same focussed frame of mind, jumping me right back to hacking as soon as the build / test run / migration is done.</p>
<p>I used to fantasize about a Tetris plugin for Visual Studio that popped up during the build and then paused and disappeared automatically when the build completed, but I never actually did anything about it. Lately we were thinking about building something into <a href="http://www.zenspider.com/" rel="nofollow noreferrer">autotest</a> which helps you learn Spanish while you wait for the tests to run, or maybe feeds you relevant stack overflow questions to answer.</p>
<p>So. Suggestions please. Points for fun yet rewarding activities.</p>
|
<ol>
<li>StackOverflow</li>
<li>Coffee</li>
<li>StackOverflow</li>
<li>Side project coding</li>
</ol>
<p>See also <a href="https://stackoverflow.com/questions/55922/how-to-keep-concentrated-and-focused-while-waiting-for-your-compiler">How to keep concentrated and focused while waiting for your compiler?</a></p>
|
<p>I usually read blogs, articles, mostly work related.<br>
I have dedicated time to read everything not work related (30 minutes time-frame after lunch).
<br> I also find myself going through our websites to see if I find a bug or something that can be improved.
<br><br> And on a Friday (like today:) ) I read Freak Angels:) Warren Ellis on-line free comic. The man is on a rampage on that one:) <br>Check it out:<a href="http://www.freakangels.com/?p=23" rel="nofollow noreferrer">http://www.freakangels.com/?p=23</a></p>
| 34,181
|
<p>I'm trying to safely update the home directory as specified in <code>/etc/passwd</code>,
but the standard Linux utils - usermod and vipw - for doing so aren't provided
by Cygwin.</p>
<p>Could anyone tell me how they changed this in Cygwin?</p>
|
<p><strong>EDIT:</strong> For recent versions of Cygwin (1.7.34 and beyond), see <a href="https://stackoverflow.com/q/1494658/1858225">this newer question</a>.</p>
<p>Like sblundy's answer, you can always edit by-hand.</p>
<p>But if you want to do it the "official" way, use the cygwin-specific <a href="https://cygwin.com/cygwin-ug-net/mkpasswd.html" rel="noreferrer"><strong><code>mkpasswd</code></strong></a> command. Below is a snippet from the official docs on <a href="https://cygwin.com/cygwin-ug-net/mkpasswd.html" rel="noreferrer"><code>mkpasswd</code></a> :</p>
<blockquote>
<p>For example, this command:</p>
<p><strong>Example 3.11. Using an alternate home root</strong></p>
<pre><code>$ mkpasswd -l -p "$(cygpath -H)" > /etc/passwd
</code></pre>
<p>would put local users' home directories in the Windows 'Profiles' directory. </p>
</blockquote>
<p>There's a bunch of other really useful commands described on the <a href="http://cygwin.com/cygwin-ug-net/using-utils.html" rel="noreferrer"><strong>Cygwin Utilities</strong></a> documentation page (which includes <code>mkpasswd</code>). The use of <code>cygpath</code> in the example above is another of these cygwin-specific tools.</p>
<p>While you're at it, you probably also want to read the <a href="http://cygwin.com/cygwin-ug-net/using-effectively.html" rel="noreferrer">Using Cygwin Effectively with Windows</a> documentation. There's a bunch of really good advice.</p>
|
<p>I edited my /etc/passwd file directly (making sure nothing else would be accessing it), and changed all references to /home to be /Users (on Windows 7). I found that, in order for everything to work correctly, I had to delete any directories in the /home directory (or move them to the appropriate other location). Otherwise, cygwin would develop a split personality where, for example, 'bash -l' would start in /home/Pablo but $HOME would be /Users/Pablo and emacs would appear to do the reverse. Once I deleted /home/Pablo, everything worked fine.</p>
| 27,909
|
<p>I'm looking to be able to reference certain state/objects through anywhere in my application. For instance, a user logs in to their application, I need to call a web service and retrieve the users information. Then I want to be able to access this information from anywhere in the application with something like the following:</p>
<pre><code>myAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
user = delegate.u;
</code></pre>
<p>Is setting an instance variable as a User object in the app delegate and referencing it from there when needed a poor way of going about it? I typically set it there upon the user's login.</p>
<p>Wanted to hear how the pros handle this one.</p>
|
<p>Normally, you should only connect things to the app delegate if they:</p>
<ul>
<li>Were created from the same NIB file as the app delegate (i.e. static UI elements in single window interfaces)</li>
<li>Are associated with application-level event handling that passes through the app delegate (like the menu item for the Preferences Window)</li>
</ul>
<p>For everything else, you should create a singleton which manages access to them.</p>
<p>Jason Coco suggested routing through the Application Controller. In my programs I normally avoid this, as I think it puts too much responsibility at the top level -- I think things should self-manage where possible and that higher level management should only be used when there is a requirement for coordination between peer-level modules.</p>
<p>I'm not going link my own blog but if you Google me and singletons you'll probably find a post I wrote going into more detail.</p>
|
<p>Usually you would ask your application's controller for this information and it would be responsible for knowing how to store it/look it up in whatever data model exists. Your application's controller may or may not be the same as the applications delegate (in most simple applications, it is the same).</p>
| 43,979
|
<p>I want to make an order with this configuration</p>
<ul>
<li>Arduino MEGA 2650 R3</li>
<li>Ramps 1.6 Plus</li>
<li>2 TMC2130 </li>
<li>2 Stepper motors 17hs3401</li>
<li>1 Fan</li>
</ul>
<p><img src="https://i.stack.imgur.com/Nl0sE.png" alt="stepper_motor"></p>
<p>But I am not sure what voltage and current would be enough to make it work. The Ramps 1.6+ board has an input of 12V as you can see in the picture, but I have read that <a href="https://3dprinting.stackexchange.com/questions/9911/tmc2130-external-vm-ramps1-4">other people</a> had to increase the voltage with a DC-DC converter.</p>
<p><img src="https://i.stack.imgur.com/RtBEr.jpg" alt="ramps_voltage"></p>
<p>So, would be 12V and 15A enough to make work that configuration?</p>
|
<p>The easiest way to know how powerful the PSU should be is to download from <a href="https://github.com/rcarlyle/StepperSim" rel="nofollow noreferrer">https://github.com/rcarlyle/StepperSim</a> the Excel workbook which simulates the power absorbed by the stepper motor. Input the motor specifications, check in the graph the max speed at which you plan to run it, check the absorbed power, add 20% for the various losses. Once you know the absorbed power, you can multiply by the number of stepper motors and obtain the current required, add 20% not to stress the PSU too much.</p>
<p>In you case, this is the result</p>
<p><a href="https://i.stack.imgur.com/yoKsG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yoKsG.jpg" alt="enter image description here"></a></p>
<p>Your motor will never absorb more than 7 W, 14 W for the two motors, around 20 W considering losses in the motors and overcapacity of the PSU. This means that around 2 A PSU will be perfect for your setup.</p>
<hr>
<p><em>Previous answer, which may not be completely correct but still provides a useful background knowledge:</em></p>
<p>The TMC drivers limit the current to the value you set, which is most of the time lower than the datasheet. In no case you will need more than 1.3 A * sqrt(2) * 2 motors = 3.6 A. In fact, you won't need this much either.</p>
<p>When there is no field in a coil, the driver applies full voltage, but the current is low (initially zero) so you don't hit the 1.3 A per coil.</p>
<p>The current increases (the higher the maximum voltage available to the driver, the faster it increases) and the driver (probably) keeps the full voltage until the preset current is reached. Just a moment before that, the current is almost there, but you still have full voltage from the power supply. This is the theoretical worst case, but it applies only for a very short amount of time.</p>
<p>As soon as the current reaches the preset, the driver "cuts the voltage" to keep 2.4 ohm * 1.3 A = 3.2 V (because V = R * I). This means that the power supply sees 3.2 A/12 V*1.3 A = 0.35 A.</p>
<p>When running, the motors almost never start from zero to max current: both coils are powered and when one increases, the other one decreases.</p>
<p>In fact, the microstepping makes the steppers act more or less like AC motors with two phases. This means that overall the current is the max current per phase multipled by sqrt(2). Also, when using microstepping one phase (coil) is not completely shut off, but two of them work at the same time (with different current levels). This means that in total one compensates the other, and the power supply only provides, more or less, 0.35 * 1.4 = 0.5 A per stepper. You have two, so it's 1 A total, therefore 2 A PSU considering the inefficiencies.</p>
<p>A very easy and complete explanation is provided <a href="https://www.njr.com/semicon/PDF/application_notes/Drive_circuit_basics_APP_E.pdf" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>By controlling the duty cycle of the chopper, an average voltage and
an average current equal to the nominal motor voltage and current are
created. </p>
<p>...</p>
<p>As the current increases, a voltage develops across the
sensing resistor, which is fed back to the comparator. At the
predetermined level, defined by the voltage at the reference input,
the comparator resets the flipflop, which turns off the output
transistor. The current decreases until the clock oscillator triggers
the flip-flops, which turns on the output transistor again, and the
cycle is repeated</p>
</blockquote>
<p>So you never have coming out of the PSU more than the preset current.</p>
<blockquote>
<p><strong>Supply current is not the same as the motor current in a copper drive</strong>. It is the motor current multiplied by the dutycycle, at
standstill typically Isupply = IM · ( VM ⁄ Vsupply ) </p>
<p>...</p>
<p>Depending on
how the H-bridge is switched during the turn-off period, the current
will either recirculate through one transistor and one diode (path 2),
giving the slow current decay, or recirculate back through the power
supply (path 3). The advantage of <strong>feeding the power back to the
power supply</strong> is the fast current decay and the ability to quickly
reduce to a lower current level.</p>
</blockquote>
|
<p>Yes, A power supply that can deliver 12 volts and up to 15 Amps will work. Since that board says 12 V, that means it is designed to work at 12V. The components on the board might not survive 24V. The TMC stepper motor drivers specified can tolerate a max of 2.5 amps. That current draw is dependent on the per phase winding impedance of the motors that are used. @2.4 ohms phase resistance, that 12 volts could generate a max of 5 amps (more than the Trinamic can tolerate). Therefore, if you configure the stepper drivers to operate at more than 50% power, they will overheat and shutdown.</p>
| 1,617
|
<p>How can I list all the local users configured on a windows machine (Win2000+) using java.<br>
I would prefer doing this with ought using any java 2 com bridges, or any other third party library if possible.<br>
Preferable some native method to Java. </p>
|
<p>Using a Java-COM Bridge , like <a href="http://danadler.com/jacob/" rel="nofollow noreferrer">Jacob</a>. You then select an appropriate COM library, e.g. <a href="http://msdn.microsoft.com/en-us/library/aa389276(VS.85).aspx" rel="nofollow noreferrer">COM API for WMI</a> to list local users, or any other Windows management information.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa394490(VS.85).aspx" rel="nofollow noreferrer">Win32_SystemUsers</a> association WMI class relates a computer system and a user account on that system.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa394061(VS.85).aspx" rel="nofollow noreferrer">Win32_Account</a> abstract WMI class contains information about user accounts and group accounts known to the computer system running Windows. User or group names recognized by a Windows NT domain are descendants (or members) of this class.</p>
<p>Working Example (jacob 1.17-M2, javaSE-1.6):</p>
<pre><code>import java.util.Enumeration;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;
public class ComTst {
public static void main(String[] args) {
ComThread.InitMTA();
try {
ActiveXComponent wmi = new ActiveXComponent("winmgmts:\\\\.");
Variant instances = wmi.invoke("InstancesOf", "Win32_SystemUsers");
Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
while (en.hasMoreElements())
{
ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());
System.out.println(bb.getPropertyAsString("PartComponent"));
}
} finally {
ComThread.Release();
}
}
}
</code></pre>
|
<p>There is a simpler solution for what I needed.<br>
This implementation will use the "<a href="http://support.microsoft.com/kb/251394" rel="nofollow noreferrer">net user</a>" command to get the list of all users on a machine. This command has some formatting which in my case I don't care about, I only care if my user is in the list or not. If some one needs the actual user list, he can parse the output format of "net user" to extract the list without the junk headers and footers generated by "net use"</p>
<pre><code>private boolean isUserPresent() {
//Load user list
ProcessBuilder processBuilder = new ProcessBuilder("net","user");
processBuilder.redirectErrorStream(true);
String output = runProcessAndReturnOutput(processBuilder);
//Check if user is in list
//We assume the output to be a list of users with the net user
//Remove long space sequences
output = output.replaceAll("\\s+", " ").toLowerCase();
//Locate user name in resulting list
String[] tokens = output.split(" ");
Arrays.sort(tokens);
if (Arrays.binarySearch(tokens, "SomeUserName".toLowerCase()) >= 0){
//We found the user name
return true;
}
return false;
}
</code></pre>
<p>The method runProcessAndReturnOutput runs the process, collects the stdout and stderr of the process and returns it to the caller.</p>
| 43,274
|
<p>What is a good command line tool to create screenshots of websites on Linux? I need to automatically generate screenshots of websites without human interaction. The only tool that I found was <a href="http://khtml2png.sourceforge.net/" rel="noreferrer">khtml2png</a>, but I wonder if there are others that aren't based on khtml (i.e. have good JavaScript support, ...).</p>
|
<p>A little more detail might be useful...</p>
<p>Start a firefox (or other browser) in an X session, either on your console or using a vncserver. You can use the <code>--height</code> and <code>--width</code> options to set the size of the window to full screen. Another firefox command can be used to set the URL being displayed in the first firefox window. Now you can grab the screen image with one of several commands, such as the "import" command from the Imagemagick package, or using gimp, or fbgrab, or xv.</p>
<pre><code>#!/bin/sh
# start a server with a specific DISPLAY
vncserver :11 -geometry 1024x768
# start firefox in this vnc session
firefox --display :11
# read URLs from a data file in a loop
count=1
while read url
do
# send URL to the firefox session
firefox --display :11 $url
# take a picture after waiting a bit for the load to finish
sleep 5
import -window root image$count.jpg
count=`expr $count + 1`
done < url_list.txt
# clean up when done
vncserver -kill :11
</code></pre>
|
<p>I don't know of anything custom built, I'm sure there could be something done with the gecko engine to render to a png file instead of the screen ...</p>
<p>Or, you could fire up firefox in full screen mode in a dedicated VNC server instance and use a screenshot grabber to take the screenshot. Fullscreen = minimal chrome, VNC server instance = no visible UI + you can choose your resolution.</p>
<p>Use xinit with Xvnc as the X server to do this - you'll need to read all the manpages.</p>
<p>Downsides are that the screenshot is always the same size, doesn't resize according to the web page ...</p>
| 15,316
|
<p>Are JKS (Java Key Store) files encrypted? Do they provide full protection for encryption keys, or do I need to rely solely on access control?<br>
Is there a way to ensure that the keys are protected?</p>
<p>I'm interested in the gritty details, including algorithm, key management, etc. Is any of this configurable?</p>
|
<p>They are encrypted.</p>
<p>The algorithm is provider dependent. The provider will return the key/certificate based on a password. If you need strong security, find a keystore provider that uses a strong encryption.</p>
|
<p>They are encrypted.</p>
<p>The algorithm is provider dependent. The provider will return the key/certificate based on a password. If you need strong security, find a keystore provider that uses a strong encryption.</p>
| 20,978
|
<p>I have a function, parseQuery, that parses a SQL query into an abstract representation of that query.</p>
<p>I'm about to write a function that takes an abstract representation of a query and returns a SQL query string.</p>
<p>What should I call the second function?</p>
|
<p>I think the verb you want is 'compose'.</p>
|
<p>I believe the answer you're looking for is: "Don't parse SQL or assemble SQL in the first place. Use an Object/Relational Mapper and stop wasting your employer's money by solving problems that have already been solved for quite some time."</p>
| 17,936
|
<p>My Anet A8 reads as 120ish degrees Celsius, but it is set to 200 degrees. I don't know if it is reading the wrong temperature because it still pushes out plastic when I force it. It will climb up and then go back down. I don't know if the hot end it broke or if the thermistor is broke.</p>
|
<h2>You are sitting on a fire risk!</h2>
<p>If you are using the stock/original firmware, you should <em><strong>immediately stop printing</strong></em>. The stock firmware of the Anet A8 has no <a href="https://3dprinting.stackexchange.com/questions/8466/what-is-thermal-runaway-protection">thermal runaway protection</a> (<em>see also <a href="/a/6953/">this answer</a></em>), this means it will keep heating until the thermistor senses 200 °C, even if it cannot do that for some reason or another.</p>
<p>When a hotend temperature does not read the correct value, your thermistor in the hotend may not be making correct contact (as you say that it goes up and down). Please ensure that the thermistor is correctly positioned, it makes good contact and the wires correctly fastened.</p>
<p>Similarly applies to the heater cartridge, which can fall out and causing a fire if not properly fastened. Ensure the heater cartridge is properly positioned and held in the heater block.</p>
<p>Fluctuations in temperature sometimes are induced by a wrongly positioned fan duct (but generally not that much). The reason why this is not the case here is that you can still push the filament through while it reads about 120 °C; <em>this temperature is generally too low to push filament through</em>. Apparently the hotend is still hot enough to push filament through while registering a low temperature.</p>
|
<p>Without any other information, the highest odds are that the fan is blowing on the hot end. If the temp drops when the fan is on, and rises when the fan is off, then simply re-position the fan nozzle. If that's not the problem, check the thermistor. If that's not it, check the termination (tighten the screws) of the hot-end wires at the control board.</p>
<p>Next, check the control board. If there's any indication that it's the board, one potential solution is to add a MOSFET (<a href="https://3dprint.wiki/reprap/electronics/heatbed_mosfet" rel="nofollow noreferrer">see the link</a>). Even if the control board isn't the problem, I would add the MOSFET.</p>
| 1,247
|
<pre><code>SELECT
avg(con_hits) as avg_hits
FROM
content
WHERE
con_type = 1
AND con_posttime < $twelve_hrs_ago
AND con_refresh = 0
ORDER BY
con_posttime DESC
LIMIT 100
</code></pre>
<p>I would like it to go to the first record that was posted at least 12 hours ago (denoted by the <code>$twelve_hrs_ago</code> variable which has the suitable timestamp), and take the average of the <code>con_hits</code> column, for the next 100 records. In my example, it disregards the <code>LIMIT</code>, and takes the average of every record in the table.</p>
<p>Is there a way to bypass that?</p>
|
<p><code>LIMIT</code> is applied to the resultset, after <code>AVG</code> is calculated. You can do what you want, with a subselect:</p>
<pre><code>SELECT avg(con_hits) as avg_hits
FROM (
SELECT con_hits
FROM content
WHERE
con_type = 1
AND con_posttime < $twelve_hrs_ago
AND con_refresh = 0
ORDER BY con_posttime DESC
LIMIT 100
) x;
</code></pre>
<p>You can use the database to calculate the time offset too. Replace <code>$twelve_hrs_ago</code> above with:</p>
<pre><code>date_add(now(), interval -12 hour)
</code></pre>
|
<p>What about:</p>
<pre><code>
SELECT avg(con_hits) as avg_hits FROM (
SELECT con_hits FROM content
WHERE con_type = 1 AND con_posttime < $twelve_hrs_ago AND con_refresh = 0
ORDER BY con_posttime DESC
LIMIT 100
)
</code></pre>
<p>Mysql supports subqueries, so this might do it for you.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/subqueries.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/subqueries.html</a></p>
| 42,987
|
<p>Are System.IO.Compression.GZipStream or System.IO.Compression.Deflate compatible with zlib compression?</p>
|
<p>From <a href="http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx" rel="noreferrer">MSDN</a> about System.IO.Compression.GZipStream:</p>
<blockquote>
<p>This class represents the gzip data format, which uses an industry standard algorithm for lossless file compression and decompression.</p>
</blockquote>
<p>From the <a href="http://www.gzip.org/zlib/zlib_faq.html" rel="noreferrer">zlib FAQ</a>:</p>
<blockquote>
<p>The gz* functions in zlib on the other hand use the gzip format.</p>
</blockquote>
<p>So zlib and GZipStream should be interoperable, but only if you use the zlib functions for handling the gzip-format.</p>
<p>System.IO.Compression.Deflate and zlib are reportedly not interoperable.</p>
<p>If you need to handle zip files (you probably don't, but someone else might need this) you need to use <a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/Default.aspx" rel="noreferrer">SharpZipLib</a> or another third-party library.</p>
|
<p>I agree with andreas. You probably won't be able to open the file in an external tool, but if that tool expects a stream you might be able to use it. You would also be able to deflate the file back using the same compression class.</p>
| 9,570
|
<p>I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys.</p>
<p>Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers(<strong><kbd>ALT</kbd>+<kbd>CTRL</kbd>+<kbd>SHIFT</kbd></strong>). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to.</p>
<p>Does anyone have any ideas or suggestions on where I should go with this?</p>
|
<p>Within your overridden ProcessCmdKey how are you determining which key has been pressed?</p>
<p>The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181.</p>
<p>You can extract the modifiers and the key pressed by ANDing with appropriate enum values:</p>
<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
bool shiftPressed = (keyData & Keys.Shift) != 0;
Keys unmodifiedKey = (keyData & Keys.KeyCode);
// rest of code goes here
}
</code></pre>
|
<p>I upvoted <a href="https://stackoverflow.com/questions/4850/c-and-arrow-keys/5026#5026">Tokabi's answer</a>, but for comparing keys there is some additional advice on <a href="https://stackoverflow.com/questions/1369312/c-keys-enumeration-confused-keys-alt-or-keys-rbutton-keys-shiftkey-keys-alt/2033796#2033796">StackOverflow.com here</a>. Here are some functions which I used to help simplify everything.</p>
<pre><code> public Keys UnmodifiedKey(Keys key)
{
return key & Keys.KeyCode;
}
public bool KeyPressed(Keys key, Keys test)
{
return UnmodifiedKey(key) == test;
}
public bool ModifierKeyPressed(Keys key, Keys test)
{
return (key & test) == test;
}
public bool ControlPressed(Keys key)
{
return ModifierKeyPressed(key, Keys.Control);
}
public bool AltPressed(Keys key)
{
return ModifierKeyPressed(key, Keys.Alt);
}
public bool ShiftPressed(Keys key)
{
return ModifierKeyPressed(key, Keys.Shift);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (KeyPressed(keyData, Keys.Left) && AltPressed(keyData))
{
int n = code.Text.IndexOfPrev('<', code.SelectionStart);
if (n < 0) return false;
if (ShiftPressed(keyData))
{
code.ExpandSelectionLeftTo(n);
}
else
{
code.SelectionStart = n;
code.SelectionLength = 0;
}
return true;
}
else if (KeyPressed(keyData, Keys.Right) && AltPressed(keyData))
{
if (ShiftPressed(keyData))
{
int n = code.Text.IndexOf('>', code.SelectionEnd() + 1);
if (n < 0) return false;
code.ExpandSelectionRightTo(n + 1);
}
else
{
int n = code.Text.IndexOf('<', code.SelectionStart + 1);
if (n < 0) return false;
code.SelectionStart = n;
code.SelectionLength = 0;
}
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
</code></pre>
| 2,683
|
<p>If I use <code>assert()</code> and the assertion fails then <code>assert()</code> will call <code>abort()</code>, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?</p>
|
<p>Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s <code>assert()</code> is exactly C's <code>assert()</code>, with the <code>abort()</code> "feature" bundled in. Fortunately, this is surprisingly straightforward.</p>
<p><em>Assert.hh</em></p>
<pre><code>template <typename X, typename A>
inline void Assert(A assertion)
{
if( !assertion ) throw X();
}
</code></pre>
<p>The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, <code>terminate()</code> will be called, which will end the program similarly to <code>abort()</code>.</p>
<p>You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you <code>Assert()</code>.</p>
<p><em>debug.hh</em></p>
<pre><code>#ifdef NDEBUG
const bool CHECK_WRONG = false;
#else
const bool CHECK_WRONG = true;
#endif
</code></pre>
<p><em>main.cc</em></p>
<pre><code>#include<iostream>
struct Wrong { };
int main()
{
try {
Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5);
std::cout << "I can go to sleep now.\n";
}
catch( Wrong e ) {
std::cerr << "Someone is wrong on the internet!\n";
}
return 0;
}
</code></pre>
<p>If <code>CHECK_WRONG</code> is a constant then the call to <code>Assert()</code> will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to <code>CHECK_WRONG</code> we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds.</p>
<p>The <code>Assert()</code> function is equivalent to typing</p>
<pre><code>if( !assertion ) throw X();
</code></pre>
<p>but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain <code>assert()</code>s.</p>
<p>For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.</p>
|
<pre><code>_set_error_mode(_OUT_TO_MSGBOX);
</code></pre>
<p>believe me, this function can help you.</p>
| 5,816
|
<p>As a UI guy (coding and designing user interfaces) I often find myself in the odd situation arguing about the quality of userinterfaces with programmers and other "laymen".</p>
<p>I find it somewhat hard to argue about things like colors, icons or layout and it doesn't seem that there is a factual right or wrong. But still - without having a convincing argument I still know (i.e. feel) that sometimes a solution is just wrong. What is your approach to this? Do you let costly usability test decide or even the customer? Do you educate yourself in usability engineering? Do you know of good books (like Joel Spolsky's "User Interface Design for Programmers") that deliver arguments? Do you avoid such discussions?</p>
|
<p>Ultimately the customer makes the decision because the customer pays the bills. However, the customer is usually paying me because they believe that I have skills and abilities that they don't possess. Typically I'll try to explain to them why I believe a particular layout or color choice makes sense from a design perspective. If I have a good enough reason, beyond personal preference, that usually does the trick. If it doesn't, then I go the customer's way. Sometimes, if I know that the customer will really hate what they "want" I'll just avoid the argument/discussion completely and do it their way and let them tell me to change it back.</p>
<p>One thing that I will say. Often these discussions end up with yet a third solution that is better than my original. Being forced to really think through my choices to defend them often results in me thinking of ways to solve the problem that addresses the customer's perspective better than the original design.</p>
<p>As far as color schemes go, you always hope to have a customer with good taste. Sadly, that doesn't always happen. And, yes, sometimes I've had to put together a solution that doesn't make it into my portfolio for this reason.</p>
|
<p>A lot of my clients are small. They don't have the money for a usability/UI expert so we make due. They understand my limitations and we both do our best to bring a little common sense to the table - understanding that we're building good-enough versus the best (UI-wise).</p>
<p>In my experience, large clients have the same attitude toward internal apps. It's only when you build something to sell that people are willing to spend extra money on the problem.</p>
<p>For myself, I believe there's no good reason to be completely ignorant. I do spend a little time reading and puttering. I've found good material with:</p>
<ul>
<li><a href="http://www.sensible.com/" rel="nofollow noreferrer">Steve Krug</a> - his book, <a href="https://rads.stackoverflow.com/amzn/click/com/0789723107" rel="nofollow noreferrer" rel="nofollow noreferrer">Don't Make Me Think!</a>, is aging but still pretty good.</li>
<li><a href="http://www.jnd.org/" rel="nofollow noreferrer">Donald Norman</a> - writes about a lot more than UI design. He gets you seeing and thinking about design everywhere.</li>
<li><a href="http://www.useit.com/" rel="nofollow noreferrer">Jakob Nielsen</a> - can be a little extreme. Still, he's not an idiot. He's thought about design (especially web design) a lot and makes some great observations.</li>
</ul>
| 47,256
|
<p>You are doing contract first development of web services in a SOA world.</p>
<p>After editing an XSD file, what is the best way to automatically (re)generate .net classes from the XSD files?</p>
|
<p>xsd.exe will generate new classes for you.</p>
<p>Depending on how Visual Studio is set up, adding xsd.exe to "Properties / build events / post-build events" will force a regeneration every time you do a rebuild.</p>
|
<p>I have used <a href="http://xsd2code.codeplex.com/releases/view/22222" rel="nofollow">http://xsd2code.codeplex.com/releases/view/22222</a> VS addin for this.</p>
| 32,490
|
<p>I currently have a functioning in-house Windows Forms application which extensively uses the <code>DataGridView</code> control for data entry. There are some support issues which are expected when we roll this out to more locations, so one of our consultants has recommended putting together an AJAX application with substantially the same functionality.</p>
<p>I have used ASP.NET a bit in the past with the old model where basically everything goes to the server, but I've heard AJAX applications can be made more UI responsive than that. </p>
<p>So my question is, what's the best way to get started with AJAX, for someone who has worked mostly in WinForms C#?</p>
|
<p>The easiest way, but not neccessarly the best way is to get familiar with the UpdatePanel, which is part of the ASP.net AJAX controls.
You can use an ASP.net GridView control (which shares much of the Winforms equiv. functionality), wrap an UpdatePanel around it and you're away.</p>
<p>Further on from that you will want to get involved with web/wcf services to make calls from javascript to the server and update your UI based on the responce. That of course involved more time, effort and knowledge!</p>
<p>There are many gridview controls you can buy that will help e.g. One from essential objects is nice, not perfect, but very cheap compared to Telerik and other big names.</p>
<p>ASP.net is still a server based technology, but with the inclusion of ASP.net AJAX calls to the server are easy and with jQuery updating the UI is getting easier!!</p>
<p>Hope this helps</p>
|
<p>What you're wanting to do isn't very hard especially with Telerik's or Infragistic's controls, but as the previous commenter stated, they aren't cheap. They are probably worth the price if you don't want to spend the time rolling your own responsive and editable grid.</p>
| 22,605
|
<p>I'm looking to start a <a href="http://en.wikipedia.org/wiki/MUD" rel="nofollow noreferrer">MUD client</a> application, which connects to a MUD hosted on a telnet server. The only thing important to me is that it runs painlessly and efficiently across any OS. Aside from that requirement, I'm not really sold on any language.</p>
<p>So I'm looking for a freely available telnet client library on which I can base my application, so I don't have to deal with the details of the protocol too much.</p>
|
<p>I would always consider <a href="http://twistedmatrix.com/trac/" rel="nofollow noreferrer">Twisted</a> for this kind of thing (Python).</p>
<p>The beauty is that if you later decide to swap it out to SSH or anything more secure than telnet, you can with little pain.</p>
|
<p>pmc ( <a href="http://sourceforge.net/projects/perlmudclient/" rel="nofollow noreferrer">http://sourceforge.net/projects/perlmudclient/</a> ) was an attempt to do exactly this. I've spent some of the last week going through it; it uses an older modified version of Net::Telnet to do its connectivity work. </p>
<p>My problem is that Net::Telnet seems to have a blocking interface when a partial line is sent by the server, i.e. a line not terminated by a newline. It has two features that support this (waitfor and its prompt mechanism), because almost all <em>telnet</em> servers have prompts that are not newline-terminated.</p>
<p>MUDs often have "prompts" that are non-standard and vary through the course of the game; the MUD I admin on has a "Your choice: " prompt as its login [it's not just for usernames], and many game features present alternative prompts. So I suspect you'll need to bear this in mind when you go looking for a cross-platform Telnet library!</p>
| 41,655
|
<p>Is there a way to set a different value for service startup timeout per service?
I can change it using the ServicesPipeTimeout registry key, but it's per machine (<a href="http://support.microsoft.com/kb/824344" rel="noreferrer">http://support.microsoft.com/kb/824344</a>).</p>
<p>At the moment the only thing I thought about was to do all the time-consuming startup actions in a different thread.</p>
|
<p>It's good practice to finish starting your service as fast as possible. So, during the <em>start</em> state, do only what you absolutely need to acknowledge it started successfully; and do the rest later. If the <em>start</em> is still a lengthy process, use <a href="http://msdn.microsoft.com/en-us/library/ms686241.aspx" rel="noreferrer">SetServiceStatus</a> periodically to inform the <em>Service Control Manager</em> that you have not yet finished, so it does not time-out your service.</p>
|
<p>I also had to deal with a service which may takes a few seconds/minutes to have a good Start. When the service starts, it tries to connect to a SQL Server. However, when the whole server was restarted , my service was starting BEFORE SQL Server. (I know about the Service dependency but it dont apply to my situation for a particular reason....). I tried to do a loop trying 10 times to connect to SQL Server, but Windows was killing my service before the 2nd try, because of the Timeout.</p>
<p><strong>My solution</strong> : I added a Timer in the "onStart()" of my service. Then, the "onTick()" method of the service was trying 10 times to connect to the SQL Server (with a waiting of 30 in it). No more Timeout at startup.</p>
<p>So basically,</p>
<ul>
<li>My service starts in 5 seconds. </li>
<li>A timer is launched 10 seconds after the service is
started.</li>
<li>The timer tries 10 times [waiting 30 seconds each time] to
connect to the SQL Server.</li>
<li>If it succeed, the timer will disable itself, if not (after 10 try), I stop the service.</li>
</ul>
<p>Note the more elegant way to resolve the problem but maybe some part of my solution may help anybody in the same situation than me,</p>
| 26,603
|
<p>I have a <code>DataGridView</code> with several created columns. I've add some rows and they get displayed correctly; however, when I click on a cell, the content disappears.</p>
<p>What am I doing wrong?</p>
<p>The code is as follows:</p>
<pre><code>foreach (SaleItem item in this.Invoice.SaleItems)
{
DataGridViewRow row = new DataGridViewRow();
gridViewParts.Rows.Add(row);
DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
cellQuantity.Value = item.Quantity;
row.Cells["colQuantity"] = cellQuantity;
DataGridViewCell cellDescription = new DataGridViewTextBoxCell();
cellDescription.Value = item.Part.Description;
row.Cells["colDescription"] = cellDescription;
DataGridViewCell cellCost = new DataGridViewTextBoxCell();
cellCost.Value = item.Price;
row.Cells["colUnitCost1"] = cellCost;
DataGridViewCell cellTotal = new DataGridViewTextBoxCell();
cellTotal.Value = item.Quantity * item.Price;
row.Cells["colTotal"] = cellTotal;
DataGridViewCell cellPartNumber = new DataGridViewTextBoxCell();
cellPartNumber.Value = item.Part.Number;
row.Cells["colPartNumber"] = cellPartNumber;
}
</code></pre>
<p>Thanks!</p>
|
<p>Just to extend this question, there's also another way to add a row to a <code>DataGridView</code>, especially if the columns are always the same:</p>
<pre><code>object[] buffer = new object[5];
List<DataGridViewRow> rows = new List<DataGridViewRow>();
foreach (SaleItem item in this.Invoice.SaleItems)
{
buffer[0] = item.Quantity;
buffer[1] = item.Part.Description;
buffer[2] = item.Price;
buffer[3] = item.Quantity * item.Price;
buffer[4] = item.Part.Number;
rows.Add(new DataGridViewRow());
rows[rows.Count - 1].CreateCells(gridViewParts, buffer);
}
gridViewParts.Rows.AddRange(rows.ToArray());
</code></pre>
<p>Or if you like ParamArrays:</p>
<pre><code>List<DataGridViewRow> rows = new List<DataGridViewRow>();
foreach (SaleItem item in this.Invoice.SaleItems)
{
rows.Add(new DataGridViewRow());
rows[rows.Count - 1].CreateCells(gridViewParts,
item.Quantity,
item.Part.Description,
item.Price,
item.Quantity * item.Price,
item.Part.Number
);
}
gridViewParts.Rows.AddRange(rows.ToArray());
</code></pre>
<p>The values in the buffer need to be in the same order as the columns (including hidden ones) obviously.</p>
<p>This is the fastest way I found to get data into a <code>DataGridView</code> without binding the grid against a <code>DataSource</code>. Binding the grid will actually speed it up by a significant amount of time, and if you have more then 500 rows in a grid, I strongly recommend to bind it instead of filling it by hand.</p>
<p>Binding does also come with the bonus that you can keep the Object in tact, f.e. if you want to operate on the selected row, you can do this is the DatagridView is bound:</p>
<pre><code>if(gridViewParts.CurrentRow != null)
{
SaleItem item = (SalteItem)(gridViewParts.CurrentRow.DataBoundItem);
// You can use item here without problems.
}
</code></pre>
<p>It is advised that your classes which get bound do implement the <code>System.ComponentModel.INotifyPropertyChanged</code> interface, which allows it to tell the grid about changes.</p>
|
<p><em>Edit: oops! made a mistake on the second line of code. - fixed it.</em></p>
<p>Sometimes, I hate defining the datasource property.</p>
<p>I think that whenever you create and set a new row for "row", for some weird reason,the old value get disposed. try not using an instance to hold the rows you create :</p>
<pre><code>int i;
i = gridViewParts.Rows.Add( new DataGridViewRow());
DataGridViewCell cellQuantity = new DataGridViewTextBoxCell();
cellQuantity.Value = item.Quantity;
gridViewParts.Rows[i].Cells["colQuantity"] = cellQuantity;
</code></pre>
<p>It seems like cells work fine with the cell instances. I have no idea why it is different for rows though. More testings may be required...</p>
| 17,934
|
<p>I need to create several applications that all share a Microsoft SQL Server database. These include ASP.NET web applications, WPF desktop applications, and probably the odd console app every now and then.</p>
<p>I'd like to use the ADO.NET Entity Framework for data access, extend its objects for my business logic, and bind those objects to controls in my UI.</p>
<p>How can I do this in each of my applications without repeating myself too much? If the database schema or my business logic changes, then I want an easy (or automatic) way to update all my applications.</p>
<p>How should I architect this system?</p>
<hr>
<p>Update: I've asked follow-up questions... </p>
<ul>
<li><a href="https://stackoverflow.com/questions/260179/how-do-i-use-linq-to-entities-in-visual-basic">How do I use LINQ to Entities in Visual Basic?</a> </li>
<li><a href="https://stackoverflow.com/questions/260233/how-do-i-extend-adonet-entity-framework-objects-with-partial-classes">How do I extend ADO.NET Entity Framework objects with partial classes?</a></li>
</ul>
|
<p>for that I would recommend creating a Visual Studio Solution that contains multiple Projects. Your DAL would be contained within its own project then for the other projects that need to make use of that functionality, create a Project Reference back to the DAL project.</p>
<p>Hope this helps!</p>
|
<p>I'd recommend creating a new Visual Studio solution that contains multiple projects. For a DAL/BLL separation I would recommend using a class library. Making this abstraction allows you to wrap it by other projects like a WCF web service for example and expose it openly to not only .NET systems -- but potentially other systems.</p>
<p>Once you've created these class library project(s) you can add a reference to them in your other projects and use them. This will help keep a clear separation of concerns.</p>
| 32,450
|
<p>When I call <code>socket.getsockname()</code> on a socket object, it returns a tuple of my machine's internal IP and the port. However, I would like to retrieve my external IP. What's the cheapest, most efficient manner of doing this?</p>
|
<p>This isn't possible without cooperation from an external server, because there could be any number of NATs between you and the other computer. If it's a custom protocol, you could ask the other system to report what address it's connected to.</p>
|
<p>Using the address suggested in the source of <a href="http://whatismyip.com" rel="nofollow noreferrer">http://whatismyip.com</a></p>
<pre><code>import urllib
def get_my_ip_address():
whatismyip = 'http://www.whatismyip.com/automation/n09230945.asp'
return urllib.urlopen(whatismyip).readlines()[0]
</code></pre>
| 8,266
|
<p>So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.</p>
<p>The code I'm working on needs to populate, let's say a <code>List<Foo></code> from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:</p>
<pre><code>Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 1);
// ....
Expect.Call(reader.Read()).Return(true);
Expect.Call(reader["foo_id"]).Return((long) 2);
// ....
Expect.Call(reader.Read()).Return(false);
</code></pre>
<p>Which is rather tedious and rather easily broken, too. </p>
<p>How should I be approaching this issue so that the result won't be a huge mess of brittle tests?</p>
<p>Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.</p>
<p>Edit: I'm also currently limited to C# 2.</p>
|
<p>To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests.</p>
<p>Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.</p>
|
<p>You can put the Foo instances in a list and compare the objects with what you read: </p>
<pre><code>var arrFoos = new Foos[]{...}; // what you expect
var expectedFoos = new List<Foo>(arrFoos); // make a list from the hardcoded array of expected Foos
var readerResult = ReadEntireList(reader); // read everything from reader and put in List<Foo>
Expect.ContainSameFoos(expectedFoos, readerResult); // compare the two lists
</code></pre>
| 4,980
|
<p>My company requires me to use Outlook for my E-mail. Outlook does virtually nothing the way I want to do it and it frustrates me greatly. (I'm not trying to start a flame war here, it must do exactly what thousands of CEO's want it to do, but I'm not a CEO.)</p>
<p>I would like to be able to automatically extract the thousands of E-mails and attachments currently in my Outlook account and save them in my own alternative storage format where I can easily search them and organize them the way I want. (I'm not requesting suggestions for the new format.)</p>
<p>Maybe some nice open source program already can do this... that would be great. Please let me know.</p>
<p>Otherwise, <b>how can I obtain the message content and the attachments without going through the huge collection manually?</b> Even if I could only get the message content and the names of the attachments, that would be sufficient. Is there documentation of the Outlook mail storage format? Is there a way to query Outlook for the data?</p>
<p>Maybe there is an alternative approach I haven't considered?</p>
<p>My preferred language to do this is C#, but I can use others if needed.</p>
|
<p><a href="http://www.dimastr.com/redemption/" rel="noreferrer">Outlook Redemption</a> is the best thing currently to use that I have found. It will allow you to get into the messages and extract the attachments and the message bodies. i am using it now to do just that.</p>
<p>Here is some code I use in a class. I included the constructor and the processing function I use to save off the attachments. I cut out the code that is specific to my needs but you can get an idea of what to use here.</p>
<pre><code> private RDOSession _MailSession = new RDOSession();
private RDOFolder _IncommingInbox;
private RDOFolder _ArchiveFolder;
private string _SaveAttachmentPath;
public MailBox(string Logon_Profile, string IncommingMailPath,
string ArchiveMailPath, string SaveAttPath)
{
_MailSession.Logon(Logon_Profile, null, null, true, null, null);
_IncommingInbox = _MailSession.GetFolderFromPath(IncommingMailPath);
_ArchiveFolder = _MailSession.GetFolderFromPath(ArchiveMailPath);
_SaveAttachmentPath = SaveAttPath;
}
public void ProcessMail()
{
foreach (RDOMail msg in _IncommingInbox.Items)
{
foreach (RDOAttachment attachment in msg.Attachments)
{
attachment.SaveAsFile(_SaveAttachmentPath + attachment.FileName);
}
}
if (msg.Body != null)
{
ProcessBody(msg.Body);
}
}
}
</code></pre>
<p><strong>edit:</strong>
This is how I call it and what is passed</p>
<pre><code>MailBox pwaMail = new MailBox("Self Email User", @"\\Mailbox - Someone\Inbox",
@"\\EMail - Incomming\Backup", @"\\SomePath");
</code></pre>
|
<p>If you want to extract your e-mails take a look at
Outlook Email Extractor
at codeproject
<a href="http://69.10.233.10/KB/dotnet/OutlookEmailExtractor.aspx" rel="nofollow noreferrer">http://69.10.233.10/KB/dotnet/OutlookEmailExtractor.aspx</a></p>
<p>rob
www.filefriendly.com</p>
| 27,597
|
<p>Does a caching-nameserver usually cache the negative DNS response SERVFAIL? </p>
<p>EDIT:
To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional?</p>
|
<p>SERVFAIL is covered by §7.1 of RFC2308:</p>
<blockquote>
<p>Server failures fall into two major
classes. The first is where a
server can determine that it has been
misconfigured for a zone. This may
be where it has been listed as a server, but not configured to be a
server for the zone, or where it has
been configured to be a server for
the zone, but cannot obtain the zone
data for some reason. This can
occur either because the zone file
does not exist or contains errors,
or because another server from which
the zone should have been available
either did not respond or was unable
or unwilling to supply the zone.</p>
<p>The second class is where the
server needs to obtain an answer from
elsewhere, but is unable to do so, due
to network failures, other servers
that don't reply, or return server
failure errors, or similar.</p>
<p>In either case a resolver MAY cache
a server failure response. If it
does so it MUST NOT cache it for
longer than five (5) minutes, and it
MUST be cached against the specific
query tuple <query name, type,
class, server IP address>.</p>
</blockquote>
<p>So basically, it's dependent on the implementation of your name server.</p>
|
<p>One of the timeout fields in the SOA is a "negative timeout". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a "positive" response.</p>
| 9,908
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.