instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I am writing a batch file script using Windows command-line environment and want to change each occurrence of some text in a file (ex. "FOO") with another (ex. "BAR"). What is the simplest way to do that? Any built in functions?</p>
|
<p>A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.</p>
<p>I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:</p>
<pre><code>powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
</code></pre>
<p>To explain it:</p>
<ul>
<li><code>powershell</code> starts up powershell.exe, which is included in Windows 7</li>
<li><code>-Command "... "</code> is a command line arg for powershell.exe containing the command to run</li>
<li><code>(gc myFile.txt)</code> reads the content of <code>myFile.txt</code> (<code>gc</code> is short for the <code>Get-Content</code> command)</li>
<li><code>-replace 'foo', 'bar'</code> simply runs the replace command to replace <code>foo</code> with <code>bar</code></li>
<li><code>| Out-File myFile.txt</code> pipes the output to the file <code>myFile.txt</code></li>
<li><code>-encoding ASCII</code> prevents transcribing the output file to unicode, as the comments point out</li>
</ul>
<p>Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is <code>C:\WINDOWS\system32\WindowsPowerShell\v1.0</code></p>
<p><strong>Update</strong><br/>Apparently modern windows systems have PowerShell built in allowing you to access this directly using</p>
<pre><code>(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
</code></pre>
|
<p>I have faced this problem several times while coding under Visual C++.
If you have it, you can use Visual studio Find and Replace Utility. It allows you to select a folder and replace the contents of any file in that folder with any other text you want.</p>
<p>Under Visual Studio:
Edit -> Find and Replace
In the opened dialog, select your folder and fill in "Find What" and "Replace With" boxes.
Hope this will be helpful. </p>
| 8,483
|
<p>I am trying to create an Xercesc DOM Parser in my code and for some reason and try to instiate an XercescDOM object I get a NULL pointer returned. I am using xercesc version 2.8
Here the code.</p>
<pre><code>using namespace xercesc;
int main(int argc, char*argv[])
{
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e)
{
char* errMsg = XMLString::transcode(e.getMessage());
cout << "Problem initializing parser: " << errMsg;
XMLString::release(&errMsg);
}
XercesDOMParser* parser = new XercesDOMParser();
if (!parser)
cout << "Failed to create parser";
}
</code></pre>
|
<p>@Doug: no, this is not related, afaik, because the code you linked to tries to fetch the document from the parse() method, but this is a <a href="http://xerces.apache.org/xerces-c/apiDocs-2/classAbstractDOMParser.html#c0b30b3d2116c488920646f0d700d9f0" rel="nofollow noreferrer">void function</a>, so the result will always be "null" this way.</p>
<p>Otherwise, I don't see any problem with the parent post. It compiles almost ok and here I have a correct result (non-null parser).</p>
|
<p>It was a bug some where else in my code.</p>
| 26,452
|
<p>I am working on g code for my homebrew 3d printer and i have found the line <code>G1 -2.000 F2400.000</code>. From what i understand there should be an axis before the number and x and y shouldnt have negative. I am using grbl which is for cnc milling but and i have been deleting this line with no problems but i am wondering what it does because i will be upgrading to a "real" 3d printer asap</p>
|
<blockquote>
<p>G1 -2.000 F2400.000</p>
</blockquote>
<p>Is not valid G-code. As you note, <code>-2.000</code> should be prefixed with an axis (X,Y,Z or E).</p>
<p>Marlin would ignore the <code>-2.000</code> bit and simply treat the command as equivalent to</p>
<pre><code>G1 F2400.000
</code></pre>
<p>which doesn't perform any movement, but sets the feedrate for any future moves to 2400mm/min.</p>
<blockquote>
<p>x and y shouldnt have negative</p>
</blockquote>
<p>Not necessarily. Even though normally printing is done in the positive quadrant, negative values can be valid. Not only in relative movement mode, but even in absolute mode (for instance, if you set the center of your bed as (0,0) or if you use a negative z-axis offset the bring the nozzle closer to the bed).</p>
|
<p>G1 indicates a movement and -2.000 the distance, F2400.000 the feed rate mm/min, normally the <strong>(-)</strong> values are for retraction on extrusion <strong>E</strong>, for example:</p>
<p>G0 X12 (move to 12mm on the X axis) <br>
G0 F1500 (Set the feedrate to 1500mm/minute) <br>
G1 X90.6 Y13.8 E22.4 (Move to 90.6mm on the X axis and 13.8mm on the Y axis while extruding 22.4mm of material) </p>
<pre><code>1. G1 F1500
2. G1 X50 Y25.3 E22.4
</code></pre>
<p>In the above example, we set the feedrate to 1500mm/minute on line 1, then move to 50mm on the X axis and 25.3mm on the Y axis while extruding 22.4mm of filament between the two points. </p>
<pre><code>1. G1 F1500
2. G1 X50 Y25.3 E22.4 F3000
</code></pre>
<p>However, in the above example, we set a <strong>feedrate of 1500 mm/minute</strong> on <strong>line 1</strong>, then do the move described above <strong><em>accelerating to a feedrate of 3000 mm/minute</em></strong> as it does so. The extrusion will accelerate along with the X and Y movement, so everything stays synchronized. </p>
<p><strong><em>So, in your case if some axis is not defined the feed rate applies to all motors.</em></strong></p>
<p><em>(part of this content is from reprap-wiki)</em></p>
<p>You will see negative numbers if your starting point is on the center of the bed just like rectangular coordinates.</p>
<pre><code>G1 X-50.318 Y8.849 E11.70313
G1 X-52.606 Y3.087 E12.26689
G1 X-53.240 Y1.297 E12.43953
G1 X-54.398 Y-2.097 E12.76562
G1 X-54.683 Y-2.995 E12.85132
</code></pre>
| 727
|
<p>I have a directory of files that I'd like to append file extension to as long as they don't have an existing, specified extension. So add .txt to all file names that don't end in .xyz. PowerShell seems like a good candidate for this, but I don't know anything about it. How would I go about it?</p>
|
<p>Here is the Powershell way:</p>
<pre><code>gci -ex "*.xyz" | ?{!$_.PsIsContainer} | ren -new {$_.name + ".txt"}
</code></pre>
<p>Or to make it a little more verbose and easier to understand:</p>
<pre><code>Get-ChildItem -exclude "*.xyz"
| WHere-Object{!$_.PsIsContainer}
| Rename-Item -newname {$_.name + ".txt"}
</code></pre>
<p>EDIT: There is of course nothing wrong with the DOS way either. :)</p>
<p>EDIT2: Powershell does support implicit (and explicit for that matter) line continuation and as Matt Hamilton's post shows it does make thing's easier to read.</p>
|
<p>Consider the DOS command FOR in a standard shell.</p>
<pre><code>C:\Documents and Settings\Kenny>help for
Runs a specified command for each file in a set of files.
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
...
In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
</code></pre>
| 31,378
|
<p>How solid is Mono for C# development on Linux and OS X? I've been thinking about learning C# on the side, and was wondering if learning using Mono would suffice.</p>
|
<p>I have been using mono for upwards of 2 years now. Work is windows and .Net, home is mono on GNU/Linux. I have been able to run both GUI and ASP.NET apps with no problems from the same SVN repository. The only changes I had to make were in connection strings. ASP.NET works well under mod_mono for apache and xsp2. Some of the .NET 3.5 pieces are not there but definitely works for .NET 2.0 and earlier. </p>
<p>Monodevelop is coming along nicely and I believe the debugger is working well too.</p>
|
<p>To learn the language, you will be just fine. There are some libraries missing in mono, but that would not prevent you from learning the language. You can find more information at the <a href="http://www.mono-project.com/FAQ:_General" rel="nofollow noreferrer">Mono Project Page: FAQ</a>.</p>
| 11,806
|
<p>I'll be using the <a href="http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=4004" rel="nofollow noreferrer">AdventureWorks Database</a> to illustrate my problem.</p>
<p>I need to show for a particular customer a list of OrderDate with the most Orders.</p>
<p>My intial attempt was as follows:</p>
<pre><code>SELECT CustomerID, OrderDate, COUNT(1) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate
ORDER BY Cnt DESC
</code></pre>
<p>This will get us the following result:</p>
<pre><code>CustomerID OrderDate Cnt
----------- ---------- ----
11300 2003-11-22 00:00:00.000 2
11300 2004-01-28 00:00:00.000 2
11300 2004-02-18 00:00:00.000 2
11300 2004-02-08 00:00:00.000 2
11300 2004-02-15 00:00:00.000 1
11300 2004-03-11 00:00:00.000 1
11300 2004-03-24 00:00:00.000 1
11300 2004-03-30 00:00:00.000 1
11300 2004-04-28 00:00:00.000 1
11300 2004-05-03 00:00:00.000 1
11300 2004-05-17 00:00:00.000 1
11300 2004-06-18 00:00:00.000 1
...
</code></pre>
<p>Not exactly what I wanted, as the result should only show all records where Cnt = 2, like so:</p>
<pre><code>CustomerID OrderDate Cnt
----------- ---------- ----
11300 2003-11-22 00:00:00.000 2
11300 2004-01-28 00:00:00.000 2
11300 2004-02-18 00:00:00.000 2
11300 2004-02-08 00:00:00.000 2
</code></pre>
<p>I'm stuck because I can't wrap my mind around two problems:</p>
<p>1) A customer might have more than one OrderDate with the same Cnt value. This means I can't do something like TOP 1 to get the desired result.<br>
2) Because the number of Orders for each customer may be different, I cannot use the following SQL statement:</p>
<pre><code>SELECT CustomerID, OrderDate, COUNT(1) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate HAVING COUNT(1) > 1
ORDER BY Cnt DESC
</code></pre>
<p>This will work for getting the right result for this customer, but will definitely be wrong if the next customer has only one Order for a particular day.</p>
<p>So, either the query is impossible in this situation, or I am approaching the query in the wrong way. Any ideas on this problem is appreciated. </p>
<p>Also, since this will be a query in a stored procedure, any ideas on solving this in T-SQL will be acceptable.</p>
<p>UPDATE: Thanks to <a href="https://stackoverflow.com/questions/347449/sql-statement-help-select-list-of-customerid-orderdate-with-the-most-records-in#347460">Mehrdad</a>, I've been introduced to <a href="http://msdn.microsoft.com/en-us/library/ms190766(SQL.90).aspx" rel="nofollow noreferrer">Common Table Expressions</a>, and Life is Good®. :) </p>
|
<p>You should use <code>TOP</code> <i><code>n</code></i> <code>WITH TIES</code> clause to accomplish the task:</p>
<pre><code>SELECT TOP 1 WITH TIES CustomerID, OrderDate, COUNT(*) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate
ORDER BY Cnt DESC
</code></pre>
<p>Alternatively, you can use a <i>common table expression (CTE)</i> to solve the problem. This solution requires SQL Server 2005 or higher:</p>
<pre><code>WITH MyTable AS (SELECT CustomerID, OrderDate, COUNT(*) Cnt
FROM Sales.SalesOrderHeader
WHERE CustomerID = 11300
GROUP BY CustomerID, OrderDate)
SELECT CustomerID, OrderDate, Cnt
FROM MyTable
WHERE Cnt = (SELECT MAX(Cnt) FROM MyTable);
</code></pre>
<p>If you're using the CTE method, make sure the previous statement is terminated by a semicolon (if it's not the first statement). It's required before a CTE expression.</p>
|
<p>I don't have a copy of AdventureWorks handy to test with, but could the WITH TIES clause help out? You could do something like:</p>
<pre><code>SELECT TOP 1 WITH TIES CustomerID, OrderDate, COUNT(*) Cnt
...
ORDER BY COUNT(*) DESC
</code></pre>
<p>... which should get you all the rows that match the value in your ORDER BY clause (the count).</p>
| 45,206
|
<p>Here's my scenario. I created an application which uses Integrated Windows Authentication in order to work. In <code>Application_AuthenticateRequest()</code>, I use <code>HttpContext.Current.User.Identity</code> to get the current <code>WindowsPrincipal</code> of the user of my website.</p>
<p>Now here's the funny part. Some of our users have recently gotten married, and their names change. (i.e. the user's NT Login changes from <code>jsmith</code> to <code>jjones</code>) and when my application authenticates them, IIS passes me their OLD LOGIN . I continue to see <code>jsmith</code> passed to my application until I reboot my SERVER! Logging off the client does not work. Restarting the app pool does not work. Only a full reboot. </p>
<p>Does anyone know what's going on here? Is there some sort of command I can use to flush whatever cache is giving me this problem? Is my server misconfigured?</p>
<p>Note: I definitely do NOT want to restart IIS, my application pools, or the machine. As this is a production box, these are not really viable options.</p>
<hr>
<p>AviD -</p>
<p>Yes, their UPN was changed along with their login name. And Mark/Nick... This is a production enterprise server... It can't just be rebooted or have IIS restarted. </p>
<hr>
<p><strong>Follow up (for posterity):</strong></p>
<p>Grhm's answer was spot-on. This problem pops up in low-volume servers where you don't have a lot of people using your applications, but enough requests are made to keep the users' identity in the cache. The key part of the <a href="http://support.microsoft.com/kb/946358" rel="noreferrer">KB</a> which seems to describe why the cache item is not refreshed after the default of 10 minutes is:</p>
<blockquote>
<p>The cache entries do time out, however chances are that recurring
queries by applications keep the existing cache entry alive for the
maximum lifetime of the cache entry.</p>
</blockquote>
<p>I'm not exactly sure what in our code was causing this (the recurring queries), but the resolution which worked for us was to cut the <code>LsaLookupCacheExpireTime</code> value from the seemingly obscene default of 1 week to just a few hours. This, for us, cut the probability that a user would be impacted in the real world to essentially zero, and yet at the same time doesn't cause an extreme number of SID-Name lookups against our directory servers. An even better solution IMO would be if applications looked up user information by SID instead of mapping user data to textual login name. (Take note, vendors! If you're relying on AD authentication in your application, you'll want to put the SID in your authentication database!)</p>
|
<p>I've had similar issues lately and as stated in Robert MacLean's <a href="https://stackoverflow.com/questions/168946/iis-returning-old-user-names-to-my-application/581346#581346">answer</a>, AviD's group policy changes don't work if you're not logging in as the users.</p>
<p>I found changing the <strong>LSA Lookup Cache</strong> size as described is MS <a href="http://support.microsoft.com/kb/946358" rel="nofollow noreferrer">KB946358</a> worked without rebooting or recycling any apppool or services.</p>
<p>I found this as an answer to this similar question: <a href="https://stackoverflow.com/questions/5551489/wrong-authentication-after-changing-users-logon-name">Wrong authentication after changing user's logon name</a>.</p>
<p>You might want to look into the following system calls such as the following ones:</p>
<pre><code>LookupAccountName()
LookupAccountSid()
LsaOpenPolicy()
</code></pre>
<p>You could use them to write a C++/CLI (/Managed-C++) app to interrogate the LSA cache.</p>
|
<p>Login to the server that runs the IIS using the new login name in question. This will refresh the credential without re-starting IIS or rebooting the server.</p>
| 20,391
|
<p>I know that in Unix (specifically, Mac OS X) the superblock stores information about the layout of data on the disk, including the disk addresses at which the inodes begin and end. I want to scan the list of inodes in my program to look for deleted files. How can I find the disk address at which the inodes begin? I have looked at the statfs command but it does not provide this information.</p>
|
<p>Since you mention Mac OS X, let's assume you mean to do this for HFS+ only. The <a href="http://en.wikipedia.org/wiki/HFS_Plus" rel="nofollow noreferrer">Wikipedia page</a> provides some information about possible ways to start, for instance it says this about the on-disk layout:</p>
<blockquote>
<p>Sectors 0 and 1 of the volume are HFS boot blocks. These are identical to the boot blocks in an HFS volume. They are part of the HFS wrapper.</p>
<p>Sector 2 contains the Volume Header equivalent to the Master Directory Block in an HFS volume. The Volume Header stores a wide variety of data about the volume itself, for example the size of allocation blocks, a timestamp that indicates when the volume was created or the location of other volume structures such as the Catalog File or Extent Overflow File. The Volume Header is always located in the same place.</p>
<p>The Allocation File which keeps track of which allocation blocks are free and which are in use. It is similar to the Volume Bitmap in HFS, each allocation block is represented by one bit. A zero means the block is free and a one means the block is in use. The main difference with the HFS Volume Bitmap, is that the Allocation File is stored as a regular file, it does not occupy a special reserved space near the beginning of the volume. The Allocation File can also change size and does not have to be stored contiguously within a volume.</p>
</blockquote>
<p>It becomes more complicated, after that. Read up on <a href="http://en.wikipedia.org/wiki/B*-tree" rel="nofollow noreferrer">B* trees</a>, for instance.</p>
<p>I'm no Mac OS user, but it would surprise me if there weren't already tools written to scan for deleted files, perhaps some are open source and could provide a more concrete starting point?</p>
|
<p>You'll have quite some trouble to find deleted files because there's not much left on the disk to find when you delete a file.</p>
<p>If you delete a file on a FAT (or UDF) file system, its directory entry simply gets marked as "deleted", with most of the dir entry still intact.</p>
<p>On HFS volumes, due to their use of B-Trees, deleted edits <em>must</em> be removed from the directory or else searching for items wouldn't work any more efficiently (well, this argument may be a bit weak, but fact is that deleted entries get removed and overwritten).</p>
<p>So, unless the deletion took place by writing over a directory sector by accident, or by re-initializing the volume, you'll not find much.</p>
| 44,133
|
<p>Some time ago I wrote a piece of code to update multiple rows in a database table. The code was like this</p>
<pre><code>var db = new MyDataContext();
db.Execute("UPDATE Details SET IsActive = 0 WHERE MasterId = 1");
</code></pre>
<p>Then the other day when I got the latest version of the file I saw that somebody changed the code to something like this</p>
<pre><code>var details = from d in db.details where d.MasterId == 1 select d;
foreach (var detail in details)
detail.IsActive = false;
db.SubmitChanges();
</code></pre>
<p>So my question is: What is the better way to update multiple rows? Using Linq or SQL?</p>
|
<p>Check the approach used in this article:</p>
<ul>
<li><a href="https://terryaney.wordpress.com/2008/04/14/batch-updates-and-deletes-with-linq-to-sql/" rel="nofollow noreferrer">Batch Updates and Deletes with LINQ to SQL</a></li>
</ul>
|
<p>The Linq-to-SQL version is going to <code>SELECT</code> every row from the <code>details</code> table that matches the query, pull them into memory, and create objects for them. Then when it applies the updates, it will use a separate <code>UPDATE</code> statement for each object, and will (by default) include a <code>WHERE</code> clause that checks the value of every column to make sure it hasn't changed since you did the <code>SELECT</code>. If the row has changed, Linq will throw an exception.</p>
<p>The Linq version of the code is going to be <strong>MUCH</strong> slower (think 100x or 1000x slower), and expose you to additional exceptions.</p>
<p>The SQL version might be a bit harder to maintain as you refactor code in the future, but it will make a world of difference to your database.</p>
<p>I generally feel that Linq-to-SQL is great for selects and individual updates, and maybe for small batches the database would be fast enough that the extra queries wouldn't a problem, but I would have to think carefully before I used Linq for large batches, or on a web server.</p>
| 45,334
|
<p>Hy, does anyone worked with N2 Content Management System(<a href="http://www.codeplex.com/n2" rel="nofollow noreferrer">http://www.codeplex.com/n2</a>).
If yes, how does it perform, performance wise(under heavy load)?
It seems pretty simple and easy to use.</p>
<p>Adrian</p>
|
<p>Maybe try this question at <a href="http://www.codeplex.com/n2/Thread/List.aspx" rel="nofollow noreferrer">http://www.codeplex.com/n2/Thread/List.aspx</a></p>
<p>They might be able to tell you about performance limitations or bottlenecks.</p>
|
<p>I tried it and it looked promising at first but quickly had issues actually deploying it to a Medium Trust host.</p>
| 3,332
|
<p>Not of the site collection itself, but the individual SPWeb's.</p>
|
<p>You should take a look at this blog entry by Alexander Meijers : <a href="http://www.bloggix.com/blogs/microsoft/archive/2008/04/03/size-of-spweb-based-on-its-folders-and-files.aspx" rel="noreferrer">Size of SPWeb based on its Folders and Files</a></p>
<p>It provides a clever way of finding the size of an SPWeb or SPFolder by iterating through his content.</p>
<pre><code>private long GetWebSize(SPWeb web)
{
long total = 0;
foreach (SPFolder folder in web.Folders)
{
total += GetFolderSize(folder);
}
foreach (SPWeb subweb in web.Webs)
{
total += GetWebSize(subweb);
subweb.Dispose();
}
return total;
}
</code></pre>
|
<p>For anyone who comes back to this question, here is the missing method:</p>
<pre><code>private long GetFolderSize(SPFolder folder)
{
long folderSize = 0;
foreach (SPFile file in folder.Files)
{
folderSize += file.Length;
}
foreach (SPFolder subfolder in folder.SubFolders)
{
folderSize += GetFolderSize(subfolder);
}
return folderSize;
}
</code></pre>
| 24,584
|
<p>The most favorite feature of StackOverflow for me is that it can automatically detect code in post and set appropriate color to the code.</p>
<p>I'm wondering how the color is set. When I do a <kbd>Ctrl</kbd>+<kbd>F5</kbd> on a page, the code seems first be black text, then change to be colorful. Is it done by jQuery?</p>
|
<p>In reply to..</p>
<blockquote>
<p>Spolsky: How do they know, how do they even know what language you're writing in?</p>
</blockquote>
<p>It doesn't. The highlighter is very dumb, but manages to gets away with it because most programming languages are so similar. Nearly everything uses syntax close-enough to..</p>
<pre><code>AFunction("a string")
1 + 4 # <- numbers
# /\ a comment
// also a comment..
</code></pre>
<p>..that most stuff highlights properly. The above isn't an actuall programming language, but it highlights perfectly.</p>
<p>There are exceptions, for example, it can sometimes treat a <code>/</code> as the start of a regex (as in Perl/Ruby). when it is not:</p>
<pre><code>this [^\s>/] # is highlighted as a regex, not a comment
</code></pre>
<p>..but these are fairly rare, and it does a good job of working out most stuff, like..</p>
<pre><code>/*
this is a multi-line comment
"with a string" =~ /and a regex/
*/
but =~ /this is a regex with a [/*] multiline comment
markers in it! */
</code></pre>
|
<p>As said by dbr, it does a dummy highlight of most common constructs of languages. Which doesn't work well with some exotic syntaxes. I wonder if we can do code sections without highlighting, BTW.</p>
<pre><code>For id = 1 To 10 Do
CallSomething() // It likes CamelCase identifiers...
End
for id = 1 to 10 do # Also highlight some common keywords...
if id % 2 then call_something(); x++; end
end
'str' "str" 12 + 15.6 * -7e+9 /* Some common constant forms */
=/regex/ ~/regex/ +/RE/ !/regexpr/ but not /[^regex]/ (no operator before it)
(* Some comment conventions are overlooked... *)
-- Lua's (and some other languages')
; So are these comments...
' And these (Basic)
</code></pre>
<p>Works well enough for common code to make illusion, and better than loading dozen of syntaxes in the browser.</p>
| 29,203
|
<p>I'm looking for a free (GPL or BSD-type license) outliner library that works in a browser. </p>
<p>It doesn't have to be too complicated, just allow keyboard control of collapsing and expanding items, and changing their order.</p>
<p>Anyone know a good library for this? Do any of the big UI component libraries have an outliner? If not, how would I go about writing it from scratch? (Eg. would it be better to start with jQuery? Or something else?)</p>
|
<p>The <a href="http://mjsarfatti.com/sandbox/nestedSortable/" rel="noreferrer">nestedSortable jQuery plugin</a> is probably a good place to start. Below is an example of using form fields in each draggable and nest-able <code><li></code>. Then it's just a matter of implementing something to handle indenting by keyboard and outputting a proper array of data or serialized string, etc.</p>
<h2><strong>Demo: <a href="http://jsfiddle.net/Marcel/YUDHG/2/show/" rel="noreferrer">jsfiddle.net/Marcel/YUDHG/2</a></strong> (<a href="http://jsfiddle.net/Marcel/YUDHG/2/" rel="noreferrer">edit</a>)</h2>
|
<p>The most difficult part will be enabling the keyboard to control the collapsing and expanding. The same functionality using only mouse events is pretty easy and you should find examples <a href="http://www.google.es/search?q=jquery+outliner" rel="nofollow noreferrer">googling</a></p>
| 32,091
|
<p>How would one configure trac to allow anonymous submission of tickets? </p>
|
<p>In your trac config you need to give the anonymous user the TICKET_CREATE permission.</p>
|
<p>Setup a trac site to allow anonymous (no actual login) login. Grant the anonymous user permission to only create tickets, and maybe view existing tickets if you wish. But deny all other permissions.</p>
<p>The trac admin plugin makes this pretty easy.</p>
| 14,737
|
<p>Can you create websites with Chinese characters in PHP? </p>
<p>UPDATE: Perhaps I should have said - is it straight forward. Because some languages like Java make it extremely easy. Perhaps localisation in PHP isn't as easy as Java???</p>
|
<p>Yes on both counts. Read <a href="http://www.herongyang.com/PHP-Chinese/" rel="nofollow noreferrer">this guide</a> on building Chinese websites in PHP.</p>
|
<p>Sure.</p>
<p><a href="http://www.onlamp.com/pub/a/php/2002/11/28/php_i18n.html" rel="nofollow noreferrer">http://www.onlamp.com/pub/a/php/2002/11/28/php_i18n.html</a></p>
| 16,869
|
<p>I am planning to use jquery in Rails instead of prototype. </p>
<p>I am not sure to use jRails or to use plain jquery and stay away from RJS.</p>
<p>What do you think about this? </p>
<p>EDIT: Two weeks later I found this <a href="http://www.loudthinking.com/posts/32-myth-3-rails-forces-you-to-use-prototype" rel="noreferrer">http://www.loudthinking.com/posts/32-myth-3-rails-forces-you-to-use-prototype</a> </p>
<p>EDIT: <a href="http://railscasts.com/episodes/136-jquery" rel="noreferrer">This</a> screencast is interesting too.</p>
|
<p>If you ask me, staying away from RJS is a great idea. RJS is an amazingly cool hack, but for production code it's a pain to test and debug. I recommend sticking to UJS (Unobtrusive JavaScript), and jQuery is a great way to do UJS.</p>
|
<p>Prototype and Scriptaculous are parts of Rails framework. IMHO, you can remove these libraries and insert others but then it will be not Rails framework and Rails project.</p>
<p>The other variant is to add jQuery to the standard Rails configuration. After that you have to fix few compatibility problems between these libraries. jQuery have published small script that make it.</p>
| 30,482
|
<p>Here's a silly fun question:</p>
<p>Let's say we have to perform a simple operation where we need half of the value of a variable. There are <em>typically</em> two ways of doing this:</p>
<pre><code>y = x / 2.0;
// or...
y = x * 0.5;
</code></pre>
<p>Assuming we're using the standard operators provided with the language, which one has better performance?</p>
<p>I'm guessing multiplication is typically better so I try to stick to that when I code, but I would like to confirm this. </p>
<p>Although personally I'm interested in the answer for <strong>Python</strong> 2.4-2.5, feel free to also post an answer for other languages! And if you'd like, feel free to post other fancier ways (like using bitwise shift operators) as well.</p>
|
<p>I think this is getting so nitpicky that you would be better off doing whatever makes the code more readable. Unless you perform the operations thousands, if not millions, of times, I doubt anyone will ever notice the difference.</p>
<p>If you really have to make the choice, benchmarking is the only way to go. Find what function(s) are giving you problems, then find out where in the function the problems occur, and fix those sections. However, I still doubt that a single mathematical operation (even one repeated many, many times) would be a cause of any bottleneck.</p>
|
<p>Well, if we assume that an add/subtrack operation costs 1, then multiply costs 5, and divide costs about 20.</p>
| 28,007
|
<p>I'm using Zend Studio for Eclipse (Linux), and I'm trying to generate getter and setters methods in a PHP class.</p>
<p>I try to do this: <a href="http://files.zend.com/help/Zend-Studio-Eclipse-Help/creating_getters_and_setters.htm" rel="nofollow noreferrer">http://files.zend.com/help/Zend-Studio-Eclipse-Help/creating_getters_and_setters.htm</a>
but I haven't "Generate Getters and Setters" option in Source Menu, it's missed!</p>
<p>Could u help me? Thanks!</p>
|
<p>It has to be there under the menu - source in Eclipse. Could you provide a snapshot of your Eclipse to verify.
EDITED: I guess it is not possible to generate getters and setters automatically in your version, though you would be able to create templates for the same and use it as per your requirements. Omnipotent (0 seconds ago)</p>
|
<p>If there is a 'Refactor' menu, check in there as well. A lot of those methods have been moved to the 'Refactor' menu in later versions of eclipse and if Zend has updated recently and not updated it's documentation, the items may have encountered an undocumented move.</p>
| 17,852
|
<p>I'm working with jQuery for the first time and need some help. I have html that looks like the following:</p>
<pre><code><div id='comment-8' class='comment'>
<p>Blah blah</p>
<div class='tools'></div>
</div>
<div id='comment-9' class='comment'>
<p>Blah blah something else</p>
<div class='tools'></div>
</div>
</code></pre>
<p>I'm trying to use jQuery to add spans to the .tools divs that call variouis functions when clicked. The functions needs to receive the id (either the entire 'comment-8' or just the '8' part) of the parent comment so I can then show a form or other information about the comment.</p>
<p>What I have thus far is:</p>
<pre><code><script type='text/javascript'>
$(function() {
var actionSpan = $('<span>[Do Something]</span>');
actionSpan.bind('click', doSomething);
$('.tools').append(actionSpan);
});
function doSomething(commentId) { alert(commentId); }
</script>
</code></pre>
<p>I'm stuck on how to populate the commentId parameter for doSomething. Perhaps instead of the id, I should be passing in a reference to the span that was clicked. That would probably be fine as well, but I'm unsure of how to accomplish that.</p>
<p>Thanks,
Brian</p>
|
<p>Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a <code>target</code> property that references the element it was called for, and the <code>this</code> variable is a reference to the element the event handler was attached to. So you could do the following:</p>
<pre><code>function doSomething(event)
{
var id = $(event.target).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
</code></pre>
<p>...or:</p>
<pre><code>function doSomething(event)
{
var id = $(this).parents(".tools").attr("id");
id = substring(id.indexOf("-")+1);
alert(id);
}
</code></pre>
|
<p>You don't have a lot of control over the arguments passed to a bound event handler.</p>
<p>Perhaps try something like this for your definition of <strong>doSomething()</strong>:</p>
<pre><code>function doSomething() {
var commentId = $(this).parent().attr('id');
alert(commentId);
}
</code></pre>
| 15,729
|
<p>I have an index on columns A, B, C, D of table T</p>
<p>I have a query that pulls from T with A, B, C in the WHERE clause.</p>
<p>Will the index be used or will a separate index be needed that only includes A, B, C?</p>
|
<p>David B is right that you should check the execution plan to verify the index is being used.</p>
<blockquote>Will the index be used or will a separate index be needed that only includes A, B, C?</blockquote>
<p>To answer this last part of the question, which I think is the core underlying topic (as opposed to the immediate solution), there is <em>almost</em> never a reason to index a subset of your indexed columns. If your index is (A, B, C, D), a WHERE against (A, B, C) will most likely result in an index <strong>seek</strong>, which is the ideal situation -- the index includes all the information the engine needs to go directly to the result set. I believe this is holds true for numeric types and for equality tests in string types, though it can break down with LIKE '%'s). On the other hand, if your WHERE only referenced D, you would most likely end up with an index <strong>scan</strong>, which would mean that the SQL engine would have to scan across all combinations of A, B, and C, and then check whether D met your criteria before deciding whether to add the row to the result set. On a particularly large table, when I found myself having to do a lot of queries against column "D", I added an additional index for D only, and saw about 90% performance improvement.</p>
<p>Edit: I should also recommend using the Database Engine Tuning Advisor in SQL Management Studio. It will tell you if your table isn't indexed ideally for the query you want to run.</p>
|
<p>Generally speaking yes it will be, all modern databases are clever enough to do this. There are exceptions, for example, if the statistics on the table show that the volume of data in it is sufficiently small that a full table read will be more efficient then the index will be discounted, but as a rule, you can rely on it where appropriate.</p>
<p>Consequently, you can take advantage of this when designing your indexes. Say for example I have a table which contains A, B, C as key values and columns Y and Z containing data which I know will be retrieved often by the statements </p>
<pre><code>SELECT Y FROM table WHERE A = alpha and B = beta and C = gamma
SELECT Z FROM table WHERE A = alpha and B = beta and C = gamma
</code></pre>
<p>The I will generally create an index on A,B,C,X,Z - assuming that X and Z are some reasonably small field. The reason for this is that I know the access pathway in the statements above will use the index, and <em>as the data I want to retrieve is already in the index read</em> then no separate read of the block of data required to retrieve the table data itself will be needed. This strategy can dramatically speed up data retrieval in some circumstances. Of course, you pay for it in update costs and disk space so you need to understand what your database is doing before applying it, but as in most databases reads dramatically outnumber writes it's generally well worth the consideration.</p>
| 16,412
|
<p>How can I send keyboard input messages to either the currently selected window or the previously selected window? </p>
<p>I have a program which I use to type some characters which are not present on my keyboard and I would like it if I could just send the input directly rather than me having to copy and paste all the time.</p>
<p>EDIT:</p>
<p>The application of this is typing the German Umlauts. I'm an American and I work in Germany. I'm working on an American keyboard and from time to time I have to type in the umlauts / the euro symbol / the sharp S. Currently I have a simple WinForms application with a textfield and some buttons with the extra characters on it. I type into the textfield and I can press the buttons to append text to the textfield. I then copy the text and paste it where ever. What would be nice though if I could just just hit one of the buttons and it would send the text where ever I'm typing / was typing. The current program works fairly well but I could make it better.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx" rel="noreferrer">SendKeys.Send</a> will help you with that.</p>
|
<p>If it's not present on your keyboard, you might simply add a button and send the code key of this character to the reference object you want to append this character. Give us an example of what you want, we might be able to show you some code.</p>
<p>Short example of code:</p>
<pre><code>myField.Text += "®"; //This is a char that I do not have on my keyboard
</code></pre>
| 44,279
|
<p>I am running tomcat and I have some custom images which when I store on my C drive do not show up.If I move them to webapp root foder, they r fine but I do not want these images to end up in the war file.As I am using Windows symbolic link is not an option. Any idea as to how I can make the images show up without storing in the webapp root?</p>
|
<p>The web server will need the images to be stored in a web folder (root or virtual directory) to interperet the URL to a local file location.</p>
<p>If on the other hand you are referencing your images using file:// then the web server is not serving the files, the OS is, and will only work for local users that have access to the files.</p>
|
<p>Well, you can also manage them by your app - that is when you get the request for the image, your application reads it from the disk, sets proper Content-type and outputs the image. </p>
<p>That is not recommended tho. Better leave this job to the web server.</p>
| 29,575
|
<p>I'm wondering if there are any good .NET recommendation algorithms available in open source projects, whether attached to a search engine or not. By recommendation I mean something that accepts a full-text article and recommends other articles from its index based on keyword similarity.</p>
<p>At the high end there are document classification engines like Autonomy; at the low-end spam filters and blog "related posts" widgets. Possibly advertisement-to-article matching, too. I'd like to incorporate one into a project but can't afford the high end and the low end seems to all be LAMP-based.</p>
<p>[Sorry, one answer asked for clarification: What I'm looking for is ideally a standalone library, but I'm willing to adapt good source code as necessary. The end result is that I need to be able to create a C# service that accepts an arbitrary amount of text and returnsa list of similar previously-indexed articles. Basicallly, the exact thing that StackOverflow itself does as you are submitting a question!]</p>
<p>Thanks!
Steve</p>
|
<p>I think that in StackOverflow they extract all common english words from the text and then compare this words with the remaining words of other posts to get the "Related" posts.</p>
|
<p>Question is not very clear (algorithm or library???) but only thing that comes to mind is Lucene.NET, the porting of the popular Lucene library on the .Net framework. HTH.</p>
| 9,759
|
<p>I am developing a web application which has Chart Controls.
I have developed a common chart User Control to use across the application. </p>
<p>I am looking for an elegent way to set the Chart control's along with other control's width, height based on the screen(browser size).</p>
<p>Please help me
Thanks
Shaik</p>
|
<p>Sounds like you want to resize a server-side dynamic image based on a client-side value. You would first need to load the page once, use Javascript to get the screen size. (Google for that. You can get the full cross browser technical list of which Javascript elements to use at <a href="http://www.quirksmode.org/dom/w3c_cssom.html" rel="nofollow noreferrer">Quirksmode.org</a>, but you'll still need to figure out how to write the script yourself.) Then, post that size back to the server, set the control with this new size, then render it to the client as usual. Keep in mind, if the user resizes the browser window at all it won't "fit" anymore. And you can always use percentage sizes with CSS like Aaron mentioned, but then of course the browser will resize the image, which never looks that good.
<p>Another alternative would be to put it in a Flash control. Those resize dynamically better usually, as long as the chart is rendered with vector elements by Flash.
<p>Either way, you'll want to make sure that this makes sense for your web design. Some times its good to make it dynamic, other times a certain amount of static size makes sense--all depends on lots of stuff, including whether or not its worth it to go to all that trouble.</p>
|
<p>a hidden div set to 100% by 100% can be used to tell you the browser window client area size; i don't think there is a way to measure the screen without a postback/callback</p>
<p>see <a href="https://stackoverflow.com/questions/90595/how-to-implement-a-web-page-that-scales-when-the-browser-window-is-resized">How to implement a web page that scales when the browser window is resized</a> for additional info</p>
| 16,182
|
<p>I've been reading through a lot of the rookie Java questions on <code>finalize()</code> and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally. </p>
<p>I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement <code>finalize()</code> in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right.</p>
<p>So my question is, what use cases are there for implementing <code>finalize()</code> that cannot be handled more reliably via another process or syntax within the language? </p>
<p>Please provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as is not the intent of this question.</p>
|
<p>You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a <code>close()</code> method and document that it needs to be called.</p>
<p>Implement <code>finalize()</code> to do the <code>close()</code> processing if you detect it hasn't been done. Maybe with something dumped to <code>stderr</code> to point out that you're cleaning up after a buggy caller.</p>
<p>It provides extra safety in an exceptional/buggy situation. Not every caller is going to do the correct <code>try {} finally {}</code> stuff every time. Unfortunate, but true in most environments.</p>
<p>I agree that it's rarely needed. And as commenters point out, it comes with GC overhead. Only use if you need that "belt and suspenders" safety in a long-running app.</p>
<p>I see that as of Java 9, <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/Object.html#finalize--" rel="noreferrer"><code>Object.finalize()</code></a> is deprecated! They point us to <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html" rel="noreferrer"><code>java.lang.ref.Cleaner</code></a> and <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ref/PhantomReference.html" rel="noreferrer"><code>java.lang.ref.PhantomReference</code></a> as alternatives.</p>
|
<p>iirc - you can use finalize method as a means of implementing a pooling mechanism for expensive resources - so they don't get GC's too.</p>
| 19,123
|
<p>I'm developing a script that involves creating an email contact and forwarding mail to that contact. Last part of the script is to automatically send a test email to the address to make sure the forwarding works.</p>
<p>So I use the following code:</p>
<pre><code>[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Core")
[void] [Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Outlook")
$olApp = New-Object Microsoft.Office.Interop.Outlook.ApplicationClass
$msg = $olApp.CreateItem(0)
$msg.Recipients.Add("me@example.com")
$msg.Subject = "test"
$msg.Body = "test"
$msg.Send()
</code></pre>
<p>I get an error at line 6: <code>"You cannot call a method on a null-valued expression."</code></p>
<p>I run the code at home, it works just fine. Difference: on a domain at work, using Exchange Server at work, using domain account at work.</p>
<p>I am using the same version of Powershell and Outlook on both machines. It's preferable to use Outlook to send the message because I already have Outlook open and that way the message will show up in my Sent Items folder.</p>
|
<p>I was having similar issues where some of the COM objects do not seem to populate fully (seems to have something to do with the corporate Outlook setup - perhaps anti-virus measures?). However, if you comment out the <code>$msg.Recipients.Add("me@example.com")</code> line and added <code>$msg.Display()</code> you can add the recipients and send from there. Not a very good solution. </p>
<p>For my question I was pointed towards Exchange Web Service (EWS) so I downloaded the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=42951" rel="nofollow" title="EWS API 2.2">EWS API 2.2</a> and used the following:</p>
<pre><code>Add-Type -LiteralPath "C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll"
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList Exchange2010_SP1
$service.AutodiscoverUrl(‘me@mydomain.com’, {$true})
$msg = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage($service)
$msg.Subject = "Sent from Powershell EWS"
$msg.Body = "<html><body><h1>TESTING</h1><p>This is a test message sent from Powershell!</p></body></html>"
$msg.ToRecipients.Add("me@mydomain.com")
$msg.SendAndSaveCopy()
</code></pre>
<p>This seemed to work pretty well and saved the message to my sent folder.</p>
<p>If you do not need the item to be saved in your sent-items folder (for example adding yourself as a recipient) it is probably easier to just use Send-MailMessage using "NT AUTHORITY\ANONYMOUS LOGON":</p>
<pre><code>$emptySecStr = New-Object System.Security.SecureString
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "NT AUTHORITY\ANONYMOUS LOGON", $emptySecStr
Send-MailMessage -SmtpServer $smtpServerName -Credential $creds -From $sendingAddr -to $sendToArray -Cc $sendCCArray -BodyAsHtml -body $htmlBody -Subject $subject
</code></pre>
<p>I got this technique from a great discussion <a href="http://powershell.com/cs/forums/t/11843.aspx" rel="nofollow">here</a>. </p>
|
<p>If you change your mind about using Outlook, look at the PowerShell Community Extensions (free) on CodePlex. They offer a cmdlet to send SMTP e-mail, which would suffice to test the newly-created address. Not sure if there's value in having the test in your Sent Items? Especially if you're doing these in bulk - it'd be much faster to use SMTP directly than to use Outlook.</p>
| 44,522
|
<p>I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which corresponds to one row in a MySQL table, but how do I produce a form that iterates over all the movie titles in the database and produces a form that lets you rate lots of them at once? </p>
<p>At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.</p>
<p>Currently, my views.py has this code:</p>
<pre><code>def survey(request):
ScoreFormSet = formset_factory(ScoreForm)
if request.method == 'POST':
formset = ScoreFormSet(request.POST, request.FILES)
if formset.is_valid():
return HttpResponseRedirect('/')
else:
formset = ScoreFormSet()
return render_to_response('cf/survey.html', {
'formset':formset,
})
</code></pre>
<p>And my survey.html has this:</p>
<pre><code><form action="/survey/" method="POST">
<table>
{{ formset }}
</table>
<input type = "submit" value = "Submit">
</form>
</code></pre>
<p>Oh, and the definition of ScoreForm and Score from models.py are:</p>
<pre><code>class Score(models.Model):
movie = models.ForeignKey(Movie)
score = models.IntegerField()
user = models.ForeignKey(User)
class ScoreForm(ModelForm):
class Meta:
model = Score
</code></pre>
<p>So, in case the above is not clear, what I'm aiming to produce is a form which has one row per movie, and each row shows a title, and has a box to allow the user to enter their score.</p>
<p>If anyone can point me at the right sort of approach to this, I'd be most grateful.</p>
|
<p>"At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean."</p>
<p>You need to get a queryset. And you need to provide that queryset to your form as initial data. See <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-initial-data-with-a-formset" rel="nofollow noreferrer">using initial data with a formset</a> for the code.</p>
<pre><code>initial = [ list of { dictionaries }, one per form ]
</code></pre>
<p>Interestingly, this is a direct feature of the model API through the <code>values</code> method of a queryset.</p>
|
<p>I have found my answer, using modelformset_factory instead formset_factory solves the problem, Thanks...</p>
| 38,260
|
<p>I would like to write a driver to talk to my Suunto t3 watch in Python on a Mac. My day job is doing basic web work in C# so my familiarity with Python and developing on a Mac is limited.</p>
<p>Can you suggest how one would start doing driver development in general and then more specifically on a Mac. I.e. how to easily see what data is being transmitted to the device? I have Python 2.5 (MacPorts) up and running.</p>
|
<p>If the watch supports a <a href="http://www.usb.org/developers/devclass_docs#approved" rel="nofollow noreferrer">standard USB device class specification</a> such as HID or serial communication, there might already be a Macintosh driver for it built into the OS. Otherwise, you're going to have to get information about the vendor commands used to communicate with it from one of three sources: the manufacturer; reverse engineering the protocol used by the Windows driver; or from others who have already reverse engineered the protocol in order to support the device on Linux or BSD.</p>
<p>USB is a packet-based bus and it's very important to understand the various transaction types. Reading the <a href="http://www.usb.org/developers/docs/" rel="nofollow noreferrer">USB specification</a> is a good place to start.</p>
<p>You can see what data is being transmitted to the device using a USB bus analyzer, which is an expensive proposition for a hobbyist but is well within the reach of most businesses doing USB development. For example, the <a href="http://www.getcatalyst.com/product-conquest.html" rel="nofollow noreferrer">Catalyst Conquest</a> is $1199. Another established manufacturer is <a href="http://www.lecroy.com/tm/products/ProtocolAnalyzers/usb.asp?menuid=67" rel="nofollow noreferrer">LeCroy (formerly CATC)</a>. There are also software USB analyzers that hook into the OS's USB stack, but they don't show all of the traffic on the bus, and may not be as reliable.</p>
<p>I'm not a Mac expert, so take this paragraph with a grain of salt: Apple has a driver development kit called the <a href="http://developer.apple.com/referencelibrary/GettingStarted/GS_HardwareDrivers/index.html" rel="nofollow noreferrer">I/O Kit</a>, which apparently requires you to write your driver in C++, unless they also have some sort of user-mode driver framework. If you're writing it in Python, it will probably be more like a Python library that interfaces to someone else's (Apple's?) generic USB driver.</p>
|
<p>If the watch supports a <a href="http://www.usb.org/developers/devclass_docs#approved" rel="nofollow noreferrer">standard USB device class specification</a> such as HID or serial communication, there might already be a Macintosh driver for it built into the OS. Otherwise, you're going to have to get information about the vendor commands used to communicate with it from one of three sources: the manufacturer; reverse engineering the protocol used by the Windows driver; or from others who have already reverse engineered the protocol in order to support the device on Linux or BSD.</p>
<p>USB is a packet-based bus and it's very important to understand the various transaction types. Reading the <a href="http://www.usb.org/developers/docs/" rel="nofollow noreferrer">USB specification</a> is a good place to start.</p>
<p>You can see what data is being transmitted to the device using a USB bus analyzer, which is an expensive proposition for a hobbyist but is well within the reach of most businesses doing USB development. For example, the <a href="http://www.getcatalyst.com/product-conquest.html" rel="nofollow noreferrer">Catalyst Conquest</a> is $1199. Another established manufacturer is <a href="http://www.lecroy.com/tm/products/ProtocolAnalyzers/usb.asp?menuid=67" rel="nofollow noreferrer">LeCroy (formerly CATC)</a>. There are also software USB analyzers that hook into the OS's USB stack, but they don't show all of the traffic on the bus, and may not be as reliable.</p>
<p>I'm not a Mac expert, so take this paragraph with a grain of salt: Apple has a driver development kit called the <a href="http://developer.apple.com/referencelibrary/GettingStarted/GS_HardwareDrivers/index.html" rel="nofollow noreferrer">I/O Kit</a>, which apparently requires you to write your driver in C++, unless they also have some sort of user-mode driver framework. If you're writing it in Python, it will probably be more like a Python library that interfaces to someone else's (Apple's?) generic USB driver.</p>
| 20,546
|
<p>When loading XML into an XmlDocument, i.e.</p>
<pre>
XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);
</pre>
<p>is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)</p>
<p>Thanks</p>
|
<p>This is a standard misunderstanding of the XML toolset. The whole business with "&#x", is a syntactic feature designed to cope with character encodings. Your XmlDocument isn't a stream of characters - it has been freed of character encoding issues - instead it contains an abstract model of XML type data. Words for this include DOM and InfoSet, I'm not sure exactly which is accurate. </p>
<p>The "&#x" gubbins won't exist in this model because the whole issue is irrelevant, it will return - if appropriate - when you transform the Info Set back into a character stream in some specific encoding.</p>
<p>This misunderstanding is sufficiently common to have made it into academic literature as part of a collection of similar quirks. Take a look at "Xml Fever" at this location: <a href="http://doi.acm.org/10.1145/1364782.1364795" rel="nofollow noreferrer">http://doi.acm.org/10.1145/1364782.1364795</a></p>
|
<p>I beleive if you enclose the entity contents in the CDATA section it should leave it all alone e.g.</p>
<pre><code><root>
<testnode>
<![CDATA[some text &#8482;]]>
</testnode>
</root>
</code></pre>
| 18,448
|
<p>How do I parse the first, middle, and last name out of a fullname field with SQL? </p>
<p>I need to try to match up on names that are not a direct match on full name. I'd like to be able to take the full name field and break it up into first, middle and last name. </p>
<p>The data does not include any prefixes or suffixes. The middle name is optional. The data is formatted 'First Middle Last'.</p>
<p>I'm interested in some practical solutions to get me 90% of the way there. As it has been stated, this is a complex problem, so I'll handle special cases individually.</p>
|
<p>Here is a self-contained example, with easily manipulated test data. </p>
<p>With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR".</p>
<p>If the middle name is missing, then you just get FIRST_NAME and LAST_NAME (MIDDLE_NAME will be NULL).</p>
<p>You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL.</p>
<p><strong>Edit-- Handle the following special cases:</strong></p>
<p><strong>1 - The NAME field is NULL</strong></p>
<p><strong>2 - The NAME field contains leading / trailing spaces</strong></p>
<p><strong>3 - The NAME field has > 1 consecutive space within the name</strong></p>
<p><strong>4 - The NAME field contains ONLY the first name</strong></p>
<p><strong>5 - Include the original full name in the final output as a separate column, for readability</strong></p>
<p><strong>6 - Handle a specific list of prefixes as a separate "title" column</strong></p>
<pre><code>SELECT
FIRST_NAME.ORIGINAL_INPUT_DATA
,FIRST_NAME.TITLE
,FIRST_NAME.FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
THEN NULL --no more spaces? assume rest is the last name
ELSE SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1
,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1
)
END AS MIDDLE_NAME
,SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
,LEN(FIRST_NAME.REST_OF_NAME)
) AS LAST_NAME
FROM
(
SELECT
TITLE.TITLE
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN TITLE.REST_OF_NAME --No space? return the whole thing
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,1
,CHARINDEX(' ',TITLE.REST_OF_NAME)-1
)
END AS FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN NULL --no spaces @ all? then 1st name is all we have
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,CHARINDEX(' ',TITLE.REST_OF_NAME)+1
,LEN(TITLE.REST_OF_NAME)
)
END AS REST_OF_NAME
,TITLE.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--if the first three characters are in this list,
--then pull it as a "title". otherwise return NULL for title.
CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3)))
ELSE NULL
END AS TITLE
--if you change the list, don't forget to change it here, too.
--so much for the DRY prinicple...
,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME))))
ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME))
END AS REST_OF_NAME
,TEST_DATA.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--trim leading & trailing spaces before trying to process
--disallow extra spaces *within* the name
REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME
,FULL_NAME AS ORIGINAL_INPUT_DATA
FROM
(
--if you use this, then replace the following
--block with your actual table
SELECT 'GEORGE W BUSH' AS FULL_NAME
UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME
UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME
UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME
UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME
UNION SELECT 'TOMMY' AS FULL_NAME
UNION SELECT 'BILLY' AS FULL_NAME
UNION SELECT NULL AS FULL_NAME
UNION SELECT ' ' AS FULL_NAME
UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME
UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME
UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME
UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME
UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME
) RAW_DATA
) TEST_DATA
) TITLE
) FIRST_NAME
</code></pre>
|
<ol>
<li>Get a sql regex function. Sample: <a href="http://msdn.microsoft.com/en-us/magazine/cc163473.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163473.aspx</a></li>
<li>Extract names using regular expressions. </li>
</ol>
<p>I recommend Expresso for learnin/building/testing regular expressions. <a href="http://www.codeproject.com/KB/dotnet/expresso.aspx" rel="nofollow noreferrer">Old free version</a>, <a href="http://www.ultrapico.com/Expresso.htm" rel="nofollow noreferrer">new commercial version</a></p>
| 19,303
|
<p>How do I ping a website or IP address with Python?</p>
|
<p>Depending on what you want to achive, you are probably easiest calling the system ping command..</p>
<p>Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!</p>
<pre><code>import subprocess
host = "www.google.com"
ping = subprocess.Popen(
["ping", "-c", "4", host],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print out
</code></pre>
<p>You don't need to worry about shell-escape characters. For example..</p>
<pre><code>host = "google.com; `echo test`
</code></pre>
<p>..will <strong>not</strong> execute the echo command.</p>
<p>Now, to actually get the ping results, you could parse the <code>out</code> variable. Example output:</p>
<pre><code>round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
</code></pre>
<p>Example regex:</p>
<pre><code>import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()
# ('248.139', '249.474', '250.530', '0.896')
</code></pre>
<p>Again, remember the output will vary depending on operating system (and even the version of <code>ping</code>). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)</p>
|
<p>Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.</p>
<pre><code>import platform,subproccess,re
def Ping(hostname,timeout):
if platform.system() == "Windows":
command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
else:
command="ping -i "+str(timeout)+" -c 1 " + hostname
proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
if matches:
return matches.group(1)
else:
return False
</code></pre>
| 40,918
|
<p>Objective: take a UIImage, crop out a square in the middle, change size of square to 320x320 pixels, slice up the image into 16 80x80 images, save the 16 images in an array.</p>
<p>Here's my code:</p>
<pre><code>CGImageRef originalImage, resizedImage, finalImage, tmp;
float imgWidth, imgHeight, diff;
UIImage *squareImage, *playImage;
NSMutableArray *tileImgArray;
int r, c;
originalImage = [image CGImage];
imgWidth = image.size.width;
imgHeight = image.size.height;
diff = fabs(imgWidth - imgHeight);
if(imgWidth > imgHeight){
resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(floor(diff/2), 0, imgHeight, imgHeight));
}else{
resizedImage = CGImageCreateWithImageInRect(originalImage, CGRectMake(0, floor(diff/2), imgWidth, imgWidth));
}
CGImageRelease(originalImage);
squareImage = [UIImage imageWithCGImage:resizedImage];
if(squareImage.size.width != squareImage.size.height){
NSLog(@"image cutout error!");
//*code to return to main menu of app, irrelevant here
}else{
float newDim = squareImage.size.width;
if(newDim != 320.0){
CGSize finalSize = CGSizeMake(320.0, 320.0);
UIGraphicsBeginImageContext(finalSize);
[squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];
playImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}else{
playImage = squareImage;
}
}
finalImage = [playImage CGImage];
tileImgArray = [NSMutableArray arrayWithCapacity:0];
for(int i = 0; i < 16; i++){
r = i/4;
c = i%4;
//*
tmp = CGImageCreateWithImageInRect(finalImage, CGRectMake(c*tileSize, r*tileSize, tileSize, tileSize));
[tileImgArray addObject:[UIImage imageWithCGImage:tmp]];
}
</code></pre>
<p>The code works correctly when the original (the variable image) has its smaller dimension either bigger or smaller than 320 pixels. When it's exactly 320, the resulting 80x80 images are almost entirely black, some with a few pixels at the edges that may (I can't really tell) be from the original image.</p>
<p>I tested by displaying the full image both directly:</p>
<pre><code>[UIImage imageWithCGImage:finalImage];
</code></pre>
<p>And indirectly:</p>
<pre><code>[UIImage imageWithCGImage:CGImageCreateWithImageInRect(finalImage, CGRectMake(0, 0, 320, 320))];
</code></pre>
<p>In both cases, the display worked. The problems only arise when I attempt to slice out some part of the image.</p>
|
<p>After some more experimentation, I found the following solution (I still don't know why it didn't work as originally written, though.) But anyway, the slicing works after the resize code is put in place even when resizing is unnecessary:</p>
<pre><code>if(newDim != 320.0){
CGSize finalSize = CGSizeMake(320.0, 320.0);
UIGraphicsBeginImageContext(finalSize);
[squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];
playImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}else{
CGSize finalSize = CGSizeMake(320.0, 320.0);
UIGraphicsBeginImageContext(finalSize);
[squareImage drawInRect:CGRectMake(0, 0, finalSize.width, finalSize.height)];
playImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
</code></pre>
<p>Anyone has any clue WHY this is going on?</p>
<p>P.S. Yes, if/else is no longer required here. Removing it <b>before</b> I knew it was going to work would be stupid, though.</p>
|
<p>Just out of curiosity, why did you make your mutable array with bound of 0 when you know you're going to put 16 things in it?</p>
<p>Well, aside from that, I've tried the basic techniques you used for resizing and slicing (I did not need to crop, because I'm working with images that are already square) and I'm unable to reproduce your problem in the simulator. You might want to try breaking your code into three separate functions (crop to square, resize, and slice into pieces) and then test the three separately so you can figure out which of the three steps is causing the problems (ie. input images that you've manipulated in a normal graphics program instead of using objective c and then inspect what you get back out!). </p>
<p>I'll attach my versions of the resize and slice functions below, which will hopefully be helpful. It was nice to have your versions to look at, since I didn't have to find all the methods by myself for once. :)</p>
<p>Just as a note, the two dimensional array mentioned is my own class built out of NSMutableArrays, but you could easily implement your own version or use a flat NSMutableArray instead. ;)</p>
<pre><code>// cut the given image into a grid of equally sized smaller images
// this assumes that the image can be equally divided in the requested increments
// the images will be stored in the return array in [row][column] order
+ (TwoDimensionalArray *) chopImageIntoGrid : (UIImage *) originalImage : (int) numberOfRows : (int) numberOfColumns
{
// figure out the size of our tiles
int tileWidth = originalImage.size.width / numberOfColumns;
int tileHeight = originalImage.size.height / numberOfRows;
// create our return array
TwoDimensionalArray * toReturn = [[TwoDimensionalArray alloc] initWithBounds : numberOfRows
: numberOfColumns];
// get a CGI image version of our image
CGImageRef cgVersionOfOriginal = [originalImage CGImage];
// loop to chop up each row
for(int row = 0; row < numberOfRows ; row++){
// loop to chop up each individual piece by column
for (int column = 0; column < numberOfColumns; column++)
{
CGImageRef tempImage =
CGImageCreateWithImageInRect(cgVersionOfOriginal,
CGRectMake(column * tileWidth,
row * tileHeight,
tileWidth,
tileHeight));
[toReturn setObjectAt : row : column : [UIImage imageWithCGImage:tempImage]];
}
}
// now return the set of images we created
return [toReturn autorelease];
}
// this method resizes an image to the requested dimentions
// be a bit careful when using this method, since the resize will not respect
// the proportions of the image
+ (UIImage *) resize : (UIImage *) originalImage : (int) newWidth : (int) newHeight
{
// translate the image to the new size
CGSize newSize = CGSizeMake(newWidth, newHeight); // the new size we want the image to be
UIGraphicsBeginImageContext(newSize); // downside: this can't go on a background thread, I'm told
[originalImage drawInRect : CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); // get our new image
UIGraphicsEndImageContext();
// return our brand new image
return newImage;
}
</code></pre>
<p>Eva Schiffer</p>
| 30,903
|
<p>I'm trying to use one of the RAMPS GPIOs to control an external device that requires a 5V low-current logic level signal from Marlin. In order to do this programmatically, my host software (Octoprint) is sending an M42 command. I am using the following syntax:</p>
<pre><code>M42 P4 S255
</code></pre>
<p>according to the pinout in the following image:</p>
<p><a href="https://i.stack.imgur.com/TRInv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TRInv.png" alt="enter image description here"></a></p>
<p>However, the pin appears to not be driven to a logic HIGH level. Is there firmware-level configuration I need to do as well, or is my syntax/pin number incorrect?</p>
|
<p>I looked at the current Marlin code and the P24 command should work as you expect it unless the pin you are trying to use in listed as the "SENSITIVE_PINS" list:</p>
<pre><code>#define SENSITIVE_PINS { 0, 1, \
X_STEP_PIN, X_DIR_PIN, X_ENABLE_PIN, X_MIN_PIN, X_MAX_PIN, \
Y_STEP_PIN, Y_DIR_PIN, Y_ENABLE_PIN, Y_MIN_PIN, Y_MAX_PIN, \
Z_STEP_PIN, Z_DIR_PIN, Z_ENABLE_PIN, Z_MIN_PIN, Z_MAX_PIN, Z_MIN_PROBE_PIN, \
PS_ON_PIN, HEATER_BED_PIN, FAN_PIN, FAN1_PIN, FAN2_PIN, CONTROLLER_FAN_PIN, \
_E0_PINS _E1_PINS _E2_PINS _E3_PINS _E4_PINS BED_PINS \
_H0_PINS _H1_PINS _H2_PINS _H3_PINS _H4_PINS \
_X2_PINS _Y2_PINS _Z2_PINS \
X_MS1_PIN, X_MS2_PIN, Y_MS1_PIN, Y_MS2_PIN, Z_MS1_PIN, Z_MS2_PIN \
}
</code></pre>
<p>These pins are printer specific; so, without access to your Marlin build, I can't see if pin 4 corresponds to one of these. If this is the problem, the command should be returning an error. If there is no error, I would look closely at the hardware.</p>
|
<p>Might be because servo pins are not connected to 5V. use Jumper as shown</p>
<p><a href="https://i.stack.imgur.com/ycegg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ycegg.png" alt="enter image description here"></a></p>
| 485
|
<p>All this originated from me poking at a compiler warning message (C4267) when attempting the following line:</p>
<pre><code>const unsigned int nSize = m_vecSomeVec.size();
</code></pre>
<p><code>size()</code> returns a size_t which although typedef'd to unsigned int, is not actually a unsigned int. This I believe have to do with 64 bit portability issues, however can someone explain it a bit better for me? ( I don't just want to disable 64bit warnings.)</p>
|
<p>It depends on the implementation. <code>std::size_t</code> for example has a minimal required size. But there is no upper limit. To avoid these kind of situations, always use the proper typedef:</p>
<pre><code>const std::vector<T>::size_type nSize = m_vecSomeVec.size();
</code></pre>
<p>You will be always on the safe side then.</p>
|
<p>Depending on the compiler, <code>int</code> may be 32-bits in 64-bit land.</p>
| 44,357
|
<p>In the last 3 companies I've worked at, the phone number columns are of type varchar(n). The reason being that they might want to store extensions (ext. 333). But in every case, the "-" characters are stripped out when inserting and updating. I don't understand why the ".ext" characters are okay to store but not the "-" character. Has any one else seen this and what explanation can you think of for doing it this way? If all you want to store is the numbers, then aren't you better off using an int field? Conversely, if you want to store the number as a string/varchar, then why not keep all the characters and not bother with formatting on display and cleaning on write? </p>
<p>I'm also interested in hearing about other ways in which phone number storage is implemented in other places.</p>
|
<p>Quick test: are you going to add/subtract/multiply/divide Phone Numbers? Nope. Similarly to SSNs, Phone Numbers are discrete pieces of data that can contain actual numbers, so a string type is probably most appropriate.</p>
|
<p>Stripping some characters and allowing others may have an impact if the database table is going to drive another system, e.g. IP Telephony of some sort. Depending on the systems involved, it may be legitimate to have etc.333 as a suffix, whereas the developers may not have accounted for "-" in the string (and yes, I am guessing here...)</p>
<p>As for storing as a varchar rather than an int, this is just plain-ole common sense to me. As mentioned before, leading zeros may be stripped in an int field, the query on an int field may perform implicit math functions (which could also explain stripping "-" from the text, you don't want to enter 555-1234 and have it stored as -679 do you?)</p>
<p>In short, I don't know the exact reasoning, but can deduce some possibilities.</p>
| 37,047
|
<p>I am sure this is a very simple problem, but I am new to VB.NET, so I am having an issue with it.</p>
<p>I have a <code>Decimal</code> variable, and I need to split it into two separate variables, one containing the integer part, and one containing the fractional part. </p>
<p>For example, for x = 12.34 you would end up with a y = 12 and a z = 0.34.</p>
<p>Is there a nice built-in functions to do this or do I have to try and work it out manually?</p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/7d101hyf.aspx" rel="noreferrer">Math.Truncate(decimal)</a> and then subtract that from the original. Be aware that that will give you a negative value for both parts if the input is decimal (e.g. -1.5 => -1, -.5)</p>
<p>EDIT: Here's a version of Eduardo's code which uses decimal throughout:</p>
<pre><code>Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _
ByRef fractionalPart As Decimal)
wholePart = Math.Truncate(number)
fractionalPart = number - wholePart
End Sub
</code></pre>
|
<p>Fractional and decimal part of a number have different significance when a number is above zero or below zero. Therefore, you have to consider both cases.
I suggest using the below code:</p>
<pre><code>Dim dbl as double = 13.067
Dim int1 As Integer = 0
Dim fraction As Double = 0
If dbl >= 0 Then
int1 = Math.Floor(dbl)
ElseIf dbl < 0 Then
int1 = Math.Ceiling(dbl)
End If
fraction = dbl - int1
</code></pre>
<p>fraction holdes 0.067, and int1 holds 13 .
Floor and Ceiling, round any fractional number to the lowest, and highest consecutive integer, respectively.</p>
| 47,303
|
<p>I am in the process of setting up CruiseControl.NET. The problem I am having is that I am running CC as a console application and when my build completes successfully and executes (using exec) it launches it within the CruiseControl DOS prompt. I am just using simple batch files to launch my app but having it run within the same prompt as CC is causing CC to think the build continues as long as my app runs.</p>
<p>Are there command line parameters to <code>cmd.exe</code> that will spawn another separate prompt window?</p>
|
<p>I think this works:</p>
<pre><code>start cmd.exe
</code></pre>
|
<p>I also tried executing batch file that run daemon process/server at the end of CCNET task;
The only way to make CruiseControl spawn an independent asynchronous process WITHOUT waiting for the end of process is: </p>
<ol>
<li>create a batch file to run the daemon process (server application) </li>
<li><p>use task scheduler to run the batch file as CCNET task (using schtasks.exe)</p>
<pre><code>schtasks.exe /create /F /SC once /ST 08:50 /TN TaskName /TR "c:/path/to/batchFileName.bat"
</code></pre>
<ul>
<li>08:50 is the HH:MM time format</li>
</ul></li>
</ol>
<p>you might need to kill the process at the start of ccnet</p>
<p>PS: the selected answer using "start cmd.exe" does not work; a new command prompt is indeed spawned, but CCNET will wait for the spawned cmd to finish.</p>
| 39,040
|
<p>For my website I configured some custom error pages.
If I generate a 404, the redirect works fine.
When hitting a 400, the "bad request" text shows up instead of the configured URl.</p>
<p>As a test I copied the URL from 404 to 400. No change.
Then I changed the redirect to a file. No change.</p>
<p>Any ideas?</p>
|
<p>Maybe <a href="https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc753103(v=ws.10)" rel="nofollow noreferrer">this</a> is your answer: this Microsoft site says re configuring custom errors in IIS6 that </p>
<blockquote>
<p>The following errors are not
customizable: 400, 403.9, 411, 414,
500, 500.11, 500.14, 500.15, 501, 503,
and 505.</p>
</blockquote>
|
<p>Check what's in your web.config file in the <code>customErrors</code> section. That has a <code>defaultRedirect</code> attribute, and an <code>error</code> subtag with a <code>redirect</code> attribute. These can conflict with your other configuration settings in IIS.</p>
| 33,713
|
<p>I'm new to .NET, so please be patient with me ;)</p>
<p>On my Windows Form, I have a DataGridView that is bound to a data source. Since my grid is read-only, I have a set of controls (textbox, checkbox, etc.) outside the grid that will be used to edit the data.</p>
<p>I want the controls to be binded to the currently selected row in the grid. Currently, if I set the DataBindings of the controls to the same data source as the grid, only the first record is showned even if I move the record pointer in the grid.</p>
<p>What am I missing?</p>
<p>Environment: Windows Form, C#, Visual Studio 2008.</p>
|
<p>to keep this completely within Visual Studio's databinding environment, you can use two BindingSources, one for the DataGridView and another for your detail controls. This is very similar to the example found here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx</a></p>
<p>But, instead of using a detail table you're using your own controls to show the details. These controls can still be databound to the 2nd BindingSource.</p>
<p>Alternatively, just handle the SelectionChanged event on your DataGridView and write code to manually update the values of your controls. This 2nd approach is a little more lightweight and will probably perform slightly better.</p>
<p>Hope this helps!</p>
<p>Adam</p>
|
<p>You want to check out the custom datagridviewcolumn types that are available with the datagridview.
Add in special columns and then bind a list of business objects to the grid (or a DataSet).</p>
<p>I think you can even ask the grid to autogenerate sensible columns based upon the objects you give it.</p>
<p>I wouldn't recommend trying to stuff normal controls into the datagrid per se, there is a grid column framework based on cells, columns and editingcontrols that deals with this stuff. Have a little searchy on Google based on those kind of words (e.g DataBinding/DataGridViewEditingControl), i'm afraid I don't have my DataGridView resources to hand right now.</p>
<hr>
<p>Oh wait, sorry I re-read. You'll want to look at the BindingContext object. </p>
| 32,437
|
<p>Does C# have the notion of private / protected inheritance, and if not, why?</p>
<p><strong>C++</strong></p>
<pre>
<code>
class Foo : private Bar {
public:
...
};
</code>
</pre>
<p><strong>C#</strong></p>
<pre>
<code>
public abstract NServlet class : private System.Web.UI.Page
{
// error "type expected"
}
</code>
</pre>
<p>I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.</p>
|
<p>C# allows public inheritance only. C++ allowed all three kinds. Public inheritance implied an "IS-A" type of relationship, and private inheritance implied a "Is-Implemented-In-Terms-Of" kind of relationship. Since layering (or composition) accomplished this in an arguably simpler fashion, private inheritance was only used when absolutely required by protected members or virtual functions required it - according to Scott Meyers in Effective C++, Item 42. </p>
<p>My guess would be that the authors of C# did not feel this additional method of implementing one class in terms of another was necessary.</p>
|
<p>No it doesn't. What would the benefit be of allowing this type of restriction?</p>
| 5,312
|
<p>If I were to include .Net Framework setup file along with my apps (installation process is done by our own technician), to be install on a clean Windows (XP SP2/SP3 or Vista SP1) without prior installation of any framework, which of the .Net Framework setup do I need to install in sequence, to get to 3.5 SP1?
Currently I have the setup file for:</p>
<ol>
<li>.Net 2.0</li>
<li>.Net 2.0 SP1</li>
<li>.Net 3.0</li>
<li>.Net 3.5</li>
<li>.Net 3.5 SP1</li>
</ol>
<p>All redistributable version.</p>
<p>EDIT : I need the full installation, client profile won't work as our client's machine might not have internet access. Basically I need a install-and-forget-it procedure, so when we decided to use anything new within 3.5 SP1 later, we can rest assure that we can just simple apply update our apps without having to install another pre-requisite </p>
|
<p>The .Net Framework 3.5 SP1 redistributable (the one that's around 230MB) contains everything (2.0 + SP1 + SP2, 3.0 + SP1 + SP2, 3.5 + SP1) in all supported architectures (x86, x64, ia64). <strong>This is the only download you need.</strong></p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=AB99342F-5D1A-413D-8319-81DA479AB0D7&displaylang=en" rel="nofollow noreferrer">Download from here</a> (click on <a href="http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe" rel="nofollow noreferrer">.NET Framework 3.5 Service Pack 1 (Full Package)</a>):</p>
<p>And then, you might want to install <a href="http://go.microsoft.com/fwlink/?LinkId=136730" rel="nofollow noreferrer">these updates</a>:</p>
<blockquote>
<p>IMPORTANT: After installing the .NET Framework 3.5 SP1 package (either the bootstrapper or the full package) you should immediately install the update <a href="http://go.microsoft.com/fwlink/?LinkId=136730" rel="nofollow noreferrer">KB959209</a> to address a set of known application compatibility issues.</p>
</blockquote>
<p>There are 3 updates (for 2.0, 3.0, and 3.5) for 2 OS "groups" (XP/2003 or Vista/2008) for 3 architectures (x86, x64, or ia64), for a total of... 16 downloads! (I know, 3 * 2 * 3 = 18, but Server 2003 ia64 only supports up to 2.0). You need to install the 3 updates in order. Or you could run Windows Update after installing 3.5 SP1 and let it figure it out.</p>
<hr>
<p>EDIT: To be clear, .Net 3.5 requires that 2.0 and 3.0 be installed and updated to SP1 level. .Net 3.5 SP1 requires that 2.0/3.0 be updated to SP2 level. But the 3.5(SP1) installers will do this automatically. That is, by installing 3.5 SP1, you don't need to worry about installing and updating 2.0 and 3.0 to SP1 or SP2. <strong>Just install 3.5 SP1 and you're done!</strong> (and the extra updates, 3.5 SP1.1?)</p>
<p>About the Client Profile, it can only be installed on x86 client machines that don't have ANY version of .Net installed, so it won't install on Vista (it already comes with .Net 3.0), any Windows Server version, nor any x64/ia64 OS. You can only install it on a Windows XP SP2+ (x86) that doesn't have any version of .Net installed, otherwise a full installation is done. The offline Client Profile installer is 255MB because it will try to do a client install first, if it can't it will fallback to a full install. Personally, I would just do a full install anyway.</p>
|
<p>NET 3.5 SP1 introduces a new setup package option for developers building .NET client applications called the "<a href="http://weblogs.asp.net/scottgu/archive/2008/05/12/visual-studio-2008-and-net-framework-3-5-service-pack-1-beta.aspx" rel="nofollow noreferrer">.NET Framework Client Profile</a>".This provides a new setup installer that enables a smaller, faster, and simpler installation experience for .NET client applications on machines that do not already have the .NET Framework installed.</p>
<p>The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios. For example: it includes Windows Forms, WPF, and WCF. It does not include ASP.NET and those libraries and components used primarily for server scenarios. We expect this setup package to be about <strong>26MB</strong> in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package.</p>
| 30,509
|
<p>EDIT, 2020/09: If anyone is wondering, 12 years later, yes, we've all moved to JSON and Kubernetes by now. Original text follows.</p>
<p>Obviously, there is no one single solution that would satisfy everyone's needs; an architecture is always a trade-off. I want to create a framework, originally aimed at RAD of web games. Target language is PHP, although the architecture should be widely applicable.</p>
<p>Goals that I have in head for this framework are: flexibility in ways you can achieve the result; maximal comfort for developers; connecting modules like LEGO® blocks; many types of input, many types of output, one format for processing.</p>
<p>The goals that are not a priority are speed, enterprise use and making money. It's supposed to be an open source project.</p>
<p>The cornerstone of this design is that all content, before transformation, is processed in XML (idea based on EAI system I've worked with, eGate). The data abstraction layer - hopefully some smart ORM - is not important now. The output will be generated using XSLT or any other custom modules, for virtually any client - HTML for old browsers, XHTML/HTML5 for modern browsers, simple HTML for mobile clients, XML for AJAX/XMLRPC, etc.</p>
<p>Main reasons for using XML are:</p>
<ul><li>it's a well-known standard</li>
<li>existing tools like XPath, SimpleXML and DOM for navigating and modifying the content</li>
<li>XSLT providing a powerful and unified way to transform the code into any tag soup</li>
<li>I find the XML markup very easily readable, therefore I don't think that advantages of JSON or YAML make a difference here</li>
<li>The content can be stacked easily, and it the order of the content doesn't really matter as long as it's transformed correctly with XSLT</li>
</ul>
<p>The page generation process would consist of these phases:</p>
<ol><li>Pre-processing: initializing modules, processing GPCS data, applying default [XML] templates</li>
<li>Processing/generation: main part of business logic, generating the bloated XML with maximum data (although hopefully optimized not to generate balast)</li>
<li>Processing: some additional business logic, e.g. cutting down some of the markup, preparing for transformation, reporting, statistics, etc.</li>
<li>Post-processing: parsing XML through the transformation engine (most probably just XSLT), output.</li>
</ol>
<p>The content would be generated with a lot of meta-data (e.g. tags, permissions, importance, necessity, aimed output type), which would be stripped down during post-processing.</p>
<p>So, my question is: except for speed, what is the downfall of this solution? Where it could go wrong both during the development/maintenance of the framework, and its applications? What are the downsides of this architecture?</p>
|
<p>XSLT can be bulky to manage, and essentially adds an extra programming language that developers would have to work in (at least if I understand your description correctly). My experience has been that relatively few people know it, and even fewer can make it do what they want.</p>
|
<p>I've worked on a few web games in the past and, to be honest, none of them have ever needed anything this complex and unwieldy.</p>
| 22,618
|
<p>In ruby, is there a way to "undefine" a variable or constant once it's been defined?</p>
<p>In our rails environemnts, we define one of three contants to be <code>true</code>, depending on the environment: <code>TESTING</code>, <code>DEVELOPMENT</code>, or <code>PRODUCTION</code>. Then, in controller code, we use <code>defined?</code> to see if what environment we're in, ie: <code>defined? PRODUCTION</code>.</p>
<p>Now, I want to unit test some of that environment-specific behavior. My initial attempt was to just set the appropriate constant in my test, and then reset them in teardown. However, I can't figure out how to reset <code>DEVELOPMENT</code> and <code>PRODUCTION</code> such that <code>defined?</code> returns false.</p>
<p>Obviously, a solution would be to just check to see if the appropriate constant is also true in addition to checking if it's defined, but this will result in having to touch a fair amount of existing code.</p>
<p>EDIT: I realize this is definitely NOT the right way to do things. Alas, changing it is a nontrivial task, so I'm looking for an easy way to just unit test what's there now. Plus, I'm also just curious about the lower level language question of whether it's possible to undefine a variable/constant.</p>
|
<p>I found <a href="http://www.ruby-forum.com/topic/2530" rel="noreferrer">this answer</a> </p>
<pre><code>Object.send(:remove_const, "TESTING")
</code></pre>
<p>If I remember correctly, using <code>send</code> here is kind of a hack, because remove_const is really a private method. You want to ask yourself why you need to define constants PRODUCTION, DEVELOPMENT and TESTING at the same time while they really are mutually exclusive ; that's why I upvoted grepsedawk's answer.</p>
|
<p>Instead of checking each constant, why not do something like:</p>
<pre><code>environment = :TESTING
if(environment == :TESTING)
</code></pre>
| 44,045
|
<p>I'd like to show a div that has a background-color with the height and width set to 100% but no content. Is it possible to do that without putting a &nbsp; inside?</p>
<p>Edit: Thanks to Mark Biek for pointing out that empty div with width and height styles shows how I'd expect. My div is in a table cell, where it does not show.</p>
<pre><code><table style="width:100%">
<tr>
<th>Header</th>
<td><div id="foo"></div></td>
</tr>
</table>
</code></pre>
|
<p>This seems to work in Firefox, Safari, IE6, & IE7.</p>
<pre><code><html>
<head>
<style>
#foo{
background: #ff0000;
width: 100%;
height: 100%;
border: 2px dashed black;
}
</style>
</head>
<body onload="">
<div id="foo"></div>
</body>
</html>
</code></pre>
<p><a href="http://farm4.static.flickr.com/3008/2938703792_886e488f68_o.png" rel="nofollow noreferrer"><img src="https://farm4.static.flickr.com/3008/2938703792_f4602930fb_m.jpg" alt="3 Browser example" /></a></p>
|
<p>You should include <code>&nbsp;</code> at all times.</p>
| 24,118
|
<p>This should be easy for many of you, but for me it's just another bit of rust needing to be chipped away as I get back into basic Java coding. Using bloody associative arrays for so long in other languages have turned me nice and spoiled. :P</p>
<p>My problem is simple: I'm storing a set of objects, each containing a string and a number, in a list. I would like each object inserted into this list to be sorted alphabetically by its string. I would also like to be able to retrieve objects from the list by their string as well. I would like to do this as formally and/or efficiently as possible.</p>
<p>Is there something already available in the Java standard libraries for this?</p>
|
<p>there is a great <a href="http://java.sun.com/docs/books/tutorial/collections/index.html" rel="nofollow noreferrer">writeup on java collections</a> which covers most of your needs.</p>
<p>short advice concerning this: use a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeMap.html" rel="nofollow noreferrer">TreeMap</a>(Comparator c) with a custom Comparator.
key ist the string, value is the composite object with string and number</p>
|
<p>I have done something similar to that, I used ArrayList to store them objects and write comparators for sorting the arraylist.</p>
| 43,779
|
<p>We are using Subversion. We would like to </p>
<pre><code>1. search across all commit messages ?
2. monitor the commits on certain important files ?
3. identify files that are never/rarely used ?
4. identify files that are most frequently changed ?
5. identify files that most developers have accessed ?
6. identify files that have been committed together many number of times ?
</code></pre>
<p>The usage of these data could be to weed out messages like <a href="https://stackoverflow.com/questions/216876/what-is-the-best-commit-message-you-have-ever-encountered#255762">these</a>, to refactor code and clean up the project of unused files. </p>
<p>Please suggest tools to achieve the same.. </p>
<p><b>EDIT:</b> We run SVN on Windows 2003.</p>
|
<p><a href="http://www.statsvn.org/" rel="nofollow noreferrer" title="StatSVN">StatSVN</a> should be able to do the majority of that for you. You'll need to set up a scheduled task to run it over your repository, however, or you can integrate it into an Ant build if you happen to use that. </p>
<p>Some of the more complex tasks, such as number 6 in your list, will probably require a custom solution, however. Alternatively, as StatSVN is open source, you could make the required changes to that and submit them back to the project. </p>
|
<p>What platform are you using? On linux, a quick shell script using <code>sed</code> should do the trick.</p>
| 32,031
|
<p>How do I detect what browser (IE, Firefox, Opera) the user is accessing my site with? Examples in Javascript, PHP, ASP, Python, JSP, and any others you can think of would be helpful. Is there a language agnostic way to get this information?</p>
|
<p>If it's for handling the request, look at the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43" rel="noreferrer">User-Agent</a> header on the incoming request.</p>
<p>UPDATE: If it's for reporting, configure your web server to log the User-Agent in the access logs, then run a log analysis tool, e.g., <a href="http://awstats.sourceforge.net/" rel="noreferrer">AWStats</a>.</p>
<p>UPDATE 2: FYI, it's <em>usually</em> (not always, usually) a bad idea to change the way you're handling a request based on the User-Agent.</p>
|
<p>It may be dependent of your setting. With apache on linux, its written in the access log /var/log/apache2/access_log</p>
| 14,753
|
<p>I'm having an issue where prints with narrow tolerance come out fused. This makes it pretty much impossible to print anything with narrow parts. It seems to be mostly (maybe only) an issue in the bottom skin layers. Once it gets through those, the rest of the print goes smoothly and tight tolerances are not a problem.</p>
<p>Here's an example where I've tried to print some hinges:</p>
<p><a href="https://i.stack.imgur.com/NrtaB.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/NrtaB.jpg" alt="First three layers" /></a></p>
<p>It's a test print where each hinge has a different tolerance, so the left and right are expected to look different. Below each real image is a preview layer from Cura showing how it's supposed to look.</p>
<p>The first layer appears OK. The second layer looks a little messy, and the gap between inner and outer circles has shrunk. By the third layer the hinge on the right is completely fused.</p>
<p>The printer is an Ender 3 Pro with a glass bed (flat glass, no special surface), BLTouch, and Marlin 1.1.9. The slicer is Cura 4.6.1, and for this test print I used the default for "Super Quality - 0.12 mm" at 200 °C and 60 °C bed with no changes. The filament is Mika3D PLA.</p>
<p>Some things I've tried to fix this:</p>
<ul>
<li>Calibrated e-steps (currently set at 95.88) - no noticeable difference</li>
<li>Calibrated flow rate (got 97.859 % but returned to 100 % for this test) - no noticeable difference</li>
<li>Varying temperatures from 190 to 230 °C by 5 °C increments - no improvement from 200 °C</li>
<li>Set "Initial Layer Horizontal Expansion" to -0.1 mm, -0.4 mm, and -1.0 mm in Cura. - no improvement.</li>
<li>Set "Initial Layer Flow" to 90 %. - no improvement.</li>
<li>Obsessively leveled and re-leveled the bed. - no improvement.</li>
<li>Moved the Z-offset up and down to get more or less squish on the first layer - no improvement.</li>
<li>Tried various brands and colors of PLA - problem is consistent.</li>
<li>Reduced build plate temperature to 45 °C after initial layer - no improvement.</li>
</ul>
<p>What else is there to check?</p>
<p><strong>Edit 2020-06-26:</strong></p>
<p>At <code>R.. GitHub STOP HELPING ICE</code>'s suggestion I returned the e-steps to default (93), re-leveled the bed, and adjusted the z-offset tighter. I made 10 attempts with varying z-offsets, and here's the best one:</p>
<p><a href="https://i.stack.imgur.com/bRrSW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/bRrSW.jpg" alt="First three layers with e-steps at 93" /></a></p>
<p>The first layer looks better! But the second and third layers are just as bad as before, in fact maybe worse. The circle on the right completely fused on only the second layer. And the top surface is just as ripple-ey and messed up as before.</p>
<p>Here's a closeup of the fourth layer to show how bad it is:
<a href="https://i.stack.imgur.com/Z7MvW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Z7MvW.jpg" alt="Fourth layer" /></a></p>
<p>So although the re-calibrated e-steps may have been <em>a</em> problem, that clearly wasn't the only problem. What else should I be looking at here?</p>
<p><strong>Edit 2020-06-27:</strong></p>
<p>At <code>Davo</code>'s suggestion I double-checked all my slicer settings. Flow is set to 100% everywhere, wall thickness is 0.8 mm for two walls (so 0.4 mm each), and nozzle diameter is correct at 0.4 mm.</p>
<p>At <code>R.. GitHub STOP HELPING ICE</code>s suggestion I double-checked my filament diameter. It is set to 1.75 mm. On the actual filament, my digital caliper measures 1.74 to 1.76, within the expected tolerance. So that doesn't appear to be the issue.</p>
<p>At <code>0scar♦</code>s suggestion I tried a print with 0.2 mm layer height. Here's the first layer:
<a href="https://i.stack.imgur.com/sFOUo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/sFOUo.jpg" alt="0.2 mm layer height, first layer" /></a>
Looks like the same over-extrusion.</p>
<p>Then I tried reducing the flow multiplier to 90% (for both "flow" and "initial layer flow") and printing at 0.2 mm layer height:
<a href="https://i.stack.imgur.com/8oloh.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8oloh.jpg" alt="90% flow with 0.2 mm layer height" /></a>
Better, but it <em>still</em> looks over-extruded!</p>
<p>I don't know what else to try.</p>
|
<p>I think this is resolved. After looking at every conceivable source of over-extrusion and coming up negative, <code>R.. GitHub STOP HELPING ICE</code> suggested that it might be a mechanical problem in Z axis movement, like in <a href="https://3dprinting.stackexchange.com/questions/8022/first-3-mm-prints-poorly-then-fine-after-that">this question</a>.</p>
<p>I checked by leveling the bed and zeroing the Z axis at 0.05 mm above the bed, using a feeler gauge. I gave it the instruction to move the Z axis up by 0.2 mm (to simulate a single layer), then checked it with a 0.25 mm feeler gauge. It did not fit. I raised it .01 mm at a time, and I was not able to insert the gauge until it hit 0.5 mm!</p>
<p>I printed a 20 mm test cube and measured the Z height:
<a href="https://i.stack.imgur.com/4Lvq2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/4Lvq2.jpg" alt="Initial 20 mm test cube" /></a></p>
<p>At 19.58 mm, it was short. Only a little bit though, which is consistent with Z problems only occurring in the first few layers for some reason.</p>
<p>Based on the advice in the other question, I fiddled with the eccentric nuts on the left and right side of X axis gantry, adjusting them to be tight enough that turning the wheels moves the gantry up and down, but loose enough that I can still turn the wheels if I hold the gantry in place.</p>
<p>I checked again with the feeler gauge, and this time the 0.25 mm gauge fit just fine at 0.2 mm. Cool! I printed another test cube and measured:</p>
<p><a href="https://i.stack.imgur.com/Yq2zW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Yq2zW.jpg" alt="Revised 20 mm test cube" /></a></p>
<p>OK, at 20.06 mm it's not perfect, but it's a lot better. I printed the hinges again:</p>
<p><a href="https://i.stack.imgur.com/Q4MYZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Q4MYZ.jpg" alt="Hinges" /></a></p>
<p>Again not perfect, but so much better. And the specific problem of uncontrollable expansion in the 2nd and 3rd layers is totally gone.</p>
|
<p>I had the same problem with my Ender-3 V2.</p>
<p>You need to check if the feeder bracket is square like explained in <a href="https://www.youtube.com/watch?v=xnzNd_FIMKY" rel="nofollow noreferrer">this YouTube</a></p>
<p>If that is not the problem maybe you need a custom bracket to change the spacing between the Z-motor and the frame like <a href="https://www.thingiverse.com/thing:2752080" rel="nofollow noreferrer">this</a>, <a href="https://www.thingiverse.com/thing:4699747" rel="nofollow noreferrer">this</a> or <a href="https://www.thingiverse.com/thing:4723087" rel="nofollow noreferrer">this</a></p>
<p>I have improved mine a lot using:</p>
<ul>
<li><a href="https://www.thingiverse.com/thing:2752080" rel="nofollow noreferrer">This Z-motor mount</a></li>
<li>Using <a href="https://www.amazon.com/s?k=Elmer%E2%80%99s+Disappearing+Purple+Glue+Stick" rel="nofollow noreferrer">glue stick</a> instead of squeezing the first layer</li>
<li><a href="https://www.youtube.com/watch?v=rDm9OziZ6dY" rel="nofollow noreferrer">Leveling the bed using a feeler gauge</a> instead of a piece of paper</li>
<li>Initial fan speed 100 %, all layers the same</li>
<li>Same flow rate, line width, line height on all layers</li>
<li>Build plate 40 °C, nozzle 205 °C</li>
<li>Seam Corner Preference: Hide or Expose Seam</li>
</ul>
| 1,694
|
<p>i search a good tutorial to learn how to use entity framework in the right manner. in particular with asp.net mvc.</p>
|
<p>I'd point you in the direction of this rather <a href="http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx" rel="nofollow noreferrer">(1) lengthy article</a> from the Entity Framework team. </p>
<p>They've done a pretty good job of explaining both the shortcomings of the initial version (v1.0) and also give plenty of ideas into what they are considering for the next version.</p>
<p>FWIW, I've done a tiny bit of ASP MVC and I'm not sure you're going to like mixing the two. </p>
<p>For the (v1.0) version of the Entity Framework you really need to either do one of two things - work with "disconnected" entity sets or retail the data context of an entity set. Either scenario has pitfalls as I'm sure you can appreciate. In short.. I don't think there is a "right manner" to pick up at this stage. At least not with ASP MVC.</p>
<p>To get started with the Entity Framework, your bet would be to take a look at the official ADO EF samples located <a href="http://code.msdn.microsoft.com/adonetefx" rel="nofollow noreferrer">(2) here.</a> The easiest to pick up and start learning with, IMHO, are the WinForms based examples, but there are a few ASP.net examples which nmight be helpful.</p>
<p>(1) [<a href="http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx]" rel="nofollow noreferrer">http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx]</a>
<br/>(2) [<a href="http://code.msdn.microsoft.com/adonetefx]" rel="nofollow noreferrer">http://code.msdn.microsoft.com/adonetefx]</a></p>
|
<p>We're currently working on an EF 4.0 Reference Implementation using ASP.NET MVC at the front end. Check it out <a href="http://dataguidance.codeplex.com/" rel="nofollow noreferrer">here</a> - We'd love to hear your feedback.</p>
| 44,195
|
<p>I have a requirement of reading subject, sender address and message body of new message in my Outlook inbox from a C# program. But I am getting security alert 'A Program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this'.</p>
<p>By some googling I found few third party COM libraries to avoid this. But I am looking for a solution which don't require any third party COM library.</p>
|
<p>Sorry, I have had that annoying issue in both Outlook 2003 and Outlook 2007 add-ins, and the only solution that worked was to purchase a <a href="http://www.dimastr.com/redemption/" rel="noreferrer">Redemption</a> license. In Outlook 2007 that pesky popup should only show up if your firewall is down or your anti-virus software is outdated as far as I recall.</p>
|
<p>You can disable the security pop-up using Outlook's Trust Center.
Check <a href="http://msdn.microsoft.com/en-us/library/bb226709.aspx" rel="nofollow noreferrer">here</a>.</p>
| 29,112
|
<p>I have not developed web services applications that publicly faced the Internet. As I begin to consider the issues of exposing schema definitions to a wide audience, I believe a certain amount of consideration should be spent on properly formatting the schema namespaces.</p>
<p>Has anybody come across a guideline document that advises how to go about standardising the namespace format for an organisation's XML schemas?</p>
<p>things like using FQDNs vs paths <a href="http://schemas.organisation.com/" rel="nofollow noreferrer">http://schemas.organisation.com/</a> vs <a href="http://organisation.com/schemas" rel="nofollow noreferrer">http://organisation.com/schemas</a></p>
<p>styles to include version paths <a href="http://organisation.com/schemas/submissions/2006" rel="nofollow noreferrer">http://organisation.com/schemas/submissions/2006</a> or <a href="http://organisation.com/schemas/submissions/v1" rel="nofollow noreferrer">http://organisation.com/schemas/submissions/v1</a></p>
<p>organisation by date or subject matter <a href="http://organisation.com/schemas/2006/submissions/" rel="nofollow noreferrer">http://organisation.com/schemas/2006/submissions/</a> vs <a href="http://organisation.com/schemas/submissions/2006" rel="nofollow noreferrer">http://organisation.com/schemas/submissions/2006</a></p>
<p>etcetera</p>
<p>12 jan 2010 UPDATE:
on revisiting this issue once again i feel it should just be wiki since there cannot be a right answer on this, if ever there are actually any written papers.</p>
|
<p>I like using separate domains, but there could be no site there now, or just xml schemas and later on could be a combination of docs and schemas. You probably should NOT include any part of the organisation's structure in either the domain name or URL path, those things change, so try to design it for the longer term.</p>
<p>Finally there is the inevitable versioning question for which dates (yyyy, yyyy-mm, yyyy-mm-dd) or vN are both fine. You should consider whether you want to have a 'symbolic' url for the latest version, and specific dates for particular releases. You can use HTTP redirects from the latest to the particular so that clients can tell what you are doing.</p>
|
<p>The closest thing i have read that mentions about how a namespaced ought to be style is this article</p>
<p><a href="http://www.builderau.com.au/strategy/architecture/soa/Good-schema-management-helps-to-maintain-XML-namespace/0,339028264,320273067,00.htm" rel="nofollow noreferrer">http://www.builderau.com.au/strategy/architecture/soa/Good-schema-management-helps-to-maintain-XML-namespace/0,339028264,320273067,00.htm</a></p>
<p>but it does not hit right on the actual topic per se, merely point out factors that indicate why proper namespacing is important.</p>
| 30,966
|
<p>Are there any decent tutorials for setting up F# in Visual Studio 2005? Everything I have found points at VS2008.</p>
<p>ie: 'F# projects' under projects, etc.</p>
|
<p>Unfortunately the CTP release of F# doesn't support VS 2005. Two options:</p>
<ol>
<li>Use 1.9.4.19, the most recent pre-CTP release</li>
<li>Download the free <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=40646580-97FA-4698-B65F-620D4B4B1ED7&displaylang=en" rel="nofollow noreferrer">VS2008</a> shell and use that instead (I haven't tried it, but apparently it <a href="http://fsharpnews.blogspot.com/2007/12/f-in-visual-studio-for-free.html" rel="nofollow noreferrer">works</a>)</li>
</ol>
|
<p><a href="http://research.microsoft.com/fsharp/manual/install.aspx" rel="nofollow noreferrer">Installing F# Editing for Microsoft Visual Studio 2005</a></p>
<p>That page also links to <a href="http://blogs.msdn.com/dsyme/" rel="nofollow noreferrer">Don Syme's F# blog</a>, which has a lot of useful stuff on working with F# in VS, including a demo of <a href="http://blogs.msdn.com/dsyme/archive/2005/01/29/362865.aspx" rel="nofollow noreferrer">F# intellisense in VS2005</a>.</p>
| 14,680
|
<p>I have a web site running via IIS7 on Vista. The site is running on port 88, so <a href="http://localhost:88" rel="noreferrer">http://localhost:88</a> should render the default /Home/Index view. </p>
<p>This works correctly, as do all other views. </p>
<p>However, one problem is resident. My script paths point to /Scripts/[FILE] and my CSS paths point to /Content/[FILE]. My assumption was that the /Content or /Scripts folder would always be at the root of the site as I have no intention to run this site in a virtual directory setting. Whenever the pages render, they have NO CSS or script! So everything looks wonky and the scripting obviously doesn't work, hence a lot of the views don't work either. </p>
<p>This is a very odd problem, one that I'm sure is a result of my lack of knowledge hosting things under IIS7. I'd appreciate any help anyone could offer. Thanks a lot!</p>
|
<p>I hope the continuation of this thread conveys a willingness to make sure this problem doesn't drive anyone off the cliff. There's a lot of documentation in various forums about solving this issue on Vista but I couldn't find any likewise articles for 2K8. As indicated in this <a href="http://forums.iis.net/p/1143592/1849083.aspx#1849083" rel="nofollow noreferrer">forum post</a> I was able to fix the issue on a Vista machine. Alas, a like execution failed to resolve the matter on 2K8. </p>
<p>I had verified that the StaticFileHandler had been included in the web.config <a href="http://www.apijunkie.com/APIJunkie/blog/post/2007/11/Breaking-changes-in-ASPNet-20-HTTP-Handlers-when-moving-from-IIS5-on-Windows-2000-to-IIS6-on-Windows-2003.aspx" rel="nofollow noreferrer">as suggested in this blog post at apijunkie.com</a>. Still, no luck. </p>
<p>Clarifying <em>no luck, here</em> - My server-side functionality was perfect. All MVC routes work like a champ. Just all CSS and JS rendering failed. When browser pointed directly at CSS or JS files resulting page was an ASP.NET 404 and not the <em>traditional</em> 404 error page. </p>
<p>So I went into the IIS7 Manager and into the Handler Mappings dialog. I added a new handler that specified the System.Web.StaticFileHandler type and gave it an extension of *.CSS. Then I repeated that for *.JS, *.PNG, and *.GIF files. When I refreshed the site in the browser, everything rendered perectly. The screen shots below demonstrate this process. </p>
<p>The Handler Mappings Window: </p>
<p><a href="https://i.stack.imgur.com/NYXjk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NYXjk.png" alt="handler mappings"></a><br>
<sub>(source: <a href="https://bradygstorage.blob.core.windows.net/images/managed-handler.png" rel="nofollow noreferrer">windows.net</a>)</sub> </p>
<p>Adding a new Managed Handler</p>
<p><a href="https://i.stack.imgur.com/5JJ8b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5JJ8b.png" alt="alt text"></a><br>
<sub>(source: <a href="https://bradygstorage.blob.core.windows.net/images/add-managed-handler.png" rel="nofollow noreferrer">windows.net</a>)</sub> </p>
<p>This resolved the problem, and now I have a perfectly functioning MVC app hosted in W2K. Time for a Guinness. </p>
|
<p>The problem not lies precisely in the authorization/authentication but in the modules that now manages the IIS.
Inside system.webServer you should have <strong>runAllManagedModulesForAllRequests</strong> set to <strong>false</strong> so you can display all images/css without problems with authentication.</p>
<p>In ASP.NET websites, the value of <strong>runAllManagedModulesForAllRequests</strong> previously had to be set to true to support routing. However, once <strong>IIS 7 has been updated with a Service Pack</strong>, the value of <strong>runAllManagedModulesForAllRequests</strong> can be set to <strong>false</strong> or omitted when working with ASP.NET routing.</p>
<p>Ref. <a href="http://www.iis.net/configreference/system.webserver/modules" rel="nofollow">http://www.iis.net/configreference/system.webserver/modules</a></p>
<p>P.S. Don't forget to add the following lines to the AppSettings section of my web.config file:</p>
<p>< add key="autoFormsAuthentication" value="false" /></p>
<p>< add key="enableSimpleMembership" value="false"/></p>
| 46,076
|
<p>Can somebody give some clear explanation of the meaning of the SIZE and RSS values we get from prstat in Solaris?</p>
<p>I wrote a testing C++ application that allocates memory with <code>new[]</code>, fills it and frees it with <code>delete[]</code>.</p>
<p>As I understood, the SIZE value should be related to how much virtual memory has been "reserved" by the process, that is memory "malloced" or "newed".</p>
<p>That memory doesn't sum up in the RSS value unless I really use it (filling with some values). But then even if I free the memory, the RSS doesn't drop.</p>
<p>I don't understand what semantic I can correctly assign to those 2 values.</p>
|
<p>RSS is (AFAIK reliably) representing how much physical memory a process is using. Using Solaris default memory allocator, freeing memory doesn't do anything about RSS as it just changes some pointers and values to tell that memory is free to be reused.
If you don't use again that memory by allocating it again, it will eventually be paginated out and the RSS will drop.</p>
<p>If you want freed memory to be returned immediately after a free, you can use the Solaris mmap allocator like this:</p>
<pre><code>export LD_PRELOAD=libumem.so
export UMEM_OPTIONS=backend=mmap
</code></pre>
|
<p>As a general rule once memory is allocated to a process it will never be given back to the operating system. On Unix systems the sbrk() call is used to extend the processes address space, and there is not analogous call to go in the other direction.</p>
| 45,068
|
<p>I need to validate an XML agaist a schema. </p>
<p>I tried XML::SAX::ParserFactory; XML::Validator::Schema and related modules but looks like they are limited.<br>
Limited in the sense that it didn't recognize schema elements such as xsd:unique, xsd:group, xsd:keyref, xsd:union and xsd:key. </p>
<p>Are these xsd:unique, etc. new additions?</p>
<p>Appreciate if you can point me to some Perl modules which are upto date and upto the task.</p>
<p>Thanks in advance.</p>
|
<p>Have you tried validating it with xmllint?</p>
|
<p>@Thushan
Is it absolutely necessary for you to use Perl? If not, why not give a try to <strong>XMLSTARLET</strong>? It's a quite nice toolkit for manipulating XMLs in a terminal!</p>
<p>It supports not just legacy DTDs and the XSD as you need, also it supports Relax-NG schemas. Check it's documentation to learn how to <a href="http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#d0e520" rel="nofollow">Validate XML Documents with xmlstarlet</a>
I hope this helps you ;)</p>
<p>Have a good day!</p>
<p>PD Oh I see you used xmllint! It's great too, but I prefer xmlstarlet =) Give it a try ;)</p>
| 41,692
|
<p>In a project I am working on, Apache is set up to only forward requests that come in as /prefix/* to mongrel. How can I tell ruby on rails to generate all URLs with that prefix? </p>
<p>I have the routes set up for forward to the correct controller action by doing this:</p>
<pre><code>map.connect 'sfc/:controller/:action'
</code></pre>
<p>but that doesn't seem to affect the way that the url writer generates the URLs.</p>
<p>Any ideas?</p>
|
<p>The <code>RAILS_RELATIVE_URL_ROOT</code> environment variable should do the trick, though I haven't tried it myself.</p>
|
<p>What about using the :path_prefix option:</p>
<pre><code>map.connect ':controller/:action', :path_prefix => 'sfc'
</code></pre>
| 28,637
|
<p>I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.</p>
<p>Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?</p>
|
<p>The problem was DBNull, doing:</p>
<pre><code>command.Parameters.AddWithValue("@parameter", null);
</code></pre>
<p>compiles OK.</p>
|
<p>It's not clear what conditions you're talking about. If you want to set column to default value, you can use <a href="http://msdn.microsoft.com/en-us/library/system.dbnull.value.aspx" rel="nofollow noreferrer">DbNull.Value</a>;</p>
<pre><code>command.AddWithValue("@param", DbNull.Value);
or
command.Parameters.Add("@param", <data type>).Value = DBNull.Value;
</code></pre>
| 7,424
|
<p>I've made a Django site, but I've drank the Koolaid and I want to make an <em>IPhone</em> version. After putting much thought into I've come up with two options:</p>
<ol>
<li>Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework.</li>
<li>Find some time of middleware that reads the user-agent, and changes the template directories dynamically.</li>
</ol>
<p>I'd really prefer option #2, however; I have some reservations, mainly because the Django documentation <a href="http://docs.djangoproject.com/en/dev/topics/settings/" rel="noreferrer">discourages changing settings on the fly</a>. I found a <a href="http://www.djangosnippets.org/snippets/1098/" rel="noreferrer">snippet</a> that would do the what I'd like. My main issue is having it as seamless as possible, I'd like it to be automagic and transparent to the user.</p>
<p>Has anyone else come across the same issue? Would anyone care to share about how they've tackled making IPhone versions of Django sites?</p>
<p><strong>Update</strong></p>
<p>I went with a combination of middleware and tweaking the template call.</p>
<p>For the middleware, I used <a href="http://code.google.com/p/minidetector/" rel="noreferrer">minidetector</a>. I like it because it detects a <a href="http://www.youtube.com/watch?v=b6E682C7Jj4" rel="noreferrer">plethora</a> of mobile user-agents. All I have to do is check request.mobile in my views.</p>
<p>For the template call tweak:</p>
<pre><code> def check_mobile(request, template_name):
if request.mobile:
return 'mobile-%s'%template_name
return template_name
</code></pre>
<p>I use this for any view that I know I have both versions.</p>
<p><strong>TODO:</strong></p>
<ul>
<li>Figure out how to access <em>request.mobile</em> in an extended version of render_to_response so I don't have to use check_mobile('template_name.html')</li>
<li>Using the previous automagically fallback to the regular template if no mobile version exists.</li>
</ul>
|
<p>Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standard html version if they are using an iphone. </p>
|
<p>A simple solution is to create a wrapper around <code>django.shortcuts.render</code>. I put mine in a <code>utils</code> library in the root of my application. The wrapper works by automatically rendering templates in either a "mobile" or "desktop" folder.</p>
<p>In <code>utils.shortcuts</code>:</p>
<blockquote>
<pre><code>from django.shortcuts import render
from user_agents import parse
def my_render(request, *args, **kwargs):
"""
An extension of django.shortcuts.render.
Appends 'mobile/' or 'desktop/' to a given template location
to render the appropriate template for mobile or desktop
depends on user_agents python library
https://github.com/selwin/python-user-agents
"""
template_location = args[0]
args_list = list(args)
ua_string = request.META['HTTP_USER_AGENT']
user_agent = parse(ua_string)
if user_agent.is_mobile:
args_list[0] = 'mobile/' + template_location
args = tuple(args_list)
return render(request, *args, **kwargs)
else:
args_list[0] = 'desktop/' + template_location
args = tuple(args_list)
return render(request, *args, **kwargs)
</code></pre>
</blockquote>
<p>In <code>view</code>:</p>
<blockquote>
<pre><code>from utils.shortcuts import my_render
def home(request): return my_render(request, 'home.html')
</code></pre>
</blockquote>
| 19,882
|
<p>I'm attempting to register an anonymous function when a user clicks a cell in an HTML table. Here's some of the raw, unadulterated code:</p>
<pre><code>document.getElementById(
"course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick =
eval("function() {PrintReceipt("+result.years[result_year_index].rul_code+");};");
</code></pre>
<p>Note the use of <code>eval</code>, since this sits in a loop and the anonymous function is different each time round.</p>
<p>Suffice to say, this works absolutely fine in Firefox 2. But, Firefox 3 throws a 'Syntax Error', pointing inside the brackets after the word 'function'.</p>
<p>Does anybody have any smart ideas on how I can fix this?</p>
<hr>
<p>Just to make it crystal clear what I'm attempting to do, here's a much simplified example:</p>
<pre><code>for (index=0; index<4; index++) {
document.getElementById("div"+index).onclick =
eval("function () {Foo(index);};");
}
</code></pre>
<p>In other words, I wish to trigger the same function with a different parameter value for each <code>div</code>.</p>
|
<p>Have you tried something like this?</p>
<pre><code>document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) =
function (nr)
{
return function () { PrintReceipt(nr) }
} (result.years[result_year_index].rul_code);
</code></pre>
<p>Can you please post the loop to help us find the problem instead of making us guess what you're trying to do?</p>
|
<p>It seems like this is the direction that you would want to go:</p>
<pre><code>document.getElementById("course"+displayed_year_index+occurrences_indices[displayed_year_index]).addeventlistener("click", function() {
var current_rul_code = result.years[result_year_index].rul_code;
PrintReceipt(current_rul_code);
}, true);
</code></pre>
<p>This should cause each to onclick event to be created within a different scope (each iteration of the loop). <a href="http://www.jibbering.com/faq/faq_notes/closures.html" rel="nofollow noreferrer">Closures</a> will take care of the rest.</p>
| 37,792
|
<p>Does the CCK api allow me to create a node type, from a custom module, with a bunch of fields that use CCK to store their state? If so can these fields be locked so that users may not alter them, but still allow the user to add more fields to the node type?</p>
<p>Thanks</p>
|
<p>I <em>think</em> the answer to your first question is "yes" (for Drupal 6, at least, which has elements of the CCK integrated into Drupal Core). I believe the <a href="http://drupal.org/project/amazon" rel="nofollow noreferrer" title="Amazon module">Amazon module</a> does this sort of thing, albeit it with just one field. </p>
<p>I don't think the idea in your second request is achievable, though. This would seem to require field-level permissions' control whilst Drupal only supports module-level permissions' control. </p>
|
<p>You could add validation code in the GUI which restricts CCK fields being interfered with on your content type. This would not prevent another module getting in there with an axe, though.</p>
<p>You could add checks which restore your preferred CCK settings whenever they detect some unwanted changes.</p>
| 35,288
|
<p>We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.</p>
<p>The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.</p>
|
<p>The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality. </p>
<p>Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder </p>
<pre><code>|---|R15|---+---|/R16|---------(R18)--------|
| |
|---|R12|---+
</code></pre>
<p>to an expression like </p>
<pre><code>always @(*) R18 = !R16 && ( R15 | R12);
</code></pre>
<p>or you could use an assign statement</p>
<pre><code>assign R18 = R16 && (R15 | R12);
</code></pre>
<p>a latching relay</p>
<pre><code>assign R18 = (set condition) || R18 && !(break condition);
</code></pre>
<p>Then use a free verilog simulator like <a href="http://www.icarus.com/eda/verilog/" rel="nofollow noreferrer">Icarus</a> to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic! And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn. </p>
<p>(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.</p>
<p>Verilog will be an easier language to develop your tests and testbenches in!</p>
<p>It may be helpful to program in some unit delays.</p>
<p>Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!</p>
<p>Good luck.
jbd</p>
<p>There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:</p>
<p><a href="http://cq.cx/ladder.pl" rel="nofollow noreferrer">http://cq.cx/ladder.pl</a></p>
|
<p>There is a program called LogixPro which has an IO simulator for ladder logic, you can try that.</p>
| 9,642
|
<p>So i'm used to PHPMySQL where if I want to transfer a table from one database to another, I:</p>
<ul>
<li>go to the table</li>
<li>click "export"</li>
<li>CTRL-C</li>
<li>go to the other database, insert SQL, CTRL-V</li>
</ul>
<p>In MS SQL Server 2008 Express, I try:</p>
<ul>
<li>right-click, script table as, CREATE TO
<ul>
<li>but this only gives me the CREATE TABLE sql, not the INSERT INTO sql</li>
</ul></li>
<li>right-click, script table as, INSERT TO
<ul>
<li>this gives me INSERT TO sql but assumes that I am going to fill in the data (!)</li>
</ul></li>
<li>so I fire up the SQL Server 2008 Express Import/Export Data Wizard, but it doesn't seem to give me the simple CREATE/INSERT INTO script that I want either. :-(</li>
</ul>
<p>So how can I get a simple SQL dump of a table in MS SQL Server 2008 Express, the kind that PHPMySQL gives me:</p>
<pre><code>-- phpMyAdmin SQL Dump
-- version 2.11.9.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Nov 23, 2008 at 03:34 PM
-- Server version: 5.0.67
-- PHP Version: 5.2.6
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- Table structure for table `members`
--
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL auto_increment,
`firstName` varchar(50) collate latin1_general_ci NOT NULL,
`lastName` varchar(50) collate latin1_general_ci NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=4 ;
--
-- Dumping data for table `members`
--
INSERT INTO `members` (`id`, `firstName`, `lastName`, `age`) VALUES
(1, 'Jim', 'Taylor', 34),
(2, 'John', 'McGregor', 23),
(3, 'Alice', 'Anderson', 33);
</code></pre>
|
<p>From the SQL Server Management Studio you can right click on your database and select:</p>
<p>Tasks -> Generate Scripts - Next -> Select objects that you need from list -> click on the advanced
Then simply proceed through the wizard. Make sure to set 'Script Data' to TRUE when prompted to choose the script options.</p>
<p>SQL Server 2008</p>
<p><img src="https://i.stack.imgur.com/pWNr4.png" alt="enter image description here"></p>
<p>SQL Server 2008 R2</p>
<p><img src="https://i.stack.imgur.com/O86uq.png" alt="enter image description here"></p>
<p>Further reading:</p>
<p>Robert Burke: SQL Server 2005 - Scripting your Database</p>
<p>Taken from stack overflow:
<a href="https://stackoverflow.com/questions/2321052/get-script-of-sql-server-data">How to get script of SQL Server data?</a></p>
|
<p>Look here: <a href="http://www.simonholywell.com/article/sql-server-2005-dump-to-sql-statements.html" rel="nofollow noreferrer">Simon Holywell: SQL Server 2005 Dump to SQL statements</a>.</p>
<p>What Simon says (no pun intended) is this: There is nothing built-in, but there is a "scripting way" to do it. He made a PHP script you can use.</p>
| 40,287
|
<p>I really want to put in some sort of section handler into App.config that will execute some code before the application actually starts executing at Main. Is there any way to do such a thing?</p>
|
<p>Why dont you put that call as the first instruction in your main function?</p>
<p>Otherwise you can define another entry point for your program and call your main from there but its basicaly the same</p>
|
<p>Why dont you put that call as the first instruction in your main function?</p>
<p>Otherwise you can define another entry point for your program and call your main from there but its basicaly the same</p>
| 23,466
|
<p>I've had a Windows app in production for a while now, and have it set up to send us error reports when it throws exceptions. Most of these are fairly descriptive and help me find the problem very quickly (I use the MS Application Exception Block). </p>
<p>On a few occasions I have reports that are issues that I can't reproduce, and seem to only happen on a few client machines. </p>
<p>I don't have physical access to these client machines, what are some strategies I can use for debugging? Would it be better to build some tracing into the code, or are there some other alternatives?</p>
<p>Thank you.</p>
<p>Edit: I should have been more clear: The error reports that I get do have the stack trace, but since it's production code, it doesn't indicate the exact line that caused the exception, just the method in which it was thrown.</p>
|
<p>One option is to generate a (mini-)dump file as close to the point where the exception is thrown as possible. This <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2008/05/28/programmatically-generating-a-dump-file.aspx" rel="nofollow noreferrer">article</a> talks about how to do this from managed code.</p>
<p>You could then load the dump file into Visual Studio or WinDbg and examine it with the aid of <a href="http://dotnetdebug.net/2006/03/20/loading-and-using-sos-from-within-visual-studio/" rel="nofollow noreferrer">SOS</a></p>
|
<p>I'd make use of the event log. Take a look here:</p>
<p><a href="http://support.microsoft.com/kb/307024" rel="nofollow noreferrer">http://support.microsoft.com/kb/307024</a></p>
| 7,613
|
<p>I'm trying to squeeze some more performance out of my rendering pipeline. The (by far) slowest part is performing a java.awt.imaging.LookupOp on a large image. </p>
<p>The image size is about 2048x2048.</p>
<p>I have figured out that having the filter done along with the drawing operation is much faster than calling the filter method. However this still leaves us with lookup ops that take around 250ms (or 4 fps). Does anyone have any rendering tips?</p>
<p>Heres essentially what we are doing:</p>
<pre><code>public void paint(Graphics g)
{
if(recalcLUT)
{
Graphics2D g2d = (Graphics2D) displayImage.getGraphics();
g2d.drawImage(srcImage, lut, 0, 0);
}
Graphics2D g2d = (Graphics2D) g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
AffineTransform at = new AffineTransform();
at.setToIdentity();
at.scale(scale, scale);
g2d.drawImage(displayImage, at, null);
}
</code></pre>
<p>the lut variable is a LookupOp usually a ShortLookupOp, the image a 16bit grayscale image</p>
<p>Thanks</p>
<p><a href="https://stackoverflow.com/users/27818/ryan-boucher" title="Ryan Bucher">Ryan Bucher:</a></p>
<p>I know there are some other obvious performance optimizations that could be done here. But the major problem is just doing the LookupOp operation so im looking for advice with regard to that.</p>
<p>Lookup Ops are essentially where you create an array and instead of rendering each pixel of the image as its color, you use the color as an index into the array and render the color as the value in the index. In this particular example Im using it to do some simple brightness/contrast operations.
You can also implement this using a rescaleOp which is essentially a way to apply a linear function to the value of all the pixels. But this turns out to be slower.</p>
|
<p>I've not used java in close to eight years so some of the syntax may be irrelevant.</p>
<p>The key to any kind of performance regarding a loop is to push as many things as possible outside the loop. If you can't then only perform calculations when they change. Often it is better to wait until the last minute to recalculate so that you can cache multiple changes.</p>
<ol>
<li><p>Move all object construction outside of your render loop. If you know how many objects you need beforehand, then pass them in; if you don't then use a object pool and have the factory create objects outside of the renderloop. This will save you the construction/destruction time.</p></li>
<li><p>Calculate your AffineTransform only when the scale changes. Push this outside the paint loop and pass it in (as a const reference... do they even exist in Java? I've been in C++ for too long)</p></li>
<li><p>You may not need to call at.setToIdentity() as your AffineTransform should default to the Identity matrix (check this)</p></li>
<li><p>Does recalcLUT need to get called every frame? Does it make sense to set recalcLUT to false after executing the if statement?</p></li>
</ol>
<p>I'm not sure what the goal of the LookupOp is. If you give me a bit more information about what it is doing, I may be able to suggest more.</p>
<p>Hopefully this helps.</p>
|
<p>Do you have the ability to push this processing on to the GPU? Multiple hardware pipelines will significantly speed up the processing.</p>
<p>If you can't then you should look into parallelising the LookupOp on the CPU. From what I understand of it each lookup can be done in isolation. Therefore you can spin up multiple threads (how many depends on your CPU Arch and whatever else is going on at the same time) and have each thread do a look up on a portion of the image. You will need a semaphore at the of each update run to wait for all threads to finish.</p>
<p>In either case you should do the following to trade off some memory consumption for every frame that doesn't have a change. Unless your framerate is capped then the more frames you have the more chance that nothing has changed. This will save you doing unnecessary work.</p>
<pre><code>//Has filter or source image changed?
// yes, recalculate filter and cache
// no, render cached image
</code></pre>
<p>Finally, do you have visibility into the implementation of LookupOp? What is it doing, are there any performance enhancements that can be gleaned by writing the implementation yourself (this should be a last resort).</p>
| 33,104
|
<p>Is there a way to read a module's configuration ini file? </p>
<p>For example I installed php-eaccelerator (<a href="http://eaccelerator.net" rel="nofollow noreferrer">http://eaccelerator.net</a>) and it put a <code>eaccelerator.ini</code> file in <code>/etc/php.d</code>. My PHP installation wont read this <code>.ini</code> file because the <code>--with-config-file-scan-dir</code> option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?</p>
|
<p>This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a <code><?php phpinfo(); ?></code> and check where it's located.</p>
<p>For example, try this:</p>
<pre><code>[eAccelerator]
extension="eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmp"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
</code></pre>
<p>Another thing you could do is set all the settings on run-time using ini_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure.</p>
|
<p>If using Apache, and mod-php, you can configure/override some php settings locally with a <a href="http://www.php.net/manual/en/apache.configuration.php" rel="nofollow noreferrer">.htaccess file</a>. Your webserver has to "AlloweOverride" appropriately in the main config file to allow you to override these settings locally. In my experience, many hosting companies will let you set php settings via htaccess.</p>
<p>(thanks commenter for pointing out this only works with mod-php)</p>
| 13,607
|
<p>How do I get the HTTP status code (eg 200 or 500) after calling curl_easy_perform? </p>
|
<p><a href="http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html" rel="noreferrer">http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html</a></p>
<pre>
CURLINFO_RESPONSE_CODE
Pass a pointer to a long to receive the last received HTTP or FTP code. This
option was known as CURLINFO_HTTP_CODE in libcurl 7.10.7 and earlier. This
will be zero if no server response code has been received. Note that a
proxy's CONNECT response should be read with CURLINFO_HTTP_CONNECTCODE
and not this.
</pre>
<pre><code>curl_code = curl_easy_perform (session);
long http_code = 0;
curl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)
{
//Succeeded
}
else
{
//Failed
}
</code></pre>
|
<p>The other answer is absolutely correct, but I would also like to add that it might not be wise to check the error code by hand, the <code>200</code> code is not the only code that signifies success.</p>
<p>I'd recoment using the libcurl option <a href="https://curl.haxx.se/libcurl/c/CURLOPT_FAILONERROR.html" rel="noreferrer">CURLOPT_FAILONERROR</a> that when activated will make libcurl consider <code>400</code> and <code>500</code> -category statuses a request failure and will not return <code>CURLE_OK</code> from perform.</p>
| 37,109
|
<p>We are currently researching ways of enhancing image quality prior to submission to OCR. The OCR engine we are currently utilizing is the Scansoft API from Nuance (v15). We were researching the <a href="http://leadtools.com/" rel="nofollow noreferrer">Lead Tools</a> but have since decided to look elsewhere. The licensing costs associated with Lead Tools is just too great. To start with we are looking for simple image enhancement features such as: deskewing, despeckling, line removal, punch hole removal, sharpening, etc. We are running a mix of .NET and Java software, but java solution would be preferred.</p>
|
<p>Kofax is good for pre-processing, but for the types of cleanup you are talking about may be overkill unless the images are really bad. Unless your specialty is in image processing, I'd recommend working with a provider that does the image cleanup and the OCR so you can focus on the value you actually add.</p>
<p>We license the OCR development kit from ABBYY (<a href="http://www.abbyy.com/sdk/" rel="nofollow noreferrer">ABBY SDK</a>) and have found it to be superb for both image processing and OCR. The API is quite extensive, and the sample apps, help and support have been beyond impressive. I definitely recommend taking a look.</p>
|
<p>Not sure if this would be quite up to the standards that you guys would need, but perhaps you should look at some of the <a href="http://www.getpaint.net/" rel="nofollow noreferrer">Paint.Net</a> APIs. I don't know how easy it would be to extract their image processing algorithms for use in your project, but I believe they do some of the things you are looking for. Plus it is an open source project with an MIT License, so it should be pretty friendly for business use.</p>
| 17,246
|
<p>Relatively new to rails and trying to model a very simple family "tree" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten).</p>
<pre><code>class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end
</code></pre>
<p>Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether?</p>
<p>Thanks!</p>
|
<p>Found a simple answer on IRC that seems to work (thanks to Radar):</p>
<pre><code>class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children_of_father, :class_name => 'Person', :foreign_key => 'father_id'
has_many :children_of_mother, :class_name => 'Person', :foreign_key => 'mother_id'
def children
children_of_mother + children_of_father
end
end
</code></pre>
|
<p>I prefer to use scopes for this issue. Like this: </p>
<pre><code>class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children_of_father, :class_name => 'Person', :foreign_key => 'father_id'
has_many :children_of_mother, :class_name => 'Person', :foreign_key => 'mother_id'
scope :children_for, lambda {|father_id, mother_id| where('father_id = ? AND mother_id = ?', father_id, mother_id) }
end
</code></pre>
<p>This trick make it easy to get children without use instances:</p>
<pre><code>Person.children_for father_id, mother_id
</code></pre>
| 39,587
|
<p>I can make a DAO recordset in VB6/Access do anything - add data, clean data, move data, get data dressed in the morning and take it to school. But I don't even know where to start in .NET. </p>
<p>I'm not having any problems retrieving data from the database, but what do real people do when they need to edit data and put it back?</p>
<p>What's the easiest and most direct way to edit, update and append data into related tables in .NET and SQL Server?</p>
|
<p>I had the same problem last week and the solution was pretty simple for me.</p>
<p>Run:</p>
<pre><code>sudo -i -u www-data
</code></pre>
<p>And then try navigating the path, directory by directory. You will notice at some point that you don't have access to open the dir.
If you get into the last directory, check that you can read the file (with head for example).</p>
|
<p>This is a permissions problem where the user that your web server is running under does not have read and/or execute permissions to the necessary directories in the symbolic link path. The quick and easy way to check is to <code>su - web-user</code> (where <code>web-user</code> is the user account that the web server is running under) and then try to cd into the path and view the file. When you come across a directory that you don't have permission to enter, you'll have to change the permissions and/or ownership to make it accessible by the web server user account.</p>
| 11,162
|
<p>What is the time complexity of dynamic memory allocation using new, malloc, etc.? I know very little about how memory allocators are implemented, but I assume the answer is that it depends on the implementation. Therefore, please answer for some of the more common cases/implementations.</p>
<p>Edit:
I vaguely remember hearing that heap allocation is unbounded in the worst case, but I'm really interested in the average/typical case.</p>
|
<p>One of the things you have to realise when dealing with O notation is that it is often very important to understand what <em>n</em> is. If the <em>n</em> is something related to something you can control (eg: the number of elements in a list you want sorted) then it makes sense to look hard at it.</p>
<p>In most heap implementations, your <em>n</em> is the number of contiguous chunks of memory the manager is handling. This is decidedly <strong>not</strong> something typically under client control. The only <em>n</em> the client really has control over is the size of the chunk of memory she wants. Often this bears no relation to the amount of time the allocator takes. A large <em>n</em> could be as quickly allocated as a small <em>n</em>, or it might take much longer, or it might even be unservicable. All this could change for the same <em>n</em> depending on how previous allocations and deallocations from other clients came in. So really, unless you are implementing a heap, then <strong>the proper answer is that it is non-deterministic</strong>.</p>
<p>This is why hard realtime programmers try to avoid dynamic allocation (after startup).</p>
|
<p>I would think it would generally be O(n) where n is the number of available memory blocks (since you have to scan the available memory blocks to find a suitable one).</p>
<p>Having said that, I've seen optimizations that can make it faster, specifically maintaining multiple lists of available blocks depending on their size ranges (so blocks less than 1k are in one list, blocks from 1k to 10k are in another list and so on).</p>
<p>This is still O(n) however, just with a smaller n.</p>
<p>I'd be interested in seeing your source that there's a heap allocation that's unbounded (if, by that, you mean it could take forever).</p>
| 35,847
|
<p>how to create a shortcut for a exe from a batch file.</p>
<p>i tried </p>
<pre><code>call link.bat "c:\program Files\App1\program1.exe" "C:\Documents and Settings\%USERNAME%\Desktop" "C:\Documents and Settings\%USERNAME%\Start Menu\Programs" "Program1 shortcut"
</code></pre>
<p>but it did not worked.</p>
<p>link.bat can be found at
<a href="http://www.robvanderwoude.com/amb_shortcuts.html" rel="noreferrer">http://www.robvanderwoude.com/amb_shortcuts.html</a></p>
|
<p>Your link points to a Windows 95/98 version and I guess you have at least Windows 2000 or XP. You should try the NT version <a href="http://www.robvanderwoude.com/amb_shortcutsnt.html" rel="noreferrer">here</a>.</p>
<p>Alternatively use a little VBScript that you can call from the command line:</p>
<pre><code>set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
' command line arguments
' TODO: error checking
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
set objSC = objWSHShell.CreateShortcut(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
</code></pre>
<p>Save the file as createLink.vbs and call it like this to get what you originally tried:</p>
<pre><code>cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Desktop\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
cscript createLink.vbs "C:\Documents and Settings\%USERNAME%\Start Menu\Programs\Program1 shortcut.lnk" "c:\program Files\App1\program1.exe"
</code></pre>
<p>That said I urge you not to use hardcoded paths like "Start Menu" since they're different in localized versions of windows. Modify the script instead to use <a href="http://gallery.technet.microsoft.com/ScriptCenter/en-us/0b3c068c-c765-4880-bc68-effb2d0e543e" rel="noreferrer">special folders</a>.</p>
|
<p>This worked for me on Windows XP ms-dos, I still haven't tried it on Windows 7. It's just like creating a symbolic link in Linux.</p>
<pre><code>shortcut -T source.exe destination.lnk
</code></pre>
| 45,037
|
<p>Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )?
I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.</p>
<p>This is what I have as a proof of concept so far, but the "<code><WebBrowser Source="{Binding Path=WebAddress}"</code>" does not compile.</p>
<pre><code><DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress">
<StackPanel Orientation="Horizontal">
<!--Web Control Here-->
<WebBrowser Source="{Binding Path=WebAddress}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Width="300"
Height="200"
/>
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" />
<TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" />
</StackPanel>
<TextBox Text="{Binding Path=Street[0]}" />
<TextBox Text="{Binding Path=Street[1]}" />
<TextBox Text="{Binding Path=PhoneNumber}"/>
<TextBox Text="{Binding Path=FaxNumber}"/>
<TextBox Text="{Binding Path=Email}"/>
<TextBox Text="{Binding Path=WebAddress}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</code></pre>
|
<p>The problem is that <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.webbrowser.source?view=netframework-4.8" rel="noreferrer"><code>WebBrowser.Source</code></a> is not a <code>DependencyProperty</code>. One workaround would be to use some <code>AttachedProperty</code> magic to enable this ability.</p>
<pre><code>public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string) obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;
}
}
}
</code></pre>
<p>Then in your xaml do:</p>
<pre><code><WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"/>
</code></pre>
|
<p>You need to declare it at the first few lines of the <code>xaml</code> file which is pointing to the class file </p>
<pre><code>xmlns:reportViewer="clr-namespace:CoMS.Modules.Report"
</code></pre>
| 32,998
|
<p>A client asked me if I knew anything about the HOME development method. I, together with wikipedia and acronymfinder, drew a complete blank.</p>
<p>Has anyone here heard about a development method called HOME?</p>
|
<p>The best answer to this is to follow this link and read the shrt description of the method by the authors themselves.<br>
<a href="http://nyttf.dk/?pagetype=book&vareid=44021-1" rel="nofollow noreferrer">http://nyttf.dk/?pagetype=book&vareid=44021-1</a><br>
I can recommend this method as I teach it in project management at a Business Academy for Multimedia Designers i Denmark</p>
|
<p>I've never heard of it, either.</p>
<p>I'm sure there's a way for you to garner insight from your client as to what he means.</p>
<p>Perhaps you could ask something like, "In what context are you interested in knowing more about HOME?"</p>
| 30,649
|
<p>I'd like to make a debug logging function with the same parameters as <code>printf</code>. But one that can be removed by the pre-processor during optimized builds.</p>
<p>For example:</p>
<pre><code>Debug_Print("Warning: value %d > 3!\n", value);
</code></pre>
<p>I've looked at variadic macros but those aren't available on all platforms. <code>gcc</code> supports them, <code>msvc</code> does not.</p>
|
<p>I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:</p>
<pre><code>#include <stdio.h>
void XTrace0(LPCTSTR lpszText)
{
::OutputDebugString(lpszText);
}
void XTrace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512]; // get rid of this hard-coded buffer
nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
::OutputDebugString(szBuffer);
va_end(args);
}
</code></pre>
<p>Then a typical #ifdef switch:</p>
<pre><code>#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif
</code></pre>
<p>Well that can be cleaned up quite a bit but it's the basic idea.</p>
|
<p>Having come across the problem today, my solution is the following macro:</p>
<pre><code> static TCHAR __DEBUG_BUF[1024];
#define DLog(fmt, ...) swprintf(__DEBUG_BUF, fmt, ##__VA_ARGS__); OutputDebugString(__DEBUG_BUF)
</code></pre>
<p>You can then call the function like this:</p>
<pre><code> int value = 42;
DLog(L"The answer is: %d\n", value);
</code></pre>
| 3,604
|
<p>My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error</p>
<pre><code>Could not connect to data source 'New Data Source':
The network connection was terminated because the host failed to send any data.
SQLSTATE: 08S01, SQLCODE: -605
</code></pre>
<p>When putting the settings in a regular connection string and opening with .NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces?</p>
<p><strong>24 Aug 08:</strong></p>
<p>Well, if normal .NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen.</p>
<p><strong>25 Aug 08:</strong></p>
<blockquote>
<p>According to <a href="http://forums.microsoft.com/msdn/showpost.aspx?postid=1155829&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=0" rel="nofollow noreferrer">this MSDN forums posting</a>, it seems to be a login issue.</p>
</blockquote>
<p>I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem.</p>
<p><strong>26 Aug 08:</strong></p>
<p>Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the .NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet</p>
<pre><code>DRDA (Security Check)
DDM (SECCHKRM)
Length: 55
Magic: 0xd0
Format: 0x02
0... = Reserved: Not set
.0.. = Chained: Not set
..0. = Continue: Not set
...0 = Same correlation: Not set
DSS type: RPYDSS (2)
CorrelId: 0
Length2: 49
Code point: SECCHKRM (0x1219)
Parameter (Severity Code)
Length: 6
Code point: SVRCOD (0x1149)
Data (ASCII):
Data (EBCDIC):
Parameter (Security Check Code)
Length: 5
Code point: SECCHKCD (0x11a4)
Data (ASCII):
Data (EBCDIC):
Parameter (Server Diagnostic Information)
Length: 34
Code point: SRVDGN (0x1153)
Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204
Data (EBCDIC): DRDA AR: AUTHENTICATION failed
</code></pre>
<p>Why the same credentials fails here while succeeding in the .NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred.</p>
<p>.NET DB2 provider</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1
2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC
5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD
6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB
7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0
8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD
9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0
13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU]
17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD
18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0
19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC
20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA
21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0
22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD
23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM
24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM
28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0
31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA
32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM
33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0
34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM
35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY
37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD
38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM
39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD
40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0
</code></pre>
<p>BizTalk DB2 adapter</p>
<pre><code>No. Time Source Destination Protocol Info
1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8
2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0
3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0
4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT
5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD
6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC
7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD
8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK
9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM
10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0
11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0
12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB
13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0
</code></pre>
<p>It is interesting to witness the .NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it.</p>
<p><strong>18 Sep 08:</strong></p>
<p>At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles.</p>
<p>What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt:</p>
<p>The BizTalk DB2 adapter is underlyingly using <strong>Microsoft ODBC Driver for DB2</strong>. The other software tests that succeed make use of <strong>IBM DB2 ODBC DRIVER</strong> or <strong>IBM DB2 ODBC DRIVER – IBMCL1</strong>. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver.</p>
|
<p>Why, it certainly took Microsoft long enough to explicitly confirm this:</p>
<p><strong>proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter</strong></p>
<p>Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question.</p>
<p><strong>MORE BACKGROUND INFO</strong></p>
<p>The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it.</p>
|
<p>I've never used this adapter but myself, so I'm guessing, but maybe it's to do with the account that BizTalk is using to connect or your ports are not configured correctly.</p>
| 4,455
|
<p>We have a piece of functionality that is used by several different applications (clients) on the same server. It can best be modeled as a service, has a backend database, and there will only be one version of the functionality and the database in use at any one time.</p>
<p>Until now we have employed simple DLL-reuse, with the functionality, its configuration file, and dependencies deployed everywhere it is used. Because any changes now have to be made several places, this method is painful when creating new versions of the functionality or when new clients want to use it.</p>
<p>We are wondering if there is a better way to do this, and have come up with two possible alternatives.</p>
<ol>
<li><p>Put the DLL (and the dependencies) in the GAC. The question is then how to configure the component. As the clients have no interest in the configuration, we are leaning towards storing the config file in a hard-coded path on the server.</p></li>
<li><p>Publish the functionality as an internal (REST-based) service. Access to it can be limited to internal clients using the firewall.</p></li>
</ol>
<p>As we see it, the pros of #1 seem to be performance and possibly security, whereas #2 can be seen as simpler to set up.</p>
<p>Are we missing anything important here? Has anybody been in a similar situation before and wants to share some insight?</p>
|
<p>This is a problem I've struggled with many times and there really isn't any best answer other then it depends. My personal opinion is that you need to stay away from option 1 for a couple of reasons:</p>
<ol>
<li>By having all your clients share a single binary it will now require all of your clients to be tested each time you make a change to it. Now I know in your exact case you might have to do this anyways since we can assume you would be modifying the database that sits behind the component. </li>
<li>Do not hard code anything. You can store your configuration path in an AppSettings section in the machine.config file. </li>
</ol>
<p>As for option 2 one alternative would be to use WCF (assuming your environment can support it). Using WCF you could then use a TCP transport using binary serilization (And there might be a shared memory transport). Both of these would help bring the performance gap closer (Although option 1 will always outperform a service based approach). </p>
<p>By going with option 2 you also alleviate the need to retest all clients, as you can develop automated tests to validate that your contract is not broken. This will allow you to publish to a single place, run quick automated tests, and know that your not breaking the clients.</p>
<p>With that said you can accomplish the same thing using option 1 and a good set of unit tests, but based on my experience option 2 will be easier in the long run.</p>
<p>Option 2 also lets you scale out the service in the future if you ever need more CPU power.</p>
<p>Personally I think Option 1 is easier to setup, as you won't have to deal with configuring your firewall, handling authentication, setting up a service etc...It will also be easier to debug (distributing an application introduces new types of failures for example the site hosting your service crashes and your clients start getting failures).</p>
<p>One last suggestion is that you use a proxy / facade pattern to insolate your clients from the actual location of the service. This will let you expand over time without having to modify the client code.</p>
|
<p>I'd say that using Option 1 would be simpler and easier, especially as youwill just have to spend extra time limiting the availability of the REST. (pun intended!)</p>
| 42,926
|
<p>I don't like WYIWYG editors, I want to be responsible for the selection and placement of each tag and attribute! Is there a good editor out there that allows you complete control over the HTML but offers useful features such as:</p>
<ul>
<li>syntax highlighting (of course)</li>
<li>suggestions of tags, attributes etc. e.g. as dropdown lists</li>
<li>validation and accessibility checking</li>
<li>previewing the HTML</li>
</ul>
<p>Currently I use TextPad with syntax highlighting, but feel I could do better.</p>
|
<p>I'm a big fan of <a href="http://www.aptana.com/" rel="nofollow noreferrer">Aptana</a> for generic HTML/CSS/Javascript editing. Based on Eclipse, but nicer usability. Automatic formatting, code suggestion (with native support for jQuery & ExtJs) and embedded browser tabs for checking your work.</p>
<p>It's also cross-platform, supports Windows Mac & Linux.</p>
|
<p>Depending on what code you will be using (ASP v. php v. ruby, etc), I would suggest Dreamweaver. It is WYSIWYG, but many of the best editors you would find are, including VS 2008. Of course, that doesn't mean you have to use it! I used Dreamweaver quite often at my last job and it was great for editing code and quickly previewing.</p>
<p>Edit: I should mention that Dreamweaver would be best for html, css, javascript, coldfusion, and php. Those are the technologies I have used it with.</p>
| 28,571
|
<p>Can anyone reccomend some good tutorials for ext js and adobe air? The ones I have seen seem to start with you knowing a lot or already having a lot of code in place.</p>
<p>What I am looking for is a simple step by step guide that takes you through the basics of Ext Js in use with adobe air, in fact i suppose just a good Ext Js tutorial for begginers would be handy I just cant find anything.</p>
<p>Im looking to build a desktop app and need to get on it quickly, but Js is my weakness and the app has some complexity (dont they always!!).</p>
<p>So Question - What are the best Ext Js tutorials for begginners (preferbly with some adobe air thrown in, but not essentiall, one step at a time ;))</p>
|
<p>If your window is the active window, then you can simply override the forms ProcessCmdKey as such below.</p>
<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
const int WM_KEYDOWN = 0x100;
const int WM_SYSKEYDOWN = 0x104;
if ((msg.Msg == WM_KEYDOWN) || (msg.Msg == WM_SYSKEYDOWN))
{
switch (keyData)
{
case Keys.Down:
this.Text = "Down Arrow Captured";
break;
case Keys.Up:
this.Text = "Up Arrow Captured";
break;
case Keys.Tab:
this.Text = "Tab Key Captured";
break;
case Keys.Control | Keys.M:
this.Text = "<CTRL> + M Captured";
break;
case Keys.Alt | Keys.Z:
this.Text = "<ALT> + Z Captured";
break;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
</code></pre>
|
<p>And if your application is NOT the main window, take a look at the <a href="http://msdn.microsoft.com/en-us/library/ms646309.aspx" rel="nofollow noreferrer">RegisterHotkey</a> Win32 API, with some info on <a href="http://pinvoke.net/default.aspx/user32/RegisterHotKey.html" rel="nofollow noreferrer">p/invoke here</a>.</p>
| 26,317
|
<p>I've got a webapp whose original code base was developed with a hand crafted hibernate mapping file. Since then, I've become fairly proficient at 'coding' my hbm.xml file. But all the cool kids are using annotations these days.</p>
<p>So, the question is: <strong>Is it worth the effort</strong> to refactor my code to use hibernate annotations? Will I gain anything, other than being hip and modern? Will I lose any of the control I have in my existing hand coded mapping file?</p>
<p>A sub-question is, <strong>how much effort will it be?</strong> I like my databases lean and mean. The mapping covers only a dozen domain objects, including two sets, some subclassing, and about 8 tables.</p>
<p>Thanks, dear SOpedians, in advance for your informed opinions.</p>
|
<p>"If it ain't broke - don't fix it!"</p>
<p>I'm an old fashioned POJO/POCO kind of guy anyway, but why change to annotations just to be cool? To the best of my knowledge you can do most of the stuff as annotations, but the more complex mappings are sometimes expressed more clearly as XML.</p>
|
<p>All the features are supported both in the XML and in annotations.
You will still be able to override your annotations with xml declaration.</p>
<p>As for the effort, i think it is worth it as you will be able to see all in one place and not switch between your code and the xml file (unless of-course you are using two monitors ;) )</p>
| 10,790
|
<blockquote>
<p><code>dict</code> methods <code>dict.keys()</code>, <code>dict.items()</code> and <code>dict.values()</code>
return “views” instead of lists.</p>
</blockquote>
<p><a href="https://docs.python.org/3/whatsnew/3.0.html#views-and-iterators-instead-of-lists" rel="nofollow noreferrer">Source</a></p>
<p>First of all, how is a view different from an iterator? Secondly, what is the benefit of this change? Is it just for performance reasons?</p>
<p>It doesn't seem intuitive to me, i.e., I'm asking for a list of things (give me all your keys) and I'm getting something else back. Will this confuse people?</p>
|
<p>You are effectively getting a list. It's just not a copy of the internal list, but something that acts as if it where a list but only represents the internal state.</p>
<p>That's the same way it's implemented in Java (and probably many other languages/environments as well).</p>
<p>The main reason is that for many use cases returning a completely detached list is unnecessary and wasteful. It would require copying the entire content (which may or many not be a lot).</p>
<p>If you simply want to iterate over the keys then creating a new list is not necessary. And if you indeed need it as a separate list (as a copy) then you can easily create that list from the view.</p>
|
<p>As was already mentioned in the related question, view has <code>len()</code> method, which the iterator lacks (yet list has it).</p>
<p>Another benefit of returning a view instead of a list is that at least for the keys it has an optimized membership testing in O(1) operations instead of O(N) for the list (or iterator).</p>
| 44,284
|
<p>I have seen bind and eval used interchangeably especially in ASP.NET GridViews. What is the difference?</p>
|
<p>Eval is one-way, read only databinding. </p>
<p>Bind is two-way, read/write databinding. </p>
<p>See <a href="http://weblogs.asp.net/leftslipper/archive/2007/06/29/how-asp-net-databinding-deals-with-eval-and-bind-statements.aspx" rel="noreferrer">here</a> and <a href="http://msdn.microsoft.com/en-us/library/ms178366.aspx" rel="noreferrer">here</a>.</p>
|
<p>Bind() is used for two-way databinding. So when used with the proper type of datasource, it will pull the altered values out of the GridView or other control, and save them back to the database.</p>
<p>Eval() is a one-way, "read only" way to bind the values.</p>
| 32,369
|
<p>In terms of Webserver and low package size installation.</p>
|
<p>To be honest, the best distro for VMWare is the one the admin has the most experience with. With the GUI stuff all disabled I've not found any difference in performance between RedHat, Centos and Ubuntu when running VMWare.</p>
<p>Picking the distro that you can adminster easiest will save you hassle. If you already have a few linux systems using the same flavour makes the admins job a lot easier.</p>
|
<p>It is not clear to me if you are asking about the distro for the Vmware host, or for the guest operating system that will be your web server.</p>
<p>I generally really like Debian or Debian based distributions. But as far as Vmware is concerned Centos or anything really should work.</p>
<p>If you are looking at setting up many vms on this server you might want to look at using the bare-metal hypervisor product that has been released as a free product. (Vmware ESX)</p>
| 13,867
|
<p>I have this bit of javascript written with jQuery 1.2.5. It's contained inside the main function() of a plugin that I wrote. The plugin is a horizontal gallery scroller very similar to jCarousel. It does alot of auto calculating of widths and determines how many to scroll based on that and the size of the images, which is what all the calculations are that are going on.</p>
<p>What my question is, how do I prevent this from firing off before a previous execution is finished. For instance, if I get a little click happy and just frantically mash down on <code>.digi_next</code>. Things don't go so well in the UI when that happens and I'd like to fix it :) I thought the answer might lie in <code>queue</code>, but all my attempts at using it haven't turned out anything worthwhile.</p>
<pre><code> var self = this;
$(".digi_next", this.container).click(function(){
var curLeft = $(".digi_container", self.container).css("left").split("px")[0];
var newLeft = (curLeft*1) - (self.containerPad + self.containerWidth) * self.show_photos;
if (newLeft < ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1) {
newLeft = ((self.digi_gal_width - (self.containerPad + self.containerWidth) * self.show_photos)) * -1;
}
$(".digi_container", self.container).animate({
left: newLeft + "px"
}, self.rotateSpeed);
});
</code></pre>
|
<p>Just use a global busy flag. When you enter your click handler, check it, and only proceed if it's false. Immediately set it to true, and then set it back to false when the animation ends. JavaScript is single-threaded, so there is no race condition to worry about.</p>
<pre><code>var busy = false;
$("...").onclick(function() {
if (busy) return false;
busy = true;
$("...").animate(..., ..., ..., function() {
busy= false;
});
return false;
});
</code></pre>
|
<p>Since JavaScript functions calls are asyncronus, you can pass as a in parameter a callback function that's called when the previous call ends (same for errors).</p>
<p>You can pass the function you wrote in this post as the callback for the function that fire before.</p>
<p>Hope this helps.</p>
<p>Regards</p>
| 14,961
|
<p>Is there a way to increase the stack size of a Windows application at compile/link time with GCC?</p>
|
<p>IIRC, In GCC you can provide the --stack,[bytes] parameter to ld.</p>
<p>E.g.</p>
<pre><code>gcc -Wl,--stack,16777216 -o file.exe file.c
</code></pre>
<p>To have a stack of 16MiB, I think that the default size is 8MiB.</p>
|
<p>When creating threads you use the dwStackSize paremater, but I'm not sure how to change the size for the main thread, this indicates its in the exe's header, so it may be an option for the compiler/linker, else you need to find the relevant part of the header and change it yourself.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx" rel="nofollow noreferrer"><a href="http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx</a></a></p>
| 18,935
|
<p>I am making a strong effort to discipline my projects and create a Vision/Scope document at the onset. Included in this are the use case diagrams. Just listing out the use cases has really helped me fully see all the requirements that the customer is asking for, and it has opened up dialog.</p>
<p>I am wondering about how detailed the use case should be. If I am making a web application and the user will login to see a report, do I list all the columns on the report in the use case description?</p>
<p>If not, then when would I document those details?</p>
|
<p>the advantage of use-case diagrams is that they are simple and end-users can read and understand them</p>
<p>the columns to go on a report are part of a design or requirements specification (details of a feature, in agile terms) and do <em>not</em> belong on a use-case diagram</p>
<p>anything that clutters the use-case diagram belongs somewhere else</p>
<p>where? it doesn't matter, as long as it's a consistent place and you know where to find it ;-)</p>
<p>to remind people what a use-case diagram looks like - and why there is no room for spurious details - <a href="https://i.stack.imgur.com/sjcGP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sjcGP.jpg" alt="" /></a><br />
<sub>(source: <a href="http://www.agilemodeling.com/images/models/useCaseDiagram.jpg" rel="nofollow noreferrer">agilemodeling.com</a>)</sub></p>
|
<p>Use case description should be between:</p>
<ul>
<li>Low details: so that user
understands it, and thinks: "<em>How
easy is that to do</em>"</li>
<li>High details: No open possibilities (Detailed description of what
happens after each step)</li>
</ul>
| 28,605
|
<p>If I have a printer hooked directly to a pc (a kiosk with a printer), how would I go about creating the ability for a web page (.net web app) to print a jpg to the kiosks printer with no user intervention other than clicking a button on the page?</p>
|
<p>This has been asked several times already, and the result is always that you <em>can't</em> do it via normal web technologies (HTML + Javascript). The best you can do is open the print dialog, and that is <em>by design</em>. What you can do since you control the kiosks is create some kind of browser extension (like a flash object, .Net hosted control, java applet, etc) and make that available to your page, so that it handles the printing part for you.</p>
|
<p>I solve this problems in 2 different ways:</p>
<ol>
<li>Using ActiveX</li>
<li>Creating a protocol like myprint://PRINT_DATA</li>
</ol>
| 25,352
|
<p>Why or why not?</p>
|
<p>For performance, especially when you're iterating over a large range, <code>xrange()</code> is usually better. However, there are still a few cases why you might prefer <code>range()</code>:</p>
<ul>
<li><p>In python 3, <code>range()</code> does what <code>xrange()</code> used to do and <code>xrange()</code> does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use <code>xrange()</code>.</p></li>
<li><p><code>range()</code> can actually be faster in some cases - eg. if iterating over the same sequence multiple times. <code>xrange()</code> has to reconstruct the integer object every time, but <code>range()</code> will have real integer objects. (It will always perform worse in terms of memory however)</p></li>
<li><p><code>xrange()</code> isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods.</p></li>
</ul>
<p>[Edit] There are a couple of posts mentioning how <code>range()</code> will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of <code>range()</code> and <code>xrange()</code></p>
<pre><code>RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: ws_comma
--- range_test.py (original)
+++ range_test.py (refactored)
@@ -1,7 +1,7 @@
for x in range(20):
- a=range(20)
+ a=list(range(20))
b=list(range(20))
c=[x for x in range(20)]
d=(x for x in range(20))
- e=xrange(20)
+ e=range(20)
</code></pre>
<p>As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.</p>
|
<p>Go with range for these reasons:</p>
<p>1) xrange will be going away in newer Python versions. This gives you easy future compatibility.</p>
<p>2) range will take on the efficiencies associated with xrange.</p>
| 16,357
|
<p>I have to sort a number of integers, which can have values between 30.000.000 and 350.000.000. There will be between 0 and 65.535 integers, with the average count being 20.000. RAM usage is irrelevant and speed only is important.</p>
<p>Later on i will also have to split them into groups, with the divide always being set whenever the gap between two of these values is >65.535, which is what i need the algorithm for.</p>
<p>If it makes any difference, the algorithm will be used in a Perl script.</p>
<p>Edit: After thinking it over and reading the answers i've come to realize something: I don't actually care about the data itself. As i really only want to find the start and end values of groups with small gaps, the sorting only needs to create buckets and can discard the data.</p>
<p>Edit2: After some testing and trying out the answers provided, the fastest way i found was this:</p>
<pre><code>my @sort = sort {$a <=> $b} @item_offsets;
my @buckets;
my $start = shift @sort;
push @buckets, [$start,$start];
for my $item ( @sort ) {
if ( $item < $buckets[$#buckets][1]+$gap ) {
$buckets[$#buckets][1] = $item;
}
else {
push @buckets, [$item,$item];
}
}
say $#buckets;
</code></pre>
|
<p>I'd just make an array of buckets before running the algorithm, one for each group of 65536 consecutive values. The buckets will contain a min and max value of their contents, but won't store the contents themselves. After running the algorithm, do a single pass over the buckets. If there are two consecutive non-empty buckets with min(bucket2)-max(bucket1) < 65536, combine them. Combining will not happen until the algorithm finishes running. Discard any empty buckets. This algorithm is linear time.</p>
<p>Take note of <a href="http://en.wikipedia.org/wiki/Bucket_sort" rel="nofollow noreferrer">Bucket Sort</a>.</p>
|
<p>If you use the number as an index to an array, and then increment the count of that position, you've "grouped" them, and done it in one pass.</p>
<p>in pseudocode:</p>
<pre><code>while(morenumbers)
sorted[[unsorted[number]]++
number++
</code></pre>
<p>If the range is known ahead of time, you can reduce index the values (for example, the value-30000 to bring it into the right range).</p>
| 36,175
|
<p>I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:</p>
<pre><code>Display(BasePage page) {
ResourceManager manager = new ResourceManager(page.GetType());
}
</code></pre>
<p>In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:</p>
<pre><code>Display(BasePage page) {
ResourceManager manager = new ResourceManager(typeof(Login));
}
</code></pre>
<p>it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"? </p>
<p>Thanks in advance!</p>
|
<p>If your code-beside looks like this:</p>
<pre><code>public partial class _Login : BasePage
{ /* ... */
}
</code></pre>
<p>Then you would get the <code>Type</code> object for it with <em><code>typeof(_Login)</code></em>. To get the type dynamically, you can find it recursively:</p>
<pre><code>Type GetCodeBehindType()
{ return getCodeBehindTypeRecursive(this.GetType());
}
Type getCodeBehindTypeRecursive(Type t)
{ var baseType = t.BaseType;
if (baseType == typeof(BasePage)) return t;
else return getCodeBehindTypeRecursive(baseType);
}
</code></pre>
|
<p>It depends where you're calling Display() from. If you're calling it from the ASPX, then you'llse "ASP_login.aspx". If you're calling it from the code-behind (i.e. the Page_Load() method) you should get the Login page type.</p>
<p>Instead of passing the Page in, you might consider just using the Page property (i.e. this.Page.GetType()) which should always be the current page/codebehind type, if I recall correctly.</p>
<p>I should also make the point that you might consider moving this sort of stuff out of the ASPX/codebehind and into some sort of service. It's generally a good idea to minimize the amount of things you do in a code behind and, instead, push logic into a presenter class and follow the MVP pattern for ASP.NET Web Forms development.</p>
| 24,696
|
<p>I've started to use constructs like these:</p>
<pre><code>class DictObj(object):
def __init__(self):
self.d = {}
def __getattr__(self, m):
return self.d.get(m, None)
def __setattr__(self, m, v):
super.__setattr__(self, m, v)
</code></pre>
<p>Update: based on this thread, I've revised the DictObj implementation to:</p>
<pre><code>class dotdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
class AutoEnum(object):
def __init__(self):
self.counter = 0
self.d = {}
def __getattr__(self, c):
if c not in self.d:
self.d[c] = self.counter
self.counter += 1
return self.d[c]
</code></pre>
<p>where DictObj is a dictionary that can be accessed via dot notation:</p>
<pre><code>d = DictObj()
d.something = 'one'
</code></pre>
<p>I find it more aesthetically pleasing than <code>d['something']</code>. Note that accessing an undefined key returns None instead of raising an exception, which is also nice.</p>
<p>Update: Smashery makes a good point, which mhawke expands on for an easier solution. I'm wondering if there are any undesirable side effects of using <strong>dict</strong> instead of defining a new dictionary; if not, I like mhawke's solution a lot.</p>
<p>AutoEnum is an auto-incrementing Enum, used like this:</p>
<pre><code>CMD = AutoEnum()
cmds = {
"peek": CMD.PEEK,
"look": CMD.PEEK,
"help": CMD.HELP,
"poke": CMD.POKE,
"modify": CMD.POKE,
}
</code></pre>
<p>Both are working well for me, but I'm feeling unpythonic about them. </p>
<p>Are these in fact bad constructs?</p>
|
<p>Your DictObj example is actually quite common. Object-style dot-notation access can be a win if you are dealing with ‘things that resemble objects’, ie. they have fixed property names containing only characters valid in Python identifiers. Stuff like database rows or form submissions can be usefully stored in this kind of object, making code a little more readable without the excess of ['item access'].</p>
<p>The implementation is a bit limited - you don't get the nice constructor syntax of dict, len(), comparisons, 'in', iteration or nice reprs. You can of course implement those things yourself, but in the new-style-classes world you can get them for free by simply subclassing dict:</p>
<pre><code>class AttrDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
</code></pre>
<p>To get the default-to-None behaviour, simply subclass Python 2.5's collections.defaultdict class instead of dict.</p>
|
<p>Because you ask for undesirable side-effects:</p>
<p>A disadvantage is that in visual editors like eclipse+pyDev, you will see many undefined variable errors on lines using the dot notation. Pydef will not be able to find such runtime "object" definitions. Whereas in the case of a normal dictionary, it knows that you are just getting a dictionary entry.</p>
<p>You would need to 1) ignore those errors and live with red crosses; 2) suppress those warnings on a line by line basis using #@UndefinedVariable or 3) disable undefined variable error entirely, causing you to miss real undefined variable definitions.</p>
| 27,671
|
<p>I basically want to do this:</p>
<pre><code>grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log
</code></pre>
<p>...with of course the filename being <b>example.com.2008-09-27-11:21:30.log</b></p>
<p>I'd then put this in crontab to run daily.</p>
|
<p>The verbose method:</p>
<pre><code>grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`
</code></pre>
<p>The terse method:</p>
<pre><code>grep 'example.com' www_log > `date +example.com.%F-%T.log`
</code></pre>
|
<p>Here is another way, that I usually use:</p>
<pre><code>grep 'example.com' www_log > example.com.`date +%F-%T`.log
</code></pre>
<hr>
<p>Backticks are a form of command substitution. Another form is to use $():</p>
<pre><code>$(command)
</code></pre>
<p>which is the same as:</p>
<pre><code>`command`
</code></pre>
| 17,548
|
<p>I need to know when my Window goes out of input focus, so I overloaded the OnKillFocus() method of the CWnd. </p>
<p>However it doesn't invoke this method when I focus another application (alt+tab), or even minimize the window. But it DOES invoke the method when I restore it from being minimized. Are these the intended times for it to trigger this method?</p>
|
<p>My guess is that you've got some sort of template that generates the same HTML header and footer regardless of the page that is requested. Sometime before the exportCSV function is called, the header is generated.</p>
<p>You don't show the bottom of the output, but I'll bet the footer is there too, since I suspect the flow control will continue on to that code after the function exits.</p>
|
<p>You've got a control flow problem somewhere - it seems the html head part and navigation is included by default in any page, including in the one that generates the CSV.
One solution would be to check for a CSV request and if that's the case, don't include the html code, another one would be to use output buffering and then discard all the previous output right before outputting the CSV data.</p>
| 25,373
|
<p>I know that this is somewhat subjective, but I wonder if there is a generally accepted standard for naming assemblies which contain some "core" functions.</p>
<p>Let's say you got a larger Projects, with Assemblies like</p>
<ul>
<li>Company.Product.WebControls.dll</li>
<li>Company.Product.Net.dll</li>
<li>Company.Product.UserPages.dll</li>
</ul>
<p>and you have a Bunch of "Core" classes, like the Global Error Handler, the global Logging functionality etc.</p>
<p>How would such an assembly generally named? Here are some things I had in mind:</p>
<ul>
<li>Company.Product.dll</li>
<li>Company.Product.Core.dll</li>
<li>Company.Product.Global.dll</li>
<li>Company.Product.Administration.dll</li>
</ul>
<p>Now, while "just pick one and go on" will not cause Armageddon, I'd still like to know if there is an "accepted" way to name those assemblies.</p>
|
<p>With .Net this is relatively easy to change, so I'd go with convenience.</p>
<p>Fewer, larger, assemblies compile quicker than many small ones, so I'd start with your 'core' stuff as a namespace inside Company.Product.dll, and split it out later if you need to.</p>
|
<p>i also used .Core, especially for the .dll</p>
<p>Its all a matter of taste imo, if the root namespace is a company name, i feel .Core/framework/common is more descriptive than just the company name.</p>
<p>However if you're working on something like a opensource project where the name of the dll/namespace is also the name of the project, .Core/../ might be a little redundant.</p>
<p>There are many example in the .net framework and other microsoft libraries where both conventions are used. there is a System.dll and a System.Core.dll for example :) </p>
| 14,979
|
<p>Does anyone know where I can get a free 3D design (STEP or STL) of an M4 Screw and nut? I have found only an M3 on Thingiverse: <a href="http://www.thingiverse.com/thing:729842" rel="nofollow noreferrer">M3 Bolt</a> by <a href="http://www.thingiverse.com/Kaleta" rel="nofollow noreferrer">Kaleta</a>.</p>
|
<p>You can get a model for nearly everything McMaster-Carr sells from their website.</p>
<p>M4 Hex Head Screw - <a href="https://www.mcmaster.com/#91280a140/=15dmpx8" rel="nofollow noreferrer">https://www.mcmaster.com/#91280a140/=15dmpx8</a></p>
<p>M4 Nut - <a href="https://www.mcmaster.com/#90592a090/=15dmqjy" rel="nofollow noreferrer">https://www.mcmaster.com/#90592a090/=15dmqjy</a></p>
<p>The options to download models are to the right of the drawings.</p>
<hr>
<p><a href="https://www.mcmaster.com/help/drawingsandmodels.asp?sesnextrep=301313211397959#disclaimer" rel="nofollow noreferrer">NOTE: the site does prohibit use of these models for direct printing.</a></p>
<blockquote>
<p>You shall not use a CAD model to engage in 3D printing or other
fabrication of the object depicted in the CAD model for any other
purpose. You shall not otherwise redistribute or make available the
CAD models (or any design drawings or prototypes that incorporate
them) to any third parties, including third parties in the business of
selling products similar to the products sold by us.</p>
</blockquote>
|
<p>The thing you linked to describes itself as being generated from a parametric model:
<a href="http://www.thingiverse.com/apps/customizer/run?thing_id=193647" rel="nofollow noreferrer">http://www.thingiverse.com/apps/customizer/run?thing_id=193647</a></p>
<p>To generate any different bolt or nut, you will need to identify the correct dimensions for not only the thread (where hints exist in the customiser), but also for the hex head. These are obviously less critical to define than the thread.</p>
<p>Once you have generated a custom model, you can share it and answer your own question.</p>
| 444
|
<p>I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?</p>
|
<p>In your action method, return Json(object) to return JSON to your page.</p>
<pre><code>public ActionResult SomeActionMethod() {
return Json(new {foo="bar", baz="Blech"});
}
</code></pre>
<p>Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as </p>
<pre><code><%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
</code></pre>
<p>SomeMethod would be a javascript method that then evaluates the Json object returned.</p>
<p>If you want to return a plain string, you can just use the ContentResult:</p>
<pre><code>public ActionResult SomeActionMethod() {
return Content("hello world!");
}
</code></pre>
<p>ContentResult by default returns a text/plain as its contentType.<br>
This is overloadable so you can also do:</p>
<pre><code>return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
</code></pre>
|
<p>Flexible approach to produce different outputs based on the request</p>
<pre><code>public class AuctionsController : Controller
{
public ActionResult Auction(long id)
{
var db = new DataContext();
var auction = db.Auctions.Find(id);
// Respond to AJAX requests
if (Request.IsAjaxRequest())
return PartialView("Auction", auction);
// Respond to JSON requests
if (Request.IsJsonRequest())
return Json(auction);
// Default to a "normal" view with layout
return View("Auction", auction);
}
}
</code></pre>
<p>The <code>Request.IsAjaxRequest()</code> method is quite simple: it merely checks the HTTP headers for the incoming request to see if the value of the X-Requested-With header is <code>XMLHttpRequest</code>, which is automatically appended by most browsers and AJAX frameworks.</p>
<p>Custom extension method to check whether the request is for json or not so that we can call it from anywhere, just like the Request.IsAjaxRequest() extension method:</p>
<pre><code>using System;
using System.Web;
public static class JsonRequestExtensions
{
public static bool IsJsonRequest(this HttpRequestBase request)
{
return string.Equals(request["format"], "json");
}
}
</code></pre>
<p>Source : <a href="https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering" rel="nofollow noreferrer">https://www.safaribooksonline.com/library/view/programming-aspnet-mvc/9781449321932/ch06.html#_javascript_rendering</a></p>
| 28,175
|
<p>I am looking for a utility that can be used against .NET assemblies to validate code against best practices, and most importantly can review the code for Security, Injection, and Cross Site Scripting vulnerabilities. I know that it isn't an exact science, but I'm looking for anyones experience/recommendations on the best way to a solution that will at least set a baseline standard. I know that nothing beats doing an individual review, but I'm looking at the high level.</p>
<p>I have been doing some research on <a href="http://www.fortify.com/products/detect/in_development.jsp" rel="nofollow noreferrer">Fortify</a>, and so far it is looking like a good tool, from what I can tell it provides a very detailed response. I know that FXCop is out there as well, but I don't know if it goes in deep enough.</p>
<p><strong>EDIT</strong> One attractive thing I found about Fortify, and that would be nice in a tool is the combination of security review, AND .NET Best practices review. IE fortify checks fo potential un-closed connections, recommends the use of Using statements, etc.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/bb429476(VS.80).aspx" rel="nofollow noreferrer">FxCop</a> is a static code analysis tool, though not specifically targetting security, it will pick up alot of common errors (be sure to turn off the naming rules you aren't interested in).</p>
<p>Also, I came across the "Performance Code Review Tool – Practices Checker" <a href="http://blogs.msdn.com/alikl/archive/2008/01/21/performance-code-review-tool-practices-checker.aspx" rel="nofollow noreferrer">here</a>.</p>
|
<p>We have licenses for <a href="http://www.ouncelabs.com/" rel="nofollow noreferrer">Ounce</a> for the development side, and I've heard great things about SpiDynamics for testing applications post development.</p>
| 24,076
|
<p>I'm asking this question purely from a usability <code>standpoint</code>!</p>
<p>Should a website <code>expand/stretch</code> to fill the viewing area when you resize a browser window?</p>
<p>I know for sure there are the obvious cons:</p>
<ul>
<li>Wide columns of text are hard to read.</li>
<li>Writing html/css using percents can be a pain.</li>
<li>It makes you vulnerable to having your design stretched past it's limits if an image is too wide, or a block of text is added that is too long. <strong>(see it's a pain to code the html/css</strong>).</li>
</ul>
<p>The only Pro I can think of is that users who use the font-resizing that is built into their browser won't have to deal with columns that are only a few words long, with a body of <code>white-space</code> on either side.</p>
<p>However, I think that may be a browser problem more than anything else (Firefox 3 allows you to zoom <strong>everything</strong> instead of just the text, which comes in handy all the time)</p>
<p><strong>edit</strong>: I noticed stack overflow is fixed width, but coding horror resizes. It seems Jeff doesn't have a strong preference either way.</p>
|
<p>Raw HTML does just that. Are you changing your data so that it doesn't render so good in random sized windows?</p>
<p>In the olden days, everyone had VGA screens. Now, that resolution is most uncommon. Who knows what resolutions are going to be common in the future? And why expect a certain minimum width or height?</p>
<p>From a usability viewpoint, demanding a certain resolution from your users is just going to create a degraded experience for anyone not using that resolution. Another thing that comes from this is what <em>is</em> fixed width? I've seen plenty of fixed size windows (popups) that just don't render right because my fonts are different from the designer's.</p>
|
<p>Paragraph widths larger than your display make a web site completely unusable. You have to jiggle the horizontal scrollbar back and forth for every single line you read. I'm doing a web design subject at university and the textbook calls the designs which adapt to your screen width <i>fluid layout</i>.<p>
I'm designing my big class project using fluid layout, it's a bit more trouble than fixed width. I suspect none of the other students will use it, the markers won't notice and none of the professional sites we're imitating are fluid either.</p>
| 4,700
|
<p>Is there a way to use <code>JQuery</code> to cloak or encrypt email addresses on an <code>HTML</code> page without changing the syntax in the <code>href</code>?</p>
|
<p>Using JQuery may not be the route you want to take since this would be on the client side... Is there a reason you're not encrypting on server side?</p>
|
<p>Semantic nazis would say "encoding", not "encrypting". Encrypting implies a secret is required to decode. Converting to <a href="http://www.asciitable.com/" rel="nofollow noreferrer">HTML entity syntax</a> would be a decent <em>encoding</em> process to keep out prying humans, but bots could easily decode it.</p>
| 6,861
|
<p>I have the following (pretty standard) table structure:</p>
<pre><code>Post <-> PostTag <-> Tag
</code></pre>
<p>Suppose I have the following records:</p>
<pre><code>PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
</code></pre>
<p>In other words, the first post has two tags, the second has one and the third one doesn't have any.</p>
<p><strong>I'd like to load all posts and it's tags in one query</strong> but haven't been able to find the right combination of operators. I've been able to load either <em>posts with tags only</em> or <em>repeated posts when more than one tag</em>.</p>
<p>Given the database above, <strong>I'd like to receive three posts and their tags (if any) in a collection property of the Post objects</strong>. Is it possible at all?</p>
<p>Thanks</p>
|
<p>Yay! It worked. </p>
<p>If anyone is having the same problem here's what I did:</p>
<pre><code>public IList<Post> GetPosts(int page, int record)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTags);
options.LoadWith<PostTag>(pt => pt.Tag);
using (var db = new DatabaseDataContext(m_connectionString))
{
var publishDateGmt = (from p in db.Posts
where p.Status != PostStatus.Hidden
orderby p.PublishDateGmt descending
select p.PublishDateGmt)
.Skip(page * record)
.Take(record)
.ToList()
.Last();
db.LoadOptions = options;
return (from p in db.Posts
where p.Status != PostStatus.Closed
&& p.PublishDateGmt >= publishDateGmt
orderby p.PublishDateGmt descending
select p)
.Skip(page * record)
.ToList();
}
}
</code></pre>
<p>This executes only two queries and loads all tags for each post.</p>
<p>The idea is to get some value to limit the query at the last post that we need (in this case the PublishDateGmt column will suffice) and then limit the second query with that value instead of Take().</p>
<p>Thanks for your help sirrocco.</p>
|
<p>I've answered this in another post : <a href="https://stackoverflow.com/questions/50169/optimizing-a-linq-to-sql-query#50240">About eager loading</a>. In your case it would probably be something like :</p>
<pre><code>DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTag);
options.LoadWith<PostTag>(pt => pt.Tag);
</code></pre>
<p>Though be careful - the DataLoadOptions must be set BEFORE ANY query is sent to the database - if not, an exception is thrown (no idea why it's like this in Linq2Sql - probably will be fixed in a later version).</p>
| 10,537
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.