instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have multiple applications running in one virtual machine. I have multiple virtual machines running on one server. And I have multiple servers. They all share a file using a shared folder on linux. The file is read and written by all applications. During the write process no application is allowed to read this file. The same for writing: If an application is reading the file no application is allowed to write it.</p>
<p><strong>How do I manage to synchronize the applications so they will wait for the write process to finish before they read, and vice versa? (the applications inside a vm have to be synchronized and also applications across servers)</strong></p>
<p><strong>Curent implementation</strong> uses "file semaphores". If the file is about to be written the application tries to "acquire" the semaphore by creating an additional file (lets name it "file.semaphore") in the shared folder. If the "file.semaphore" file already exists this means the semaphore is already locked by a different application. This approach has the <strong>problem</strong> that I cannot make sure that the "file exists"-test and "create file"- operation are executed atomic. This way it is possible that two applications test for the "file.semaphore" file, see it does not exist and try to create the file at the same time.</p>
|
<p>You can use NIO locking capabilities. See <a href="http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#lock()" rel="nofollow noreferrer">FileChannel#lock()</a>.</p>
<p>However, this will work only if underlying filesystem supports locking over the network. Recent NFS should support it. Probably, Samba supports them too, but can’t say for sure.</p>
<p>See <a href="http://www.javabeat.net/tips/37-locking-files-using-java.html" rel="nofollow noreferrer">article</a> for example.</p>
|
<p>Have a look at the Javadocs for the <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html#createNewFile()" rel="nofollow noreferrer">createNewFile()</a> method - it specifically states that creating files is not a reliable method for synchronization, and recommends the <a href="http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html" rel="nofollow noreferrer">FileLock</a> class instead (it's another package in java.nio.channels so is essentially the same as what Ivan Dubrov is suggesting).</p>
<p>This would imply that your identification of the problem is accurate, and no amount of playing around will solve this with traditional file creation. My first thought was to check the return code from createNewFile(), but if the Javadocs say it's not suitable then it's time to move on.</p>
| 41,408
|
<p>To preface I am using Borland C++ and the VCL.</p>
<p>I need some sort of structured storage object which can be saved to disk as a single file and can contain multiple named blobs of binary data which I can programatically enumerate, access and manipulate.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aa380015(VS.85).aspx" rel="nofollow noreferrer">IStorage</a> interface seems to be close what I want but I would prefer a VCL style solution as converting TStream's (VCL) to IStream's among other things gets awkward and their must be a simpler solution using the VCL stuff allready available, like a TIniFile but for binary data.</p>
<p>I don't want to use XML as the binary data blobs are very large and when correctly encoded for use in XML it's completely inneficient.</p>
<p>Thanks in advance for all suggestions.</p>
|
<p>A zip file is de facto a standard container, and it seems you can get a TStream interface to them: <a href="http://www.tek-tips.com/faqs.cfm?fid=6734" rel="nofollow noreferrer">http://www.tek-tips.com/faqs.cfm?fid=6734</a></p>
|
<p>I went for <a href="http://www.componentace.com/zip_component_zip_delphi_zipforge.htm" rel="nofollow noreferrer">ZipForge</a> by ComponentAce. It's fast, is being actively developed/supported and has the perfect interface to support what I want.</p>
<p>Thanks for everybodys other suggestions.</p>
| 27,048
|
<p>I'm currently using the Infragistics component set for .Net 2.0, Visual Studio 2005 and C#. I have the following chunk of javascript code (text and other variables are declared elsewhere):</p>
<blockquote>
<p>***alert(box[select].value);</p>
<p>text.value(box[select].value);</p>
<p>alert(text.value);***</p>
</blockquote>
<p>'text' is an Infragistics webTextEdit, while box is just a standard listbox. The two alerts seem to be working fine. Before I set the value, the listBox's selected value might be 'hello', and the alert box which pops up after I've assigned this value to 'text' is also 'hello'.</p>
<p>However, the value shown in the box on my form never appears to get updated. Anybody have some suggestions as to where I'm going wrong, gotchas in how Infragistics handles this kind of thing or anything else? I'm aware there may not be enough info here to diagnose the problem.</p>
|
<p>The first time I looked into PRADO, I spent about 10 days using it and kept saying to myself: "This framework is amazing!". A couple of months later, I started working on a big project where the customer had chosen to use PRADO... And Hell began... As long as we kept using PRADO's base components, everything was perfect and development was fast. But as soon as the customer wanted an out-of-the-box thing, we literaly spent 2 to 3 times the amount of time we would have done it with another framework. And I'm not talking about big customizations. The PRADO framework forces the application to have a particular structure and workflow. If that logic is not working for you, then check out another framework.</p>
|
<p>We are working with PRADO framework since 4 years.
We are developing huge (+4000 programs) web apps for e-Goverment with Oraracle and MySql databases containing more than 60 millon records. As infrastructure for development we use SVN+TRAC+ our own tools for project control AND phpEdit w/tortoiseSVN as client tools.
Currently we are thinking on changing to Yii. </p>
| 11,941
|
<pre><code>Type.GetType("System.String")
</code></pre>
<p>Is there a lookup for the aliases available somewhere?</p>
<pre><code>Type.GetType("string")
</code></pre>
<p>returns <code>null</code>.</p>
|
<p>This is not possible programmatically, since the 'aliases' are in fact keywords introduced in C#, and <code>Type.GetType</code> (like every other framework method) is part of the language-independent framework.</p>
<p>You could create a dictionary with the following values:</p>
<pre><code> bool System.Boolean
byte System.Byte
sbyte System.SByte
char System.Char
decimal System.Decimal
double System.Double
float System.Single
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
object System.Object
short System.Int16
ushort System.UInt16
string System.String
</code></pre>
|
<p>The "aliases" are part of the language definition. You need to look them up in the <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="nofollow noreferrer">language spec</a> in question. They are compiled away, and don't exist at runtime - string becomes System.String, int becomes System.Int32, etc.</p>
| 41,522
|
<p>I've read a little bit about unit testing and was wondering how YOU unit test. Apparently unit testing is supposed to break a program down into very small "units" and test functionality from there.</p>
<p>But I'm wondering, is it enough to unit test a class? Or do you take it even further and unit test algorithms, formulas, etc.? Or do you broaden it to unit test asp pages/functionality? Or do you unit test at all?</p>
|
<blockquote>
<p>But I'm wondering, is it enough to unit test a class? Or do you take it even further and unit test algorithms, formulas, etc.? Or do you broaden it to unit test asp pages/functionality? Or do you unit test at all?</p>
</blockquote>
<p>An algorithm should be in a class and automatically should be Unit Tested. A formula is inside the class as a function and they are <strong>unit</strong> tested too. Unit testing tests behavior, state and all things that can be tested for the smallest unit of development. So yes, the algorithm is tested with all its detail. Later, when you have classes that use the other class, you will do <strong>integration</strong> tests (those are often tested with Unit Test programs). This will be the same but at a higher level.</p>
|
<p>We usually program in Java libraries for machines. A program is usually formed by over twenty libraries so what we do is unit test each library. It is not an easy task since many times libraries are very coupled between each other and this is not many times possible. </p>
<p>Our code is not as modular as we would like it to be but we must live with it for compatibility issues and break coupling means breaking compatibility in many cases too.</p>
| 42,281
|
<p>I'm a PHP developer who knows a little bit of Ruby. I want to learn Ruby on Rails, but most of the resources I've come across treat RoR functionality as "magic" -- i.e., it has a certain internal consistency, but don't bother asking how it works in terms of Ruby, MySQL, etc.</p>
<p>Anyway, I want a deep understanding of how RoR works, the design decisions that went into building it, etc. In particular I'm interested in ActiveRecord, but really I'm looking for the whole package.</p>
<p>Any books / sites / advice welcome.</p>
|
<p>The books "Agile Web Development with Rails" and "The Rails Way" are both pretty good. "Pro Active Record" goes really in depth for Active Record, but doesn't touch on too much else. The podcast Railscasts sometimes just uses the magic, but sometimes it explains what is really going on. Various blogs such as <a href="http://www.artofmission.com/articles" rel="noreferrer">Art of Mission</a> can get into what your looking for.</p>
<p>Additionally, using the ruby-debug gem gives you a much better understanding of what is going on - you can step into what is running behind the scenes.</p>
|
<p>If you really want to understand Rails, read the source for the bit of Rails that you want. </p>
<p>/Library/Ruby/Gems/1.8/gems/ on OSX or freeze rails and have access to it in your RAILS_ROOT/vendor/ directory</p>
| 24,870
|
<p>I'm looking to convert a SQL like statement on the fly to the equivalent regex i.e. </p>
<pre><code>LIKE '%this%'
LIKE 'Sm_th'
LIKE '[C-P]arsen'
</code></pre>
<p>What's the best approach to doing this?</p>
<p>P.S. I'm looking to do this on the .Net Framework (C#).</p>
|
<p>The following Regex converts an SQL like pattern into a Regex pattern with the help of a <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx" rel="nofollow noreferrer"><code>MatchEvaluator</code></a> delegate. It correctly handles square bracket blocks and escapes special Regex characters.</p>
<pre><code>string regexPattern = "^" + Regex.Replace(
likePattern,
@"[%_]|\[[^]]*\]|[^%_[]+",
match =>
{
if (match.Value == "%")
{
return ".*";
}
if (match.Value == "_")
{
return ".";
}
if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))
{
return match.Value;
}
return Regex.Escape(match.Value);
}) + "$";
</code></pre>
|
<p>I found a Perl module called <a href="http://search.cpan.org/dist/Regexp-Wildcards/lib/Regexp/Wildcards.pm" rel="nofollow noreferrer">Regexp::Wildcards</a>. You can try to port it or try Perl.NET. I have a feeling you can write something up yourself too.</p>
| 6,924
|
<p>We have a service that handles authorization based on a User Name and Password. Instead of making the username and password part of the call, we place it in the SOAP header. </p>
<p>In a typical scenario, a Web Service calls the Authorization service at the start of execution to check that the caller is allowed to call it. The problem is though that some of these Web services call each other, and it would mean that on every sub-call the user's permissions are checked, and that can be very expensive.</p>
<p>What I thought of doing was to have the Authorization service return a Security Token after the first call. Then, instead of having to call the Authorization service each time, the Web Service can validate the Security Header locally.</p>
<p>The Security Header looks something like this (C# code - trimmed to illustrate the essential concept):</p>
<pre><code>public sealed class SecurityHeader : SoapHeader
{
public string UserId; // Encrypted
public string Password; // Encrypted; Just realized this field isn't necessary [thanks CJP]
public DateTime TimeStamp; // Used for calculating header Expiry
public string SecurityToken;
}
</code></pre>
<p>The general idea is that the SecurityHeader gets checked with every call. If it exists, hasn't expired, and the SecurityToken is valid, then the Web Method proceeds as normal. Otherwise it will either return an error, or it will attempt to re-authorize and generate a new SecurityHeader</p>
<p>The SecurityToken is based on a salted hash of the UserId, Password, and TimeStamp. The salt is changed every day to prevent replays.</p>
<p>The one problem I do see is that a user might have permission to access Web Service A, but not Web Service B. If he calls A and receives a security token, as it stands now it means that B will let him through if he uses that same token. I have to change it so that the security token is only valid from Web Service to Web Service, rather than User to Web Service ie. It should be OK if the user calls A which calls B, but not OK if the user calls Service A and then Service D. A way around that is to assign a common key (or a set of keys) to logically related services. (ie. if client can do A then logically he can do B as well).</p>
<p>Alternatively, I'd have to encode the user's entire permission set as part of the security header. I'll have to investigate what the overhead will be.</p>
<p>Edit:</p>
<p>Several people have mentioned looking at other security schemes like WS-Security and SAML etc. I already have. In fact, I got the idea from WS-Security. The problem is that other schemes don't provide the functionality I need (caching authorization information and protecting against replays without an intemediary database). If someone knows of a scheme that does then I will glady use it instead. Also, this is <em>not</em> about authentication. That is handled by another mechanism beyond my control.</p>
<p>If it turns out that there is no way to cache authorization data, then it means that I'll just have to incur the overhead of authorization at each level.</p>
|
<p>Ok, replacing my older answers with hopefully a better one.</p>
<p>What you describe should work if you have a way to securely share data between your services. For example, if your services share a secret key with the Authorization Service, you can use this key to get the salt.</p>
<p>BTW, I don't know enough cryptography to say whether it's safe enough to add secret salt + hash (although seems fine); I'm pretty sure it's safe to <a href="http://en.wikipedia.org/wiki/HMAC" rel="nofollow noreferrer">HMAC</a> with a secret or private key. Rotating keys is a good idea, so you would still have a master key and propagate a new signing key.</p>
<p>Other issues with your approach are that (a) you're hardcoding the hashing logic in every service, and (b) the services might want to get more detailed data from the Authorization Service than just a yes/no answer. For example, you may want the Authorization Service to insert into the header that this user belongs to roles A and B but not C.</p>
<p>As an alternative, you can let the Authorization Service create a new header with whatever interesting information it has, and sign that block. </p>
<p>At this point, we're discussing a Single Sign-On implementation. You already know about <a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss" rel="nofollow noreferrer">WS-Security</a> specs. This header I described sounds a lot like a <a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=security" rel="nofollow noreferrer">SAML</a> assertion. </p>
<p><a href="http://www.oracle.com/technology/tech/java/newsletter/articles/wsaudit/ws_audit.html" rel="nofollow noreferrer">Here's an article</a> about using WS-Security and SAML for Single Sign-On.</p>
<p>Now, I don't know whether you need all this... there are in-between solutions too. For example, the Authorization Service could sign the original Username block; if you worry about public/private crypto performance, and you're ok sharing secret keys, you could also use a secret key to sign instead of public/private keys.</p>
|
<p>First of all, read @CJP 's post, he makes an excellent and valid point.<br>
If you want to go ahead and roll it yourself anyway (maybe you do have a good reason for it), I would make the following points: </p>
<ul>
<li>You're talking about an Authentication Service, NOT an authorization service. Just to make sure you know what you're talking about...?</li>
<li>Second, you need to separate between the salt (which is not secret) and the key (which is). You should have a keyed hash (e.g. HMAC), together with salt (or a keyed salted hash. Sounds like a sandwich.). The salt, as noted, is not secret, but should be changed FOR EACH TOKEN, and can be included in the header; the key MUST be secret and being changed every day is good. Of course, make sure you're using strong hash (e.g. SHA-256), proper key management techniques, etc etc.</li>
</ul>
<p>Again, I urge you to reconsider rolling your own, but if you have to go out on your own...</p>
| 18,503
|
<p>Let's say I have a payments table like so:</p>
<pre><code>CREATE TABLE Payments (
PaymentID INT,
CustomerID INT,
Value INT,
PaidOn DATE
);
INSERT INTO Payments
VALUES
(1, 1, 5, '2000-01-01'),
(2, 1, 10, '2000-02-01'),
(3, 2, 10, '2000-01-02'),
(4, 2, 10, '2000-01-20'),
(5, 2, 5, '2000-02-02'),
</code></pre>
<p>And I want to run a query for the entire row for the maximum payment made by each customer. Is this possible using a single SQL query, to avoid having to dig through every row that I'm not interested -- or worse, run a query for each customer?</p>
<p>The best I have come up with so far is:</p>
<pre><code>SELECT CustomerID, MAX(Value)
FROM Payments
GROUP BY CustomerID;
</code></pre>
<p>But this does not give me the <code>PaymentId</code> or <code>PaidOn</code> values for the rows it finds.</p>
|
<p>The following query will accomplish that. It pulls out all the rows for which there is not a greater Value.</p>
<pre><code>SELECT *
FROM payments p
WHERE NOT EXISTS (
SELECT *
FROM payments p2
WHERE p2.CustomerID = p.CustomerId
AND p2.Value > p.Value
)
</code></pre>
|
<p>One more using Self join - matter of syntactic sugar. Easier to understand and good on performance.</p>
<pre><code>select PaymentID, CustomerID, Value, PaidOn
from
( select customerID, max(value) as maxValue
from payments
group by customerID
)as T
INNER JOIN payments as P
ON P.Value=T.maxValue AND P.CustomerID = T.CustomerID
</code></pre>
<p>-Maulik Modi</p>
| 49,102
|
<p>I was reading Jeff Atwood's blog on <a href="http://www.codinghorror.com/blog/archives/001105.html" rel="noreferrer">Behold WordPress, Destroyer of CPUs</a> and saw that many people there considered 20 SQL Queries per page load to be a lot. What is the average amount of queries per page nowadays for a highly dynamic page with auto suggest, auto refreshing of data, customized pages, and the kitchen sink? </p>
<p>For a simple example, Amazon.com practically customizes my homepage with stuff they think I will buy. To me, that doesn't look it just uses 5 or less queries for the front page. </p>
<p>I'm still a newbie with databases so please tell me if I'm missing something obvious. </p>
|
<p>You can usually bring all the data in two or three big queries instead of on twenty small ones. Minimizing the amount of queries is as important as, if not most important than, writing optimal queries to maximize performace. </p>
<p>Of course you should always analyze the query plans and aim towards optimal queries, be them small or big.</p>
<p>The thing is that badly designed webpages do many queries, one per each tiny little task, which could easily be grouped in a single query. </p>
<p>For example, a <strong>badly designed stackoverflow could</strong> do a query to get all the question ids it will show on the main page, then do one query per each question to get the summary and the votes. Then you have easily 20 useless queries. A well designed will do a single query getting all the information about all the questions it'll display.</p>
<p>Of course the impact of this all is reduced with good caching, which is what all big sites do, that way you actually can do a lot of queries and still get decent performance.</p>
|
<p>My rule of thumb is keep the front pages down to under 5-7 if possible, depending on the type of the site.</p>
<p>Interior pages, depending on what they need might have more, but I do what I can to keep it under 20.</p>
<p>However, at the same time, depending on what you are trying to do AND what types of caching you are doing with that information 20 may not be bad if 15 of them are heavily cached...</p>
| 44,526
|
<p>I'm no UNIX Guru, but I've had to set up a handful of slices for various web projects. I've used the articles on there to set up users, a basic firewall, nginx or apache, and other bits and pieces of a basic web server. </p>
<p>I foresee more slice administration in my future. <strong>Is there a more efficient way to set up users, permissions, and software on a clean slice than configuration by hand?</strong></p>
|
<p>It sounds like you can create a new slice from the backup of an existing one. This might not work for you if the slices would be different sizes, different distros, etc. Their forums mention this: <a href="http://forum.slicehost.com/comments.php?DiscussionID=1902" rel="nofollow noreferrer">Clone a slice?</a></p>
|
<p>Depending on the number of machines you might find it makes sense to use something like CFEngine, or Puppet, to configure the new installs.</p>
<p>That brings your work down to configuring each new machine as a CFEngine, for example, client. Then that may be used to install the packages, edit files, & etc.</p>
<p>There are a few articles I wrote on the subject, with a Debian bias, here:</p>
<p><a href="http://www.debian-administration.org/tag/cfengine" rel="nofollow noreferrer">http://www.debian-administration.org/tag/cfengine</a></p>
| 18,137
|
<p>I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:</p>
<pre><code>http://mysite.com/configs/.vim/
</code></pre>
<p>.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?</p>
|
<p>You have to pass the <code>-np</code>/<code>--no-parent</code> option to <code>wget</code> (in addition to <code>-r</code>/<code>--recursive</code>, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:</p>
<pre><code>wget --recursive --no-parent http://example.com/configs/.vim/
</code></pre>
<p>To avoid downloading the auto-generated <code>index.html</code> files, use the <code>-R</code>/<code>--reject</code> option:</p>
<pre><code>wget -r -np -R "index.html*" http://example.com/configs/.vim/
</code></pre>
|
<p>You should be able to do it simply by adding a -r</p>
<pre><code>wget -r http://stackoverflow.com/
</code></pre>
| 34,492
|
<p>What is the best way to create a lock on a file in Perl?</p>
<p>Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?</p>
|
<p>If you end up using flock, here's some code to do it:</p>
<pre><code>use Fcntl ':flock'; # Import LOCK_* constants
# We will use this file path in error messages and function calls.
# Don't type it out more than once in your code. Use a variable.
my $file = '/path/to/some/file';
# Open the file for appending. Note the file path is quoted
# in the error message. This helps debug situations where you
# have a stray space at the start or end of the path.
open(my $fh, '>>', $file) or die "Could not open '$file' - $!";
# Get exclusive lock (will block until it does)
flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";
# Do something with the file here...
# Do NOT use flock() to unlock the file if you wrote to the
# file in the "do something" section above. This could create
# a race condition. The close() call below will unlock the
# file for you, but only after writing any buffered data.
# In a world of buffered i/o, some or all of your data may not
# be written until close() completes. Always, always, ALWAYS
# check the return value of close() if you wrote to the file!
close($fh) or die "Could not write '$file' - $!";
</code></pre>
<p>Some useful links:</p>
<ul>
<li><a href="http://www.perlmonks.org/?node_id=7058" rel="noreferrer">PerlMonks file locking tutorial</a> (somewhat old)</li>
<li><a href="http://perldoc.perl.org/functions/flock.html" rel="noreferrer"><code>flock()</code> documentation</a></li>
</ul>
<p>In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics).</p>
|
<p>Use the <a href="http://perldoc.perl.org/functions/flock.html" rel="nofollow noreferrer">flock</a> Luke. </p>
<p><strong>Edit:</strong> <a href="http://www.perlmonks.org/?node_id=7058" rel="nofollow noreferrer">This</a> is a good explanation.</p>
| 5,530
|
<p>I have an ender 5, and I'm not certain that the bed is getting up to temperature. Or maybe I'm not understanding what it should be like when it gets up to temperature.</p>
<p>If I use an infrared thermometer, where should I aim it, and what should it be saying in comparison to what the screen on the printer says?</p>
<p>For example, if the screen says 50 degrees should the thermometer read 50 degrees, or should it read something different because that's an internal temperature or something not a surface temperature?</p>
<p>At the moment the bed seems "nicely warm" when the temperature on the display says that I should burn my hand if I touch it.</p>
|
<h2>Sensor mounting</h2>
<p>An Infrared Thermometer prefers a non-reflective surface to accurately read the temperature reliably - glass is reflective for Infrared light under many angles and can in the worst case result in measuring anything <em>but</em> what you want to measure. To that degree, a piece of paper tape (Painter's tape or Washi-tape works fine) can act as a mounted measuring point.</p>
<p>A contact temperature sensor can be mounted touching the plate in a location easily by putting it in contact using some tape.</p>
<h2>Sensor positioning</h2>
<p>However, do note that the temperature sensor of the printer is not mounted on the top of the build platform but at the heater element under it. This means two things:</p>
<p>There is a temperature differential between the heater (which would be quite hot but not scorching in an instant of touching it) under the aluminium bed, the top of the aluminium bed, and even more if correlated against the surface of your build platform.</p>
<p>On the other hand, to verify your sensor setting, you need to measure under the bed at the heating element or at the interface between the heater and the aluminium bed. For example, you could use a spot right next to the heater as your probing point. This is incidentally quite close to where the temperature sensor should be mounted anyway.</p>
<h2>Bed temperature control</h2>
<p>Depending on your setup, the temperature difference between heater and the build surface could be up to about 15 °C and I would deem that an acceptable number. In accounting for the wanted build surface temperature, one can adjust the set heater temperature accordingly, as shown in this experience I had:</p>
<p>On particularly a cold day in late 2021 the heating in the room was not gaining enough heating water from the central unit set to a lower setting than it ought to. As a result, the room was down from the usual temperature to a rather cold ca. 12 °C. On that day I had to increase the bed temperature by a couple of degrees to gain proper bed adhesion, but it fixed itself once I figured out to fix the setting on the central unit.</p>
|
<p>The actual numerical reading doesn't really matter - as long as the first layer goes down, and stays down through the entire print.</p>
<p>I've noticed that the center of the bed is ~2 degrees C under the set temp, and the edges could be 15 degrees low.</p>
<p>So "verify by effect" - if the bed seems too cold and you're getting lifting, then raise the temp and use that new value. Write it on the side of the filament spool too.</p>
<hr />
<p>If you're looking for a hardware solution, some of the IR cameras or camera add-ons for cellphones may be suitable.</p>
<p>FLIR is one such device - be aware they're not cheap! Some photos at <a href="https://toms3d.org/2019/05/02/testing-5-different-heated-beds/" rel="nofollow noreferrer">https://toms3d.org/2019/05/02/testing-5-different-heated-beds/</a></p>
<p><a href="https://i.stack.imgur.com/RqfkL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RqfkL.jpg" alt="enter image description here" /></a></p>
| 2,092
|
<p>I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.</p>
<p>My HTML Code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="middle">
<img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" />
<div id="ctl00_menuPanel" class="menu">
<a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;">Home</a> |
<a id="ctl00_leden" href="Leden.aspx">Leden</a> |
<a id="ctl00_agenda" href="Agenda.aspx">Agenda</a> |
<a id="ctl00_fotos" href="Fotos.aspx">Foto's</a> |
<a id="ctl00_geschiedenis" href="Geschiedenis.aspx">Geschiedenis</a> |
<a id="ctl00_gastenboek" href="Gastenboek.aspx">Gastenboek</a>
</div>
</div></code></pre>
</div>
</div>
</p>
|
<p>Try the IE Developer Toolbar, which will let you inspect what is going on with the elements and give you outlines of the areas covered. It might give you a better understanding of the problem.</p>
|
<p>The solution: </p>
<pre><code>img {
padding: 0px;
margin: 0px;
display: block;
}
</code></pre>
<p>display: block</p>
| 3,478
|
<p>I am preparing a presentation using Google Slides, though I can also work on the presentation within Open Office that will include code snippets. </p>
<p>Is there any easy way to perform basic syntax highlighting on the code snippets with either Google Docs or Open Office Presenter?</p>
<p><b>Edit:</b> Since I believe that I can find a way to embed HTML, any tools that can perform syntax highlighting on HTML would also be welcome suggestions.</p>
|
<p>An on-line syntax highlighter:</p>
<p><a href="http://hilite.me/" rel="noreferrer">http://hilite.me/</a></p>
<p>Just copy and paste into your document.</p>
|
<p>Check out <a href="http://codepad.org" rel="nofollow">http://codepad.org</a>. It probably won't solve the poster's problem; but, I think it will be of use to others who read this article. </p>
| 35,551
|
<p>I understand that you can use forms authentication to grant/deny access to certain pages based on the criteria of your choosing.</p>
<p>However I wish to go in a little more specific than that and say, have different buttons appear for users based on thier permissions.</p>
<p>I know I could do something like</p>
<pre><code>if(((User)ViewData["CurrentUser"]).IsEmployee).....
</code></pre>
<p>But that doesn't seem very elegant and could get messy very quickly.</p>
<p>Are there any guidelines/tools/framework features that could help me out here?</p>
|
<p>Use role-based authentication, then set roles appropriately. Then you can do things like:</p>
<pre><code>if (ViewContext.HttpContext.User.IsInRole("vEmployee") {
</code></pre>
<p>The advantage of this is that it's core ASP.NET functionality -- not even MVC-specific -- so it's going to work with every possible membership provider.</p>
<p>Then you can add a view helper overload for whatever control you want to conditionally display:</p>
<pre><code>public static string TextBox(this HtmlHelper helper,
string name, string value, string role, object htmlAttributes)
{
if helper.ViewContext.HttpContext.User.IsInRole(role) {
return helper.TextBox(name, value, htmlAttributes);
}
else
{
return null;
}
}
</code></pre>
<p>...and call it:</p>
<pre><code><%= Html.TextBox("name", "value", "vEmployee", null) %>
</code></pre>
|
<p>Don't do it. Use the controller for that kind of logic</p>
| 48,465
|
<p>Frameworks simplify coding at the cost of speed and obfuscation of the OS. With the passing of Moore's law do you thing that there might be a shift away from Frameworks?</p>
<p>I suspect that one of the reasons for Vista not being an outstanding success was that it ran much slower than XP, and, because computers had not improved as greatly in speed as in the past, this change seemed like a step backwards.</p>
<p>For years CPU speed outstripped the speed of software so new frameworks that added layers of OS obfuscation and bloat did little harm. Just imagine how fast Windows 95 would run on today's hardware (given a few memory tweaks). Win2K then WinXP were great improvements, and we could live with them being slower because of faster computers.</p>
<p>However, even years ago, I noticed that programs written in MS foundation classes didn't seem quite as crisp as code doing the same thing written directly to the API. Since the proliferation of these frameworks like .Net and others can only have made this situation worse, is it possible that we might discover that being able to write code in 'C' directly to the Win32 API (or the equivalent in other OS's) will become a strong competitive advantage, even if it does take longer to write? Or will the trade off in longer development time just not ever be worth it?</p>
|
<p>If there is selective pressure to make apps faster, I think that people will become better at writing frameworks that encapsulate functionality without slowing down the system too much.</p>
<p>The Boost::Gil framework that handles pixels is a nice template-based system that boils down to many inlined functions - the compiler creates the same output as it would if you had no wrapper for the pixels and accessed the values directly. </p>
<p>So - as for your question, I think the ball is in the court of the framework writers to ensure that their frameworks are fast and lean. This might mean that they detect which features are in use and remove code relating to unused features.</p>
|
<p>Stepping away from frameworks would be a step backwards and I think and hope that this won't happen.</p>
| 10,447
|
<p>How can you programmatically tell an HTML <code>select</code> to drop down (for example, due to mouseover)?</p>
|
<p><em>This used to actually be possible with HTML+Javascript, despite everywhere else people say it is not, but it was deprecated later on and does not work now.</em></p>
<p><strong>However, this only worked in Chrome. Read more if you're interested.</strong></p>
<hr>
<p>According to <a href="http://www.w3.org/TR/html5/content-models.html#interactive-content" rel="noreferrer">W3C Working Draft for HTML5, Section 3.2.5.1.7. Interactive Content</a>:</p>
<blockquote>
<p>Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism [...] <strong>for instance using keyboard or voice input, or through mouse clicks</strong>.</p>
<p>When the user triggers an element with a defined activation behavior in a manner other than clicking it, <strong>the default action of the interaction event must be to run</strong> synthetic click activation steps on the element.</p>
</blockquote>
<p><code><select></code> being an Interactive Content, I believed that it is possible to programatically display its <code><option></code>s. After a few hours of playing around, I discovered that using <code>document.createEvent()</code> and <code>.dispatchEvent()</code> works.</p>
<p>That said, demo time. <a href="http://jsfiddle.net/fz2sY/39/" rel="noreferrer"><strong>Here is a working Fiddle.</strong></a></p>
<hr>
<p>HTML:</p>
<pre><code><select id="dropdown">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" onclick="runThis()">Show dropdown items</button>
</code></pre>
<p>Javascript:</p>
<pre><code>// <select> element displays its options on mousedown, not click.
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
// This isn't magic.
window.runThis = function () {
var dropdown = document.getElementById('dropdown');
showDropdown(dropdown);
};
</code></pre>
<p>If anyone finds a way to do the same but not in Chrome, <a href="http://jsfiddle.net/fz2sY/39/" rel="noreferrer">please feel free to modify this fiddle</a>.
</p>
|
<p>I don't know if I'm fully understanding the question, but to open a dropdown, this simple approach worked for me.</p>
<p>You have an element:</p>
<pre><code><span onclick="openDropdown();">Open dropdown</span>
</code></pre>
<p>You have a dropdown:</p>
<pre><code><select class="dropdown">
<option value="A">Value A</option>
<option value="B">Value B</option>
<option value="C">Value C</option>
</select>
</code></pre>
<p>And with JavaScript you can do the following:</p>
<pre><code>document.querySelector('.dropdown').focus();
</code></pre>
| 30,973
|
<p>Is there a simple Model Checker tool. I am planning to implement a model checker tool which will analyze the code for some of the predefined properties.</p>
|
<p>One important tool is <a href="http://spinroot.com" rel="noreferrer">SPIN</a>, with the Promela language. If you use LaTeX, there is also <a href="http://research.microsoft.com/users/lamport/tla/tla.html" rel="noreferrer">TLA+</a>.</p>
<p>These will not analyse your code, but will let you express a model for your assumtions and state transitons, and will then analyse for invalid states. In other words, they will detect problems in your model, not the implementation of your model.</p>
<p>I have seen a demo of <a href="http://ertos.nicta.com.au/publications/papers/Fehnker_HJLR_06.pdf" rel="noreferrer">Goanna</a>, but I don't know if it is available at all (commercial or otherwise); this has the advantage of actually analysing your source code.</p>
<p>Just looking at your question, and the comments in your question again, it sounds like you really should read some of the literature first. Perhaps, <a href="https://rads.stackoverflow.com/amzn/click/com/0321228626" rel="noreferrer" rel="nofollow noreferrer">The Spin Model Checker</a>, or <a href="https://rads.stackoverflow.com/amzn/click/com/032114306X" rel="noreferrer" rel="nofollow noreferrer">Specifying Systems</a> (downloadable from <a href="http://research.microsoft.com/users/lamport/tla/book.html" rel="noreferrer">Leslie Lamport's website</a>). You need to reframe your problem so that you don't try to solve the halting problem.</p>
|
<p><a href="http://www.cs.cmu.edu/~modelcheck/cbmc/" rel="nofollow noreferrer">CBMC</a> is one simple-ish tool I'm aware of that actually operates on code. Model checking in general is a heavily-researched field, but as folks have already commented, this breadth makes it difficult to suggest something with the info provided. There are thousands of SAT solvers, formal tools for HDL/state machine verification, and plenty of commercial static source analyzers.</p>
<p>In any case, CBMC is a good tool, but don't take my word for it; Ed Clarke, the main faculty member behind this work, won the Turing Award this year ;-)</p>
| 26,947
|
<p>I am trying to come up with the best way to render some hierarchical data in to a nested unordered list using ASP.NET MVC. Does anyone have any tips on how to do this?</p>
|
<p>I suggest jquery tree view plugins for making it function like a tree, but as for render, just put it in a recursive lambda helper to do the nesting.</p>
|
<p>For that (rendering hierarchical menu, treeview, etc) i use recursive calls of custom component (ascx, or aspx in new preview5).<br>
I give component first level of items (List of items), and component then check for each item in list if there's any child items and call itself with list of that child items.<br>
You can build hierarchical graph of objects in controller, or just 1 dimensional list with ParentID property.</p>
| 8,256
|
<p>In my views.py, i have a snippit of code like this:</p>
<pre><code>def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if request.POST:
if form.is_valid():
clean_post_data(form)
form.save()
action = "Added new product"
return render_to_response('cms/admin/action.html', {'action' : action},context_instance=RequestContext(request))
else:
action = "There was an error. Please go back and try again"
return render_to_response('cms/admin/action.html', {'action' : action}, context_instance=RequestContext(request))
return render_to_response('cms/admin/editproduct.html', {'form' : form, 'action' : action, 'image' : image}, context_instance=RequestContext(request))
</code></pre>
<p>But when i run that, i get the following error <code>'list' object has no attribute 'rstrip'</code>. What am i doing wrong.</p>
<p>I originally had the <code>for i in form.cleaned_data:</code> loop directly in the view (not in another function) and it worked fine, but now when i try it i get the same error as above. <a href="http://dpaste.com/92836/" rel="nofollow noreferrer">http://dpaste.com/92836/</a></p>
|
<p>The <code>clean_post_data</code> shouldn't be a stand-alone function.</p>
<p>It should be a method in the form, named <code>clean</code>. See <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow noreferrer">Form and Field Validation</a>.</p>
|
<p>Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list</p>
<p>If you want to skip (or do something special about) such cases you need to check for it:</p>
<pre>
def clean_post_data(form):
for i in form.cleaned_data:
if('__iter__' in dir(form.cleaned_data[i])):
print "skip this element: " + str(form.cleaned_data[i])
else:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
</pre>
| 40,058
|
<p>How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows. </p>
<p>Program flow:
1) Window A OpenWithParm
2) Window B is now open
3) User interacts with both windows
3) User closes Window B
4) Window B needs to pass a structure back to window A</p>
|
<p>You won't be able to accomplish this the way you are thinking. Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together. </p>
<p>But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure. Then from the child window before you close it, explicitly set the variable in the parent window via something like this:</p>
<pre><code>w_my_parent_window_name.istr_my_structure = lstr_my_structure
</code></pre>
<p>This should only be done if there will only be one instance of w_my_parent_window_name instantiated.</p>
|
<p>If you're using the PFC, if I remember right there was a service that you could use as well.</p>
| 19,910
|
<p>I have an SLA printed part I want to put a brass threaded insert in using a soldering iron. The insert is slightly larger than the hole so I would assume the edge will melt and re-freeze around the teeth. Are there any issues with melting SLA or this idea in general? </p>
|
<p>The plastic used in SLA printing is what is known as a <em>thermoset</em> plastic, as opposed to the <em>thermoplastic</em> plastics used in FDM printing. What this means, is that it <em>can not be melted</em>. The reaction that hardens SLA materials is irreversible. If you heat up the plastic it won't melt, it will just burn (if it gets hot enough). What you're planning is a bad idea, and it won't work.</p>
|
<p>Is it possible to make the hole larger, put the brass insert with a pre-installed screw inside the hole, fill the area with resin and cure with UV lamp?</p>
| 1,066
|
<p>Have people been using 3D printing to genuinely create a number of needed objects in their homes, and if so, what? Or is 3D printing better for special niche interests like art projects, home engineering projects, etc?</p>
|
<p>Both.</p>
<p>3D printing is especially useful for creating replacement parts for things for which it would otherwise be difficult, expensive, or impossible to obtain a conventionally manufactured one. You may have seen in the news recently the <a href="https://www.bbc.com/news/technology-51911070" rel="nofollow noreferrer">story about 3D printing being used to replace hospital ventilator valves</a> that were not available in time to save patients who needed them, and that normally cost \$11000 from the manufacturer. But the same kind of thing applies to regular household items too. For example, I've replaced broken wheels on my child's toy cars, a broken windshield washer fluid coupling in my car, and various similar things. I'm also planning to replace broken plastic wheel bearings in my vacuum cleaner (the manufacturer's design was atrociously bad and I'll probably adapt it to use real bearings with a 3D printed adapter), a window switch in my car, and lots of other things I can't remember at the moment.</p>
<p>Of course you can do craft and hobby things too. I don't think this really calls for examples/evidence.</p>
|
<p>Both.</p>
<p>3D printing is especially useful for creating replacement parts for things for which it would otherwise be difficult, expensive, or impossible to obtain a conventionally manufactured one. You may have seen in the news recently the <a href="https://www.bbc.com/news/technology-51911070" rel="nofollow noreferrer">story about 3D printing being used to replace hospital ventilator valves</a> that were not available in time to save patients who needed them, and that normally cost \$11000 from the manufacturer. But the same kind of thing applies to regular household items too. For example, I've replaced broken wheels on my child's toy cars, a broken windshield washer fluid coupling in my car, and various similar things. I'm also planning to replace broken plastic wheel bearings in my vacuum cleaner (the manufacturer's design was atrociously bad and I'll probably adapt it to use real bearings with a 3D printed adapter), a window switch in my car, and lots of other things I can't remember at the moment.</p>
<p>Of course you can do craft and hobby things too. I don't think this really calls for examples/evidence.</p>
| 1,614
|
<p><a href="http://subclipse.tigris.org/" rel="noreferrer">Subclipse</a>, <a href="http://www.eclipse.org/subversive/" rel="noreferrer">Subversive</a>, or <a href="http://www.google.com/search?hl=en&safe=off&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=svn+eclipse&spell=1" rel="noreferrer">something else</a>?</p>
<p>There's a bit of <a href="http://www.google.com/search?source=ig&hl=en&rlz=&q=subclipse+vs+subversive&btnG=Google+Search&meta=" rel="noreferrer">debate</a> around the topic, can we come to some conclusion here?</p>
<p><strong>EDIT:</strong>
It's been a couple months now, and I ended up deciding the plugin slowed Eclipse down too much, and was a hassle to use every time I changed a file from outside Eclipse.
I ditched the plugin all together and just went with TortiseSVN.</p>
|
<p>This depends. <a href="http://subclipse.tigris.org/" rel="noreferrer">Subclipse</a> has superior support for checking out projects as maven projects - this is the sole reason we use Subclipse. Other than that, I have noticed subclipse bugs with syncing with SVN.</p>
<p><a href="http://www.eclipse.org/subversive/" rel="noreferrer">Subversive</a> is much better at detecting new files to add to version control, and is also far superior with merging code from a branch, or even syncing with SVN (fewer bugs, etc.). So really, you should ask yourself what value you want. If you're not using maven, I would definitely go for Subversive.</p>
|
<p>subclipse is fully packed with features, I have never had an issue with it.</p>
| 22,434
|
<p>I have three tables <code>tag</code>, <code>page</code>, <code>pagetag</code></p>
<p>With the data below</p>
<p><strong><em>page</em></strong></p>
<pre><code>ID NAME
1 page 1
2 page 2
3 page 3
4 page 4
</code></pre>
<p><strong><em>tag</em></strong></p>
<pre><code>ID NAME
1 tag 1
2 tag 2
3 tag 3
4 tag 4
</code></pre>
<p><strong><em>pagetag</em></strong></p>
<pre><code>ID PAGEID TAGID
1 2 1
2 2 3
3 3 4
4 1 1
5 1 2
6 1 3
</code></pre>
<p>I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.</p>
<pre><code>ID NAME TAGS
1 page 1 tag 1, tag 2, tag 3
2 page 2 tag 1, tag 3
3 page 3 tag 4
4 page 4
</code></pre>
<p>Is this possible with SQL?</p>
<hr>
<p>I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.</p>
|
<blockquote>
<p>Sergio del Amo:</p>
<blockquote>
<p>However, I am not getting the pages without tags. I guess i need to write my query with left outer joins.</p>
</blockquote>
</blockquote>
<pre><code>SELECT pagetag.id, page.name, group_concat(tag.name)
FROM
(
page LEFT JOIN pagetag ON page.id = pagetag.pageid
)
LEFT JOIN tag ON pagetag.tagid = tag.id
GROUP BY page.id;
</code></pre>
<p>Not a very pretty query, but should give you what you want - <code>pagetag.id</code> and <code>group_concat(tag.name)</code> will be <code>null</code> for page 4 in the example you've posted above, but the page shall appear in the results.</p>
|
<p>I think you may need to use multiple updates.</p>
<p>Something like (not tested):</p>
<pre><code>select ID as 'PageId', Name as 'PageName', null as 'Tags'
into #temp
from [PageTable]
declare @lastOp int
set @lastOp = 1
while @lastOp > 0
begin
update p
set p.tags = isnull(tags + ', ', '' ) + t.[Tagid]
from #temp p
inner join [TagTable] t
on p.[PageId] = t.[PageId]
where p.tags not like '%' + t.[Tagid] + '%'
set @lastOp == @@rowcount
end
select * from #temp
</code></pre>
<p>Ugly though.</p>
<p>That example's T-SQL, but I think MySql has equivalents to everything used.</p>
| 5,849
|
<p>movie id tt0438097 can be found at <a href="http://www.imdb.com/title/tt0438097/" rel="noreferrer">http://www.imdb.com/title/tt0438097/</a></p>
<p>What's the url for its poster image?</p>
|
<p>As I'm sure you know, the actual url for that image is </p>
<p><a href="http://ia.media-imdb.com/images/M/MV5BMTI0MDcxMzE3OF5BMl5BanBnXkFtZTcwODc3OTYzMQ@@._V1._SX100_SY133_.jpg" rel="noreferrer">http://ia.media-imdb.com/images/M/MV5BMTI0MDcxMzE3OF5BMl5BanBnXkFtZTcwODc3OTYzMQ@@._V1._SX100_SY133_.jpg</a></p>
<p>You're going to be hard pressed to figure out how it's generated though and they don't seem to have a publicly available API.</p>
<p>Screenscraping is probably your best bet.</p>
<p>The picture seems to generally be inside a div with <strong>class=photo</strong> and the name of the <strong>a</strong> tag is <em>poster</em>. </p>
<p>The image itself is just inside the <strong>a</strong> tag.</p>
|
<p>Now a days, all modern browser have "<strong>Inspect</strong>" section:</p>
<p>100% Correct for Google Chrome only:</p>
<ol>
<li>Take your cursor on image.</li>
<li>Right click on it, select "<strong>Inspect Element</strong>".</li>
<li>In the window appear, under <strong>Elements</strong> tab you will find the highlighted text as
</li>
<li>Just click on it.</li>
<li>In the Resource tab, right click on image.</li>
<li>Select "<strong>Copy image URL</strong>" option.</li>
</ol>
<p>Try to paste it any where as URL in any browser, you will only get the image.</p>
| 18,233
|
<p>Several questions are related to first layer calibration or issues: I found 43 of them with "first layer" in the title alone, 150 with "first layer" anywhere (no duplicates).</p>
<p>I propose adding a "first-layer" tag to more easily retrieve said questions.</p>
<p>I already applied it to my latest question without thinking about it, but I can remove it if desired.</p>
|
<p>I think the <a href="https://3dprinting.stackexchange.com/questions/tagged/adhesion" class="post-tag" title="show questions tagged 'adhesion'" rel="tag">adhesion</a> tag should be used instead.</p>
|
<p>Yes, I support this idea. A <a href="https://3dprinting.stackexchange.com/questions/tagged/first-layer" class="post-tag" title="show questions tagged 'first-layer'" rel="tag">first-layer</a> tag would be useful.</p>
| 76
|
<p>Ok: This is some of my table structure that matters here</p>
<pre><code>CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)
</code></pre>
<p>Part of my procedure</p>
<pre><code>Declare @Temp table(CaseStudyID int,
Title nvarchar(50))
Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title
Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going
Select * From @Temp
</code></pre>
<p>Can anyone help?</p>
|
<p>I'm not sure whether you need every single row of the orginal table. So here is my alternative solution which gives you every row:</p>
<pre><code>SELECT CaseStudyID, Title
FROM CaseStudy c1
WHERE NOT EXISTS (
SELECT * FROM CaseStudy c2
WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title
)
UNION ALL
SELECT CaseStudyID, OverrideTitle
FROM CaseStudy c1
WHERE exists (
SELECT * FROM CaseStudy c2
WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title
)
ORDER BY Title
</code></pre>
|
<p>You could achieve it without using tempory table this way:</p>
<pre><code>SELECT
MIN(CaseStudyID) AS CaseStudyID,
CASE WHEN count(*) = 1 THEN
MIN(Title)
ELSE
MIN(OverrideTitle)
END AS Title
FROM CaseStudy
GROUP BY Title
ORDER BY Title
</code></pre>
| 28,838
|
<p>Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions?</p>
<p>Example:</p>
<pre><code>a = 1 AND (b = 1 OR b = 2)
</code></pre>
<p>The expression as a whole shouldn't be stored as varchar to preserve data integrity.</p>
|
<p>Option 1 would be to use a nested table (a tree with id / parent_id structure), like Gamecat suggested. This is relatively expensive to do, and requires issuing SQL queries repetitively to build the equivalent of a single nested expression.</p>
<p>Option 2 would be to use a serialized object and store it into a varchar column. For example, JSON would be a good choice. It is not white-space sensitive, can be created and parsed in a vast number of languages, and it retains data integrity.</p>
<p>As soon as you have parsed your expression string into a tree object in memory, you can serialize it and store it. If there was no need to manipulate the expression on the database level, I guess I would go that route.</p>
|
<p>Adding to @Gamechat answer</p>
<p>I think it should be like this</p>
<p>ID </p>
<p>TypeExpression (and, or etc...) </p>
<p>FirstChildID --This can be a leaf node or a pointer to another row in same table</p>
<p>SecondChildID --This can be a leaf node or a pointer to another row in same table</p>
<p>isFirstChildLeaf</p>
<p>isSecondChildLeaf</p>
| 32,736
|
<p>I restored my development database from production, and the stored procedures I need in my development environment doesn't exist in my production database. Is there a command Ii can use to import the developmetn stored procedures back into SQL Server. There are about 88 files, as each procedure is in a different text file.</p>
<p>TIA!
Chris</p>
|
<p>Oops, you did the painful way of generating scripts. You should have created a single script for all procedures by right clicking on the database in SSMS, choosing Tasks -> Generate Scripts.</p>
<p>However, if you don't want to go through that process again, open up a cmd shell in the folder and remember those old batch file days:</p>
<pre><code>for %f in (*.sql) do sqlcmd -i %f
</code></pre>
<p>This should do the trick!
You could add other parameters to sqlcmd if required (i.e. login, password, server name, ...). To see a list of switches just do a <code>sqlcmd -h</code>.</p>
|
<p>Right click on the development database Hit Generate SQL Scripts and then only select stored precedures. If you need need additional filtering you can even select the stored procedures you dont want.</p>
<p>Then just run that query on development.</p>
| 49,587
|
<p>What's the best way to combine results sets from disparate data sources in SSRS?</p>
<p>In my particular example, I need to write a report that pulls data from SQL Server and combines it with another set of data that comes from a DB2 database. In the end, I need to join these separate data sets together so I have one combined dataset with data from both sources combined on to the same rows. (Like an inner join if both tables were coming from the same SQL DB). I know that you can't do this "out of the box" in SSRS 2005. I'm not excited about having to pull the data into a temporary table on my SQL box because users need to be able to run this report on demand and it seems like having to use SSIS to get the data into the table on demand will be slow and hard to manage with multiple users trying to get at the report simultaneously. Are there any other, more elegant solutions out there?</p>
<p>I know that the linked server solution mentioned below would technically work, however, for some reason our DBAs will simply not allow us to use linked servers.</p>
<p>I know that you can add two different data sets to a report, however, I need to be able to join them together. Anybody have any ideas on how to best accomplish this?</p>
|
<p>We had to do something similar (i.e. inner join 2 data sources from different servers). I believe the best way is to write your own custom Data Extension. It's not very difficult and it would give you the ability to do this and more.</p>
|
<p>You could attach both the MSSQL tables and the DB2 tables to a Jet database and bind your report to the Jet database. I don't know the implications of the single threaded nature of Jet, or how much work would be delegated to the backing stores.</p>
| 5,575
|
<p>I want to intercept a request in a filter/servlet and add a few parameters to it. However, the request does not expose a 'setParameter' method and the parameter map when manipulated throws an error saying it is locked. Is there an alternative I can try?</p>
|
<p>Subclass <a href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequestWrapper.html" rel="noreferrer"><code>HttpServletRequestWrapper</code></a> and override the <code>getParameter</code> methods. The description of this class reads:</p>
<blockquote>
<p>Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet.</p>
</blockquote>
<p>In the filter, wrap the request in an instance of your subclass.</p>
|
<p>Otherwise, you can use the setAttribute() method which is strongly typed. Therefore, the getAttribute() method can be used ...</p>
| 23,167
|
<p>We need some input on what is a good design pattern on using AJAX in a Java application. </p>
<p><strong>Consider a simple scenario:</strong></p>
<ol>
<li>User clicks a button which sends a request to a Java method to fetch data from DB.</li>
<li>Java object is returned by method and needs to be converted into a HTML table.</li>
<li>HTML table is shown on JSP.</li>
</ol>
<p><strong>What we currently do:</strong></p>
<ol>
<li>On a JSP page, user clicks "Show Users" button</li>
<li>Button using Prototype.js calls a "middleman" JSP which forwards the request to the Java method to get the data from the DB.</li>
<li>The method returns the Java object to the "middleman" JSP which converts the Java object into HTML (since the AJAX call from the calling JSP won't be able to handle the Java object directly).</li>
<li>The HTML is then returned to the Prototype call which updates the div on the calling JSP.</li>
</ol>
<p><strong>Our concerns are:</strong></p>
<ol>
<li>We would like to keep the separation of business/presentation logic and would prefer no HTML/JavaScript code inside our Java methods.</li>
<li>Keeping (1) in mind, is having a "middleman" JSP an OK way to do this? Or should we return the Java object as XML/XSLT to the AJAX request?</li>
<li>The above way we're doing has very little JavaScript and works in all browsers.</li>
<li>We looked at some other packages - DWR, GWT, but either there was too much dependency on JavaScript or required UI components to be present in the Java classes.</li>
</ol>
<p>Is our way of doing things above OK? Or is there another preferable way?</p>
<p>Any help/thoughts would be appreciated.</p>
<p>Thanks,</p>
<p>SP</p>
|
<p>Sounds fine. You are separating view components from model components. It shouldn't matter how the call comes to the server, AJAX or not, it should be received by a controller (a servlet say) that interacts with the model, thats your Java classes that get the data from the database and forward to a JSP page for rendering the view.</p>
<p>There are frameworks that could simplify the boilerplate code but the design you describe sounds fine.</p>
|
<p>I'm not sure if you noticed, but there's one significant difference between your solution and what Vincent proposed. This is that the request should be initially received by a servlet (or controller, or Struts action, etc.) rather than a "middleman" JSP.</p>
<p>MVC dictates that JSPs should really only we used for generating the view from the model data, flow control is better handled in Java code.</p>
| 34,041
|
<p>In Visual Studio 2005, whenever I would view a file in the main editor, the Solution Explorer would find and highlight that file. Some time ago, this stopped working and the Solution Explorer would do nothing.</p>
<p>This has become quite a pain since following a chain of "Go To Definition"s can lead you all over your solution. Where is the setting to turn this back on?</p>
|
<p>Click on the Tools → Options menu. Select the Projects and Solutions → General option page.</p>
<p>Make sure "Track active item in Solution Explorer" is checked. That should do it.</p>
|
<p>Tools->Options->Project and Solutions->General</p>
<p>Check the box "Track Active Item in Solution Explorer"</p>
| 5,107
|
<p>I was working on some code recently and came across a method that had 3 for-loops that worked on 2 different arrays. </p>
<p>Basically, what was happening was a foreach loop would walk through a vector and convert a DateTime from an object, and then another foreach loop would convert a long value from an object. Each of these loops would store the converted value into lists.</p>
<p>The final loop would go through these two lists and store those values into yet another list because one final conversion needed to be done for the date. </p>
<p>Then after all that is said and done, The final two lists are converted to an array using ToArray().</p>
<p>Ok, bear with me, I'm finally getting to my question. </p>
<p>So, I decided to make a single for loop to replace the first two foreach loops and convert the values in one fell swoop (the third loop is quasi-necessary, although, I'm sure with some working I could also put it into the single loop). </p>
<p>But then I read the article "What your computer does while you wait" by Gustav Duarte and started thinking about memory management and what the data was doing while it's being accessed in the for-loop where two lists are being accessed simultaneously. </p>
<p>So my question is, what is the best approach for something like this? Try to condense the for-loops so it happens in as little loops as possible, causing multiple data access for the different lists. Or, allow the multiple loops and let the system bring in data it's anticipating. These lists and arrays can be potentially large and looping through 3 lists, perhaps 4 depending on how ToArray() is implemented, can get very costy (O(n^3) ??). But from what I understood in said article and from my CS classes, having to fetch data can be expensive too. </p>
<p>Would anyone like to provide any insight? Or have I completely gone off my rocker and need to relearn what I have unlearned?</p>
<p>Thank you</p>
|
<p>The best approach? Write the most readable code, work out its complexity, and work out if that's actually a problem.</p>
<p>If each of your loops is O(n), then you've still only got an O(n) operation.</p>
<p>Having said that, it does sound like a LINQ approach would be more readable... and quite possibly more efficient as well. Admittedly we haven't seen the code, but I suspect it's the kind of thing which is <em>ideal</em> for LINQ.</p>
|
<p>Thank you every one for the information. Thinking in terms of Big-O and how to optimize has never been my strong point. I believe I am going to put the code back to the way it was, I should have trusted the way it was written before instead of jumping on my novice instincts. Also, in the future I will put more reference so everyone can understand what the heck I'm talking about (clarity is also not a strong point of mine :-/).</p>
<p>Thank you again.</p>
| 43,562
|
<p>I am new to 3D printing and just purchased an Ender 3 V2 about two weeks ago. Since I've got it, I've been having trouble leveling the bed. I've tried watching videos, but they don't say how much friction on the paper is good or bad. I have even tried foil, playing cards, and a business card but still can't tell if it's good enough or not. Then when I would try printing calibration squares and adjust as it prints, but when it prints all looks good when printing the outside ring, but when it gets to the square parts there are bumps on the print from the nozzle being too close. Also when I seem to have corner perfect, when it gets to the center it's too close to the nozzle and doesn't even print. I'm using the stock glass bed so I'm not sure if that could be the issue. This is getting frustrating as I really want to start printing. And I want to save money for other parts and try avoiding purchasing a BL Touch if I don't need to. Am I doing something wrong? How can I get this resolved?</p>
<p>Forgot to mention, I upgraded the springs to these yellow ones on Amazon.</p>
|
<p>Step 1: stop using paper and get some feeler gauges. The gauge should be able to just barely pass under the HEATED nozzle.</p>
<p>Step 2: What are you using for bed adhesion? I use Elmer's white glue. After you think you've trammed (aka levelled) the bed, apply a generous layer of the glue in a coat on the bed. Let it dry.</p>
<p>Step 3: Verify bed level with a large square print that will cause the head to move to the outermost parts of the bed. Stop the print after a few outlines. Try to remove the print. If some areas are easier to remove than others, apply another coat of Elmer's glue to those areas.</p>
<p>Note: Do not hold down all four (4) corners of the glass bed. The aluminium plate is not going to be flatter than the glass. Only attach the glass to the bed on one side of the bed. I use the side that is furthest from the nozzle.</p>
|
<p>Don't worry too much about it. If you print with a first layer height of 0.3mm, bed levelling only needs to be approximate. If that doesn't work, and you cannot get good bed adhesion, try printing onto blue painter's tape (ScotchBlue). This makes a very forgiving build surface. You will need to clean it well with isopropyl alcohol (or acetone), since it is coated with a wax-based release agent that may prevent the filament from sticking. Once you have got used to printing, you can then refine your bed-levelling techniques.</p>
| 1,801
|
<p>I have a class that processes a 2 xml files and produces a text file. </p>
<p>I would like to write a bunch of unit / integration tests that can individually pass or fail for this class that do the following:</p>
<ol>
<li>For input A and B, generate the output.</li>
<li>Compare the contents of the generated file to the contents expected output</li>
<li>When the actual contents differ from the expected contents, fail and display some <strong>useful</strong> information about the differences.</li>
</ol>
<p>Below is the prototype for the class along with my first stab at unit tests.</p>
<p><strong>Is there a pattern I should be using for this sort of testing, or do people tend to write zillions of TestX() functions?</strong></p>
<p><strong>Is there a better way to coax text-file differences from NUnit?</strong> Should I embed a textfile diff algorithm?</p>
<hr>
<pre><code>class ReportGenerator
{
string Generate(string inputPathA, string inputPathB)
{
//do stuff
}
}
</code></pre>
<hr>
<pre><code>[TextFixture]
public class ReportGeneratorTests
{
static Diff(string pathToExpectedResult, string pathToActualResult)
{
using (StreamReader rs1 = File.OpenText(pathToExpectedResult))
{
using (StreamReader rs2 = File.OpenText(pathToActualResult))
{
string actualContents = rs2.ReadToEnd();
string expectedContents = rs1.ReadToEnd();
//this works, but the output could be a LOT more useful.
Assert.AreEqual(expectedContents, actualContents);
}
}
}
static TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
[Test]
public void TestX()
{
TestGenerate("x1.xml", "x2.xml", "x-expected.txt");
}
[Test]
public void TestY()
{
TestGenerate("y1.xml", "y2.xml", "y-expected.txt");
}
//etc...
}
</code></pre>
<hr>
<h2>Update</h2>
<p>I'm not interested in testing the diff functionality. I just want to use it to produce more readable failures.</p>
|
<p>As for the multiple tests with different data, use the NUnit RowTest extension:</p>
<pre><code>using NUnit.Framework.Extensions;
[RowTest]
[Row("x1.xml", "x2.xml", "x-expected.xml")]
[Row("y1.xml", "y2.xml", "y-expected.xml")]
public void TestGenerate(string pathToInputA, string pathToInputB, string pathToExpectedResult)
{
ReportGenerator obj = new ReportGenerator();
string pathToResult = obj.Generate(pathToInputA, pathToInputB);
Diff(pathToExpectedResult, pathToResult);
}
</code></pre>
|
<p>Rather than call .AreEqual you could parse the two input streams yourself, keep a count of line and column and compare the contents. As soon as you find a difference, you can generate a message like...</p>
<blockquote>
<p>Line 32 Column 12 - Found 'x' when 'y' was expected</p>
</blockquote>
<p>You could optionally enhance that by displaying multiple lines of output</p>
<blockquote>
<p>Difference at Line 32 Column 12, first difference shown<br>
A = this is a t<strong>x</strong>st<br>
B = this is a t<strong>e</strong>sts</p>
</blockquote>
<p>Note, as a rule, I'd generally only generate through my code one of the two streams you have. The other I'd grab from a test/text file, having verified by eye or other method that the data contained is correct!</p>
| 17,182
|
<p>We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ.</p>
<p>Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)</p>
|
<p>If you are building your own expressions and compiling them, or using AsQueryable, then yes; the LINQ-generated methods will be a royal pain to debug.</p>
<p>You can save some pain by using small fragements of <em>actual</em> methods - at least something useful will show in the stack trace...</p>
<p>Another consideration is: rather than having one huge expression, if you can daisy-chain things a bit more you might have more idea (from the stack trace) where it is failing. The downside is performance - a Where(foo).Where(bar) is two delegate invokes, where-as Where(foo && bar) can be one.</p>
<p>One option might be to swap in a debug version of the extension methods; unfortunately it is a little inconvenient because <code>IQueryable<T></code> and <code>Queryable</code> are in the same namespace... this works, though...</p>
<p>Output first:</p>
<pre><code>>Where: x => ((x % 2) = 0)
<Where: x => ((x % 2) = 0)
>Count
'WindowsFormsApplication2.vshost.exe' (Managed): Loaded 'Anonymously Hosted DynamicMethods Assembly'
<Count
</code></pre>
<p>Code:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace Demo
{
using DebugLinq;
static class Program
{
static void Main()
{
var data = System.Linq.Queryable.AsQueryable(new[] { 1, 2, 3, 4, 5 });
data.Where(x => x % 2 == 0).Count();
}
}
}
namespace DebugLinq
{
public static class DebugQueryable
{
public static int Count<T>(this System.Linq.IQueryable<T> source)
{
return Wrap(() => System.Linq.Queryable.Count(source), "Count");
}
public static System.Linq.IQueryable<T> Where<T>(this System.Linq.IQueryable<T> source, Expression<Func<T, bool>> predicate)
{
return Wrap(() => System.Linq.Queryable.Where(source, predicate), "Where: " + predicate);
}
static TResult Wrap<TResult>(Func<TResult> func, string caption)
{
Debug.WriteLine(">" + caption);
try
{
TResult result = func();
Debug.WriteLine("<" + caption);
return result;
}
catch
{
Debug.WriteLine("!" + caption);
throw;
}
}
}
}
</code></pre>
|
<p>Take a look at the <a href="http://weblogs.asp.net/rosherove/archive/2007/11/02/debugger-visualizers-for-methodinfo-dynamicmethod-and-methodbase.aspx" rel="nofollow noreferrer">debug visualizer</a> for dynamic methods originally developed by <a href="http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx" rel="nofollow noreferrer">Haibo Luo</a> and taken further by <a href="http://weblogs.asp.net/rosherove/archive/2006/04/25/MethodsVisualizer.aspx" rel="nofollow noreferrer">Roy Osherove</a></p>
| 30,537
|
<p>I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query. </p>
<p>Is this a decent practice or should I be checking for the error in between every query?</p>
<p>Thanks! </p>
<pre><code>$mysqli->autocommit(FALSE);
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
if ( 0==$mysqli->errno ) {
$mysqli->commit();
} else {
$mysqli->rollback();
// Handle error
}
</code></pre>
|
<p>mysqli_errno — Returns the error code for <strong>the most recent function call</strong>.</p>
|
<p>No you have to check in between every query because it will always give you error for last query only... So if your first query failed and last execute properly then you will not get error... so check after all query one by one not at last...</p>
| 41,300
|
<p>I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download. What's the best / most efficient way to build such a text file on a .net web server?</p>
<p>Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file.</p>
<p>Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly. Thanks, all!</p>
|
<p>The answer will depend on whether, as Forgotten Semicolon mentions, you need repeated downloads or once-and-done throwaways.</p>
<p>Either way, the key will be to set the content-type of the output to ensure that a download window is displayed. The problem with straight text output is that the browser will attempt to display the data in its own window.</p>
<p>The core way to set the content type would be something similar to the following, assuming that text is the output string and filename is the default name you want the file to be saved (locally) as.</p>
<pre><code>HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/octet-stream";
response.Charset = "";
response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", filename));
response.Flush();
response.Write(text);
response.End();
</code></pre>
<p>This will prompt a download for the user.</p>
<p>Now it gets trickier if you need to literally save the file on your web server -- but not terribly so. There you'd want to write out the text to your text file using the classes in System.IO. Ensure that the path you write to is writable by the Network Service, IUSR_MachineName and ASPNET Windows users. Otherwise, same deal -- use content type and headers to ensure download.</p>
<p>I'd recommend not literally saving the file unless you need to -- and even then, the technique of doing so directly on the server may not be the right idea. (EG, what if you need access control for downloading said file? Now you'd have to do that outside your app root, which may or may not even be possible depending on your hosting environment.)</p>
<p>So without knowing whether you're in a one-off or file-must-really-save mode, and without knowing security implications (which you'll probably need to work out yourself if you really need server-side saves), that's about the best I can give you.</p>
|
<p>Bear in mind it doesn't ever need to be a 'file' at the server end. It's the client which turns it into a file.</p>
| 15,782
|
<p>When using tables in a CSS-based layout, I've noticed if I have a table with 4 columns (2 on the side are small for spacing, 2 in the middle are for content), when I type content in one of the two middle columns, it will stay at the top, which is perfect.</p>
<p>However, if I type content in the other middle column, and press enter, the content in the other middle content will come down.</p>
<p>This means I can never type content in the two columns while keeping the content in both columns glued to the top (roof) of the table column. I have tried everything, is there a way I can do this? If I can't do this, my content looks wonky as it's not level in the two columns, and thus unprofessional.</p>
|
<p>I believe the solution would be to create a rule which aligns text to the top of table cells.</p>
<pre><code>td {
vertical-align:top;
}
</code></pre>
<p>As an alternative, you can use column groups and columns to specify the vertical alignment of different columns. An example:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Table Columns Alignments</title>
</head>
<body>
<table>
<colgroup>
<col valign="bottom"/>
<col />
<col valign="top"/>
</colgroup>
<tbody>
<tr>
<td>aligned to bottom</td>
<td>no special<br/>alignment<br/><p>here</p></td>
<td>aligned to top</td>
</tr>
</tbody>
</table>
</body>
</html>
</code></pre>
<p>However, the browser support for this is not across the board, so YMMV.</p>
|
<p>I'm not sure if I understand the problem entirely but you could look at the <a href="http://www.w3schools.com/Css/pr_pos_vertical-align.asp" rel="nofollow noreferrer">vertical-align css property</a>.</p>
| 39,520
|
<p>My CR-10 is starting prints, BUT then makes weird spiral pattern, layers go up vertically with large gaps. Hollow infill.</p>
<p><img src="https://i.stack.imgur.com/cQynM.jpg" alt="wierd vertical spiral layering pattern">
<img src="https://i.stack.imgur.com/bEbhg.jpg" alt="printed fine at base then randomly happened">
<img src="https://i.stack.imgur.com/kkMB3.jpg" alt="This one was printing the weird pattern at base but not as obviously, but got worse about six inches up until it made the top completely hollow"></p>
<p>I don’t know if it’s:
- My Slicing skills
- original files
- the printer itself
Long explanation. Questions at the end. I’ve had beautiful normal prints. Then I’ve had these abnormal spiral layer prints with infill issues and spaghetti monsters (the images don’t show but, where the prints pictured end, is not the full print, it did the weird spiral then just stopped layering altogether). I’m semi-new to printing and don’t have too much of a tech background apart from average use. Been researching a couple months, I’ve only been printing for about a week. I’ve had an amazing couple prints. Baby groot was flawless, barely noticeable layers. The test print (a rather thick disk with deep grid marks and a puppy on top) that came with the printer was the same smooth flawless, it wasn’t my first print though. So the behavior seems erratic. The two prints pictured had several successful print in between them. </p>
<p>I do know:</p>
<p>The elder wand file was in several tutorials and was printed successfully. Its in two parts. The first part, which is way shorter and thicker printed Amazingly. The second part pictured was double the height+ and 1/4 the thickness. I even printed it successfully once before going horizontally and flat against the bed. BUT I had to run the print three times because the filament would not stick to the glass. It was just being dragged along behind the nozzle. But I was observing so I ended the print before it went too far. All I did to change this was add a brim and supports. Which gave a “successful print” except the fact that one of the knobs has a flat spot and the support remnants were very noticeable. Resolution was terrible too. Hence why I decided to try printing it vertically.</p>
<p>The bigger print pictured is the base of a hufflepuff horecrux cup, the first time I printed it was with cura slicer, it came out beautifully but the stem snapped right under the base of the cup part st some point, and the left handle had some wierd stringing issues, like 7 pure strands of filament hanging out one corner, and the print failed s fee layers from top. However the file description only had one previous make listed and the thing with the top of the handle and print failed about the same with that persons print.</p>
<p>Sorry for the long post. I’d just really appreciate any help, and I wanted to give all the details.</p>
|
<p><sub>This is partial answer and comment as it was too big to fit the comment section, it will be a proper answer once the question is updated by the OP.</sub></p>
<p>What you call a weird spiral pattern is the result of under-extrusion. When there is under-extrusion, the resulting print is sparsely filled. The reason for this under-extrusion is most probably partial clogging of the nozzle, or an issue with the extruder itself. One explanation could be that you are suffering from heat creep, but the information you provide is not enough to explain this or any other solution further in detail. Clogging can e.g. be caused by retraction settings and/or temperature settings, without your settings it is a guess what this is actually causing this.</p>
<hr />
<p>Looking at the print deteriorate the higher the Z becomes this is most probably a heat creep issue, so you print too hot with too large retraction settings.</p>
|
<p>While uncommon, this issue could be caused by having no minimum layer time set. This could lead to printing on a still very hot surface, which in turn ripples and moves, creating a little wave pattern. The wave pattern then can grow into this diagonal pattern.</p>
<p>You might manage to reduce the issue by setting a minimum layer time of 10 to 15 seconds.</p>
| 1,191
|
<p>I have a command-line process I would like to automate and capture in C#.</p>
<p>At the command line, I type:</p>
<pre><code>nslookup
</code></pre>
<p>This launches a shell which gives me a > prompt. At the prompt, I then type:</p>
<pre><code>ls -a mydomain.local
</code></pre>
<p>This returns a list of local CNAMEs from my primary DNS server and the physical machines they are attached to.</p>
<p>What I would like to do is automate this process from C#. If this were a simple command, I would just use Process.StartInfo.RedirectStandardOutput = true, but the requirement of a second step is tripping me up.</p>
|
<pre><code>ProcessStartInfo si = new ProcessStartInfo("nslookup");
si.RedirectStandardInput = true;
si.RedirectStandardOutput = true;
Process nslookup = new Process(si);
nslookup.Start();
nslookup.StandardInput.WriteLine("ls -a mydomain.local");
nslookup.StandardInput.Flush();
// use nslookup.StandardOutput stream to read the result.
</code></pre>
|
<p>I know this is an old one, but still like to contribute.
I used the shell output from "NsLookup Hostname Server" to get the IPv4 addresses from a computername in our domain and strip out any other information like DNS server / ipv6 addresses..</p>
<p>This is kinda quickly done but it works, there is also a failover added if the shell fails that you would use the built in nslookup method from C#.</p>
<p>it is rather long but it gave me the possibility to read the ipv4 from the shell without using an external library or without using the built in nslookup function as it does allow to choose the dns server.</p>
<p>If you are wondering about the if loops in the middle, there might be more elegant solutions but for my personal use, this worked out quite well, most hosts in our domain returned 2 ipv6 and 2 ipv4, therefore, it test up to 4 times.</p>
<p>Hope this can help..</p>
<pre><code> private void button1_Click(object sender, EventArgs e)
{
IPAddress[] ips = NsLookup(computername, dnsserver);
txtResult.Text = string.Empty;
if (ips != null)
{
txtResult.Text = ips[0].ToString();
txtResult.Text += Environment.NewLine;
if (ips[1] != null)
{
txtResult.Text += ips[1].ToString();
}
else
{
}
}
else
{
txtResult.Text = "No IP found";
}
}
public IPAddress[] NsLookup(string computername, string domaincontroller)
{
IPAddress[] ips = new IPAddress[2];
try
{
// Creating streamreaders to read the output and the errors
StreamReader outputReader = null;
StreamReader errorReader = null;
string nslookup = @"C:\Windows\System32\Nslookup.exe";
try
{
// Setting process startupinfo
ProcessStartInfo processStartInfo = new ProcessStartInfo(nslookup, computername + " " + domaincontroller);
processStartInfo.ErrorDialog = false;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Minimized;
// Starting Process
Process process = new Process();
process.StartInfo = processStartInfo;
bool processStarted = process.Start();
if (processStarted)
{
// Catching the output streams
outputReader = process.StandardOutput;
errorReader = process.StandardError;
string errorresult = errorReader.ReadLine();
errorReader.Close();
if (errorresult != null)
{
// Failure got thrown in NsLookup Streamreading, try build-in Method
try
{
ips = Dns.GetHostAddresses(computername);
return ips;
}
catch
{
return null;
}
}
else
{
// Clearing out all the values before the addresses.
outputReader.ReadLine();
outputReader.ReadLine();
outputReader.ReadLine();
outputReader.ReadLine();
// Reading and Verifying the first outputline (the address is found after "Addresses: ") - 2 part of the array is taken (after second space)
string outputline = outputReader.ReadLine();
string[] outputlineaftersplit = outputline.Split(' ');
string ipfortesting = outputlineaftersplit[2].Trim();
if (verifyIP(ipfortesting) != null) // First entry is ipv4
{
ips[0] = verifyIP(ipfortesting);
outputline = outputReader.ReadLine();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null) // First and second entry are ipv4
{
ips[1] = verifyIP(ipfortesting);
return ips;
}
else
{
return ips;
}
}
else
{
outputline = outputReader.ReadLine();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null)
{
ips[0] = verifyIP(ipfortesting);
outputline = outputReader.ReadLine();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null)
{
ips[0] = verifyIP(ipfortesting);
outputline = outputReader.ReadLine();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null)
{
ips[1] = verifyIP(ipfortesting);
return ips;
}
else
{
return ips;
}
}
else
{
return ips;
}
}
else
{
outputline = outputReader.ReadLine();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null)
{
ips[0] = verifyIP(ipfortesting);
outputline = outputReader.ReadToEnd();
ipfortesting = outputline.Trim();
if (verifyIP(ipfortesting) != null)
{
ips[1] = verifyIP(ipfortesting);
return ips;
}
else
{
return ips;
}
}
else
{
ips = null;
return ips;
}
}
}
}
}
else
{
// Failure got thrown in NsLookup Streamreading, try build-in Method
try
{
ips = Dns.GetHostAddresses(computername);
return ips;
}
catch
{
return null;
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("ERROR 1");
// Failure got thrown in NsLookup Streamreading, try build-in Method
try
{
ips = Dns.GetHostAddresses(computername);
return ips;
}
catch
{
return null;
}
}
finally
{
if (outputReader != null)
{
outputReader.Close();
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("ERROR 2");
// Failure got thrown in NsLookup Streamreading, try build-in Method
try
{
ips = Dns.GetHostAddresses(computername);
return ips;
}
catch
{
return null;
}
}
}
public IPAddress verifyIP(string ipfromreader)
{
IPAddress ipresult = null;
bool isIP = IPAddress.TryParse(ipfromreader, out ipresult);
if (isIP && (ipresult.AddressFamily != AddressFamily.InterNetworkV6))
{
return ipresult;
}
else
{
return null;
}
}
}
</code></pre>
<p>}</p>
| 46,057
|
<p>What is the best MemCache solution for ASP.NET applications running in a windows server environment? Why?</p>
|
<p>You could also check out <a href="http://code.msdn.microsoft.com/velocity" rel="nofollow noreferrer">Microsoft Velocity</a>, especially if you're at a place that prefers Microsoft products.</p>
|
<p>My sentiments exactly - <a href="https://stackoverflow.com/questions/161106/distributed-cachesession-where-should-i-turn">My Question</a></p>
<p>From what I've gathered, <a href="http://sourceforge.net/projects/memcacheddotnet/" rel="nofollow noreferrer">memcacheddotnet</a> is the best free options,
<a href="http://www.scaleoutsoftware.com/" rel="nofollow noreferrer">scaleout</a> if you want to pay</p>
| 19,560
|
<p>My main JavaScript framework is <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>, so I would like my unit test and mocking frameworks to be compatible with that. I'd rather not have to introduce another JavaScript framework.</p>
<p>I am currently using <a href="http://docs.jquery.com/QUnit" rel="nofollow noreferrer">QUnit</a> for unit testing and <a href="https://github.com/keronsen/jack" rel="nofollow noreferrer">Jack</a> for mocking, but I am pretty new to the whole unit testing of JavaScript.</p>
<p>Is there a better tool to suggest? What has worked for you?</p>
|
<p><a href="http://docs.jquery.com/QUnit" rel="nofollow noreferrer">QUnit</a> <br/>
<a href="http://code.google.com/p/jqunit/" rel="nofollow noreferrer">jqUnit</a> <br/>
<a href="http://wiki.fluidproject.org/display/fluid/Writing+JavaScript+Unit+Tests" rel="nofollow noreferrer">Writing JavaScript tests with QUnit and jqUnit</a></p>
<p>QUnit is the unit testing framework for the jQuery JavaScript framework. The testing framework itself uses the jQuery library, but the tests can be written for any JavaScript and do not require the code to use jQuery.</p>
<p>jqUnit is a modified version of QUnit that adds in the setup, teardown, and assert functions that are more typical of an xUnit framework, and encapsulates everything in one global variable.</p>
<p>The visual interface of the testrunner page is nice, allowing you to drill down and see each assert in every test method. Writing tests is fairly easy, and you can run the test code directly on the testRunner page [8]. This allows for easy and visible DOM testing.</p>
<p>QUnit: MIT or GPL (choose) jqUnit: MIT License</p>
<p><strong>Pros</strong></p>
<ul>
<li>Asynchronous support</li>
<li>Good for DOM testing</li>
<li>Tests always run sequentially in the order they are added to a suite</li>
<li>Debug on test page using firebug</li>
<li>Syntax is similar to JUnit if using jqUnit, but simple to learn if using QUnit</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>Automation would be difficult to implement</li>
</ul>
|
<p>I know you are asking for jQuery-compatible frameworks, but I want to throw <a href="http://github.com/madrobby/scriptaculous/wikis" rel="nofollow noreferrer">script.aculo.us</a> into the mix for completeness. They have a <a href="http://github.com/madrobby/scriptaculous/wikis/unit-testing" rel="nofollow noreferrer">unit test</a> suite that isn't bad.</p>
| 25,701
|
<p>I would like to monitor a log file that is being written to by an application. I want to process the file line by line as, or shortly after, it is written. I have not found a way of detecting that a file has been extended after reaching eof.</p>
<p>The code needs to work on Mac and PC, and can be in any language, though I am most familiar with C++ and Perl.</p>
<p>Does anybody have a suggestion for the best way to do it?</p>
|
<p>In Perl, the <a href="http://search.cpan.org/dist/File-Tail/" rel="noreferrer">File::Tail</a> module does exactly what you need.</p>
|
<p>I'd have thought outputting the actions via tee, and thence tail'ing (or using the loop <a href="https://stackoverflow.com/questions/62832#63446">above</a>) the file created by tee some use.</p>
| 8,833
|
<p>I currently work at a company that has a lot of custom applications that are made internally. There are not currently standards for a lot of things. I would like to implement a way to record/track errors that happen in this programs (most are asp.net).</p>
<p>I am currently thinking of handling this in the Global.asax in the Application Error method. First trying to save the information to an Error Log/Tracking database, and if that fails, try sending an e-mail.</p>
<p>What type of information is the most useful to get from the error message and other application variables (page, username etc).</p>
<p>I am currently thinking of using two tables, one to get the general error and application information, and a second that holds the exception information. This will be a one to many relationship to hand the inner Exceptions that can come from one Application level exception.</p>
<p>I am sure that I am missing a lot of details and would like to hear your strategy for handling this issue.</p>
|
<p>Jeff Atwood wrote a great Exception Handler that you should look at on <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">CodeProject</a></p>
<p>I would attempt to collect as much information as possible.
Stack Information
Session Information
Location of Error</p>
<p>I would also setup a webservice that the applications call to save off the exception information into your system.</p>
|
<p>It actually sounds like you've thought out the solution pretty well. </p>
<p>I work in web development shop, so in addition to logging errors, I also make sure that any system critical errors such as failing db query's and the like are also emailed so that we can jump on them and fix them right away. </p>
<p>An alternative to consider would be to email a report each day that provides information on each error thrown in each application and any relevant information that you would want in the email. </p>
<p>We log all of our errors into a single table for that application (of course that's easier to do when your working on applications where the databases are all contained in-house) including the timestamp of the error and the full text of the exception message that has also been emailed. </p>
<p>The exception message contains a function trace so you know what the original calling function was as well as file and line numbers for all functions in the stack. This makes back-tracking any given bug super simple.</p>
| 29,307
|
<p>Does combining an Enterprise Messaging solution with Web Services result in a real performance gain over simple HTTP requests over sockets?</p>
<p>(if implementation details will help, interested in JMS with a SOAP webservice)</p>
|
<p>yes, make a copy of the FlowDocument before printing it. This is because the pagination and margins will be different. This works for me.</p>
<pre><code> private void DoThePrint(System.Windows.Documents.FlowDocument document)
{
// Clone the source document's content into a new FlowDocument.
// This is because the pagination for the printer needs to be
// done differently than the pagination for the displayed page.
// We print the copy, rather that the original FlowDocument.
System.IO.MemoryStream s = new System.IO.MemoryStream();
TextRange source = new TextRange(document.ContentStart, document.ContentEnd);
source.Save(s, DataFormats.Xaml);
FlowDocument copy = new FlowDocument();
TextRange dest = new TextRange(copy.ContentStart, copy.ContentEnd);
dest.Load(s, DataFormats.Xaml);
// Create a XpsDocumentWriter object, implicitly opening a Windows common print dialog,
// and allowing the user to select a printer.
// get information about the dimensions of the seleted printer+media.
System.Printing.PrintDocumentImageableArea ia = null;
System.Windows.Xps.XpsDocumentWriter docWriter = System.Printing.PrintQueue.CreateXpsDocumentWriter(ref ia);
if (docWriter != null && ia != null)
{
DocumentPaginator paginator = ((IDocumentPaginatorSource)copy).DocumentPaginator;
// Change the PageSize and PagePadding for the document to match the CanvasSize for the printer device.
paginator.PageSize = new Size(ia.MediaSizeWidth, ia.MediaSizeHeight);
Thickness t = new Thickness(72); // copy.PagePadding;
copy.PagePadding = new Thickness(
Math.Max(ia.OriginWidth, t.Left),
Math.Max(ia.OriginHeight, t.Top),
Math.Max(ia.MediaSizeWidth - (ia.OriginWidth + ia.ExtentWidth), t.Right),
Math.Max(ia.MediaSizeHeight - (ia.OriginHeight + ia.ExtentHeight), t.Bottom));
copy.ColumnWidth = double.PositiveInfinity;
//copy.PageWidth = 528; // allow the page to be the natural with of the output device
// Send content to the printer.
docWriter.Write(paginator);
}
}
</code></pre>
|
<p>I am also generating a WPF report off a Flow document, but I am purposely using the flow document as a print preview screen. I there for want the margins to be the same. You can read about <a href="http://kiwiingenuity.net.nz/post/My-First-WPF-Report" rel="nofollow noreferrer">how I did this here</a>.</p>
<p>In your scenario I'm thinking why not just make a copy of your settings, instead of the entire flow document. You can then re-apply the settings if you wish to return the document back to it's original state. </p>
| 44,888
|
<p>I found this:</p>
<p><a href="http://www.evolt.org/failover-database-connection-with-php-mysql" rel="nofollow noreferrer">http://www.evolt.org/failover-database-connection-with-php-mysql</a></p>
<p>and similar examples. But is there a better way?</p>
<p>I am thinking along the lines of the <a href="http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD" rel="nofollow noreferrer">Automatic Failover Client</a> in the MS SQL Native Client.</p>
|
<p>It's traditional to handle failover strategies at the system level; that way all applications can enjoy a robust environment.</p>
<p>I'd like to refer to <a href="http://dev.mysql.com/tech-resources/articles/failover-strategy-part1.html" rel="nofollow noreferrer">MySQL failover strategy</a> and <a href="http://forge.mysql.com/wiki/MySQL_Proxy" rel="nofollow noreferrer">MySQL proxy</a>. The latter describes a MySQL utility that can do load balancing and failover, and seems quite easy to set up.</p>
<p>Not the answer to the question, but it is the more common solution to handle failover.</p>
|
<p>No, it does not have that build in. I think an easy way is to employ <a href="http://forge.mysql.com/wiki/MySQL_Proxy" rel="nofollow noreferrer">MySQL Proxy</a>. Otherwise, but the <em>logic</em> (<code>if (fails) { connect to another }</code>) in your application, but that's not so pretty and great in terms of performance.</p>
| 23,261
|
<p>I need to put the image from an NSProgressIndicator into an NSOutlineView Cell. I have written up code that does this for a determinate indicator and it works just great:</p>
<pre><code>NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)];
[progressIndicator setStyle:NSProgressIndicatorSpinningStyle];
[progressIndicator setIndeterminate:NO];
[progressIndicator setMaxValue:100.0];
[progressIndicator setDoubleValue:somePercentage];
NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]];
[progressIndicator release];
return [updateImage autorelease];
</code></pre>
<p>I have tried to modify the code to also give me indeterminate indicator images. However for the indeterminate case, I always get a blank 16x16 image. (I have confirmed this by writing the image to a file in each case, the determinate case gives me the progress indicator image, the indeterminate case is always 16x16 white square).</p>
<p>The modified code is:</p>
<pre><code>if(self.lengthUnknown)
{
NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)];
[progressIndicator setStyle:NSProgressIndicatorSpinningStyle];
[progressIndicator setIndeterminate:YES];
NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]];
[progressIndicator release];
return [updateImage autorelease];
}
else
{
// Same code as the first listing, this case works fine
}
</code></pre>
<p>Do indeterminate progress indicators use some type of drawing that causes -dataWithPDFInsideRect: to be unable to capture their image?</p>
<hr>
<p>More information: I tried setting the progress indicator to not use threaded animation as well as trying to grab the contents through NSImage's lockFocus method as suggested below but neither of those attempts made a difference.</p>
<p>The progress indicator cell code that Dave mentions below (<a href="http://www.harmless.de/cocoa-code.php" rel="nofollow noreferrer">AMIndeterminateProgressIndicatorCell</a>) is a great workaround, but I would still like to know why I can't use the same technique that works with the determinate mode.</p>
|
<p>I've used <a href="https://www.harmless.de/cocoa-code.php" rel="nofollow noreferrer">AMIndeterminateProgressIndicatorCell</a> for indeterminate progress indicators in cells. It's not a true NSProgressIndicator, as it does it's own drawing, but it's a pretty good replica, IMO.</p>
<p><a href="https://i.stack.imgur.com/KcXmM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KcXmM.png" alt="alt text"></a><br>
<sub>(source: <a href="http://www.harmless.de/images/progressindicator.png?harmless=e55652fb0a6b5e2d88a22e9b37c9bbc1" rel="nofollow noreferrer">harmless.de</a>)</sub> </p>
|
<p>Progress indicators do use a background thread to keep their animation drawing even if the main thread is busy doing something else, so it's possible that's what's causing the problem. You might try calling setUsesThreadedAnimation:NO on the progress indicator before doing your drawing to see if that makes a difference.</p>
<p>Another tact would be to create a blank NSImage, and then call the progress indicator's drawRect: method to render its contents into the image buffer. That would look something like:</p>
<pre>
NSProgressIndicator* progressIndicator;
NSImage* image = [[NSImage alloc] initWithSize:[progressIndicator bounds].size];
[image lockFocus];
[progressIndicator drawRect:[progressIndicator bounds]];
[image unlockFocus];
</pre>
| 32,842
|
<p>Anyone got a working example of using ruby to post to a presigned URL on s3</p>
|
<p>I have used aws-sdk and right_aws both.</p>
<p>Here is the code to do this.</p>
<pre><code>require 'rubygems'
require 'aws-sdk'
require 'right_aws'
require 'net/http'
require 'uri'
require 'rack'
access_key_id = 'AAAAAAAAAAAAAAAAA'
secret_access_key = 'ASDFASDFAS4646ASDFSAFASDFASDFSADF'
s3 = AWS::S3.new( :access_key_id => access_key_id, :secret_access_key => secret_access_key)
right_s3 = RightAws::S3Interface.new(access_key_id, secret_access_key, {:multi_thread => true, :logger => nil} )
bucket_name = 'your-bucket-name'
key = "your-file-name.ext"
right_url = right_s3.put_link(bucket_name, key)
right_scan_command = "curl -I --upload-file #{key} '#{right_url.to_s}'"
system(right_scan_command)
bucket = s3.buckets[bucket_name]
form = bucket.presigned_post(:key => key)
uri = URI(form.url.to_s + '/' + key)
uri.query = Rack::Utils.build_query(form.fields)
scan_command = "curl -I --upload-file #{key} '#{uri.to_s}'"
system(scan_command)
</code></pre>
|
<p>I've managed to sort it out. Turns out the HTTP:Net in Ruby is has some short comings. Lot of Monkeypatch later I got it working.. More details when I have time. thank</p>
| 11,554
|
<p>I have an abstract base class and I want to declare a field or a property that will have a different value in each class that inherits from this parent class. </p>
<p>I want to define it in the baseclass so I can reference it in a base class method - for example overriding ToString to say "This object is of type <i>property/field</i>".
I have got three ways that I can see of doing this, but I was wondering - what is the best or accepted way of doing this? Newbie question, sorry.</p>
<p><strong>Option 1:</strong><br>
Use an abstract Property and override it on the inherited classes. This benefits from being enforced (you have to override it) and it is clean. But, it feels slightly wrong to return a hard-code value rather than encapsulate a field and it is a few lines of code instead of just. I also have to declare a body for "set" but that is less important (and there is probably a way to avoid that which I am not aware of). </p>
<pre><code>abstract class Father
{
abstract public int MyInt { get; set;}
}
class Son : Father
{
public override int MyInt
{
get { return 1; }
set { }
}
}
</code></pre>
<p><strong>Option 2</strong><br>
I can declare a public field (or a protected field) and explicitly override it in the inherited class. The example below will give me a warning to use "new" and I can probably do that, but it feels wrong and it breaks the polymorphism, which was the whole point. Doesn't seem like a good idea...</p>
<pre><code>abstract class Mother
{
public int MyInt = 0;
}
class Daughter : Mother
{
public int MyInt = 1;
}
</code></pre>
<p><strong>Option 3</strong><br>
I can use a protected field and set the value in the constructor. This seems pretty tidy but relies on me ensuring the constructor always sets this and with multiple overloaded constructors there is always a chance some code path won't set the value.</p>
<pre><code>abstract class Aunt
{
protected int MyInt;
}
class Niece : Aunt
{
public Niece()
{
MyInt = 1;
}
}
</code></pre>
<p>It's a bit of a theoretical question and I guess the answer has to be option 1 as it is the only <i>safe</i> option but I am just getting to grips with C# and wanted to ask this of people with more experience.</p>
|
<p>Of the three solutions only <strong>Option 1</strong> is <strong>polymorphic</strong>. </p>
<p>Fields by themselves cannot be overridden. Which is exactly why <strong>Option 2</strong> returns the <strong><em>new</em></strong> keyword warning. </p>
<p>The solution to the warning is not to append the “new” keyword, but to implement Option 1. </p>
<p><strong>If you need your field to be polymorphic you need to wrap it in a Property.</strong></p>
<p><strong>Option 3</strong> is OK if you don’t need polymorphic behavior. You should remember though, that when at runtime the property MyInt is accessed, the derived class has no control on the value returned. The base class by itself is capable of returning this value.</p>
<p>This is how a truly polymorphic implementation of your property might look, allowing the derived classes to be in <em>control</em>.</p>
<pre><code>abstract class Parent
{
abstract public int MyInt { get; }
}
class Father : Parent
{
public override int MyInt
{
get { /* Apply formula "X" and return a value */ }
}
}
class Mother : Parent
{
public override int MyInt
{
get { /* Apply formula "Y" and return a value */ }
}
}
</code></pre>
|
<p>I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.</p>
<pre><code>abstract class Base
{
protected int myInt;
protected abstract void setMyInt();
}
class Derived : Base
{
override protected void setMyInt()
{
myInt = 3;
}
}
</code></pre>
<p>By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.</p>
<pre><code>abstract class Father
{
abstract public int MyInt { get; }
}
class Son : Father
{
public override int MyInt
{
get { return 1; }
}
}
</code></pre>
| 42,265
|
<p>I'm trying to use a generic list as a property of the users profile. I'll admit this is probably just making my life harder than it needs to be but I don't want to change the programming model just because the data store struggles.</p>
<p>I have this in my web.config</p>
<p>
</p>
<pre><code> </providers>
<properties>
.....
<add name="AListProperty" type="System.Collections.Generic.List`1[[System.Int32]]"/>
<add name="AnotherListProperty" type="System.Collections.Generic.List`1[[MyNamespace.Web.UI.MyReallySimpleClass]]">
</properties>
</profile>
</code></pre>
<p>The first property, "AListProperty" works fine. The second one throws a variety of exceptions depending on how I delcare it in the web.config. MyReallySimpleClass is public, serializable and consists of 2 public fields (at present)</p>
<p>So, my questions are
1. Does anyone know where the format for declaring these types in the web.config is documented.
2. What I'm doing wrong? It looks fine, I can't see any semantic difference between the two declarations.</p>
<p>Thanks</p>
|
<p>Try <code>VerticalAlignment="Top"</code> and <code>HorizontalAlignment="Left"</code> on your viewbox. It will cause it to be anchored to the top and left side.</p>
<pre><code><Grid>
<Viewbox VerticalAlignment="Top" HorizontalAlignment="Left">
...
</Viewbox>
</Grid>
</code></pre>
<p>If you want it to completely fill (but keep it uniform) you can use <code>Stretch="UniformToFill"</code></p>
|
<p>According to <a href="http://msdn.microsoft.com/en-us/library/ms741838.aspx" rel="nofollow noreferrer">MSDN</a> the Viewbox is used to stretch the child elements. Since the child elements would be stretched, you would have to set the content alignment of the children.</p>
<p>You may want to look at this for more information on the Viewbox: <a href="https://stackoverflow.com/questions/288954/how-do-i-keep-aspect-ratio-on-scalable-scrollable-content-in-wpf">How do I keep aspect ratio on scalable, scrollable content in WPF?</a></p>
| 44,470
|
<p>How do I declare a session variable in PL/SQL - one that will persist for the duration of the session only, without me having to store it in the database itself?</p>
|
<p>You create a package level variable. This is a minimal example:</p>
<pre><code>CREATE OR REPLACE PACKAGE my_package
AS
FUNCTION get_a RETURN NUMBER;
END my_package;
/
CREATE OR REPLACE PACKAGE BODY my_package
AS
a NUMBER(20);
FUNCTION get_a
RETURN NUMBER
IS
BEGIN
RETURN a;
END get_a;
END my_package;
/
</code></pre>
<p>If you do this you should read up on (and handle correctly) <code>ORA-04068</code> errors. Each database session will have it's own value for a. You can try this with:</p>
<pre><code>SELECT my_package.get_a FROM DUAL;
</code></pre>
|
<p>I like to use a <strong>short, but intuitive syntax</strong> and thus would create e.g. some <strong><code>ctx</code> package</strong> that just provides <strong>one function to set and get some global "variables"</strong>.<br>
(valid for the current session only ; in my case no need to implement it as user-created-context variables, but easily changeable to it under the hood ; example with some <code>foo varchar2</code> and <code>bar number</code> vars)</p>
<p><strong>usage</strong>:</p>
<pre><code>select ctx.foo from dual -- => null (init)
select ctx.foo('a') from dual -- => 'a'
select ctx.foo('b') from dual ; select ctx.foo from dual -- => 'b', 'b'
</code></pre>
<p>.</p>
<pre><code>-- (optimizer should cause the subquerys unselected columns not to be executed:)
select 'ups' from (select ctx.foo('a') from dual) ; select ctx.foo from dual -- => null
select ctx.bar(1.5) from dual ; select ctx.bar from dual -- => 1.5, 1.5
-- ...
</code></pre>
<p><strong>package header</strong>:</p>
<pre><code>create or replace package ctx as
-- select ctx.foo from dual -- => null (init)
-- select ctx.foo('a') from dual -- => 'a'
-- select ctx.foo('b') from dual ; select ctx.foo from dual -- => 'b', 'b'
-- (optimizer should cause the subquerys unselected columns not to be executed:)
-- select 'ups' from (select ctx.foo('a') from dual) ; select ctx.foo from dual
-- => null
-- parallel_enable for queries since it should not change inside of them
function foo( set varchar2 := null ) return varchar2 parallel_enable;
-- (samples like in foo above as executable test comments like in foo above skipped for
-- brevity)
function bar( set number := null ) return number parallel_enable;
end;
</code></pre>
<p><strong>package body</strong>:</p>
<pre><code>create or replace package body ctx as
foo_ varchar2(30); -- e.g. 'blabla'
bar_ number;
-- internal helper function for varchars
function set_if_not_null( ref in out varchar2, val varchar2 ) return varchar2 as
begin
if val is not null then ref := val; end if;
return ref ;
end;
-- internal helper function for numbers
function set_if_not_null( ref in out number, val number ) return number as begin
if val is not null then ref := val; end if;
return ref ;
end;
-- (same test comments like in foo above skipped for brevity)
function foo( set varchar2 := null ) return varchar2 parallel_enable as begin
return set_if_not_null( foo_, set ) ;
end;
-- (same test comments like in foo above skipped for brevity)
function bar( set number := null ) return number parallel_enable as begin
return set_if_not_null( bar_, set ) ;
end;
end;
</code></pre>
<p>If you know that the <strong>variable (<code>foo</code>) may change within a single query then remove <code>parallel_enable</code></strong>, which should otherwise be more performant if queries are parallelizable.</p>
<p>Depending on ones needs one could of course add some <code>foo_reset()</code> to set it to null etc..</p>
| 38,657
|
<p>What's the difference between a string and a symbol in Ruby and when should I use one over the other?</p>
|
<p>The main difference is that multiple symbols representing a single value are identical whereas this is not true with strings. For example:</p>
<pre><code>irb(main):007:0> :test.object_id
=> 83618
irb(main):008:0> :test.object_id
=> 83618
irb(main):009:0> :test.object_id
=> 83618
</code></pre>
<p>Those are three references to the symbol <code>:test</code>, which are all the same object.</p>
<pre><code>irb(main):010:0> "test".object_id
=> -605770378
irb(main):011:0> "test".object_id
=> -605779298
irb(main):012:0> "test".object_id
=> -605784948
</code></pre>
<p>Those are three references to the string "test", but are all different objects.</p>
<p>This means that using symbols can potentially save a good bit of memory depending on the application. It is also faster to compare symbols for equality since they are the same object, comparing identical strings is much slower since the string values need to be compared instead of just the object ids.</p>
<p>As far as when to use which, I usually use strings for almost everything except things like hash keys where I really want a unique identifier, not a string.</p>
|
<p>A symbol is something you use to represent names and strings. You would want to use a symbol when you may have need to use a string several times as this far easier and more productive.</p>
<p>And just found this via google, which may offer greater detail: <a href="http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols" rel="nofollow noreferrer">Here you go</a></p>
| 31,826
|
<p>The <strong><code>fuser</code></strong> command lets me know which processes are using a file or directory.</p>
<p>I'm looking for command that does the opposite: lets me know which files are being used by a process.</p>
<hr>
<h2>Update</h2>
<p>Forgot to mention that it's for a Solaris system.</p>
|
<pre><code>lsof -p <pid>
</code></pre>
<p>From <a href="http://ph7spot.com/articles/leveraging_lsof" rel="noreferrer">here</a></p>
<blockquote>
<p>lsof stands for “<strong>LiSt Open Files</strong>”. This shell command seems deceptively simple: It lists information about files opened by processes on a UNIX box.</p>
<p>Despite its (apparent) modest mission statement, lsof is actually one of the most powerful and useful UNIX commands. Its raw power comes from one of UNIX’s design principle often described as ”in UNIX everything is a file”. What this means is that the lsof concept of an open file not only covers regular files but also the following:</p>
</blockquote>
<ul>
<li>Directories</li>
<li>Streams or network files (for example, Internet or UNIX domain sockets and NFS files)</li>
<li>Native libraries (for example, .soor .dylibdynamic libraries linked to a process)</li>
<li>Block and character special files (for example, disk volume, external hard drive, console, or mouse)</li>
<li>Pipes</li>
</ul>
<hr />
<p><strong>Wait, I Cannot Find lsof on My System!</strong></p>
<blockquote>
<p>lsof is such a popular tool that it has been ported to pretty much all UNIX dialects (Linux, Mac OS X, BSD, Solaris, and so on). If it is unavailable on your box, use your usual package management system to install it. You can find lsof packages for Solaris on <a href="http://www.sunfreeware.com/programlistsparc10.html#lsof" rel="noreferrer">Sun Freeware</a>.</p>
</blockquote>
|
<p>You can get lsof from <a href="http://www.sunfreeware.com/programlistsparc10.html#lsof" rel="nofollow noreferrer">http://www.sunfreeware.com/programlistsparc10.html#lsof</a></p>
<p>You can also try pfiles:</p>
<p><a href="http://docs.oracle.com/cd/E23823_01/html/816-5165/pfiles-1.html#scrolltoc" rel="nofollow noreferrer">http://docs.oracle.com/cd/E23823_01/html/816-5165/pfiles-1.html#scrolltoc</a></p>
| 38,638
|
<p>I can't seem to find any <em>useful</em> documentation from Microsoft about how one would use the <code>Delimiter</code> and <code>InheritsFromParent</code> attributes in the <code>UserMacro</code> element when defining user Macros in <code>.vsprops</code> property sheet files for Visual Studio.</p>
<p>Here's sample usage:</p>
<pre><code><UserMacro Name="INCLUDEPATH" Value="$(VCROOT)\Inc"
InheritsFromParent="TRUE" Delimiter=";"/>
</code></pre>
<p>From the above example, I'm guessing that <em>"inherit"</em> really means <em>"a) if definition is non-empty then append delimiter, and b) append new definition"</em> where as the non-inherit behavior would be to simply replace any current macro definition. Does anyone know for sure? Even better, does anyone have any suggested source of alternative documentation for Visual Studio <code>.vsprops</code> files and macros?</p>
<p>NOTE: this is <em>not</em> the same as the <code>InheritedPropertySheets</code> attribute of the <code>VisualStudioPropertySheet</code> element, for example:</p>
<pre><code><VisualStudioPropertySheet ... InheritedPropertySheets=".\my.vsprops">
</code></pre>
<p>In this case <em>"inherit"</em> basically means <em>"include"</em>.</p>
|
<p><em>[Answering my own question]</em></p>
<p><code>InheritsFromParent</code> means prepend. To verify this, I did an experiment that reveals how User Macros work in Visual Studio 2008. Here's the setup:</p>
<ul>
<li>Project <code>p.vcproj</code> includes the property sheet file <code>d.vsprops</code> ('d' for <em>derived</em>) using the <code>InheritedPropertySheets</code> tag.</li>
<li><code>d.vsprops</code> includes the property sheet file <code>b.vsprops</code> ('b' for <em>base</em>.)</li>
<li><code>p.vcproj</code> also defines a Pre-Build Event which dumps the environment.</li>
<li>Both <code>.vsprops</code> files contain User Macro definitions.</li>
</ul>
<p><strong>b.vsprops</strong></p>
<pre><code>...
<UserMacro Name="NOENV" Value="B"/>
<UserMacro Name="OVERRIDE" Value="B" PerformEnvironmentSet="true"/>
<UserMacro Name="PREPEND" Value="B" PerformEnvironmentSet="true"/>
...
</code></pre>
<p><strong>d.vsprops</strong></p>
<pre><code>...
<VisualStudioPropertySheet ... InheritedPropertySheets=".\b.vsprops">
<UserMacro Name="ENV" Value="$(NOENV)" PerformEnvironmentSet="true"/>
<UserMacro Name="OVERRIDE" Value="D" PerformEnvironmentSet="true"/>
<UserMacro Name="PREPEND" Value="D" InheritsFromParent="true"
Delimiter="+" PerformEnvironmentSet="true"/>
...
</code></pre>
<p><strong>p.vcproj</strong></p>
<pre><code>...
<Configuration ... InheritedPropertySheets=".\d.vsprops">
<Tool Name="VCPreBuildEventTool" CommandLine="set | sort"/>
...
</code></pre>
<p><strong>build output</strong></p>
<pre><code>...
ENV=B
OVERRIDE=D
PREPEND=D+B
...
</code></pre>
<p>From these results we can conclude the following:</p>
<ol>
<li><code>PerformEnvironmentSet="true"</code> is necessary for User Macros to be defined in the environment used for build events. Proof: <code>NOENV</code> not shown in build output.</li>
<li>User Macros are <strong><em>always</em></strong> inherited from included property sheets regardless of <code>PerformEnvironmentSet</code> or <code>InheritsFromParent</code>. Proof: in <code>b.vsprops</code>, <code>NOENV</code> is not set in the environment and in <code>d.vsprops</code> it is used without need of <code>InheritsFromParent</code>.</li>
<li>Simple redefinition of a User Macro <strong><em>overrides</em></strong> any previous definition. Proof: <code>OVERRIDE</code> is set to <code>D</code> although it was earlier defined as <code>B</code>.</li>
<li>Redefinition of a User Macro with <code>InheritsFromParent="true"</code> <strong><em>prepends</em></strong> the new definition to any previous definition, separated by a specified <code>Delimiter</code>. Proof: <code>PREPEND</code> is set to <code>D+B</code> (not <code>D</code> or <code>B+D</code>.)</li>
</ol>
<p>Here are some additional resources I found for explanation of Visual Studio <code>.vsprops</code> files and related topics, it's from a few years back but it is still helpful:</p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/02/03/66965.aspx" rel="noreferrer">understanding the VC project system part I: files and tools</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/02/04/67705.aspx" rel="noreferrer">understanding the VC project system part II: configurations and the project property pages dialog</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/02/05/68366.aspx" rel="noreferrer">understanding the VC project system part III: macros, environment variables and sharing</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/02/09/70335.aspx" rel="noreferrer">understanding the VC project system part IV: properties and property inheritance</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/02/13/72844.aspx" rel="noreferrer">understanding the VC project system part V: building, tools and dependencies</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/03/02/83035.aspx" rel="noreferrer">understanding the VC project system part VI: custom build steps and build events</a></p>
<p><a href="http://blogs.msdn.com/josh_/archive/2004/05/18/134638.aspx" rel="noreferrer">understanding the VC project system part VII: "makefile" projects and (re-)using environments</a></p>
|
<p>There's documentation on the UI version of this <a href="http://msdn.microsoft.com/en-us/library/a2zdt10t.aspx" rel="nofollow noreferrer">here</a>.
A lot of the XML files seem somewhat undocumented, often just giving a <a href="http://msdn.microsoft.com/en-us/library/ak4435es.aspx" rel="nofollow noreferrer">schema file</a>. Your guess as to how they function is pretty much right.</p>
| 17,242
|
<p>I need an API that can make menus like Win32API,<br>
But something simpler and better than WinAPI.<br>
That can make GUI, with text zones, buttons etc...like an average Windows program.(Windows GUI Style)<br>
Can anyone recommand on one like it? Thanks.</p>
|
<p><a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a>:</p>
<blockquote>
<p>wxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature. </p>
</blockquote>
|
<p>If you really are using Win32 directly, you might try MFC.</p>
<p>Or if you want something more modern, WTL</p>
<p><a href="http://wtl.sourceforge.net/" rel="nofollow noreferrer">http://wtl.sourceforge.net/</a></p>
<blockquote>
<p>Windows Template Library (WTL) is a
C++ library for developing Windows
applications and UI components. It
extends ATL (Active Template Library)
and provides a set of classes for
controls, dialogs, frame windows, GDI
objects, and more.</p>
</blockquote>
| 20,629
|
<p>We are trying to automate a build of one of our products which includes a step where it packages some things with WISE. At one point WISE pops up a window with a progress bar on it to show how it is doing. If one is connected to the machine with remote desktop the build works fine but if one is not connected the build stalls until you reconnect at which point the window opens and the build progresses. Does anybody know of a work around for this? Some way of tricking windows into believing that there is a desktop session connected? </p>
|
<p>Sorry for yet another guess - but I had a problem with a wise installer locking up. It was because WISE had installed a "font" and so broadcast a "system config changed" message. My DELL had a Dell utility running on it that had a message queue it wasn't reading from so the broadcast locked up the installer. WISE made a new version for me that did an async broadcast instead to fix the problem. It's possible that there's an app on your system that doesn't bother reading its msg queue when there is no desktop.</p>
<p>Finally the answer: check you have the latest patches for your WISE installer. In particular, look for patches that fix lock-ups related to the windowing system.</p>
|
<p>What version are you using? Looking at the feature set, it looks like their "std" version might be limited. Perhaps unattended installs require the Pro version?
That's just a guess....</p>
<p>Regardless, I wonder whether you could simply code up an auto-run task for the box that calls<br>
<a href="http://msdn.microsoft.com/en-us/library/ms682124(VS.85).aspx" rel="nofollow noreferrer">CreateDesktop</a> to pretend there's an interactive login?</p>
<p>I found a <a href="http://www.codeproject.com/KB/cs/csdesktopswitching.aspx" rel="nofollow noreferrer">CreateDesktop example</a>
that's about desktop switching, and <a href="http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2008-02/msg00083.html" rel="nofollow noreferrer">an example about unattended installs</a> -- you might be able to use one of them as a starting point to "fake out" WISE :)</p>
<p>It might be worth a try...</p>
| 19,857
|
<p>I faced a little trouble - I do not know if I can define my own operators for my classes.
For example:<br></p>
<pre><code>type
TMinMatrix = class(TMatrix)
private
RowAmount: Byte;
ColAmount: Byte;
Data: DataMatrix;
DemVector, SupVector: SupplyDemand;
public
constructor Create(Rows, Cols: Byte);
function GetRowAmount: Byte; override;
function GetColAmount: Byte; override;
destructor Destroy;
end;
</code></pre>
<p>How can I - or can`t I:) - do something like:</p>
<pre><code>TMinMatrix TMinMatrix::operator=(TMinMatrix* matr) (c++ code)
</code></pre>
<p>And, by the way, can I define copy constructor for my class?</p>
|
<p>Operator overloading is possible in Delphi .NET versions, older versions of Delphi don't support it.</p>
|
<p>I suppose copy constructor is an idiom, not a language feature.<br>
So I can do it like this:<br>
constructor CreateCopy(var t: MyType);<br></p>
<p>constructor MyType.CreateCopy(var t: MyType);<br>
begin<br>
//...<br>
end;<br></p>
| 42,676
|
<p>Our company makes the web based application which is priced per workstation.</p>
<p>That means that user/pass credentials should only be used from one particular machine. </p>
<p>Currently what is happening that several users are sharing credentials and we do not have any way to prevent this if they are not doing it concurrently. </p>
<p>The nature on the application is such that user needs to use it once in a while so the inability to work concurrently does not bother the users much and the company loses it's possible revenues. </p>
<p>The application currently is purely AJAX without flash/activeX/Java applets. </p>
<p>The ideal solution would be to read the computer name or IP address of the client with javascript using "Shell.Network" scripting interface. </p>
<p>But this is impossible because of the strict security settings in Internet Explorer. I have to mention that cross browser functionality does not matter and the only browser supported is IE. </p>
<p>Searching google I came across this solution here <a href="http://www.reglos.de/myaddress/MyAddress.html" rel="nofollow noreferrer">http://www.reglos.de/myaddress/MyAddress.html</a> but it requires JAVA applet so will not be very convenient. </p>
<p>Are there any other solutions for this? </p>
|
<p>Set a cookie on the machine with an id. Retrieve the cookie each time the user logs in. If you see several different cookies alternating for a single user you know you've got something odd going on. </p>
<p>(Of course a single switch may just mean they've moved to a new PC as one off. )</p>
<p>Alternatively, price per usage, 'query' or some other item.</p>
|
<p>There's no easy answer as your clients (the software) are effectively anonymous and the users are self-identifying.</p>
<p>For IE "locking you out" (I'm hardly an IE expert), but can't the IE settings be set for particular domains? You could simply make it a requirement that the users configure their browsers to give your app superior access.</p>
<p>I don't see any reason why you can't have certain requirements for the users browser (i.e. only IE 6/7/8, these security settings, etc.).</p>
| 31,359
|
<p>How would I get the <code>here</code> and <code>and here</code> to be on the right, on the same lines as the lorem ipsums? See the following:</p>
<pre class="lang-none prettyprint-override"><code>Lorem Ipsum etc........here
blah.......................
blah blah..................
blah.......................
lorem ipsums.......and here
</code></pre>
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="position: relative; width: 250px;">
<div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;">
here
</div>
<div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;">
and here
</div>
Lorem Ipsum etc <br />
blah <br />
blah blah <br />
blah <br />
lorem ipsums
</div></code></pre>
</div>
</div>
</p>
<p>Gets you pretty close, although you may need to tweak the "top" and "bottom" values.</p>
|
<p>The first line would consist of 3 <code><div></code>s. One outer that contains two inner <code><div></code>s. The first inner <code><div></code> would have <code>float:left</code> which would make sure it stays to the left, the second would have <code>float:right</code>, which would stick it to the right.</p>
<pre><code><div style="width:500;height:50"><br>
<div style="float:left" >stuff </div><br>
<div style="float:right" >stuff </div>
</code></pre>
<p>... obviously the inline-styling isn't the best idea - but you get the point.</p>
<p>2,3, and 4 would be single <code><div></code>s.</p>
<p>5 would work like 1.</p>
| 9,129
|
<p>Does anyone know of a good YAML Parser for PHP? If so, what are the pros and cons of this library?</p>
|
<blockquote>
<p><strong>Last updated</strong>: July 26th, 2017</p>
</blockquote>
<p>Here's a summary of the state of YAML in PHP:</p>
<ul>
<li>Wrappers to C libraries: You'll probably want these if you need sheer speed:
<ul>
<li><a href="https://pecl.php.net/package/yaml" rel="noreferrer">php-yaml</a>: Wrapper for <a href="http://pyyaml.org/wiki/LibYAML" rel="noreferrer">LibYAML</a>. Available as a PECL extension; it is also the one on <a href="http://php.net/manual/en/book.yaml.php" rel="noreferrer">PHP's docs</a>.</li>
<li><a href="https://pecl.php.net/package/syck" rel="noreferrer">syck</a>: Binding to syck; also available as a PECL extension. (dated, see below)<br>
<br /></li>
</ul></li>
<li><p>Pure PHP implementations: </p>
<ul>
<li><a href="http://symfony.com/doc/current/components/yaml.html" rel="noreferrer">sfYaml</a>: Symfony's YAML component. You can see its authors' motivations <a href="http://fabien.potencier.org/article/40/the-state-of-yaml-in-php" rel="noreferrer">here</a>. He wanted something that was "<em>easy to use, fast, unit tested and had clear error messages</em>."</li>
<li><a href="https://github.com/mustangostang/spyc" rel="noreferrer">spyc</a>: YAML parser without dependencies</li>
</ul></li>
</ul>
<p>At the time of this writing, the latest versions release dates for the aforementioned libraries and the versions of the <a href="http://www.yaml.org/" rel="noreferrer">YAML spec</a> (1.2 is the latest version) they support are:</p>
<pre><code>php-yaml 1.3.0 2016-09-24 YAML 1.1 [PHP 5]
php-yaml 2.0.0 2016-09-24 YAML 1.1 [PHP 7]
syck 0.9.3 2008-11-18 YAML 1.0
sfYaml 3.3.5 2017-06-15 YAML 1.1, most of 1.2
spyc 0.6.2 2017-02-24 YAML 1.1
</code></pre>
|
<p>If you're using a lot of YAML in your project you may find that the pure PHP libraries like spyc or Symfony YAML are not fast enough. There are at least two PHP bindings for C YAML parsers:</p>
<ul>
<li><a href="http://pecl.php.net/package/yaml/" rel="nofollow noreferrer">yaml</a> - a wrapper for the LibYAML YAML 1.1 parser library</li>
<li><a href="http://pecl.php.net/package/syck/" rel="nofollow noreferrer">syck</a> - a wrapper for the Syck YAML 1.0 parser library</li>
</ul>
| 37,575
|
<p>Although I've done programming, I'm not a programmer. I've recently agreed to coordinate getting a Website up for a club. The resources are--me, who has done Web content maintenance (putting content into HTML and ColdFusion templates via a gatekeeper to the site itself; doing simple HTML and XML coding); a serious Web developer who does database programming, ColdFusion, etc., and talks way over the heads of the rest of us; two designers who use Dreamweaver; the guy who created the original (and now badly broken) site in Front Page and wants to use Expression Web; and assorted other club members who are even less technically inclined.</p>
<p>What we need up first is some text and graphics (a gorgeous design has been created in Dreamweaver), some links (including to existing PDF newsletters for download), and maybe hooking up an existing Blogspot blog. Later (or earlier if it's not hard), we may add mouseover menus to the links, a gallery, a calendar, a few Mapquest hotlinks, and so on.</p>
<p>My question--First, is there any real problem with sticking with HTML and jpegs for the initial site? Second, for the "later" part of the site development, what's the simplest we can go with? Third, are there costs in doing this the simple way that will make us regret it down the road? Also, is there a good site/resource where I can learn more about this from a newbie perspective?
</p>
|
<p>If you don't require any dynamic content, heck, if you don't plan on editing the content more than once a week, I'd say stick to basic HTML.</p>
<p>Later, you'd probably want a basic, no-fuss and easily installable CMS. The brand really depends on the platform (most likely PHP/Rails/ASP), but most of them can be found by typing " CMS" into Google. Try prefixing it with "free" or "open source" if you want.</p>
<p>I'm pretty sure you can do all this for absolutely free. Most PHP and Ruby CMS's are free and web hosting is free/extremely cheap if you're not demanding.</p>
<p>And last/best tip: Find someone who has done this before, preferably more than once. He'll probably set you up so you never have to look at anything more complicated than a WYSIWYG editor.</p>
|
<p>Personally, I'd never use JPEG images on a website, mainly because of three reasons:</p>
<ol>
<li>JPEGs often contains artifacts.</li>
<li>Quality is often proportional
with filesize. </li>
<li>Does not support
alpha transparency.</li>
</ol>
<p>That said, I'd recommend you to use PNGs for images since it's lossless and a 24-bit palette (meaning full colors + alpha transparency). The only quirk is that IE6 and below does not support native alpha for PNGs, however this could be resolved by running a javascript which would fix this issue.</p>
<p>As for designing a website, there's both pros and cons for this. I suggest you read through:</p>
<ul>
<li><a href="http://www.37signals.com/svn/posts/1061-why-we-skip-photoshop" rel="nofollow noreferrer">37 Signal's Why We Skip Photoshop</a></li>
<li><a href="http://jeffcroft.com/blog/2008/jun/04/why-we-dont-skip-photoshop/" rel="nofollow noreferrer">Jeff Croft's Why We Don't Skip Photoshop</a></li>
</ul>
<p>As for newbie resources, I'd recommend you flip through the pages at <a href="http://w3schools.com/" rel="nofollow noreferrer">W3 Schools</a>.</p>
| 3,796
|
<p>Im trying to add a connection to a database in SQL Server 2008 using Visual Studio 2008. When testing the connection, it says that it is successful. However, once I said okay, it complains and say: "Cannot add data connection. Object reference not set to an instance of an object."</p>
<p>How do I go about adding a data connection to a SQL Server 2008 using Visual Studio 2008?</p>
|
<p>Via code would be something like:</p>
<pre><code>var conn = new SqlConnection([connectionString]);
conn.Open();
</code></pre>
|
<p>"Object reference not set to an instance of an object" is usually an indicator of not using the Keyword "New".</p>
| 47,870
|
<p>What are all the other things the <code>new</code> operator does other than allocating memory and calling a constructor?</p>
|
<p>The C++ standard has this to say about the single object form (the form usually used) of the new operator from the <code><new></code> header:</p>
<blockquote>
<p>Required behavior: </p>
<p>Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a
bad_alloc exception. This requirement is binding on a replacement version of this function.</p>
<p>Default behavior:</p>
<p>— Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether
the attempt involves a call to the Standard C library function malloc is unspecified.</p>
<p>— Returns a pointer to the allocated storage if the attempt is successful. Otherwise, if the last argument to
set_new_handler() was a null pointer, throw bad_alloc.</p>
<p>— Otherwise, the function calls the current new_handler (18.4.2.2). If the called function returns, the loop
repeats.</p>
<p>— The loop terminates when an attempt to allocate the requested storage is successful or when a called
new_handler function does not return.</p>
</blockquote>
<p>The standard has a lot of other stuff to say about the new operator and dynamic memory allocation (an awful lot to say), but I think the "Default behavior" list sums up the basics of the new operator pretty well.</p>
|
<p>Depends on if it's overloaded or not, if you built the app for debugging, if you're using a memory leak detector, if you have some kind of memory pooling scheme, if you have something like the Boehm garbage collector that's marking/unmarking bits, etc., etc. It could be doing a lot of custom stuff inside, or nothing special at all.</p>
| 49,386
|
<p><strong>To Clarify to all this problem absolutely does not stem from rebinding of the controls and the value does not remain the initial value after binding.</strong></p>
<p>I have a DropDownList on an aspx page which is being used in multiple projects.</p>
<p>Along the life cycle of the page the SelectedValue is changed prior to the handling of the SelectedIndexChanged event.</p>
<p>In one project when the code reaches the event handler the SelectedValue is back to what was posted from the client, while in the other the new SelectedValue is present.</p>
<p>Viewstate is on in both cases, the control is not being rebound and follows the exact same flow from all that I can gather.</p>
<p>The control is not being initialized again, I checked this thoroughly and does not retain the initial value but rather the value set in the code.</p>
<p>I actually need the posted value at the point of the event handler like is happening in the first project but do not understand why it would be changing back to the posted value and how to replicate this behavior in the second project.</p>
<p>I will be happy to clarify further if any of this is unclear.</p>
|
<p>Maybe some initialization is performed twice in the on_load event because you dont check the page is posted back using <a href="http://msdn.microsoft.com/fr-fr/library/system.web.ui.page.ispostback(VS.80).aspx" rel="nofollow noreferrer">IsPostBack</a> in a test ?</p>
<p>It exactly happens to one of my colleague ten minutes ago :-)</p>
|
<p>I usually see this behavior when I've forgotten to check IsPostback somewhere. The page will load all of the original data before going to the SelectedIndexChanged event handler.</p>
| 21,499
|
<p>I want the equivalent online resource to DNS in Twenty-One Days. I need one evening's reading that will explain what the different record types do, how do propagation and caching work, what is an SoA, etc.</p>
<p>I don't want anything that begins by explaining what DNS is.</p>
<p>Can anybody please point me in the right direction to find some online 'DNS for Geniuses' guide, please? </p>
|
<p>Check out <a href="http://www.zytrax.com/books/dns/" rel="nofollow noreferrer">DNS for Rocket Scientists</a></p>
<p>It does start with a very brief "What DNS is" but you can easily skip that.</p>
<p>You can also check out <a href="http://www.dnsmadeeasy.com/s0306/res/recs.html" rel="nofollow noreferrer">Records 101</a> which gives a good overview of the different record types - the examples are specific to DNSMadeEasy though. </p>
|
<p>When I set up DNS for the first time I read <a href="http://www.langfeldt.net/DNS-HOWTO/BIND-9/" rel="nofollow noreferrer">DNS HOWTO</a>. It worked pretty well for me.</p>
| 34,789
|
<p>I'm looking for an algorithm to generate permutations of a set in such a way that I could make a lazy list of them in Clojure. i.e. I'd like to iterate over a list of permutations where each permutation is not calculated until I request it, and all of the permutations don't have to be stored in memory at once.</p>
<p>Alternatively I'm looking for an algorithm where given a certain set, it will return the "next" permutation of that set, in such a way that repeatedly calling the function on its own output will cycle through all permutations of the original set, in some order (what the order is doesn't matter).</p>
<p>Is there such an algorithm? Most of the permutation-generating algorithms I've seen tend to generate them all at once (usually recursively), which doesn't scale to very large sets. An implementation in Clojure (or another functional language) would be helpful but I can figure it out from pseudocode.</p>
|
<p>Yes, there <em>is</em> a "next permutation" algorithm, and it's quite simple too. The C++ standard template library (STL) even has a function called <code>next_permutation</code>.</p>
<p>The algorithm actually finds the <em>next</em> permutation -- the lexicographically next one. The idea is this: suppose you are given a sequence, say "32541". What is the next permutation?</p>
<p>If you think about it, you'll see that it is "34125". And your thoughts were probably something this: In "32541",</p>
<ul>
<li>there is no way to keep the "32" fixed and find a later permutation in the "541" part, because that permutation is already the last one for 5,4, and 1 -- it is sorted in decreasing order.</li>
<li>So you'll have to change the "2" to something bigger -- in fact, to the smallest number bigger than it in the "541" part, namely 4.</li>
<li>Now, once you've decided that the permutation will start as "34", the rest of the numbers should be in increasing order, so the answer is "34125".</li>
</ul>
<p>The algorithm is to implement precisely that line of reasoning:</p>
<ol>
<li>Find the longest "tail" that is ordered in decreasing order. (The "541" part.)</li>
<li>Change the number just before the tail (the "2") to the smallest number bigger than it in the tail (the 4).</li>
<li>Sort the tail in increasing order.</li>
</ol>
<p>You can do (1.) efficiently by starting at the end and going backwards as long as the previous element is not smaller than the current element. You can do (2.) by just swapping the "4" with the '2", so you'll have "34521". Once you do this, you can avoid using a sorting algorithm for (3.), because the tail was, and is still (think about this), sorted in decreasing order, so it only needs to be reversed.</p>
<p>The C++ code does precisely this (look at the source in <code>/usr/include/c++/4.0.0/bits/stl_algo.h</code> on your system, or see <a href="http://marknelson.us/2002/03/01/next-permutation" rel="noreferrer">this article</a>); it should be simple to translate it to your language: [Read "BidirectionalIterator" as "pointer", if you're unfamiliar with C++ iterators. The code returns <code>false</code> if there is no next permutation, i.e. we are already in decreasing order.]</p>
<pre><code>template <class BidirectionalIterator>
bool next_permutation(BidirectionalIterator first,
BidirectionalIterator last) {
if (first == last) return false;
BidirectionalIterator i = first;
++i;
if (i == last) return false;
i = last;
--i;
for(;;) {
BidirectionalIterator ii = i--;
if (*i <*ii) {
BidirectionalIterator j = last;
while (!(*i <*--j));
iter_swap(i, j);
reverse(ii, last);
return true;
}
if (i == first) {
reverse(first, last);
return false;
}
}
}
</code></pre>
<p>It might seem that it can take O(n) time per permutation, but if you think about it more carefully, you can prove that it takes O(n!) time for all permutations in total, so only O(1) -- constant time -- per permutation.</p>
<p>The good thing is that the algorithm works even when you have a sequence with repeated elements: with, say, "232254421", it would find the tail as "54421", swap the "2" and "4" (so "232454221"), reverse the rest, giving "232412245", which is the next permutation.</p>
|
<p>It looks necromantic in 2022 but I'm sharing it anyway</p>
<p><a href="https://github.com/hextriclosan/algorithm" rel="nofollow noreferrer">Here</a> an implementation of C++ <code>next_permutation</code> in Java can be found. The idea of using it in Clojure might be something like</p>
<pre><code>(println (lazy-seq (iterator-seq (NextPermutationIterator. (list 'a 'b 'c)))))
</code></pre>
<p>disclaimer: I'm the author and maintainer of the project</p>
| 45,861
|
<p>Does anyone have some numbers on this? I am just looking for a percentage, a summary will be better.</p>
<p>Standards compliance: How does the implementation stack up to the standard language specification?</p>
<p>For those still unclear: I place emphasis on <strong>current</strong>. The IronPython link provided below has info that was last edited more than 2 years back.</p>
|
<p>The following sites usually have updates as to how their 'compliance' is progressing:</p>
<p>IronPython -</p>
<p><a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython" rel="nofollow noreferrer">http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython</a><br>
<a href="http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Regression%20Tests&referringTitle=More%20Information" rel="nofollow noreferrer">http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Regression%20Tests&referringTitle=More%20Information</a></p>
<p>IronRuby -</p>
<p><a href="http://www.ironruby.net/" rel="nofollow noreferrer">http://www.ironruby.net/</a></p>
<p>In fact from the IronRuby site - </p>
<p>"We showed IronRuby dispatching some static and dynamic Rails requests at RailsConf this year. We are running the RubySpecs to measure our conformity with Ruby and we're passing the core specs at a 71% rate (12026 / 16793 expectations for RubySpec core)."</p>
|
<p>We don't actively track these kinds of numbers, but you could download them and run them against the respective test suites for the languages if you wanted to boil it down to a single numeric value.</p>
| 16,258
|
<p>In a table, I have three columns - id, name, and count. A good number of name columns are identical (due to the lack of a UNIQUE early on) and I want to fix this. However, the id column is used by other (4 or 5, I think - I would have to check the docs) tables to look up the name and just removing them would break things. So is there a good, clean way of saying "find all identical records and merge them together"?</p>
|
<p>This kind of question comes up from time to time. No, there's not a really clean way to do it. You have to change all the rows in the child table that depend on unwanted values in the parent table before you can eliminate the unwanted rows in the parent table.</p>
<p>MySQL supports multi-table <code>UPDATE</code> and <code>DELETE</code> statements (unlike other brands of database) and so you can do some pretty neat tricks like the following:</p>
<pre><code>UPDATE names n1
JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name)
JOIN child_table c ON (n2.id = c.id)
SET c.name_id = n1.id
ORDER BY n1.id DESC;
</code></pre>
<p>Once you have done this on all the child table(s), you can use MySQL's multi-table <code>DELETE</code> syntax to remove unwanted rows in the parent table:</p>
<pre><code>DELETE FROM n2
USING names n1 JOIN names n2 ON (n1.id < n2.id AND n1.name = n2.name);
</code></pre>
|
<p>Why can't you do something like</p>
<pre><code>update dependent_table set name_id = <id you want to keep> where name_id in (
select id from names where name = 'foo' and id != <id you want to keep>)
</code></pre>
| 31,721
|
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p>
<p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p>
<p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p>
<p>Has anyone else encountered this problem?</p>
<p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
|
<p>From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.</p>
<pre><code>import gzip
content = b"Some content"
f = open("/tmp/f.gz", "wb")
gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0)
gz.write(content)
gz.close()
f.close()
</code></pre>
|
<p>In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:</p>
<pre><code>def _write_gzip_header(self):
self.fileobj.write('\037\213') # magic header
self.fileobj.write('\010') # compression method
fname = self.filename[:-3]
flags = 0
if fname:
flags = FNAME
self.fileobj.write(chr(flags))
write32u(self.fileobj, long(time.time())) # The current time!
self.fileobj.write('\002')
self.fileobj.write('\377')
if fname:
self.fileobj.write(fname + '\000')
</code></pre>
<p>As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will "return the time as a floating point number expressed in seconds since the epoch, in UTC." So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!</p>
| 33,088
|
<p>I'm working with an XML file that subscribes to an industry standard. The standards document for the schema defines one of the fields as a rational number and its data is represented as two integers, typically with the second value being a 1 (e.g. <code><foo>20 1</foo></code>). I've been hunting around without a great deal of success to see if there's an XML-defined standard for rational numbers. I did find this (8 year old) exchange on the mailing list for XML-SCHEMA:</p>
<p><a href="http://markmail.org/message/znvfw2r3a2pfeykl" rel="nofollow noreferrer">http://markmail.org/message/znvfw2r3a2pfeykl</a></p>
<p>I'm not clear that there is a standard "XML way" for representing rational numbers and whether the standard applying to this document is subscribing to it, or whether they've cooked up their own way of doing it for their documents and are relying on people to read the standard. The document is not specific beyond saying the field is a rational number.</p>
<p>Assuming there is a standard way of representing rational numbers and this document is correctly implementing it, does the functionality in System.Xml recognize it? Again, my searches have not been particularly fruitful.</p>
<p>Thanks for any feedback anyone has.</p>
|
<p>This isn't exactly an answer to the XML-side of things, but if you are wanting a C# class for representing rational numbers, I write a very flexible one a while back as part of my <a href="https://github.com/mckamey/exif-utils.net" rel="nofollow noreferrer">ExifUtils library</a> (since most EXIF values are represented as rational numbers).</p>
<ul>
<li><code>Rational<T></code> <a href="https://github.com/mckamey/exif-utils.net/blob/master/ExifUtils/ExifUtils/Rational.cs" rel="nofollow noreferrer">https://github.com/mckamey/exif-utils.net/blob/master/ExifUtils/ExifUtils/Rational.cs</a></li>
</ul>
<p>The class itself is generic accepting a numerator/denominator of any type implementing <code>IConvertable</code> (which includes all BCL number types) and will serialize (ToString) and deserialize (Parse/TryParse) which may give you exactly what you need for your XML representation.</p>
<p>If you absolutely must represent a rational number with a space, you could adapt it to use space <code>' '</code> as the delimiter with literally a single character change in the source.</p>
<hr>
<p>As a slightly off-topic aside in response to Steven Lowe's comments, the use of rational numbers while seemingly unintuitive has some advantages. Numbers such as PI cannot be represented as a decimal/floating point number either. The <em>approximation</em> of PI (e.g. the value in Math.PI) can be just as precisely represented as a rational number:</p>
<pre><code>314159265358979323846 / 100000000000000000000
</code></pre>
<p>Whereas the very simple rational number <code>2/3</code> is impossible to represent to the same precision as any sort of floating point / fixed precision decimal number:</p>
<pre><code>0.66666666666666666667
</code></pre>
|
<p>i'm glad they didn't accept this proposal as a standard! the guy proposing to base all other numbers on a 'rational number' primitive has never heard of transcendental numbers (like Pi, for example) which cannot be represented in this manner</p>
<p>but back to your question - i've only run across rational numbers in xml as part of an RDF specification for certain engineering values related to the power industry. I think it was just a pair of numbers separated by a comma</p>
<p><a href="http://www.w3.org/TR/2000/WD-CCPP-vocab-20000721/#2.2.4" rel="nofollow noreferrer">this document</a> defines the format as N/M, while another reference has it as N,M</p>
| 37,162
|
<p>how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools? </p>
<p>I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to import dynamically another compressed repository created with pyInstaller and execute the code - this may be a simple plugin engine.</p>
<p>Problems appears when the plugin (this what is imported dynamically) uses a library that is not present in original repository (never imported). This is because import hook is for the original application and searches for packages in original repository - not the one imported later (plugin package repository). </p>
<p>Is there an easy way to solve this problem? Maybe there exist such engine?</p>
|
<p>When compiling to exe, your going to have this issue.</p>
<p>The only option I can think of to allow users access with thier plugins to use any python library is to include all libraries in the exe package. </p>
<p>It's probably a good idea to limit supported libraries to a subset, and list it in your documentation. Up to you.</p>
<p>I've only used py2exe.</p>
<p>In py2exe you can specify libraries that were not found in the search in the <strong>setup.py</strong> file.</p>
<p>Here's a sample:</p>
<pre><code>from distutils.core import setup
import py2exe
setup (name = "script2compile",
console=['script2compile.pyw'],
version = "1.4",
author = "me",
author_email="somemail@me.com",
url="myurl.com",
windows = [{
"script":"script2compile.pyw",
"icon_resources":[(1,"./ICONS/app.ico")] # Icon file to use for display
}],
# put packages/libraries to include in the "packages" list
options = {"py2exe":{"packages": [ "pickle",
"csv",
"Tkconstants",
"Tkinter",
"tkFileDialog",
"pyexpat",
"xml.dom.minidom",
"win32pdh",
"win32pdhutil",
"win32api",
"win32con",
"subprocess",
]}}
)
import win32pdh
import win32pdhutil
import win32api
</code></pre>
|
<p>PyInstaller <em>does</em> have a plugin system for handling hidden imports, and ships with several of those already in. See the webpage (<a href="http://www.pyinstaller.org" rel="nofollow noreferrer">http://www.pyinstaller.org</a>) which says:</p>
<blockquote>
<p>The main goal of PyInstaller is to be compatible with 3rd-party packages out-of-the-box. This means that, with PyInstaller, all the required tricks to make external packages work are already integrated within PyInstaller itself so that there is no user intervention required. You'll never be required to look for tricks in wikis and apply custom modification to your files or your setup scripts. Check our compatibility list of SupportedPackages. </p>
</blockquote>
| 39,550
|
<p>My php is weak and I'm trying to change this string:</p>
<pre><code>http://www.example.com/backend.php?/c=crud&m=index&t=care
^
</code></pre>
<p>to be:</p>
<pre><code>http://www.example.com/backend.php?c=crud&m=index&t=care
^
</code></pre>
<p>removing the <code>/</code> after the <code>backend.php?</code>. Any ideas on the best way to do this?</p>
<p>Thanks!</p>
|
<p>I think that it's better to use simply <a href="http://www.php.net/str_replace" rel="noreferrer">str_replace</a>, like the manual says:</p>
<blockquote>
<p>If you don't need fancy replacing
rules (like regular expressions), you
should always use this function
instead of ereg_replace() or
preg_replace().</p>
</blockquote>
<pre><code><?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);
</code></pre>
|
<p>While a regexp would suit here just fine, I'll present you with an alternative method. It <em>might</em> be a tad faster than the equivalent regexp, but life's all about choices (...or something).</p>
<pre><code>$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
if ($urlString[$i] === '?') {
$urlString[$i+1] = '';
break;
}
}
</code></pre>
<p>Weird, I know.</p>
| 33,129
|
<p>I have a string coming from a table like "can no pay{1},as your payment{2}due on {3}". I want to replace {1} with some value , {2} with some value and {3} with some value .</p>
<p>Is it Possible to replace all 3 in one replace function ? or is there any way I can directly write query and get replaced value ? I want to replace these strings in Oracle stored procedure the original string is coming from one of my table I am just doing select on that table </p>
<p>and then I want to replace {1},{2},{3} values from that string to the other value that I have from another table </p>
|
<p>Although it is not one call, you can nest the <code>replace()</code> calls:</p>
<pre><code>SET mycol = replace( replace(mycol, '{1}', 'myoneval'), '{2}', mytwoval)
</code></pre>
|
<p>If you are doing this inside of a select, you can just piece it together, if your replacement values are columns, using string concatenation.</p>
| 10,941
|
<p>There are many editions of Eclipse for Java development. I am trying out MyEclipse and am pretty impressed with the out-of-box experience. Before I get too comfortable with it, I would like to find out if it is the best edition available. Feel free to list free or commercial packages, but for the sake of other readers, please mention if there is a cost.</p>
<h2>Considerations</h2>
<p>I am mostly concerned with the code editing experience. Here is a list of <em>some</em> factors that would affect my decision:</p>
<ul>
<li>Extensive support for refactoring</li>
<li>Code suggestions (like suggesting refactorings)</li>
<li>Easily configurable keyboard shortcuts</li>
<li>Easily configurable colours (I use dark colour schemes, and setting this up with MyEclipse was hell; that said, I only really need to do it once)</li>
<li>Excellent debugging support</li>
<li>Source control plugins (SVN or git if one exists)</li>
<li>Don't care about GUI designers</li>
</ul>
<p>I am aware that there is a thread discussing the best IDE for Java development; however, most of the responses do not detail recommended editions of Eclipse.</p>
|
<p>I'm always just downloading <strong>classic</strong> edition and just add plugins I need. That way I keep Eclipse as lean as possible.</p>
|
<p>Agree with <a href="https://stackoverflow.com/questions/305708/best-eclipse-version-for-java-development#305743">Marko</a> and <a href="https://stackoverflow.com/questions/305708/best-eclipse-version-for-java-development#305749">Epaga</a></p>
<p>I have Eclipse 3.4 (Ganymede) with following additional plugins (links are the update site URLs):</p>
<ul>
<li><a href="http://subclipse.tigris.org/update_1.4.x" rel="nofollow noreferrer">Subclipse</a> for Subversion</li>
<li><a href="http://springide.org/updatesite" rel="nofollow noreferrer">Spring IDE</a> for Spring. Favourite features: Advanced spring xml completion and bean visualisations.</li>
<li><a href="http://m2eclipse.sonatype.org/update/" rel="nofollow noreferrer">m2eclipse</a> for Maven. Favourite features: transitive dependency tree and graph visualisations. </li>
</ul>
| 39,328
|
<p>I need to test a url that it <strong>does not</strong> end with <code>.asp</code></p>
<p>So <code>test</code>, <code>test.html</code> and <code>test.aspx</code> should match, but <code>test.asp</code> should not match.</p>
<p>Normally you'd test if the url <strong>does</strong> end with .asp and negate the fact that it matched using the NOT operator in code:</p>
<pre><code>if(!regex.IsMatch(url)) { // Do something }
</code></pre>
<p>In that case the regular expression would be <code>\.asp$</code> but in this case I need the regular expression to result in a match. </p>
<hr>
<p>Background: I need to use the regular expression as a route contraint in the ASP.NET MVC <code>RouteCollection.MapRoute</code> extension method. The route needs to match all controllers but it should fall through when the controller in the url ends with .asp</p>
|
<p>The trick is to use <a href="http://www.regular-expressions.info/lookaround.html" rel="noreferrer">negative lookbehind</a>.</p>
<p>If you need just a yes/no answer:</p>
<pre><code>(?<!\.asp)$
</code></pre>
<p>If you need to match the whole URL:</p>
<pre><code>^.*(?<!\.asp)$
</code></pre>
<p>These regexes will work with any URL where the file name occurs at the end of the URL (i.e. URLs without a query or fragment). I'm assuming your URLs fit this limitation given the regex .asp$ in your question. If you want it to work with all URLs, try this:</p>
<pre><code>^[^#?]+(?<!\.asp)([#?]|$)
</code></pre>
<p>Or this if you want the regex to match the whole URL:</p>
<pre><code>^[^#?]+(?<!\.asp)([#?].+|$)
</code></pre>
|
<p>Try this</p>
<pre><code>^((?!\.asp$).)*$
</code></pre>
| 41,907
|
<p>I've created an Access 2007 form that displays, for example, Products from a Product table. One of the fields in the Product table is a CategoryID that corresponds to this product's parent category.</p>
<p>In the form, the CategoryID needs to be represented as a combo box that is bound to the Category table. The idea here is pretty straightforward: selecting a new Category should update the CategoryID in the Product table.</p>
<p>The problem I'm running into is that selecting a new Category updates the CategoryName of the Category table instead of updating the CategoryID in the Product table. The reason for this is that it seems that the combo box must be bound only to the CategoryName of the Category table.</p>
<p>What happens is if the current product has a CategoryID of 12 which is the CategoryName "Chairs" in the Category table then selecting a new value, let's say "Tables" (CategoryID 13) in the combo box updates the CategoryID of 12 with the new CategoryName "Tables" instead of updating the Product table CategoryID to 13.</p>
<p>How can I bind the Category table to a combox box so that the datatextfield (which I wish existed in Access) is the CategoryName and the datavaluefield is the CategoryID and only the CategoryID of the Product will be updated when the selected combo box item is changed?</p>
<p><strong>Edit:</strong> See the accepted answer below. I also needed to change the column count to 2 and everything started to work perfectly. </p>
|
<p>You need to use both values in the query for the combo box.<br>
e.g. SELECT CategoryId, CategoryName FROM CategoryTable...
Bind the combo box to the fist column, CategoryId.
Set the column widths for the combo box to 0in (no second value need, so there is no limit). This will hide the first column which contains your selected value; all that shows it the description value, which is all you want to see.
So now when you select a different option in the combobox, the value returned by the combo box will be the bound value, CategoryId, not CategoryName.</p>
<p>Ah, yes Alison, sorry, I forgot about setting the combobox columncount = 2.</p>
|
<p>You should also check that your categories table has a primary key on the CategoryName field. You original configuration should have thrown an error or message saying the update would violate the key. As it is it seems you can have 2 categories with the same name.</p>
| 9,449
|
<p>Can we write an regular expression such that it splits the stored procedure in multiple SQL statements.
It should split update, delete select etc statements.</p>
<p>Edit: my attempt to solve the problem <a href="http://tsqlparsergdr.codeplex.com/" rel="nofollow noreferrer">http://tsqlparsergdr.codeplex.com/</a></p>
|
<p>If you have the grammar for the stored procedure language you could use <a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> so parse the procedure to get the relevant parts of the language out and the do any further processing necessary. It should be reletively easy to get a grammar going from scratch as well.</p>
<p>There would need to be a set of regex expressions to deal with the whole procedure. I.e. a regex to mach just insert statements that possible spans many lines and possible has local variables from the proc in it and so on.</p>
|
<p>To parse arbitrary stored procedures, you're far better off with a SQL parser. Trying to parse arbitrary SQL with regexes will amount to writing your own parser.</p>
<p>To parse a specific set of stored procedures, a regex may be able to do the job. You'll need to provide a few examples of the input you have and the desired output if you want a more detailed answer.</p>
| 44,125
|
<p>So, I have a pair of typeclasses that I'll be using a lot together, and I want to avoid specifying both each time. Basically, instead of putting</p>
<pre><code>:: (Ord a, Fractional a, Ord b, Fractional b, ... Ord z, Fractional z) =>
</code></pre>
<p>at the beginning of all my type specifications, I'd rather put</p>
<pre><code>:: (OrdFractional a, OrdFractional b, ... OrdFractional z)
</code></pre>
<p>So, my initial idea on how to do this was to just declare a new typeclass</p>
<pre><code>module Example where
class (Fractional a, Ord a) => OrdFractional a
example :: (OrdFractional a, OrdFractional b) => (a,b) -> (a,b) -> (a,b) -> Bool
example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 < x2/x3) && (y1/y2 < y2/y3)
</code></pre>
<p>But this didn't work as automagically as I wished it would:</p>
<pre><code>% ghci
Prelude> :l Example.hs
Ok, modules loaded: Example.
Prelude Example> example (1::Float,3::Float) (2,2) (3,1)
<interactive>:1:0:
No instance for (OrdFractional Float)
arising from a use of `example' at <interactive>:1:0-39
Possible fix:
add an instance declaration for (OrdFractional Float)
In the expression: example (1 :: Float, 3 :: Float) (2, 2) (3, 1)
In the definition of `it':
it = example (1 :: Float, 3 :: Float) (2, 2) (3, 1)
</code></pre>
<p>Manually creating instances seems like a drag so, next, I thought I might try to automatically create instances:</p>
<pre><code>module Example where
class OrdFractional a
instance (Fractional a, Ord a) => OrdFractional a
example :: (OrdFractional a, OrdFractional b) => (a,b) -> (a,b) -> (a,b) -> Bool
example (x1,y1) (x2,y2) (x3,y3) = (x1/x2 < x2/x3) && (y1/y2 < y2/y3)
</code></pre>
<p>But the compiler didn't like that:</p>
<pre><code>ghc -c Example.hs
Example.hs:4:0:
Illegal instance declaration for `OrdFractional a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are type *variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `OrdFractional a'
</code></pre>
<p>So is there a way I can do this?</p>
|
<p>With the ConstraintKinds extension introduced in GHC 7.4, constraints are now types of kind <code>Constraint</code>, so you can use ordinary type synonyms to get what you want:</p>
<pre><code>{-# LANGUAGE ConstraintKinds #-}
type OrdFractional a = (Ord a, Fractional a)
</code></pre>
|
<p>No.</p>
<p>Your solution of a superclass implying the other classes is the closest to what you want that is possible in Haskell. Even though that requires manual instances of that new class it is sometimes used, for example in the <a href="http://hackage.haskell.org/package/rewriting" rel="nofollow noreferrer">rewriting</a> library.</p>
<p>As CesarB mentioned class aliases do what you want (and more), but they're just a proposal that's been around for years now and have never been implemented, probably because there are numerous problems with it. Instead, various other proposals have popped up, but none of those were implemented either. (For a list of those proposals, see this <a href="http://haskell.org/haskellwiki/Comparing_class_alias_proposals" rel="nofollow noreferrer">Haskellwiki page</a>.) One of the projects at <a href="http://haskell.org/haskellwiki/Hac5" rel="nofollow noreferrer">Hac5</a> was to modify the GHC to include a small subset of class aliases called <em>context synonyms</em> (which do exactly what you are asking for here and nothing more), but sadly it was never finished.</p>
| 39,401
|
<p>If it does, then how do you justify the overheads incurred (journaling etc.)?
If it does not, then how come the pagefile gets fragmented?
Additionally, would increasing the cluster size improve pagefile performance (cluster slack space is a non-issue)?</p>
|
<p>You can skip the boost namespace entirely by using the techniques described <a href="http://through-the-interface.typepad.com/through_the_interface/2006/07/advanced_visual_1.html" rel="noreferrer">here</a>. Just use something like:</p>
<p><code>boost\:\:.*=NoStepInto</code></p>
<p>... in the relevant registry entry.</p>
<p>However if your code gets called from within boost (e.g. through a <code>boost::function</code> or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for <em>that</em> problem...</p>
|
<p>You can skip the boost namespace entirely by using the techniques described <a href="http://through-the-interface.typepad.com/through_the_interface/2006/07/advanced_visual_1.html" rel="noreferrer">here</a>. Just use something like:</p>
<p><code>boost\:\:.*=NoStepInto</code></p>
<p>... in the relevant registry entry.</p>
<p>However if your code gets called from within boost (e.g. through a <code>boost::function</code> or similar) then your code will be skipped as well! I'll be interested if someone can come up with a good solution for <em>that</em> problem...</p>
| 38,143
|
<p>I'm reading text from a flat file in c# and need to test whether certain values are dates. They could be in either YYYYMMDD format or MM/DD/YY format. What is the simplest way to do this in .Net?</p>
|
<pre class="lang-cs prettyprint-override"><code>string[] formats = {"yyyyMMdd", "MM/dd/yy"};
var Result = DateTime.ParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
</code></pre>
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>DateTime result;
string[] formats = {"yyyyMMdd", "MM/dd/yy"};
DateTime.TryParseExact(input, formats, CultureInfo.CurrentCulture, DateTimeStyles.None, out result);
</code></pre>
<p>More info in the MSDN documentation on <a href="https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact" rel="nofollow noreferrer">ParseExact</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact" rel="nofollow noreferrer">TryParseExact</a>.</p>
|
<p>You can also do Convert.ToDateTime</p>
<p>not sure the advantages of either</p>
| 15,000
|
<p>I have a structure that represents a wire format packet. In this structure is an array of other structures. I have generic code that handles this very nicely for most cases but this array of structures case is throwing the marshaller for a loop.</p>
<p>Unsafe code is a no go since I can't get a pointer to a struct with an array (argh!).</p>
<p>I can see from <a href="http://www.codeproject.com/KB/dotnet/ReadingStructures.aspx" rel="nofollow noreferrer">this codeproject article</a> that there is a very nice, generic approach involving C++/CLI that goes something like...</p>
<pre><code>public ref class Reader abstract sealed
{
public:
generic <typename T> where T : value class
static T Read(array<System::Byte>^ data)
{
T value;
pin_ptr<System::Byte> src = &data[0];
pin_ptr<T> dst = &value;
memcpy((void*)dst, (void*)src,
/*System::Runtime::InteropServices::Marshal::SizeOf(T::typeid)*/
sizeof(T));
return value;
}
};
</code></pre>
<p>Now if just had the structure -> byte array / writer version I'd be set! Thanks in advance!</p>
|
<p>Using memcpy to copy an array of bytes to a structure is extremely dangerous if you are not controlling the byte packing of the structure. It is safer to marshall and unmarshall a structure one field at a time. Of course you will lose the generic feature of the sample code you have given.</p>
<p>To answer your real question though (and consider this pseudo code):</p>
<pre><code>public ref class Writer abstract sealed
{
public:
generic <typename T> where T : value class
static System::Byte[] Write(T value)
{
System::Byte buffer[] = new System::Byte[sizeof(T)]; // this syntax is probably wrong.
pin_ptr<System::Byte> dst = &buffer[0];
pin_ptr<T> src = &value;
memcpy((void*)dst, (void*)src,
/*System::Runtime::InteropServices::Marshal::SizeOf(T::typeid)*/
sizeof(T));
return buffer;
}
};
</code></pre>
|
<p>Not altering the structure is certainly sound advice. I use liberal amounts of StructLayout attributes to specify the packing, layout and character encoding. Everything flows just fine.</p>
<p>My issue is just that I need a performant and preferably generic solution. Performance because this is a server application and generic for elegance. If you look at the codeproject link you'll see that the StructureToPtr and PtrToStructure methods perform on the order of 20 times slower than a simple unsafe pointer cast. This is one of those areas where unsafe code is full of win. C# will only let you have pointers to primitives (and it's not generic - can't get a pointer to a generic), so that's why CLI.</p>
<p>Thanks for the psuedocode grieve, I'll see if it gets the job done and report back.</p>
| 42,758
|
<p>I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.</p>
|
<pre><code>void create_dump(void)
{
if(!fork()) {
// Crash the app in your favorite way here
*((void*)0) = 42;
}
}
</code></pre>
<p>Fork the process then crash the child - it'll give you a snapshot whenever you want</p>
|
<p>The source code to produce a core dump is in 'gcore', which is part of the gdb package.</p>
<p>Also, the Sun has <a href="http://docs.oracle.com/cd/E23823_01/html/816-5165/gcore-1.html" rel="nofollow noreferrer">gcore</a>.</p>
<p>Also, you have to have a separate process running the core dump, as the current process must be suspended. You'll find the details in the gcore source, or you can just run your platform's gcore with your process as the target.</p>
| 15,949
|
<p>As the title really, I'm in one part of my code and I would like to invoke any methods that have been added to the Button.Click handler.</p>
<p>How can I do this?</p>
|
<p>Do you mean you need to access it from elsewhere in your code? It may be an idea to refactor that section to it's own method then call that method whenever you need to access it (including in the Click event)</p>
|
<p>You will need an event to act as a proxy, but you are pretty much better off just refactoring your code.</p>
<pre><code> private EventHandler ButtonClick;
protected override void CreateChildControls()
{
base.CreateChildControls();
m_Button = new Button{Text = "Do something"};
m_Button.Click += ButtonClick;
ButtonClick += button_Click;
Controls.Add(m_Button);
}
private void MakeButtonDoStuff()
{
ButtonClick.Invoke(this, new EventArgs());
}
private void button_Click(object sender, EventArgs e)
{
}
</code></pre>
<p>Do not do this if you really dont need it. It will make a mess of your code.</p>
| 36,421
|
<p>If I have a class that needs to implement an interface but one or more of the methods on that interface don't make sense in the context of this particular class, what should I do?</p>
<p>For example, lets say I'm implementing an adapter pattern where I want to create a wrapper class that implements <a href="http://java.sun.com/javase/6/docs/api/java/util/Map.html" rel="nofollow noreferrer">java.util.Map</a> by wrapping some immutable object and exposing it's data as key/value pairs. In this case the methods put and putAll don't make sense as I have no way to modify the underlying object. So the question is what should those methods do?</p>
|
<p>Any method that cannot be implemented according to the semantics of the interface should throw an <a href="http://java.sun.com/javase/6/docs/api/java/lang/UnsupportedOperationException.html" rel="nofollow noreferrer">UnsupportedOperationException</a>.</p>
|
<p>Your two choices are really only:</p>
<ol>
<li>Do nothing.</li>
<li>Throw an exception.</li>
</ol>
<p>Both have disadvantages. In the first case, by having an empty method, you could mislead the programmer into thinking something happened to your data. The second case breaks the whole idea of polymorphism inherent in interfaces.</p>
| 21,641
|
<p>I'm writing an HTTP Cache library for Java, and I'm trying to use that library in the same application which is started twice. I want to be able to share the cache between those instances.</p>
<p>What is the best solution for this? I also want to be able to write to that same storage, and it should be available for both instances.</p>
<p>Now I have a memory-based index of the files available to the cache, and this is not shareable over multiple VMs. It is serialized between startups, but this won't work for a shared cache.</p>
<p>According to the HTTP Spec, I can't just map files to URIs as there might be a variation of the same payload based on the request. I might, for instance, have a request that varies on the 'accept-language' header: In that case I would have a different file for each subsequent request which specifies a different language.</p>
<p>Any Ideas?</p>
|
<p>First, are you sure you want to write your own cache when there are several around? Things like:</p>
<ul>
<li><a href="http://ehcache.sourceforge.net/" rel="nofollow noreferrer">ehcache</a></li>
<li><a href="http://www.jboss.org/jbosscache/" rel="nofollow noreferrer">jboss cache</a></li>
<li><a href="http://www.danga.com/memcached/" rel="nofollow noreferrer">memcached</a></li>
</ul>
<p>The first two are written in Java and the third can be accessed from Java. The first two also handle distributed caching, which is the general case of what you are asking for, I think. When they start up, they look to connect to other members so that they maintain a consistent cache across instances. Changes to one are reflected across instances. They can be set up to connect via multicast or with specific lists of servers specified.</p>
<p>Memcached typically works in a slightly different manner in that it is running externally to the Java processes you are running, so that all Java instances that start up will be talking to a common service. You can set up memcached to work in a distributed manner, but it does so by hashing keys so that the server you want to connect to can be determined by what it is you are looking for.</p>
<p>Doing a true distributed cache with consistent content is very hard to do well, which is why I suggest looking at an existing library. If you want to do it yourself, it would still help to look at those listed to see how they go about it and consider using something like JGroups as your underlying mechanism.</p>
|
<p>I think you should have a look at the <a href="http://www.greenbytes.de/tech/webdav/" rel="nofollow noreferrer">WebDav-Specifications</a>. It's an HTTP extension for sharing/editing/storing/versioning resources on a server. There exists an implementation as an <a href="http://www.webdav.org/mod_dav/" rel="nofollow noreferrer">Apache module</a>, wich allows you a swift start using them.</p>
<p>So instead of implementing your own cache server implementation, you might be better off with a local Apache + mod-dav instance that is available to both of your applications.</p>
<p>Extra bonus: Since WebDav is a specified protocoll you get the interoperability with lots of tools for free.</p>
| 38,431
|
<p>Encouraged by SO, I'm trying to write an ASP.NET site that uses OpenID for user authentication. It's a regular WinForms site (not MVC.NET), using the <a href="http://code.google.com/p/dotnetopenid/" rel="nofollow noreferrer">DotNetOpenId</a> library for authentication.</p>
<p>Is it safe for me to permit/deny administrative functions on the site by simply comparing the current session's "ClaimedID" (as returned in the OpenIdLogin_LoggedIn event, as member DotNetOpenId.RelyingParty,OpenIdEventArgs.Response.ClaimedIdentifier) to a known administrator's OpenID (i.e. mine)?</p>
<p>If so, is it safe for this ID to be visible (e.g. in open source code), or should it be "hidden" in a configuration file or a database row? (I know it's better design to make it configurable, my question is just about safety.)</p>
|
<p>Jarrett makes some good comments about using database tables.</p>
<p>Just to answer another one of your questions, no, it's not a confidentiality thing to put your OpenID in your code generally. If setting up roles seems overkill for your site, a simple equality check against your ClaimedIdentifier is just perfect. </p>
|
<p>My solution is to follow the same idea of the Roles table. After you've authenticated the user, look up that user's roles. If the user has role "Administrator" in the UserRoles table, then they can do whatever the Administrator can do.</p>
<p>I don't broadcast open ID's in my app. They're stored in the table. On every action result, I'm hitting the Users table, since I have also modified mine to store various user state information. With the exception of the home page, there is going to be some user information that I need from that table. I'm using LINQ, so I include the .LoadWith() to load the User with his list of roles when it serializes.</p>
| 8,109
|
<p>I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc. My solution has revolved around <a href="http://www.castleproject.org/container/index.html" rel="nofollow noreferrer">Castle Windsor</a> and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at <a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a> as it's supposed to be a "better" solution. I've had a quick look at PostSharp, but I've been put off by the Attribute usage.</p>
<p>Has anyone tried both solutions and would care to share their experiences?</p>
|
<p>I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.</p>
<p>Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.</p>
<p>But...</p>
<p>If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.</p>
|
<p>I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.</p>
<p>Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.</p>
<p>But...</p>
<p>If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.</p>
| 8,828
|
<p>Currently I know of only two ways to cache data (I use PHP but I assume that the same will apply to most languages).</p>
<ol>
<li>Save the cache to a file</li>
<li>Save the cache to a large DB field</li>
</ol>
<p>Are there any other (perhaps better) ways of caching or is it really just this simple?</p>
|
<p>Maybe you want to explicit more precisely what you want to cache. You have all this opportunities to cache: </p>
<ul>
<li><b>Accessing the Data Base</b> where you cache the data first correctly tuning your RDBMS, then using a layer to delegate the decision to detect multiple queries for the same data (with <a href="http://adodb.sourceforge.net/" rel="nofollow noreferrer">AdoDB</a> for example.)</li>
<li><b>Extracting calculations from loops in the code</b> so you don't compute the same value multiple times. <i>Here your third way: storing results in the session for the user.</i></li>
<li><b>Precompiling the PHP code</b> with an extension like <a href="http://pecl.php.net/package/APC" rel="nofollow noreferrer">APC Cache</a>. This way you don't have to compile the same PHP code for every request.</li>
<li><b>The page sent to the user</b> making sure you're setting the right META tags (do a good thing for the world and don't use ETL at least absolutly necessary); or maybe making dynamic pages completely static (having a batch process that generates .html pages); or by using a proxy cache like <a href="http://www.squid-cache.org/" rel="nofollow noreferrer">Squid</a>.</li>
<li><b>Prefetching</b> and by this I refer all those opportunities you have to improve the user experience just by doing things while the user don't look your way. For example, preloading IMG tags in the HTML file, tunning the RDBMS for prefectching, precomputing results storing complex computations in the database, etc. </li>
</ul>
<p>From my experience, I'd bet you that your code can be improved a lot before we start to talk about caching things. Consider, for example, how well structured is the navigation of your site and how well you control the user experience. Then check your code with a tool like <a href="http://xdebug.org/" rel="nofollow noreferrer">XDebug</a>. </p>
<p>Verify also how well are you making your SQL queries and how well are you indexing your tables. Then check your code again to look for opportunities to apply the rule "read many times but write just once"</p>
<p>Use a simple tool like <a href="http://developer.yahoo.com/yslow/" rel="nofollow noreferrer">YSlow</a> to hint other simple things to improve. Check your code again looking for opportunities to put logic in the browser (via JavaScript)</p>
|
<p>Seconding memcached, does the simple stuff well and can go distributive and all that jazz if you need it too</p>
| 2,608
|
<p>MXML lets you do some really quite powerful data binding such as:</p>
<pre><code><mx:Button id="myBtn" label="Buy an {itemName}" visible="{itemName!=null}"/>
</code></pre>
<p>I've found that the BindingUtils class can bind values to simple properties, but neither of the bindings above do this. Is it possible to do the same in AS3 code, or is Flex silently generating many lines of code from my MXML?
Can anyone duplicate the above in pure AS3, starting from:</p>
<pre><code>var myBtn:Button = new Button();
myBtn.id="myBtn";
???
</code></pre>
|
<p>The way to do it is to use <code>bindSetter</code>. That is also how it is done behind the scenes when the MXML in your example is transformed to ActionScript before being compiled.</p>
<pre><code>// assuming the itemName property is defined on this:
BindingUtils.bindSetter(itemNameChanged, this, ["itemName"]);
// ...
private function itemNameChanged( newValue : String ) : void {
myBtn.label = newValue;
myBtn.visible = newValue != null;
}
</code></pre>
<p>...except that the code generated by the MXML to ActionScript conversion is longer as it has to be more general. In this example it would likely have generated two functions, one for each binding expression.</p>
|
<p>I believe flex generates a small anonymous function to deal with this.</p>
<p>You could do similar using a ChangeWatcher. You could probably even make a new anonymous function in the changewatcher call.</p>
| 12,772
|
<p>I am generating the json from PHP.</p>
|
<p>The correct way is to use <a href="http://www.php.net/json_encode" rel="noreferrer">json_encode()</a></p>
|
<p>The JSON is just a subset of Javascript, so everything you know about escaping strings in Javascript applies to JSON.</p>
<p>And yes, the correct answer is to use one of library functions, there is a quite a few of them around: see <a href="http://gggeek.altervista.org/sw/article_20061113.html" rel="nofollow noreferrer">A completely fair and balanced comparison of php json libraries</a>.</p>
| 31,535
|
<p>Is there a control or method to accept formatted input in VB.NET?</p>
<p>i.e. It accepts input in a given format ##/##/## or similar?</p>
|
<p>You want the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx" rel="nofollow noreferrer">MaskedTextBox</a> control, I believe.</p>
|
<p>You want the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx" rel="nofollow noreferrer">MaskedTextBox</a> control, I believe.</p>
| 24,827
|
<p>I've been preparing to deliver a presentation on SQL Server Compact Edition 3.5 (SP1 - recently released) and I was wondering if anyone had designed (or contemplated designing) a system with SQL Server CE 3.5 (or earlier versions)?</p>
<p>In particular, has anyone thought of (or experienced) using SQLCE as a solution for offline data storage (as part of a connected system design)?</p>
<p>Version 3.5 looks to be pretty feature rich compared to its predecessors, is it ready for serious consideration (now that it supports LINQ to SQL, identity columns and an assortment of important T-SQL)?</p>
<p>Would you consider using it if you had the need for a lightweight low-footprint file based database (especially if it needed to be supported on mobile devices and desktop systems), or are there better options?</p>
|
<p>At work, we recently had to migrate a project that was designed for SQL Server Express to SQLCE. At first I thought it was going to be awful, mainly due to the fact that there are no stored procedures. Once we started digging into it though, and saw what it DOES offer, we were convinced it was the right move. It supports LINQ, querying alot of data took MUCH quicker than we thought it would. Inserting and Updating were a little slower, but really not too bad at all. The only problems we ran into really were A) Management Studio 2005 doesn't support it, and although 2008 does, it's very limited. Not sure why, hopefully they'll change that for future releases, but it bugged the hell outta me. B) When trying to migrate an existing SQL Server DB to a SQLCE, there's really no easy way to create the schema from the existing one, and to move all the data. You'll probably have to roll your own tool to do that (we had to). </p>
<p>All that being said though, the end result was amazing. The install time was cut down to a third now that users didn't have to install SQL Express, and the application ran much smoother on machines with less memory. All in all, I was amazed at how well it actually works.</p>
|
<p>Tried SQLCE several times. Always ended up using something else (Firebird (embedded), SQLite, VistaDB). IMO SQLCE is way to limited to be useful in more or less complex scenarios. Though I have no real-world experience with latest version (3.5) but I suspect it still sucks :)</p>
| 23,139
|
<p>I have an application which tries to load some expected registry settings within its constructor.</p>
<p>What is the most appropriate .NET Exception from the BCL to throw if these (essential, non-defaultable) registry settings cannot be loaded?</p>
<p>For example:</p>
<pre><code> RegistryKey registryKey = Registry.LocalMachine.OpenSubkey("HKLM\Foo\Bar\Baz");
// registryKey might be null!
if (registryKey == null)
{
// What exception to throw?
throw new ???Exception("Could not load settings from HKLM\foo\bar\baz.");
}
</code></pre>
|
<p>I'd go with <a href="http://msdn.microsoft.com/en-us/library/system.argumentexception.aspx" rel="noreferrer">ArgumentException</a> or <a href="http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception.aspx" rel="noreferrer">ArgumentOutOfRangeException</a>..</p>
<pre><code>throw new ArgumentException("Could not find registry key: " + theKey);
</code></pre>
<p>Quoting MSDN:</p>
<blockquote>
<p>The exception that is thrown when one
of the arguments provided to a method
is not valid.</p>
</blockquote>
<p>...</p>
<p><strong>IMO writing a proper exception message is more important.</strong></p>
|
<p>I think just Exception itself could do the job. If your message is descriptive enough, then it's all good. If you really want to be precise about it, then I'd agree with petr k. Just roll your own.</p>
| 48,162
|
<p>I've been teaching OOP and was trying to convey to my students the important difference between inheritance and the creation of a subtype relation between two types. For example, in C++, I could use private inheritance to ensure that nobody outside sees the subtyping relation.</p>
<p>However, while I can think of a lot of situations where I wouldn't want to create a subtyping relation (e.g., implementing a Stack via a doubly-linked list class), I can't really think of good design examples where I would actually choose to follow inheritance without creating a public subtying relation (rather than, say, use aggregation).</p>
<p>Any ideas of good examples?</p>
|
<p>As a Python programmer, let me say that these are matters that are way, way too subtle. They appear to be purely C++-isms.</p>
<p>In Python, we have inheritance, which creates proper subtypes.</p>
<p>And we have composition using simple attributes, or of the available collections.</p>
<p>This business of private inheritance being a kind of composition seems to be simply confusing. And largely useless. </p>
<p>The C++ examples show private inheritance to create composition with a common interface. In Java, we'd have a common interface. In Python, we have duck typing and don't need the formalisms.</p>
<p>I don't think there are good examples -- I think the concept is too subtle to be of any real value. </p>
|
<p>Code reuse without subtyping is done using <em>delegation</em>.</p>
<p><a href="http://c2.com/cgi/wiki?DelegationIsInheritance" rel="nofollow noreferrer">Delegation is inheritance</a>.</p>
| 31,873
|
<p>I'd hate to have to relearn C++ just for this! Any libraries/URLs would be great and yes, Google didn't help much here :-( </p>
<p>This is for an upcoming project in which my product (Java based) would provide support for Microsoft's Hyper-V virtualization platform. Unlike VMware, which provides a Web-service, the Hyper-V APIs are mere extensions of WMI. I'd prefer not to use commercial tools such as J-Integra for Java integration into COM/WMI and the few open source tools I found are way outdated.</p>
<p>I would rather use JNI with C than C++. Anybody know where I can find libraries et cetera for using C for WMI operations? In the same vein as Python clients can be used? (And yes, I know C is not an OOP language :D ).</p>
<p>Thanks in advance.</p>
|
<p>WMI is acessed via COM right?</p>
<p>While it is more verbose and more error-prone (it is easy to accidentally use different pointers for the vtable and the "this" parameter), you can also use COM from the C language.</p>
<p>You also could use C++ but treat it as "C with language extensions to make using COM easier".</p>
|
<p>The JNI interface itself is a derivative of COM and you will find those methods and the methods of the WMI interfaces much easier to use if you use enough C++ to treat interfaces as implemented by C++ classes.</p>
<p>The other thing that will be helpful is that you will be able to use the COM interface pointers and reference counting as a way to bind the lifecyle of the COM interface to the lifecycle of your JNI-implemented Java classes. </p>
<p>I used an approach like this to implement a Java bridge, via JNI, to some C Language interfaces on Windows. I hand-rolled COM interfaces and a .lib that is used in building the JNI DLL.</p>
<p>The difficult part, with WMI, is that you will want to use the standard COM APIs to Instantiate the COM objects, whereas I created my own custom "factory" code, since it was all a private implementation.</p>
<p>You can download a snapshot of my development tree for the <a href="http://odma.info/dev/devNotes/2006/12/d061201g.htm" rel="nofollow noreferrer">ODMJNI 1.0 0.50beta Function-Complete Release</a>. If you look at info.odma.odmjni100 in the development tree you'll see how the JNI DLL is built (using VC++ 2005 Express Edition) and Java 1.5. The OdmJniBind.java class consists of the static methods that are used in the Java classes to coordinate object lifecycles between Java Classes and COM Object interfaces. (the OdmNative peer section of the tree provides the implementation of the OdmNative100.lib that is used in compiling the odmjni100.dll that is used via JNI.</p>
| 36,422
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.