instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have an SQL Server DB with a table with these fields:</p>
<ol>
<li>A <code>bit</code> with the default value 1, <code>NOT NULL</code>.</li>
<li>A <code>smalldatetime</code> with the default value <code>gettime()</code>, <code>NOT NULL</code>.</li>
<li>An <code>int</code> with no default value, <code>IDENTITY</code>, <code>NOT NULL</code>.</li>
</ol>
<p>When I generate Linq to SQL for this table, the following happens:</p>
<ol>
<li>The <code>bit</code> is given no special treatment.</li>
<li>The <code>smalldatetime</code> is given no special treatment.</li>
<li>The <code>int</code> is marked as <code>IsDbGenerated</code>.</li>
</ol>
<p>This means that when I make inserts using Linq to SQL, the following will happen:</p>
<ol>
<li>The <code>bit</code> will be sent as 0, overriding the default value. <strong>Right?</strong></li>
<li>The <code>smalldatetime</code> will be sent as an uninitialized <code>System.DateTime</code>, producing an error in SQL server since it doesn't fall with the SQL Server smalldatetime range. <strong>Right?</strong></li>
<li>The <code>IsDbGenerated</code> <code>int</code> will not be sent; the DB will generate a value which Linq to SQL will then read back.</li>
</ol>
<p><strong>What changes do I have to make to make this scenario work?</strong> </p>
<p>To summarize: I want non-nullable fields with DB-assigned default values, but I don't want them <code>IsDbGenerated</code> if it means I cannot provide values for them when making updates or inserts using Linq to SQL. I also do not want them <code>IsDbGenerated</code> if it means I have to hand-modify the code generated by Linq to SQL.</p>
<p><em>EDIT: The answer seems to be this is a limitation in the current Linq to SQL.</em></p>
|
<p>Linq-To-Sql generated classes do not pick up the Default Value Constriants.</p>
<p>Maybe in the future, but the issue is constraints aren't always simple values, they can also be scalar functions like <code>GetDate()</code>, so linq would somehow have to know how to translate those. In short, it doesn't even try. It's also a very database-specific type of thing.</p>
<ul>
<li>You could write a code generator to create entity partial classes where you can extract the default value constriant. </li>
<li>Alternatively your business layer code could set the defaults in constructors from an xml file, and all you need to do is keep the xml file up-to-date. </li>
<li>Instead of doing the work in constructors, you could emulate sql and add default values by inspecting the ChangeSet before submitting changes to the database.</li>
</ul>
<p>The issue you are having is described at length in <a href="http://www.codeproject.com/KB/linq/SettingDefaultValues.aspx" rel="nofollow noreferrer">CodeProject - Setting Default Values for LINQ Bound Data</a></p>
|
<p>You can create another file for your datacontext (partial class) and then use the InsertYOURENTITY and UpdateYOURENTITY partial methods to inspect your properties and assign the proper values.
Call ExecuteDynamicInsert or ExecuteDynamicUpdate after your code and you're set.</p>
| 24,639
|
<p>I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines:</p>
<pre><code>[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller : DefaultManagementInstaller { }
</code></pre>
<p>I gather the purpose of this installation is because the Windows WMI infrastructure needs to be aware of the structure of my WMI provider before it is used.</p>
<p>My question is - when is this "installer" ran? MSDN says that the installer will be invoked "during installation of an assembly", but I am not sure what that means or when it would happen in the context of a class library containing a WMI provider.</p>
<p>I was under the impression that this was an automated replacement for manually running <strong>InstallUtil.exe</strong> against the assembly containing the WMI provider, but changes I make to the provider are not recognised by the Windows WMI infrastructure unless I manually run InstallUtil from the command prompt. I can do this on my own machine during development, but if an application using the provider is deployed to other machines - what then?</p>
<p>It seems that this RunInstaller / DefaultManagementInstaller combination is not working properly - correct?</p>
|
<p>As I understand, DefaultManagementInstaller is ran by installutil.exe - if you don't include it, the class is not installed in WMI. Maybe it is possible to create a 'setup project' or 'installer project' that runs it, but I'm not sure because I don't use Visual Studio.</p>
<p>[edit]</p>
<p>for remote instalation, an option could be to use Installutil with /MOF option to generate MOF for the assembly and use mofcomp to move it to WMI.</p>
|
<p>Thanks Uros. It does look like all that RunInstaller and DefaultManagementInstaller do is enable you to run InstallUtil successfully against the assembly. This is strange because I'm almost certain that I didn't know about InstallUtil at the point where I'd compiled and played with my first WMI provider.</p>
<p>I will look in to using the MOF file and for my own use I can just run the InstallUtil command line as a post build event in VS.</p>
| 19,713
|
<p>I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.</p>
<p>What is the best way to convert the entire file format using Python?</p>
|
<p>You can convert the file easily enough just using the <code>unicode</code> function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.</p>
<p><a href="http://www.peterbe.com/plog/unicode-to-ascii" rel="noreferrer">This blog</a> recommends the <code><a href="http://www.python.org/doc/2.5.2/lib/module-unicodedata.html" rel="noreferrer">unicodedata </a></code> module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g.</p>
<pre><code>>>> title = u"Klüft skräms inför på fédéral électoral große"
</code></pre>
<p>is typically converted to </p>
<pre><code>Klft skrms infr p fdral lectoral groe
</code></pre>
<p>which is pretty wrong. However, using the <code>unicodedata</code> module, the result can be much closer to the original text:</p>
<pre><code>>>> import unicodedata
>>> unicodedata.normalize('NFKD', title).encode('ascii','ignore')
'Kluft skrams infor pa federal electoral groe'
</code></pre>
|
<p>It's important to note that there is no 'Unicode' file format. Unicode can be encoded to bytes in several different ways. Most commonly UTF-8 or UTF-16. You'll need to know which one your 3rd-party tool is outputting. Once you know that, converting between different encodings is pretty easy:</p>
<pre><code>in_file = open("myfile.txt", "rb")
out_file = open("mynewfile.txt", "wb")
in_byte_string = in_file.read()
unicode_string = bytestring.decode('UTF-16')
out_byte_string = unicode_string.encode('ASCII')
out_file.write(out_byte_string)
out_file.close()
</code></pre>
<p>As noted in the other replies, you're probably going to want to supply an error handler to the encode method. Using 'replace' as the error handler is simple, but will mangle your text if it contains characters that cannot be represented in ASCII.</p>
| 21,129
|
<p>I have two tables Institutions and Results and I want to see if there are any results for institutions that way I can exclude the ones that don't have results.</p>
<p>Can I get better performance using a JOIN or using EXISTS?</p>
<p>Thank you,<br>
-Nimesh</p>
|
<p>Depending on the statement, statistics and DB server it may make no difference - the same optimised query plan may be produced.</p>
<p>There are basically 3 ways that DBs join tables under the hood:</p>
<ul>
<li><p>Nested loop - for one table much bigger than the second. Every row in the smaller table is checked for every row in the larger.</p></li>
<li><p>Merge - for two tables in the same sort order. Both are run through in order and matched up where they correspond.</p></li>
<li><p>Hash - everything else. Temporary tables are used to build up the matches.</p></li>
</ul>
<p>By using exists you may effectively force the query plan to do a nested loop. This may be the quickest way, but really you want the query planner to decide.</p>
<p>I would say that you need to write both SQL statements and compare the query plans. You may find that they change quite a bit depending on what data you have.</p>
<p>For instance if [Institutions] and [Results] are similar sizes and both are clustered on InstitutionID a merge join would be quickest. If [Results] is much bigger than [Institutions] a nested loop may be quicker.</p>
|
<p>If you're referring to using a left (or right) outer join or a not exists subquery, I'm fairly certain the left outer join wins performance-wise. For example:</p>
<p><code>SELECT t1.* FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.id = t2.id WHERE t2.id IS NULL
</code></p>
<p>The above should be quicker than the equivalent sub-query, and if you're referring specifically to exists - well, where structure allows, an inner join will always be the preferred option.</p>
| 28,090
|
<p>I have two versions of my application, one "stage" and one "dev."</p>
<p>Right now, "stage" is exposed to the real world for beta-testing.</p>
<p>From time to time, I want an exact replica of the data to be replicated into the "dev" database.</p>
<p>Both databases are on the same hosted Linux machine.</p>
<p>Sometimes I create "dummy" data in the development environment. At this stage, I'd be fine if it needs to get written over in stage.</p>
<p>Thanks.</p>
|
<p>Be sure to add security to your script so only the user you are authorizing is able to run that script. basically you want to use mysql and mysqldump commands.</p>
<pre><code>mysqldump -u username --password=userpass --add-drop-database --add=locks --create-options --disable-keys --extend-insert --result-file=database.sql databasename
mysql -u username --password=userpass -e "source database.sql;"
</code></pre>
<p>The first command will make the backup the second command will bring the backup to another database engine. <strong>Be careful</strong> because if you run it on the same exact process of mysql you are only backing up the database adn then restoring it to the same database, you have to change the database name.</p>
<p>Hope this helps.</p>
|
<p>Just use <a href="http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html" rel="nofollow noreferrer">mysqldump</a> to create a backup of the staging database and then load the dump file over your dev database. This will give you an exact copy of the stage data.</p>
| 49,764
|
<p>I have a problem with the jQuery-UI dialog in my ASP.NET form:</p>
<pre><code>$("#pnlReceiverDialog").dialog({
autoOpen:false,
modal: true,
height:220,
width:500,
resizable :false,
overlay: { opacity: 0.5,background: "black" },
buttons: {
"Cancel": function() {
$(this).dialog("close");
},
"Ok": function() {
__doPostBack('ctl00$phContent$ctl00$LetterLocation$pupNewReceiver','')
}
}
});
</code></pre>
<p><code>pnlReceiverDialog</code> contains an ASP.NET <code>TextBox</code>.</p>
<p>When I click on the OK button, the form posts back but the textbox doesn't have a value.</p>
|
<p>I know that you probably already checked that the object name is the one that you wrote (ctl00$phContent$ctl00$LetterLocation$pupNewReceiver) but the first thing that i would do is to double or triple check it... </p>
<p>i once spent almost a day in a similar situation where the only thing that was wrong was the object name because there was a difference between the client object id and client object name.</p>
<p>Check the Request.Params collection to make sure that the name is right.</p>
<p>You can also use the second parameter of the __doPostBack function to specify the value that you want to postback</p>
<p>Here is an exemple of what i usually do:</p>
<p>__doPostBack($("#<%=Me.btnDeleteItem.ClientID %>").attr("name"), $("#<%=txtId.ClientID%>").val());</p>
|
<p>JQuery Script encapsulated in the ASP.Net custom Control and use
Page.ClientScript.GetPostBackEventReference(this,"").
pnlReceiverDialog is a DIV outside the control.</p>
<p>I was checked the Request.Params, value of the TextBox dosn't exist.</p>
| 48,494
|
<p>The product we are working on allows the user to easily set it up to run automatically whenever the computer is started. This is helpful because the product is part of the basic work environment of most of our users.<br>
This feature was implemented not so long ago and for a while all was well, but when we started testing this feature on Vista the product started behaving really weird on startup. Specifically, our product makes use of another product (lets call it X) that it launches whenever it needs its services. The actual problem is that whenever X is launched immediately after log-on, it crashes or reports critical errors related to disk access (this happens even when X is launched directly - not through our product).</p>
<p>This happens whenever we run our product by registering it in the "Run" key in the registry or place a shortcut to it in the "<em>Startup</em>" folder inside the "<em>Start Menu</em>", even when we put a delay of ~20 seconds before actually starting to run. When we changed the delay to 70 seconds, all is well.</p>
<p>We tried to reproduce the problem by launching our product manually immediately after logon (by double-clicking on a shortcut placed on the desktop) but to no avail.</p>
<p>Now how is it possible that applications that run normally a minute after logon report such hard errors when starting immediately after logon?</p>
|
<p>This is the effect of a new feature in Vista called "Boxing":
Windows has several mechanisms that allow the user/admin to set up applications to automatically run when windows starts. This feature is mostly used for one of these purposes:
1. Programs that are part of the basic work environment of the user, such that the first action the user would usually take when starting the computer is to start them.
2. All sorts of background "agents" - skype, messenger, winamp etc.</p>
<p>When too many (or too heavy) programs are registered to run on startup the end result is that the user can't actually do anything for the first few seconds/minutes after login, which can be really annoying. In comes Vista's "Boxing" feature:</p>
<p>Briefly, Vista forces all programs invoked through the Run key to operate at low priority for the first 60 seconds after login. This affects both <strong>I/O priority (which is set to Very Low) and CPU priority</strong>. Very Low priority I/O requests do not pass through the file cache, but go directly to disk. Thus, they are much slower than regular I/O.
The length of the boxing period is set by the registry value:
"HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced\DelayedApps\Delay_Sec". </p>
<p>For a more detailed explanation see <a href="http://blogs.technet.com/askperf/archive/2008/03/28/startup-programs-on-windows-vista-inside-the-box.aspx" rel="nofollow noreferrer">here</a> and <a href="http://myitforum.com/cs2/blogs/scassells/archive/2008/02/05/boxing-and-the-case-of-the-slow-or-hanging-logon-script-in-vista.aspx" rel="nofollow noreferrer">here</a></p>
|
<p>The program probably needs some more info put into its properties. It needs to "Run As", instead of just running.</p>
<p>Maybe this application should be developed as a service, instead of a program to be launched, or you could have service that launches the program when its determined the best window of opportunity. </p>
| 3,662
|
<p>I have a need to find all of the writable storage devices attached to a given machine, <strong>whether or not</strong> they are mounted.</p>
<p>The dopey way to do this would be to <em>try</em> every entry in <code>/dev</code> that corresponds to a writable devices (<code>hd* and sd*</code>)......</p>
<p>Is there a better solution, or should I stick with this one?</p>
|
<p><code>/proc/partitions</code> will list all the block devices and partitions that the system recognizes. You can then try using <code>file -s <device></code> to determine what kind of filesystem is present on the partition, if any.</p>
|
<p>Modern linux systems will normally only have entries in /dev for devices that exist, so going through hda* and sda* as you suggest would work fairly well.</p>
<p>Otherwise, there may be something in /proc you can use. From a quick look in there, I'd have said /proc/partitions looks like it could do what you need.</p>
| 24,534
|
<p>I have a list of integers, <code>List<Integer></code> and I'd like to convert all the integer objects into Strings, thus finishing up with a new <code>List<String></code>.</p>
<p>Naturally, I could create a new <code>List<String></code> and loop through the list calling <code>String.valueOf()</code> for each integer, but I was wondering if there was a better (read: <em>more automatic</em>) way of doing it?</p>
|
<p>As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this):</p>
<pre><code>List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<>(oldList.size());
for (Integer myInt : oldList) {
newList.add(String.valueOf(myInt));
}
</code></pre>
|
<p>I just wanted to chime in with an object oriented solution to the problem.</p>
<p>If you model domain objects, then the solution is in the domain objects. The domain here is a List of integers for which we want string values.</p>
<p>The easiest way would be to not convert the list at all.</p>
<p>That being said, in order to convert without converting, change the original list of Integer to List of Value, where Value looks something like this...</p>
<pre><code>class Value {
Integer value;
public Integer getInt()
{
return value;
}
public String getString()
{
return String.valueOf(value);
}
}
</code></pre>
<p>This will be faster and take up less memory than copying the List.</p>
| 3,908
|
<p><strong>Model:</strong> Infitary M508</p>
<p><strong>Details:</strong> The filament is stuck in the extruder preheated for PLA (the filament is PLA 1.75 white). The extruder's motor works and the filament is in the hole of the extruder (not somewhere else). I took the fan covering the motor apart, to show what is inside, so you might see it on the attached image:</p>
<p><a href="https://i.stack.imgur.com/znCxG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/znCxG.png" alt="enter image description here"></a></p>
<p>You might also see this video for details: <a href="https://www.youtube.com/watch?v=R8rYGhuYWvc" rel="noreferrer">https://www.youtube.com/watch?v=R8rYGhuYWvc</a></p>
<p>I'm able to pull the filament out, when I uncouple the motor's gear, but it doesn't go through the extruder when I push it in.</p>
<p>What can I do to fix this? Thanks!</p>
<p>P.S. It's the first start of the printer.</p>
|
<p>Unfortunately you're going to have to tear the extruder head apart and clean the nozzle. There are kits like the following (found on Amazon - No affiliation):</p>
<p><a href="https://i.stack.imgur.com/aDs2P.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aDs2P.jpg" alt="enter image description here"></a></p>
<p>This will give you everything you need to clear the nozzle. The only other solution is to replace the nozzle and extruder tube. The filament is stuck in either or both of these parts. </p>
<p>(As an aside ... a wise person < <em>cough</em> > @0scar < <em>cough</em> > once told me I should keep extras of these parts, as well as the thermister and heating elements on hand. Treat them as disposable parts ... once they're dead, just replace them.)</p>
<p>What you need to figure out though, is why it clogged in the first place. More than likely you tried to extrude filament before the nozzle was up to temperature. If your readout said it was good, then you need to get a no-touch thermometer and check the nozzle for the proper temperature prior to printing to ensure it's all good.</p>
|
<p>Unfortunately you're going to have to tear the extruder head apart and clean the nozzle. There are kits like the following (found on Amazon - No affiliation):</p>
<p><a href="https://i.stack.imgur.com/aDs2P.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aDs2P.jpg" alt="enter image description here"></a></p>
<p>This will give you everything you need to clear the nozzle. The only other solution is to replace the nozzle and extruder tube. The filament is stuck in either or both of these parts. </p>
<p>(As an aside ... a wise person < <em>cough</em> > @0scar < <em>cough</em> > once told me I should keep extras of these parts, as well as the thermister and heating elements on hand. Treat them as disposable parts ... once they're dead, just replace them.)</p>
<p>What you need to figure out though, is why it clogged in the first place. More than likely you tried to extrude filament before the nozzle was up to temperature. If your readout said it was good, then you need to get a no-touch thermometer and check the nozzle for the proper temperature prior to printing to ensure it's all good.</p>
| 1,312
|
<p>I have the following text</p>
<pre><code>tooooooooooooon
</code></pre>
<p>According to this book I'm reading, when the <code>?</code> follows after any quantifier, it becomes non greedy.</p>
<p>My regex <code>to*?n</code> is still returning <code>tooooooooooooon</code>.</p>
<p>It should return <code>ton</code> shouldn't it?</p>
<p>Any idea why?</p>
|
<p>A regular expression can only match a fragment of text that actually exists.</p>
<p>Because the substring 'ton' doesn't exist anywhere in your string, it can't be the result of a match. A match will only return a substring of the original string</p>
<p>EDIT: To be clear, if you were using the string below, with an extra 'n'</p>
<pre><code>toooooooonoooooon
</code></pre>
<p>this regular expression (which doesn't specify 'o's)</p>
<pre><code>t.*n
</code></pre>
<p>would match the following (as many characters as possible before an 'n')</p>
<pre><code>toooooooonoooooon
</code></pre>
<p>but the regular expression</p>
<pre><code>t.*?n
</code></pre>
<p>would only match the following (as few characters as possible before an 'n')</p>
<pre><code>toooooooon
</code></pre>
|
<p>The string you are searching in (the haystack as it were) does not contain the substring "ton".</p>
<p>It does however contain the substring "tooooooooooooon".</p>
| 30,556
|
<p>What are the pros / cons of using <code>pthread_cond_wait</code> or using a semaphore ?
I am waiting for a state change like this :</p>
<pre><code>pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);
</code></pre>
<p>Using a properly initialised semaphore, I think I could do it like this :</p>
<pre><code>while(cam->status == WAIT_DISPLAY) {
sem_wait(&some_semaphore);
}
</code></pre>
<p>What are the pros and cons of each method ?</p>
|
<p>A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore.</p>
<p>A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never).</p>
<p>So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again.</p>
<p>It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions.</p>
<p>Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns.</p>
<p>IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.</p>
|
<p>In your second snippet, you're getting the lock multitude of times, never releasing it.</p>
<p>In general, the state you're waintin on can be completely expressed by a semaphore, then you can use just that. A lock structure is smaller in size, and it requires less atomic operations to check/set/release.</p>
<p>Otherwise, if the state is complex, and different parts of the code wait on different conditions of the same variable (eg, here you want x<10; there you want y>x), use cond_wait.</p>
| 9,624
|
<p>I'm looking to increase the printing speed, through increasing the volumetric flow rate, which is currently at 5 mm³/s. Larger amounts cause the feeding mechanism to skip steps.</p>
<p>I'm running at 190 °C, which helps with easier bridging less stringing and personally see no reason to increase the temperature to the popular 205 °C.</p>
<p>So, my thought process is the following: since I run at lesser temperature, there is still potential for the heating block to provide more heat and I need a longer nozzle to accumulate more heat and provide more surface area for transfer to the fillament (PLA), to speed up the melting of the plastic inside the nozzle (<em>which seems to be the bottleneck</em>). </p>
<p><em>That's similar to using larger tips for soldring iron, when faced with heating up large surfaces in order to desolder something large, since we need to stay at precise temperature, and need to increase the heat supply as well.</em></p>
<p>The suggested solution is to switch to the E3D's Volcano "everything included" kit. Which is nice and cool, but I don't think it's that necessary.</p>
<ul>
<li>Is it possible to just switch to a volcano nozzle? (Manufacturer#: VOLCANO-NOZZLE-175-0400)</li>
<li>Would it actually noticeably help to increase the extrusion speed?</li>
</ul>
<p><em>Current setup:</em></p>
<ul>
<li><em>Ender 3 Pro, no mods</em></li>
<li><em>Classic 0.4 mm nozzle</em></li>
</ul>
|
<p>This is opinion-based, but the volcano has drawbacks that affect print quality, mine is oozier and sloppier than a V6 with the shorter, more precise melt zone. It isn’t a slam dunk upgrade, more of a special applications part. I think there is no point to using a Volcano unless you’re running big nozzles fast, like .8 mm.</p>
<p>Your 5 mm<sup>3</sup>/s throughput is low, the V6 is generally known as a ~13 mm<sup>3</sup>/s volumetric throughput, vs the Volcano at 25 mm<sup>3</sup>/s. This is due to the low temperature you favor, possibly something not ideal with your extruder. I could see...</p>
<ul>
<li><p>just living with the slow speed. I realize I vastly prefer print quality over print speed because one takes no human interaction and the other does.</p>
</li>
<li><p>do what everyone else does. go hotter, plastic viscosity goes way down even with a 5-10 degree increase</p>
</li>
<li><p>increase extruder torque. If you can increase stepper current safely (know the limit for your driver and motor!) with a trim pot on the stepper driver, you may be able to get more torque before the motor skips steps. This can increase motor temperature. If you get more torque, at some point the filament will slip and get carved up by the extruder’s hobbed gear. Double geared extruder designs like Bondtech can grip the filament from both sides and get more traction on the filament if you want to get diabolical shoving the filament.</p>
</li>
<li><p>use a larger nozzle for faster printing at your preferred temp. I’m loving the .6 mm nozzle for bigger prints. It has most of the detail of the .4 mm but double the plastic comes out. A larger nozzle hole means less pressure in the nozzle at a given temp and extruder feed rate</p>
</li>
</ul>
<p>If you think the extruder might not be all it can be, try heating up the nozzle hotter than usual, and get the extruder going slow and steady, and pull a little on the filament by hand, see if it skips steps easily with a little resistance. It should pull pretty strong. I had a failing wire to my extruder that manifested in wimpy extrusion.</p>
|
<p>Yes, the Volcano or the Super Volcano allow for larger flow rate (typically when using larger nozzles), that is where they were designed for. Just the nozzle will not help you, you need this larger nozzle shaft to be inside a Volcano heater block, else you cannot transfer the heat.</p>
<p>According to measurements from Metaform, the volumetric flow of a Volcano hotend is larger than the regular E3D V6 hotend.</p>
<p><a href="https://i.stack.imgur.com/5p6Le.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5p6Le.png" alt="enter image description here" /></a></p>
| 1,651
|
<p>I've got a couple large checkouts where the .svn folder has become damaged so I'm getting and error, "Cleanup failed to process the following path.." And I can no longer commit or update files in that directory.</p>
<p>I'd just delete and do the checkout again but the whole directory is over a gig.</p>
<p>Is there a tool that will restore the .svn folders for specific folders without having to download everything?</p>
<p>I understand that it's going to have to download all the files in that one folder so that it can determine if they've been changed..but subdirectories with valid .svn folders should be fine.</p>
<p>Oh.. I'm a big fan of TortoiseSVN or the command line for linux.</p>
<p>Thoughts?</p>
|
<p>In case you have changes to the files, and cannot delete them, you can use the Subversion 1.5 feature that allows you to 'checkout with obstructions'.</p>
<p>Just delete the .svn directory in this directory and:<br>
(you don't need to delete inside directories when using --depth files, thanks Eric)</p>
<p>In case the broken directory was the top directory of the working copy:</p>
<pre><code>svn checkout --depth files --force REPOS WC
</code></pre>
<p>And if the directory above the broken one is still versioned run:</p>
<pre><code>svn update --depth files --force WC
</code></pre>
<p>in that directory.<br>
In both samples REPOS is the url in the repository that matches the broken directory, and WC is the path to the directory.</p>
<p>Files that were originally modified will be in the modified state after this.</p>
|
<p>I encountered the same error today. It happened when I tried to switch branches and fail to delete one of the file that is not in svn repository. After that, the folder was locked and I can't use any command to get it work again. </p>
<p>I basically deleted what I had and redo the checkout. It is time consuming, but I really want to make sure svn is clear before I can start working again. Thanks!</p>
| 12,192
|
<p>I have a web application that makes heavy use of the Session state to store information about the current user, their personal settings, record their session history and so on. </p>
<p>I have found myself retrieving this session information in my business layer, like so:</p>
<pre><code>((UserSession)HttpContext.Current.Session["UserSession"]).User.Info
</code></pre>
<p>This poses a problem - at some point in the future my application will have a Windows client which obviously cannot reference the web Session state. So I need a host or customized session class that I can reference in my business layer that is agnostic of whether the application is running on the web or desktop. Something like:</p>
<pre><code>IHost.User.Info
</code></pre>
<p>Behind the scenes, the web implementation will obviously utilize the Session state to store information, but I need to hide this away from my business layer. Has anyone solved this problem or got any practival advice on how best to approach this?</p>
<p>Help appreciated. </p>
|
<p>Assuming that the business layer is a separate DLL, I would never add a reference to <code>System.Web</code> and in consequence I would never use the <code>Session</code> object directly. This would lead to a different design of the business layer and of the exposed interfaces to a client (either web or winforms). </p>
<p>That said, as a quick workaround I would suggest to write a wrapper class in your business layer that hides the <code>Session</code> object from your code. Your calls from code will be something like this:</p>
<pre><code>((UserSession) DualContext.Current["UserSession"]).User.Info
</code></pre>
<p>and the wrapper implementation will be something like this (not completed and tested):</p>
<pre><code>public class DualContext
{
private Dictionary<string, object> winFormsSession = new Dictionary<string, object>();
private static readonly DualContext instance = new DualContext();
public static DualContext Current
{
get { return instance; }
}
public object this[string key]
{
get
{
if (HttpContext.Current != null)
return HttpContext.Current.Session[key];
else
return winFormsSession[key];
}
set
{
if (HttpContext.Current != null)
HttpContext.Current.Session[key] = value;
else
winFormsSession[key] = value;
}
}
}
</code></pre>
|
<p>I guess you need to create a webservice or RESTfull service. The service will return an XML file representing your user information. You will be able to invoke the service wither from you windows or web application. </p>
| 29,252
|
<p>I tried to make a dynamic 2D array of <code>char</code> as follow:</p>
<pre><code>char** ppMapData = (char**)malloc(sizeof(char*)*iMapHeight);
for (int i=0; i< iMapHeight; i++)
{
ppMapData[i] = (char*)malloc(sizeof(char)*iMapWidth);
//do something
}
// do something
for (int i=0; i<iMapHeight; i++)
free(ppMapData[i]);
free(ppMapData);
</code></pre>
<p>It looks fine to me; however, when it comes to run time, my program crash at the line which calls <code>free(ppMapData[i])</code>. Any ideas what is the problem here.
Thank you very much.</p>
|
<p>At a quick glance, the frees look fine. The next thing you should test is to make sure you aren't overrunning any of these arrays past the end. This can cause problems with memory allocation systems.</p>
<p>If you are using visual studio, you can call _CrtCheckMemory to help verify that you aren't trashing things. That call only works in a DEBUG build.</p>
|
<p>Is iMapHeight / iMapWidth constant? If not, they could be changed in between, causing problems.
Also, as suggested by others, check for null returns by malloc.</p>
| 47,125
|
<p>I have a char array buffer that I am using to store characters that the user will input one by one. My code below works but has a few glitches that I can't figure out:</p>
<ol>
<li>when I execute a printf to see what's in Buffer, it does fill up but I get garbage characters at the end</li>
<li>it won't stop at 8 characters despite being declared as char Buffer[8];</li>
</ol>
<p>Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks.</p>
<pre><code>char Buffer[8]; //holds the byte stream
int i=0;
if (/* user input event has occurred */)
{
Buffer[i] = charInput;
i++;
// Display a response to input
printf("Buffer is %s!\n", Buffer);
}
</code></pre>
<p>Output:</p>
<pre>
tagBuffer is 1┬┬w!
tagBuffer is 12┬w!
tagBuffer is 123w!
tagBuffer is 1234!
tagBuffer is 12345!
tagBuffer is 123456=!
tagBuffer is 1234567!
tagBuffer is 12345678!</pre>
<p>tagBuffer is 123456789!</p>
|
<p>You have to end the string with a <code>\0</code> character. That's why they are called zero terminated strings.</p>
<p>It is also wise to allocate 1 extra char to hold the <code>\0</code>.</p>
|
<p>You might also want to look into using a <code>stringstream</code>.</p>
| 34,034
|
<p>How do I tar a list of files and folders (all in the same directory) with the exclusion of a single directory (which contains a huge amount of data)</p>
|
<p><code>tar --exclude=PATTERN xvzf nameof.tar.gz ./*</code></p>
<p>PATTERN can be the directory name. GNU tar. </p>
|
<p>I think it may depend on your version of tar. You can use 'man tar' or 'tar --help' to check for details on your version. But the options I found are:</p>
<p>tar -X <em>filename</em>: excludes anything listed in the given text file<br>
tar --exclude=<em>pattern</em>: excludes anything matching the pattern</p>
| 17,128
|
<p>I work on a variety of projects using different languages and platforms. Parts of them I abstract out into their own separate projects, and I want to open some of these up to the public.</p>
<p>What gets me stuck is the christening.</p>
<p>So, does it matter? Should I just choose something and stick with it?</p>
<p>And if it does matter, what's better: a cool-sounding name that's memorable, or a descriptive name that's easier to find?</p>
|
<p>I think naming is an important part of getting ideas to spread. What I look for in a name are:</p>
<ol>
<li>Memorable. It should be different than other names but easy to remember.</li>
<li>Accurate. It is helpful if the name reflects something about the project.</li>
<li>Positive. It is helpful if the opposite of the name is unattractive. For example, Structured Programming follows this rule because no one wants to be unstructured.</li>
<li>Clever. Clever is optional, but it helps make a name memorable when you achieve it. Clever ages badly, though.</li>
</ol>
<p>It's not worth waiting to program until you have cool name. The more experience you have with the project, the easier it is to name. JUnit wasn't christened until several months after its debut.</p>
<p>For more information about naming, I highly recommend "<a href="http://books.google.com/books?id=vHqxeKVLAYAC" rel="noreferrer">Words That Work: It's Not What You Say, It's What People Hear</a>" by Frank Luntz. He is an amoral political operative, but he loves language and communicates that love effectively.</p>
<p>One last point about "sticky" projects: be sure to tell the "creation myth" frequently, the story of how the project got started. Every project I've seen that has had long-term impact has had an oft-repeated story about its genesis.</p>
|
<p>Would be hard to suggest a name to use if we don't know what the product is.</p>
<p>Also, this sounds a lot like a marketing question. I would say something cool and memorable but is descriptive as well. iTunes comes to mind.</p>
| 23,506
|
<p>Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.</p>
|
<p>You can't do something like this:</p>
<pre><code>class A {
B b;
};
class B {
A a;
};
</code></pre>
<p>The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!</p>
<p>You can, however, do this:</p>
<pre><code>class B; // this is a "forward declaration"
class A {
B *b;
};
class B {
A a;
};
</code></pre>
<p>Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.</p>
|
<p>Is this close to what you want: The first class contains the second class, but the second class (that is to be created first) just has a reference to the first class?</p>
| 13,845
|
<p>Let's say I have a database, and an RSS feed. I have to find out what is the new data from an RSS feed, that isn't already in the database. How would you go about approaching this problem?</p>
|
<p>How about generating a hashcode or some unique identifier to each RSS item, then storing it in the database? Then you just generate the hashcode for each item in the new RSS, and check it against the database.</p>
|
<p>Pull from a unique field of a particular item in the rss feed. Then check to see if that item is already in the db. Run this logic in a loop.</p>
| 20,617
|
<pre><code><div spry:region="ds1" spry:repeatchildren="ds1">
<b spry:if=" '{title}'!='' ">
<!-- this is the first if -->
<a href="#" spry:if=" '{author}'!='' ">{author}
<!-- this is the second if -->
</a>
</b>
</div>
</code></pre>
<p><br><br>
I wonder if there is any method as simple as </p>
<pre><code>if(x==y && i>j)
</code></pre>
<p>in </p>
<pre><code><b>spry</b>
</code></pre>
<p>region.
I can't find any information in spry docs (labs.adobe.com/technologies/spry/)</p>
|
<p>The syntax inside the <code>spry:if</code> attribute is Javascript, so you can use <code>&&</code>:</p>
<pre><code><b spry:if="'{title}' != '' && '{author}' != ''">
<!-- ... -->
</b>
</code></pre>
|
<p>Normally I do like this </p>
<pre><code><div spry:region="ds1" spry:repeatchildren="ds1">
<b spry:if=" '{ds1::title}'!='' && '{ds1::author}'!=''">
<a href="#">{author}</a>
</b>
</div>
</code></pre>
| 21,527
|
<p>I have an <strong>if</strong> condition which checks for value and the it throws new <strong>NumberFormatException</strong></p>
<p>Is there any other way to code this</p>
<pre><code>if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
</code></pre>
|
<p>If your aim is to avoid to throw a new exception:</p>
<pre><code>if(foo)
{
//some msg...
} else
{
//do something else
}
</code></pre>
|
<p>In Java, you can try parsing a string with regular expressions before trying to convert it to a number.</p>
<p>If you're trying to catch your own exception (why???) you could do this:</p>
<pre><code>try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
</code></pre>
| 18,422
|
<p>I've download an image from the Internet and converted to a String (This is not changeable)</p>
<pre><code>Dim Request As System.Net.WebRequest = _
System.Net.WebRequest.Create( _
"http://www.google.com/images/nav_logo.png")
Dim WebResponse As System.Net.HttpWebResponse = _
DirectCast(Request.GetResponse(), System.Net.HttpWebResponse)
Dim Stream As New System.IO.StreamReader( _
WebResponse.GetResponseStream, System.Text.Encoding.UTF8)
Dim Text as String = Stream.ReadToEnd
</code></pre>
<p>How can I convert the String back to the Stream?</p>
<p>So I can use that stream to get the image.</p>
<p>Like this:</p>
<pre><code>Dim Image As New Drawing.Bitmap(WebResponse.GetResponseStream)
</code></pre>
<p>But now I've only the Text String, so I need something like this:</p>
<pre><code>Dim Stream as Stream = ReadToStream(Text, System.Text.Encoding.UTF8)
Dim Image As New Drawing.Bitmap(Stream)
</code></pre>
<p>EDIT:</p>
<p>This engine was primarily used for downloading web pages but I'm trying to use it for downloading images too.
The format of the string is UTF8, as given in the example code...</p>
<p>I've tried to use the <code>MemoryStream(Encoding.UTF8.GetBytes(Text))</code>, but I got this error when loading the stream to the image:</p>
<blockquote>
<p>A generic error occurred in GDI+.</p>
</blockquote>
<p>What gets lost in the conversions?</p>
|
<p>Why have you converted binary (image) data to a string? This makes no sense... unless you are using base-64?</p>
<p>Anyway, to reverse what you have done, you could try using <code>new MemoryStream(Encoding.UTF8.GetBytes(text))</code>?</p>
<p>This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.</p>
<p>(edit)</p>
<p>I should add that to work with base-64, simply get the data as a <code>byte[]</code>, then call <code>Convert.ToBase64String(...)</code>; and to get back the array, just use <code>Convert.FromBase64String(...)</code>.</p>
<hr>
<p>Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a <code>byte[]</code>, so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).</p>
<p>To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that <code>WebClient</code> might make this simpler, as it exposes <code>byte[]</code> functionality directly:</p>
<pre><code>using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
</code></pre>
<p>Anyway, using a standard <code>Stream</code> approach, here's how to encode and decode the base-64:</p>
<pre><code> // ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
</code></pre>
|
<p>Converting binary data to a string in the way you have shown will render it useless. You can't pull it pack out. The text encoding hoses it.</p>
<p>You need to use Base64 - like <a href="https://stackoverflow.com/questions/351126/convert-a-string-to-stream#351156">@Marc</a> shows.</p>
| 45,707
|
<p>Just one quick question about the filament. </p>
<p>Can I leave the filament in the extruder for a prolonged period of time while the printer is off?</p>
|
<p>Most filaments you can leave in the extruder indefinitely without any ill effects.</p>
<p>There are some filaments that need to be stored away from moisture, particularly Nylon, because they absorb moisture from the air and don't print well if they contain a lot of absorbed moisture. However, this isn't an inherent issue with having the filaments in the extruder (if you had some setup that protected the filament from moisture while in the extruder, that would be fine as well - but in most cases it is more practical to store such filament in an airtight box). </p>
<p>Most commodity filaments (ABS/PLA/PETG) don't suffer from this as much (PLA supposedly also absorbs moisture but I haven't noticed this to be a problem, perhaps it depends on the conditions of the room in which your printer is kept) so they're fine to leave in the extruder.</p>
|
<p>If you "planing" to leave the filament there for months, then it would be a good idea to store it away, but for most filaments it is not a big deal to be stay loaded... provided that the humidity is not high (e.g. a shower or kitchen next to it would be not so good). </p>
<p>My experiences with "moistured" filament is that they get brittle, but only breaks when I don't print something. And it is a pain in the a** to get out the last part of the filament that broke right at the entrance... so store it away is always a good idea, if you are not too lazy ;) </p>
| 928
|
<p>I'm trying to get my head around SPL iterators and I've come up with 2 ways to handle it. I see the first version to be less complicated but the second version has composition feel to it (I think).</p>
<p>What am I not seeing is which one is preferable over the other? Or am I just over complicating this?</p>
<p>Here are my thoughts:</p>
<p>The object implements an iterator:</p>
<pre><code>class BoxOfChocolates implements Iterator {
private $id
private $name; // e.g. Valentine's Heart Box
private $maker; // e.g. Hersheys
private $items; // array
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}
</code></pre>
<p>The object contains an iterate-able object:</p>
<pre><code>class BoxOfChocolates {
private $id;
private $name;
private $maker;
private $items; // chocolates object
public function getChocolates() {
$this->items = new Chocolates();
$this->items->getChocolates();
}
}
class Chocolates implements Iterator {
private $items;
public function getChocolates() {
$query = ...
foreach($rows as $row) {
$this->_items[] = new Chocolate() ...
}
}
// ... necessary iterator implementation stuff
}
</code></pre>
|
<p>It depends on the situation. Is the box of chocolates going t0 contain multiple collections? If so you need to have the collections be members.</p>
<p>Think of it this way. Is a box of chocolates a collection (i.e. PersonList) or something that owns a collection (i.e. a car may own a collection of it's last owners).</p>
<p>I think this falls under the first group</p>
<p>:)</p>
|
<p>Well, I don't know PHP, so I can't properly answer the question, but I'll try relating it to an area that I do know.</p>
<p>In C#, there are two interfaces: IEnumerable and IEnumerator. In your example, BoxOfChocolates would be Enumerable, Chocolates would be an Enumerator.</p>
<p>Enumerables merely have a method which returns an Enumerator. Enumerators have a concept of a current item, and a means of moving to the next item. In most cases, the Enumerator class isn't "seen". For example, in the line "foreach(Chocolate item in boxOfChoclates)" boxOfChocolates is a Enumerable; the Enumerator object is completely hidden by the foreach.</p>
| 26,566
|
<h2><strong>Accuracy Vs. Precision</strong></h2>
<p>What I would like to know is whether I should use <strong>System.currentTimeMillis()</strong> or <strong>System.nanoTime()</strong> when updating my object's positions in my game? Their change in movement is directly proportional to the elapsed time since the last call and I want to be as precise as possible.</p>
<p>I've read that there are some serious time-resolution issues between different operating systems (namely that Mac / Linux have an almost 1 ms resolution while Windows has a 50ms resolution??). I'm primarly running my apps on windows and 50ms resolution seems pretty inaccurate.</p>
<p>Are there better options than the two I listed?</p>
<p>Any suggestions / comments?</p>
|
<p>If you're just looking for extremely precise measurements of <strong>elapsed time</strong>, use <code>System.nanoTime()</code>. <code>System.currentTimeMillis()</code> will give you the most accurate possible elapsed time in milliseconds since the epoch, but <code>System.nanoTime()</code> gives you a nanosecond-precise time, relative to some arbitrary point.</p>
<p>From the Java Documentation:</p>
<blockquote>
<pre><code>public static long nanoTime()
</code></pre>
<p>Returns the current value of the most precise available system timer, in nanoseconds.</p>
<p>This method can only be used to
measure elapsed time and is not
related to any other notion of system
or wall-clock time. The value returned
represents nanoseconds since some
fixed but arbitrary <em>origin</em> time (perhaps in
the future, so values may be
negative). This method provides
nanosecond precision, but not
necessarily nanosecond accuracy. No
guarantees are made about how
frequently values change. Differences
in successive calls that span greater
than approximately 292 years (2<sup>63</sup>
nanoseconds) will not accurately
compute elapsed time due to numerical
overflow.</p>
</blockquote>
<p>For example, to measure how long some code takes to execute:</p>
<pre><code>long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
</code></pre>
<p>See also: <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--" rel="noreferrer">JavaDoc System.nanoTime()</a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--" rel="noreferrer">JavaDoc System.currentTimeMillis()</a> for more info.</p>
|
<p>one thing here is the inconsistency of the nanoTime method.it does not give very consistent values for the same input.currentTimeMillis does much better in terms of performance and consistency,and also ,though not as precise as nanoTime,has a lower margin of error,and therefore more accuracy in its value. i would therefore suggest that you use currentTimeMillis</p>
| 45,777
|
<p>I have just been getting into low level programming (reading/writing to memory that sort of thing) and have run into an issue i cannot find an answer to.</p>
<p>The piece of information i want to read from has an address that is relative to a DLL loaded in memory e,g, it is at mydll.dll + 0x01234567. the problem im having is that the dll moves around in memory but the offset stays the same. Is there anyway to find out the location of this dll in memory.</p>
<p>I am currently trying to do this preferably in c# but i would be grateful for help in most highish level languages.</p>
|
<p>i tried the method Rob Walker suggested and could not get it to work (i think it did not work because the dll was loaded as part of another executable so it could not be found so easily).</p>
<p>I did however discover a solution that worked for me so here it is:</p>
<p>i created an object of type Process</p>
<pre><code>String appToHookTo = "applicationthatloadedthedll";
Process[] foundProcesses = Process.GetProcessesByName(appToHookTo)
ProcessModuleCollection modules = foundProcesses[0].Modules;
ProcessModule dllBaseAdressIWant = null;
foreach (ProcessModule i in modules) {
if (i.ModuleName == "nameofdlliwantbaseadressof") {
dllBaseAdressIWant = i;
}
}
</code></pre>
<p>now you have the module you can just do dllbaseAdressIWant.BaseAddress to get the value.</p>
<p>Hope this helps</p>
|
<p>From a Win32 perspective you need to use the <a href="http://msdn.microsoft.com/en-us/library/ms683199(VS.85).aspx" rel="nofollow noreferrer">GetModuleHandle</a> and <a href="http://msdn.microsoft.com/en-us/library/ms683201(VS.85).aspx" rel="nofollow noreferrer">GetModuleInformation</a> functions. These let you look the module handle up by name, and then retrieve information, including the base address about that handle.</p>
<p>It should be straight forward to wrap these APIs using the standard P/Invoke wrappers.</p>
| 33,818
|
<p>Not quite sure what's happening here. I printed it as a single ball and had this effect. I thought it might be a cooling issue so I printed 4 at once but the issue still occurred. If I size the ball up, the problem reduces.</p>
<p>Note that the hole is supposed to be a cylinder.</p>
<p><a href="https://i.stack.imgur.com/owZtw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/owZtw.jpg" alt="Photo of four balls exhibiting bumps around a cyclindrical through hole"></a></p>
|
<p>It looks like possibly a combination of too high of extruder temperature and poor retraction.</p>
<ol>
<li>First, try <strong><em>reducing your extruder temperature</em></strong>. PLA ideal extruder temps range from about 185C to 225C; depending on purity, quality, and climate. This can help prevent additional oozing and clogging. If your extruder clogs easily, you probably have too high of temperature.</li>
<li>After you've verified you have correct extrusion temperature. Try <strong><em>finding/adjusting retraction settings</em></strong> in your preferred slicing engine. Here's a good troubleshoot page from <a href="https://www.simplify3d.com/support/print-quality-troubleshooting/#blobs-and-zits" rel="nofollow noreferrer">Simplify3D's website</a>.</li>
</ol>
|
<p>It looks like it is trying to fill in what might be small gaps and is putting blobs down because the gaps to too small of a detail to accurately fill.</p>
| 411
|
<p>I'm looking for something that will let me parse Atom and RSS in Ruby and Rails. I've looked at the standard RSS library, but is there one library that will auto-detect whatever type of feed it is and parse it for me?</p>
|
<p>Feedzirra is one of the better options: <a href="http://www.pauldix.net/2009/02/feedzirra-a-ruby-feed-library-built-for-speed.html" rel="noreferrer">http://www.pauldix.net/2009/02/feedzirra-a-ruby-feed-library-built-for-speed.html</a></p>
<p>Of course, I'm biased since I wrote it. :)</p>
|
<p>I like using niokrigi or scrapi for parsing the xml in the atom/rss feeds.
<a href="http://www.rubyinside.com/nokogiri-ruby-html-parser-and-xml-parser-1288.html" rel="nofollow noreferrer">http://www.rubyinside.com/nokogiri-ruby-html-parser-and-xml-parser-1288.html</a></p>
| 26,376
|
<p>So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields. </p>
<p>One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? For example:</p>
<pre><code>var bmp = System.Drawing.Bitmap.LoadFromFile("Image01.jpg");
</code></pre>
<p>As for static fields, is creating singelton-objects their best use? </p>
|
<p>It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.</p>
<p><strong>EDIT</strong>: From stevemegson in the comments</p>
<blockquote>
<p>A static factory can also return null, and can more easily return an instance that it got from cache. Many of my classes have a static FromId(int) to get an instance from a primary key, returning an existing cached instance if we have one.</p>
</blockquote>
|
<p>You may use static methods when the client of the class do not have an instance of the class to work with. For instance the Singleton design pattern is used to ensure that only one instance of a class exist in the system. It requires that the constructors of the Singleton be private so that no instances can be created by the client.</p>
<p>So if you cannot create an instance how do you access the instance methods of the class? By calling a static method that returns the Singleton instance of the class.</p>
<p>This is of course just one scenario but there are many others.</p>
| 24,773
|
<p>I would like to hear of the experiences of classic vb developers who migrated their applications to delphi rather than vb.net. How has it worked out? Are you glad or sorry that you didn't move to vb.net? </p>
|
<p>I am not really a vb developer but rather a Delphi developer who was forced to maintain some vb apps for a while. I tried to migrate one vb app to vb.net and after that experience I never tried it again. I successfully migrated several vb apps to Delphi. It wasn't easy and it became a pain in the lower back to find native Delphi replacements for some of the OCXes that had been used (I will never again rely on a third party library for which I do not have the source code.), but it worked out OK.</p>
<p>But as said above: I am an experienced Delphi developer, so I didn't have to learn Delphi at the same time as migrating a vb app. That certainly made it much easier.</p>
|
<p>I did try in two instance to migrate from VB to Delphi but unfortunately I had to abort midway in one app as it used a lot of third party ActiveX (most from ComponentOne and a few from CodeJoke). We had to abort midway as we could not find any VCL components having equivalent functionality to the ActiveX used in the project.</p>
<p>It was a nightmare for us. Thank god we aborted midway and switched to C#. It was unbelievable that we could get all the features in .NET component to the ditto!</p>
<p>The app we managed to convert, went well off but we had to get rid of a few features that we had implemented in the original software as they required more work in Delphi.</p>
| 45,750
|
<p>I want to show the publish date in the About dialog.</p>
|
<p>Unfortunately, no. ApplicationDeployment class exposes only the <a href="http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.currentversion(VS.80).aspx" rel="nofollow noreferrer">CurrentVersion</a> property, not the publish time.</p>
<p>You could use the revision field to store the date of the build to show in the About dialog.</p>
|
<p>Unfortunately, no. ApplicationDeployment class exposes only the <a href="http://msdn.microsoft.com/en-us/library/system.deployment.application.applicationdeployment.currentversion(VS.80).aspx" rel="nofollow noreferrer">CurrentVersion</a> property, not the publish time.</p>
<p>You could use the revision field to store the date of the build to show in the About dialog.</p>
| 26,816
|
<p>I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.</p>
|
<p>You actually want <code>/proc/self/status</code>, which will give you information about the currently executed process.</p>
<p>Here is an example:</p>
<pre><code>$ cat /proc/self/status
Name: cat
State: R (running)
Tgid: 17618
Pid: 17618
PPid: 3083
TracerPid: 0
Uid: 500 500 500 500
Gid: 500 500 500 500
FDSize: 32
Groups: 10 488 500
VmPeak: 4792 kB
VmSize: 4792 kB
VmLck: 0 kB
VmHWM: 432 kB
VmRSS: 432 kB
VmData: 156 kB
VmStk: 84 kB
VmExe: 32 kB
VmLib: 1532 kB
VmPTE: 24 kB
Threads: 1
SigQ: 0/32268
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
Cpus_allowed: 00000003
Mems_allowed: 1
voluntary_ctxt_switches: 0
nonvoluntary_ctxt_switches: 3
</code></pre>
<p>You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at <code>/etc/passwd</code>, or calling the relevant functions for mapping uid to username in whatever language you're using.</p>
<p>Ideally, you would just call the system call <code>getuid()</code> to look up this information, doing it by looking at <code>/proc/</code> is counterproductive.</p>
|
<p>The things you are looking for may be in environment variables. You need to be careful about what shell you are using when you check environment variables. bash uses "UID" while tcsh uses "uid" and in <code>*nix</code> case matters. I've also found that tcsh sets "gid" but I wasn't able to find a matching variable in bash.</p>
| 11,521
|
<p>I've recently come across this piece of JavaScript code:</p>
<pre><code>if (",>=,<=,<>,".indexOf("," + sCompOp + ",") != -1)
</code></pre>
<p>I was intrigued, because to write this test I would have done:</p>
<pre><code>if (/(>=|<=|<>)/.test(sCompOp))
</code></pre>
<p>Is this just a stylistic difference, or does the author of the other code know something about optimization that I don't? Or perhaps there is a different good reason to do this, or to not use regexes...?</p>
<p>It seems to me that using <code>String.indexOf()</code> for this is a little more difficult to read (but then, I'm quite comfortable with regular expressions), but are there instances where it might be "better" than writing an equivalent regex?</p>
<p>By "better" that might be quicker or more efficient, (although obviously that depends on the browser's JavaScript engine), or some other reason I'm not aware of. Can anyone enlighten me?</p>
|
<p>I ran some tests. The first method is slightly faster, but not by enough to make any real difference even under heavy use... <em>except</em> when <code>sCompOp</code> could potentially be a very long string. Because the first method searches a fixed-length string, its execution time is very stable no matter how long <code>sCompOp</code> gets, while the second method will potentially iterate through the entire length of <code>sCompOp</code>.</p>
<p>Also, the second method will potentially match invalid strings - "blah blah blah <= blah blah" satisfies the test...</p>
<p>Given that you're likely doing the work of parsing out the operator elsewhere, i doubt either edge case would be a problem. But even if this were not the case, a small modification to the expression would resolve both issues:</p>
<pre><code>/^(>=|<=|<>)$/
</code></pre>
<hr />
<h3>Testing code:</h3>
<pre><code>function Time(fn, iter)
{
var start = new Date();
for (var i=0; i<iter; ++i)
fn();
var end = new Date();
console.log(fn.toString().replace(/[\r|\n]/g, ' '), "\n : " + (end-start));
}
function IndexMethod(op)
{
return (",>=,<=,<>,".indexOf("," + op + ",") != -1);
}
function RegexMethod(op)
{
return /(>=|<=|<>)/.test(op);
}
function timeTests()
{
var loopCount = 50000;
Time(function(){IndexMethod(">=");}, loopCount);
Time(function(){IndexMethod("<=");}, loopCount);
Time(function(){IndexMethod("<>");}, loopCount);
Time(function(){IndexMethod("!!");}, loopCount);
Time(function(){IndexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){IndexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
Time(function(){RegexMethod(">=");}, loopCount);
Time(function(){RegexMethod("<=");}, loopCount);
Time(function(){RegexMethod("<>");}, loopCount);
Time(function(){RegexMethod("!!");}, loopCount);
Time(function(){RegexMethod("the quick brown foxes jumped over the lazy dogs");}, loopCount);
Time(function(){RegexMethod("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");}, loopCount);
}
timeTests();
</code></pre>
<p>Tested in IE6, FF3, Chrome 0.2.149.30</p>
|
<p>Is it a really old piece of code? It may have been written before regexes were widely used in javascript. Overall it looks like someone was trying to be too clever and "optimized" that statement or came from a C background and wasn't used to regexes. A regular expression can be expensive to use but string concatenation can be too and if it's not in a loop I would go with whichever one is easier to understand (for me, the regex).</p>
| 22,188
|
<p>In a servlet I do the following:</p>
<pre><code> Context context = new InitialContext();
value = (String) context.lookup("java:comp/env/propertyName");
</code></pre>
<p>On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key <em>propertyName</em>?</p>
<p>In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.</p>
|
<p>One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more <code><env-entry></code> tags. For example, something like the following:</p>
<pre><code><env-entry>
<description>My string property</descriptor>
<env-entry-name>propertyName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>Your string goes here</env-entry-value>
</env-entry>
</code></pre>
<p>Each env-entry tag declares a new environment variable that you can then access from the <code>java:comp/env</code> context.</p>
<p>Once you add the necessary <code>env-entry</code>'s you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work.</p>
|
<p>It is possible to put your properties in a file and make the name and location of the file a resource-ref of type URL in web.xml. The value of the resource is set in geronimo-web.xml.</p>
<p>Your web.xml will have the following entry:</p>
<pre><code><resource-ref>
<res-ref-name>configFileName</res-ref-name>
<res-type>java.net.URL</res-type>
</resource-ref>
</code></pre>
<p>In geronimo-web.xml you define the value for the configFileName</p>
<pre><code><name:resource-ref>
<name:ref-name>configFileName</name:ref-name>
<name:url>file:///etc/myConfigFile</name:url>
</name:resource-ref>
</code></pre>
<p>In java you have the following code to lookup the value:</p>
<pre><code>initialContext = new InitialContext();
URL url = (URL) initialContext.lookup("java:comp/env/configFileName");
String configFileName = url.getPath();
</code></pre>
<p>Then you have to open the file and read whatever value is in there.</p>
<p>The result of all this is that you have the properties in a file on the filesystem. It will not be overwritten if you redeploy your application.</p>
| 16,962
|
<p>Some of Oracle's analytic functions allow for a <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i97640" rel="nofollow noreferrer">windowing clause</a> to specify a subset of the current partition, using keywords like "unbounded preceding/following", "current row", or "value_expr preceding/following" where value_expr is a physical or logical offset from the current row or value (depending on whether you have specified ROW or RANGE, respectively). </p>
<p>Here is an example using scott/tiger that displays employees in dept 30, and a count of the number of employees in their dept hired before them (including themselves):</p>
<pre><code>select deptno,
empno,
hiredate,
count(*) over (partition by deptno
order by hiredate
range between unbounded preceding and current row) cnt_hired_before1,
count(*) over (partition by deptno
order by hiredate
range between unbounded preceding and 0 preceding) cnt_hired_before2
from emp
where deptno = 30
order by deptno, hiredate;
</code></pre>
<p>...can anyone provide an example or documentation where "current row" is different than "0 preceding/following"? It just seems like syntactic sugar to me...</p>
|
<p>It doesn't really matter which you use. They are two different ways of expressing the windowing, but the optimizer will perform the query the same way. The term "current row" is one that is common to multiple databases with analytic functions, not just Oracle. It's more of a stylistic difference, in the same way that some people prefer count(*) over count(1).</p>
|
<p>It is all about what you're trying to accomplish.
You may want to use RANGE BETWEEN/ROWS BETWEEN use it to find LAST_VALUE within the sub-set or compare things within a sub-set. But most certainly you don't need for the example you provided.</p>
<pre><code> select deptno,
empno,
hiredate,
count(*) over (partition by deptno, trunc(hiredate,'mm')) cnt_same_month
from emp
where deptno = 30
order by deptno, hiredate
</code></pre>
| 49,741
|
<p>We often send emails in HTML for clients (Dont like it but not my choice)</p>
<p>Does anyone have any info or a link on support for the dynscrc attribute or img in email clients?</p>
|
<p>My solution here would be to have a screenshot (perhaps with a 'click to watch' overlay) of your movie that links to a non-mail page that has a player in it.</p>
<p>Dealing with html email, in my experience, isn't so much about having standards as it is learning to compromise. Web client and (the increasingly rare) desktop clients have differing behaviors that make website browser compliance seem like preschool by comparison.</p>
|
<p>I found some info here <a href="http://stylecampaign.com/blog/?p=29" rel="nofollow noreferrer">http://stylecampaign.com/blog/?p=29</a></p>
<p>not comprehensive.</p>
<p>Ben suggestion is something I would consider myself if appropriate to the situation</p>
| 39,170
|
<p>I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:</p>
<pre><code>vector<int> n
</code></pre>
<p>and the values are inserted like this:</p>
<pre><code>srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
</code></pre>
<p>I'm creating a separate function to find all the non-prime values. Here is what I have now, but I know it's completely wrong as I get both prime and composite in the series.</p>
<pre><code>void sieve(vector<int> v, int n)
{
int i,j;
for(i = 2; i <= n; i++)
{
cout << i << " % ";
for(j = 0; j <= n; j++)
{
if(i % v[j] == 0)
cout << v[j] << endl;
}
}
}
</code></pre>
<p>This method typically worked when I just had a series of numbers from 0-1000, but it doesn't seem to be working now when I have numbers out of order and duplicates. Is there a better method to find non-prime numbers in a vector? I'm tempted to just create another vector, fill it with n numbers and just find the non-primes that way, but would that be inefficient?</p>
<p>Okay, since the range is from 0-1000 I am wondering if it's easier to just create vector with 0-n sorted, and then using a sieve to find the primes, is this getting any closer?</p>
<pre><code>void sieve(vector<int> v, BST<int> t, int n)
{
vector<int> v_nonPrime(n);
int i,j;
for(i = 2; i < n; i++)
v_nonPrime[i] = i;
for(i = 2; i < n; i++)
{
for(j = i + 1; j < n; j++)
{
if(v_nonPrime[i] % j == 0)
cout << v_nonPrime[i] << endl;
}
}
}
</code></pre>
|
<p>In this code:</p>
<pre><code>if(i % v[j] == 0)
cout << v[j] << endl;
</code></pre>
<p>You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:</p>
<pre><code>if(v[j] % i == 0)
</code></pre>
<p>Right now, you are printing random divisors of i. You are not printing out random numbers which are known not to be prime. Also, you will have duplicates in your output, perhaps that is ok.</p>
|
<p>The idea of the sieve that you try to implement depends on the fact that you start at a prime (2) and cross out multitudes of that number - so all numbers that depend on the prime "2" are ruled out beforehand. </p>
<p>That's because all non-primes can be factorized down to primes. Whereas primes are not divisible with modulo 0 unless you divide them by 1 or by themselves.</p>
<p>So, if you want to rely on this algorithm, you will need some mean to actually restore this property of the algorithm.</p>
| 30,866
|
<p>We have various servers that have many directories shared. It's easy enough to look at the share browser to see what the "top level" shares are, but underneath is a jumbled mess of custom permissions, none of which is documented.</p>
<p>I'd like to enumerate all the shares on the domain (definitely all the 'servers', local PCs would be nice) and then recurse down each one and report any deviation from the parent. If the child has the same permissions, no need to report that back.</p>
<p>I'd prefer a simple script-y solution to writing a big C# app, but any method that works will do (even existing software).</p>
<p>For example, I'd like to get:</p>
<pre><code>SERVER1\
\-- C: (EVERYONE: Total control, ADMINs, etc. etc.)
\-- (skip anything that is not the same as above)
\-- SuperSecretStuff (Everyone: NO access; Bob: Read access)
SERVER2\
\-- Stuff (some people)
</code></pre>
<p>etc.</p>
|
<p>According to the JEdit <a href="http://jedit.org/index.php?page=features" rel="nofollow noreferrer">features page</a> it already supports Objective C.</p>
|
<p>One of my favorite things about JEdit is how easy it is to define a new syntax highlighting mode. I work in a land in which every fool wants to create his own custom configuration file language and I've gotten to where I can create a new approximate syntax highlighting mode in about 5 minutes. I start by copying a mode that is similar to the new language I wanted to create and then iteratively refining the edit mode as I learn more parts of the language. I did this with Specman ( a hardware verification language ) as I was going through the intro course.</p>
| 14,094
|
<p>Is it possible to use the Flex Framework and Components, without using MXML? I know ActionScript pretty decently, and don't feel like messing around with some new XML language just to get some simple UI in there. Can anyone provide an example consisting of an .as file which can be compiled (ideally via FlashDevelop, though just telling how to do it with the Flex SDK is ok too) and uses the Flex Framework? For example, just showing a Flex button that pops open an Alert would be perfect.</p>
<p>If it's not possible, can someone provide a minimal MXML file which will bootstrap a custom AS class which then has access to the Flex SDK?</p>
|
<p>I did a simple bootstrap similar to Borek (see below). I would love to get rid of the mxml file, but if I don't have it, I don't get any of the standard themes that come with Flex (haloclassic.swc, etc). Does anybody know how to do what Theo suggests and still have the standard themes applied?</p>
<p>Here's my simplified bootstrapping method:</p>
<p>main.mxml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<custom:ApplicationClass xmlns:custom="components.*"/>
</code></pre>
<p>ApplicationClass.as</p>
<pre><code>package components {
import mx.core.Application;
import mx.events.FlexEvent;
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.controls.Button;
public class ApplicationClass extends Application {
public function ApplicationClass () {
addEventListener (FlexEvent.CREATION_COMPLETE, handleComplete);
}
private function handleComplete( event : FlexEvent ) : void {
var button : Button = new Button();
button.label = "My favorite button";
button.styleName="halo"
button.addEventListener(MouseEvent.CLICK, handleClick);
addChild( button );
}
private function handleClick(e:MouseEvent):void {
Alert.show("You clicked on the button!", "Clickity");
}
}
}
</code></pre>
<hr>
<p>Here are the necessary updates to use it with Flex 4:</p>
<p>main.mxml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<local:MyApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:local="components.*" />
</code></pre>
<p>MyApplication.as</p>
<pre><code>package components {
import flash.events.MouseEvent;
import mx.controls.Alert;
import mx.events.FlexEvent;
import spark.components.Application;
import spark.components.Button;
public class MyApplication extends Application {
public function MyApplication() {
addEventListener(FlexEvent.CREATION_COMPLETE, creationHandler);
}
private function creationHandler(e:FlexEvent):void {
var button : Button = new Button();
button.label = "My favorite button";
button.styleName="halo"
button.addEventListener(MouseEvent.CLICK, handleClick);
addElement( button );
}
private function handleClick(e:MouseEvent):void {
Alert.show("You clicked it!", "Clickity!");
}
}
}
</code></pre>
|
<p>Yes, you just need to include the flex swc in your classpath. You can find flex.swc in the flex sdk in frameoworks/lib/flex.swc</p>
<p>edit: One more thing: if you're using Flex Builder you can simply create a new ActionScript project, which will essentially do the same as above.</p>
| 17,067
|
<p>I finally manage to setup the ABL on my Prusa.
I run G28 to home all axes (for z I use the same probe used for ABL). Then
I run G29 E ( I use E because otherwise for some reason I have not understood yet, Z does not lift during probings) probing 4 points on the corners of the bed.</p>
<p>finally I get the map of the bed:</p>
<pre><code>Bed Level Correction Matrix:
+0.999999 +0.000000 +0.001233
-0.000005 +0.999992 +0.003905
-0.001233 -0.003905 +0.999992
</code></pre>
<p>and after that, the print starts.
The first layer looks perfect however I have not seen Z moving a single step along the printing.</p>
<p>Any hint about what to check? Is the obtained map indicating that the bed is already too leveled to act on any compensation?</p>
<p><strong>UPDATE</strong>
I printed a 180 mm diamater cylinder and the Z axis is not compensating the 1mm difference from edge to edge of the bed.</p>
|
<p>I found the issue. As I mentioned in my question UPDATE, trying to print something that cover the full bed, the ABL was not working.
The issue was the Gcode I added after the G29.
In fact for some reason I added a G28 X0 after the G29 and that basically cancel the data acquired in the G29.
I learned something new, do not use G28 after G29!</p>
<p>Now it is working nicely.</p>
|
<p>I believe that the matrix is shown transposed from how it should be, but that doesn't affect the answer. The compensated Z position is derived from the original <code>(X,Y,Z)</code> position by multiplying the corresponding vector with that matrix. This means that the new Z position would be</p>
<pre><code>Z' = 0.999992Z - 0.001233X - 0.003905Y
</code></pre>
<p>If you have a 200 x 200 printbed, a diagonal move from one corner to the other would correspond to a 1mm change in Z-height. This should be noticeable, but if perhaps you're printing something quite small you might not notice it.</p>
<p>Though, if your first layer is perfect, I would see no reason to mess with it.</p>
| 423
|
<p>When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using <code>{{ myVar }}</code>.</p>
<p>Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.</p>
|
<p>The <code>{{variable}}</code> is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.</p>
<p>Having said that, you can put this kind of substitution into your JavaScript.</p>
<pre class="lang-html prettyprint-override"><code><script type="text/javascript">
var a = "{{someDjangoVariable}}";
</script>
</code></pre>
<p>This gives you "dynamic" javascript.</p>
|
<p>you can assemble the entire script where your array variable is declared in a string, as follows, </p>
<blockquote>
<p>views.py</p>
</blockquote>
<pre><code> aaa = [41, 56, 25, 48, 72, 34, 12]
prueba = "<script>var data2 =["
for a in aaa:
aa = str(a)
prueba = prueba + "'" + aa + "',"
prueba = prueba + "];</script>"
</code></pre>
<p>that will generate a string as follows</p>
<pre><code>prueba = "<script>var data2 =['41','56','25','48','72','34','12'];</script>"
</code></pre>
<p>after having this string, you must send it to the template</p>
<blockquote>
<p>views.py</p>
</blockquote>
<pre><code>return render(request, 'example.html', {"prueba": prueba})
</code></pre>
<p>in the template you receive it and interpret it in a literary way as htm code, just before the javascript code where you need it, for example</p>
<blockquote>
<p>template</p>
</blockquote>
<pre><code>{{ prueba|safe }}
</code></pre>
<p>and below that is the rest of your code, keep in mind that the variable to use in the example is data2</p>
<pre><code><script>
console.log(data2);
</script>
</code></pre>
<p>that way you will keep the type of data, which in this case is an arrangement</p>
| 38,259
|
<p>I'm working on a game for the iPhone and would like it to be able to submit scores back to the server. Simple enough, but I want the scores to be verified to actually come from a game-play. With the (defacto) prohibition on real crypto with the export conditions, what would be the best way to get information back in a secure/verified channel?</p>
<p>All my thoughts lead back to an RSA-style digital signature algorithm, but would prefer something less "crypto" to get past that export question.</p>
<p>Thanks!</p>
|
<p>Couldn't you just use a client certificate (signed by you) and establish an HTTPS connection to your server, which has been configured to only accept connections begun with a client certificate signed by you?</p>
|
<p>generate a random, something fairly long, then tack the score to the end, and maybe the name or something else static, then sha1/md5 it, and pass both to the server, verify that the random hashes, to be equal to the hash.</p>
<p>After-thought: If you want to make it harder to reverse engenier, then multiply your random by the numerical representation of the day (monday=1, tuesday=2,...)</p>
| 10,405
|
<p>I have the need to be able to cycle my linksys router via a program, the reason I want to do this is complex, so let's just assume there is no better option.</p>
<p>Is there anyway to do this? I think there is because when I install a firmware update to the router via the admin console, it cycles the router.</p>
|
<p>If you can find the function to do that on the router's web interface, you can achieve the same via a suitable HTTP request. Also, you can often telnet to the router and reboot it through its command-line interface. Programmatically you can achieve the same, by using a tool like <a href="http://en.wikipedia.org/wiki/Expect" rel="nofollow noreferrer">expect</a>.</p>
|
<p><a href="https://github.com/danielrussellLA/restart-linksys-EA2700-router" rel="nofollow noreferrer">https://github.com/danielrussellLA/restart-linksys-EA2700-router</a> you can try using a nightwatch bot similar to this one to programatically restart your router through its browser ui. This works well if your router does not have a command line interface that you can access (through telnet, ssh etc). It's pretty hacky, but it gets the job done.</p>
| 17,664
|
<p>i have a sharepoint list </p>
<p>with 2 users for examole (user A and user B)</p>
<p>i need a calculated field in the list items such that if user "A" created the item the field vaule will be "X" and if user "B" created the item fields value would be "Y"</p>
<p>but i couldnt use [created by] in the furmiula of the calculated field !! why is that ?!! and is there another way to do what i need to do ?!</p>
|
<p>If using Sharepoint Designer is an option you can create a workflow for that list. Set it to start when a new item is created -or- edited, use a condition of "If Created_By equals ..." and an action of "Set yourfield to yourvalue", then add an Else If branch and repeat. This will always override anything a user enters in "yourfield". Takes about 2 minutes to do all of this.</p>
|
<p>I believe you can create a text field that has the default value set to [Me] which should then be usable in a calculated field.</p>
| 13,393
|
<p>I am having a listbox in ASP.net. I am populating the listbox values from another listbox in a page dynamically. During postbacks the values of output listbox are not persisted.
(while going to another page and come back to this page).</p>
<p>Please suggest some good answer. EnableViewstate = "true" is not working.</p>
|
<p>Are you doing anything in Page_Load that should be in a </p>
<pre><code>if(!IsPostBack) {}
</code></pre>
<p>Initialization code in load needs to only be called when the page is first loaded, not on postbacks.</p>
<p>If you are going to another page and then coming back to this page, I think you need to preserve the information yourself in the Session and then restore it when you come back to the page.</p>
|
<p>Initialize the content of your controls in your Page's Init event (Page_Init). That way any values the user supplies are not overwritten by your defaults.</p>
| 25,038
|
<p>So our scenario is this: We have multiple Sharepoint sites that are created dynamically on a "as requested" basis. Basically there's a new site for each new project. Now, for every site we want to add a search clause that says that only contents with a metadata tag value equal to the sitename should be found. Quick example:
There are 2 sites/projects: Bear and Wolf. Sharepoint Search has index all of the documents/lists/etc from these sites and a common archive for them. All documents in the common archive has a property called "ProjectName". When Bill, who's on the Wolf team, wants to search for "specifications" in his project site (Wolf) he only wants to see documents relevant to that project.
So how do I make sure that all the documents have the "ProjectName" value set to "Wolf"?</p>
<p>I'm guessing I <em>could</em> use Scopes here, but currently there are ~200 sites and this is growing every month and so maintaining that manually is not an option. If there's a relativly easy way of automating Scopes; excellent.</p>
|
<p>You can use script if you want to see if the logged on user is an administrator</p>
<pre><code>Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName
isAdministrator = false
Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
If objUser.Name = strUser Then
isAdministrator = true
End If
Next
If isAdministrator Then
Wscript.Echo strUser & " is a local administrator."
Else
Wscript.Echo strUser & " is not a local administrator."
End If
</code></pre>
<p>I am not sure how to handle it when the script is run with "Runas" I am afraid.</p>
|
<pre><code>Function isAdmin
Dim shell
Set shell = CreateObject("WScript.Shell")
isAdmin = false
errorLevel = shell.Run("%comspec% /c net session >nul 2>&1", 0, True)
if errorLevel = 0
isAdmin = true
End If
End Function
</code></pre>
| 38,745
|
<p>I'm trying to produce sheets of photographs with captions arranged in a grid using XSLT and XSL-FO. The photo URLs and captions are produced using a FOR XML query against an SQL Server database, and the number of photos returned varies from sheet to sheet. I want to lay the photos out in four columns, filling the grid from left to right and from top to bottom. In HTML I'd do this by putting each photo and caption into a div and using "float: left" to make them flow into the grid. Is there a similarly elegant method using XSL-FO?</p>
|
<p>To keep life simple I would normally setup a table for this, it's quite simple and will ensure that things get laid out right. If you wanted to do it similarly to how you would do it in HTML then you should layout block-container elements.</p>
<p>However you decide to do it I would always recommend using the <a href="http://www.zvon.org/xxl/xslfoReference/Output/index.html" rel="nofollow noreferrer">ZVON Reference</a> site. Nice lookup of elements and available attributes, and while their XSL-FO doesn't include much in the way of explanation every page deep links to the standards document.</p>
|
<p>In the end I used a table with one row and four cells for this. In each one I selected the source elements with position() mod 4 equal to 0, 1, 2 or 3 as appropriate, and then made sure that the photo and caption was always the same height so the rows lined up correctly.</p>
| 7,748
|
<p>I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable?</p>
|
<p>Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:</p>
<pre><code>a {
display: block;
width: 100%;
}
</code></pre>
|
<p>If you only have the text in the <a> ... </a>, that's the only part that can be clicked on. Move your graphics, etc. inside the link.</p>
| 12,596
|
<p>Well, i've got a nice WPF book its called Sams Windows Presentation Foundation Unleashed.
I really like to read and learn with it. Are there any other WPF books you could recommend? </p>
|
<p>I've found the following books very useful:</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0672328917" rel="noreferrer" rel="nofollow noreferrer">Windows Presentation Foundation Unleashed - Adam Nathan</a><br />
You mention you already have this book, however I wanted to give my opinion on it. It is a great book for the newcomer - it is printed in full color which is a great help for visualizing both xaml and concepts for WPF.<br /><br />
<a href="https://rads.stackoverflow.com/amzn/click/com/0321374479" rel="noreferrer" rel="nofollow noreferrer">Essential Windows Presentation Foundation - Chris Anderson</a><br />
This is also another great book for the newcomer. While it is not printed in color, it does give a great insight into how WPF works.<br /><br />
<a href="https://rads.stackoverflow.com/amzn/click/com/1590599551" rel="noreferrer" rel="nofollow noreferrer">Pro WPF in C# 2008 - Matthew Macdonald</a><br />
This is a great reference book - one that sits on my desk and is constantly referred too. However, I didn't feel is was as newbie friendly as the other two books above. This is the most recently released book (at the time of this posting), and has been updated for VS2008. This is useful, as there are some changes with the versions of WPF. I believe there is a VB.NET version available.<br /><br />
<a href="https://rads.stackoverflow.com/amzn/click/com/0596510373" rel="noreferrer" rel="nofollow noreferrer">Programming WPF - Chris Sells & Ian Griffiths</a><br />
Another great book - I wish this was available when I was first learning the framework.<br /><br />
<a href="https://rads.stackoverflow.com/amzn/click/com/0735619573" rel="noreferrer" rel="nofollow noreferrer">Application = Code + Markup - Charles Petzold</a><br />
This was the very first WPF I purchased. It is <em>not</em> very newbie friendly, and I wouldn't recommend it for a first-time-wpf'er. The fact that Xaml is not introduced until page 457 makes learning the technology for the real world very difficult. That said, this book is invaluable if you really want to understand how things work at a very deep level (which is also important to get the most of the framework.</p>
<p>The only book I would totally avoid is:</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0470041803" rel="noreferrer" rel="nofollow noreferrer">Professional WPF Programming - Chris Andrade et al.</a><br />
While the content was Ok in this book, I just found the other books to be much clearer and delve to a much deeper level.<br /><br /></p>
<p>Hope this helps! WPF has a steep learning curve, but once you "get it", UI programming can actually become "fun"!</p>
|
<p>Yes, I highly recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0596510373" rel="nofollow noreferrer" rel="nofollow noreferrer">this one</a></p>
| 3,096
|
<p>I have an RSS source:</p>
<pre><code>http://feedity.com/rss.aspx/mr1-kossuth-hu/VVdXUlY
</code></pre>
<pre><code><item>
<title>2008. november 23.</title>
<link>http://www.mr1-kossuth.hu/m3u/0039c36f_3003051.m3u</link>
<description>........</description>
<pubDate>Wed, 26 Nov 2008 00:00:00 GMT</pubDate>
</item>
</code></pre>
<p>From this, I want to create a podcast-friendly feed. I want to replace the LINK children to:</p>
<pre><code>http://stream001.radio.hu:8000/content/*.mp3
</code></pre>
<p>Example:</p>
<pre><code><item>
<title>2008. november 23.</title>
<link>http://stream001.radio.hu:8000/content/0039c36f_3003051.mp3</link>
<description>........</description>
<pubDate>Wed, 26 Nov 2008 00:00:00 GMT</pubDate>
</item>
</code></pre>
<p>How I can do that in PHP?</p>
|
<p><strong>This is a simple and pure XSLT 1.0 solution</strong>, consisting of just 47 lines, half of which are closing tags. <strong>The following transformation</strong>:</p>
<pre>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:param name="pNewLink"
select="'http://stream001.radio.hu:8000/content/'"/>
<xsl:param name="pNewExt" select="'.mp3'"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="link">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:variable name="vFName">
<xsl:call-template name="GetFileName">
<xsl:with-param name="pFPath" select="."/>
</xsl:call-template>
</xsl:variable>
<xsl:value-of select="concat($pNewLink,$vFName,$pNewExt)"/>
</xsl:copy>
</xsl:template>
<xsl:template name="GetFileName">
<xsl:param name="pFPath"/>
<xsl:choose>
<xsl:when test="not(contains($pFPath, '/'))">
<xsl:value-of select="substring-before($pFPath, '.')"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="GetFileName">
<xsl:with-param name="pFPath"
select="substring-after($pFPath, '/')"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
</pre>
<p><strong>when applied on the provided source XML document</strong>:</p>
<pre>
<item>
<title>2008. november 23.</title>
<link>http://www.mr1-kossuth.hu/m3u/0039c36f_3003051.m3u</link>
<description>........</description>
<pubDate>Wed, 26 Nov 2008 00:00:00 GMT</pubDate>
</item>
</pre>
<p><strong>produces the wanted result</strong>:</p>
<pre>
<item>
<title>2008. november 23.</title>
<link>http://stream001.radio.hu:8000/content/0039c36f_3003051.mp3</link>
<description>........</description>
<pubDate>Wed, 26 Nov 2008 00:00:00 GMT</pubDate>
</item>
</pre>
<p><strong>Do note the following</strong> specific features of this solution:</p>
<ol>
<li><p>We use the XSLT design pattern of using and overriding the <a href="http://www.w3.org/TR/xslt#copying" rel="nofollow noreferrer"><strong>identity transformation</strong></a>.</p></li>
<li><p><strong>The template named "GetFileName</strong>" extracts from the complete URL (passed as parameter), just the filename with the file extension stripped off. This <strong>is a good example of a named template that calls itself recursively</strong>.</p></li>
<li>The constituents of the desired new URLs are specified as global <code><xsl:param></code>s</li>
</ol>
|
<p>The easiest way is a simple string replace:</p>
<pre><code>$str = file_get_contents('http://feedity.com/rss.aspx/mr1-kossuth-hu/VVdXUlY');
$str = str_replace('<link>http://www.mr1-kossuth.hu/m3u/', '<link>http://stream001.radio.hu:8000/content/', $str);
$str = str_replace('m3u</link>', 'mp3</link>', $str);
</code></pre>
<p>Done!</p>
| 41,659
|
<p>I would like to evaluate .NET as a development platform for a desktop application. I am looking for good examples of .NET desktop applications used in the mainstream. The only ones I know of are:</p>
<ol>
<li>Visual Studio (The copy website form
is one example.)</li>
<li>Team Explorer UI</li>
<li>Paint.NET</li>
<li>Reflector</li>
<li>Gnome Do (An app launcher for Gnome; runs on Mono)</li>
</ol>
<p>I am looking for more examples; open source, freeware or a demo version in that order.</p>
<p>Suggestions?</p>
|
<p><a href="http://www.icsharpcode.net/OpenSource/SD/" rel="noreferrer">SharpDevelop</a> is an open source Development IDE for .NET very much like VS.NET written in .NET (iirc it still has some pinvokes, but it is all managed code) and is quite large and feature complete.</p>
<p>You can even get the <a href="http://www.icsharpcode.net/OpenSource/SD/Download/" rel="noreferrer">source code</a> for it to look at.</p>
|
<p>Windows Media Center has a managed API I believe. I'm not sure how much .Net stuff is in WMC, but you can check it out.</p>
| 21,902
|
<p>I have got the following problem since the server has safe mode turned on, and directories are being created under different users:</p>
<ol>
<li>I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.</li>
<li>New directory is created, but it belongs to 'apache' user.</li>
<li>'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.</li>
<li>Now I have a problem!</li>
</ol>
<p>One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.</p>
<p>But I have to ask. Is there a programatical solution for my problem?</p>
<p>I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.</p>
|
<p>I've used this workaround:</p>
<p>instead of php mkdir you can create directories by FTP with proper rights.</p>
<pre><code> function FtpMkdir($path, $newDir) {
$path = 'mainwebsite_html/'.$path;
$server='ftp.myserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "user@myserver.com";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
</code></pre>
|
<p>You might be able to turn safe mode off for a specific directory via a .htaccess file (if on Apache). </p>
<pre><code>php_value safe_mode = Off
</code></pre>
<p>You might need to get your hosting provider to make this change for you though in the httpd.conf.</p>
| 31,472
|
<p>Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?</p>
<p>The ideal would be something like:</p>
<pre><code>var myXML: XML = ???; // ... load xml data into the XML object
myXML.someAttribute = newValue;
</code></pre>
|
<p>Attributes are accessible in AS3 using the <code>@</code> prefix.</p>
<p>For example:</p>
<pre><code>var myXML:XML = <test name="something"></test>;
trace(myXML.@name);
myXML.@name = "new";
trace(myXML.@name);
</code></pre>
<p>Output:</p>
<pre><code>something
new
</code></pre>
|
<p>Problem is with some attributes, like @class. Just imagine you want to create HTML source and want to create tag test</p>
<p>So code should be</p>
<p>var myDiv:XML = test
myDiv.@class = "myClass"; //I want to set it here, because it can vary</p>
<p>but this is not compilable and it throw error (at least in Flex Builder)</p>
<p>in that case you can also use this:</p>
<p>myDiv.@['class'] = "myClass";</p>
| 11,671
|
<p>I want (barely computer literate) people to easily submit a large number of files (pictures) through my web application. Is there a simple, robust, free/cheap, widely used, standard tool/component (Flash or .NET - sorry no java runtime on the browser) that allows a web user to select a folder or a bunch of files on their computer and upload them? </p>
|
<p><a href="http://www.swfupload.org" rel="nofollow noreferrer">swfupload</a>, the best tool I know that lets you do that. Simple, easy to use and even has a fallback mechanism for the 1% web users that don't have flash 8+.</p>
|
<p>We had a company come up with a Silverlight upload that could resize the pictures before hand so that the 5MB files didn't have to be uploaded and then resized. The image resizing capability wasn't included with the clr that comes with Silverlight. Occipital came up with their own. You can see it here:
<a href="http://www.occipital.com/fjcore.html" rel="nofollow noreferrer">http://www.occipital.com/fjcore.html</a></p>
<p>I don't know what they would charge, but we have been extremely happy with how it works. If you don't need the resize capability before uploading then I would go with one of the flash upload options like <a href="http://swfupload.org" rel="nofollow noreferrer">http://swfupload.org</a> or <a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/FlashUpload.aspx</a></p>
| 12,267
|
<p>Is it possible to access the following formatted menu item like any other standard menu item (using the underscore-method, e.g. "_File" would be accessible by pressing "f")? I would like to use "O" as "access key" here.</p>
<p>Unfortunately, <code><AccessText></code> does not seem to be usable directly (I imaginged something like </p>
<pre><code><AccessText Visibility="Collapsed">_O2-Genion</AccessText>
</code></pre>
<p>in a <code><StackPanel></code>, but alas, this did not work out.)</p>
<pre><code><MenuItem>
<MenuItem.Header>
<TextBlock>
O
<Span BaselineAlignment="Subscript">
<TextBlock Margin="-3,0,0,0" FontSize="8">
2
</TextBlock>
</Span>
-Genion
</TextBlock>
</MenuItem.Header>
</MenuItem>
</code></pre>
<p>Any suggestions?</p>
|
<p>As I need the subscript, I cannot avoid the custom formatting. What I found out to be an ugly, but obviously possible solution is the following:</p>
<pre><code><MenuItem>
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<AccessText>_O</AccessText>
<TextBlock>
<Span BaselineAlignment="Subscript" FontSize="8">2</Span>-Genion
</TextBlock>
</StackPanel>
</MenuItem.Header>
</MenuItem>
</code></pre>
|
<p>Do you even need to use an AccessKey at all? Assuming that you didn't need/want the custom styling of the MenuItem header text, you could get the same affect by doing the following:</p>
<pre><code><MenuItem HeaderText="_02" />
</code></pre>
<p>Would just putting an underscore before the 0 work? Although I seem to recall that one difference between TextBlock and Label is that TextBlock doesn't support access keys, but Label does. If that's the case, maybe use a Label instead of a TextBlock in your menu item?</p>
| 41,457
|
<p>In <strong>classic ASP</strong> there is a global object called <strong>"Application"</strong> that is accessed simultaniously by all sessions.</p>
<p>As the "Application" object is a shared resource, can it cause <strong>dead locks?</strong></p>
<p>EDIT: If not, why does it has <strong>lock</strong> and <strong>unlock</strong> methods for? <a href="http://www.w3schools.com/asp/asp_ref_application.asp" rel="nofollow noreferrer">Reference</a></p>
|
<p><b>Deadlock</b> is different from normal <b>blocking</b>. Since pages are processed in different threads, if you want to prevent another request from modifying that shared resource, you use Lock, and to allow modification again, you use the Unlock method. The thing is, if you don't use those methods, <i>another request can change the value of an item in the application state, while you're relying on an old value</i>. Or two requests can try to modify it simultaneously and it might cause problems. Lock method causes a request to wait until the other request unlocks application; after that, it can continue. </p>
<p>Deadlock is a situation in which <i>thread A</i> <b>locks</b> <i>resource 1</i> and <b>waits</b> for <i>resource 2</i> to become available. At the same time <i>thread B</i>, which has <b>locked</b> <i>resource 2</i> needs to access <i>resource 1</i> (which is locked by <i>thread A</i>) to continue to work and be able to release the resource afterwards. In this situation, <b>none</b> of the threads can continue (one of them <b>has to be terminated</b> to allow continuation). This is a <b>deadlock</b>. Application.Lock will not cause deadlocks on its own if correctly used. But if it's not used correctly, it might cause deadlocks (when coupled with another shared resource that needs locking and deadlocks are not taken care of).</p>
|
<p>No, it never blocks.</p>
| 40,496
|
<p>We've probably all heard about the connecting lava lamps and <a href="http://www.ambientdevices.com/cat/orb/orborder.html" rel="noreferrer">ambient orbs</a> to your continuous integration systems. I was curious to know what other interesting things people are using or have heard of for extreme feedback devices? Also, this <a href="http://www.kysoh.com/" rel="noreferrer">Tux Droid</a> seemed pretty sweet</p>
|
<p>An idea I have is to buy one of those <a href="http://www.microplex.no/aspx/produkt/prdinfovnet.aspx?plid=45595" rel="noreferrer">USB missile launchers</a> and write a program that can aim it at the stations of known users...</p>
|
<p>CruiseControl.NET + CCTray + Growl + Prowl = iPhone Push Notifications of when and who broke the build.</p>
| 39,008
|
<p>Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is <strong>fuzzy</strong>, but I believe it has something to do with why I can define a class method at all (<code>class foo; def foo.bar ...</code>).</p>
<p>What is the singleton class in Ruby?</p>
|
<p>First, a little definition: a <strong>singleton method</strong> is a method that is defined only for a single object. Example:</p>
<pre><code>irb(main):001:0> class Foo; def method1; puts 1; end; end
=> nil
irb(main):002:0> foo = Foo.new
=> #<Foo:0xb79fa724>
irb(main):003:0> def foo.method2; puts 2; end
=> nil
irb(main):004:0> foo.method1
1
=> nil
irb(main):005:0> foo.method2
2
=> nil
irb(main):006:0> other_foo = Foo.new
=> #<Foo:0xb79f0ef4>
irb(main):007:0> other_foo.method1
1
=> nil
irb(main):008:0> other_foo.method2
NoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4>
from (irb):8
</code></pre>
<p>Instance methods are methods of a class (i.e. defined in the class's definition). Class methods are singleton methods on the <code>Class</code> instance of a class -- they are not defined in the class's definition. Instead, they are defined on the <strong>singleton class</strong> of the object.</p>
<pre><code>irb(main):009:0> Foo.method_defined? :method1
=> true
irb(main):010:0> Foo.method_defined? :method2
=> false
</code></pre>
<p>You open the singleton class of an object with the syntax <code>class << obj</code>. Here, we see that this singleton class is where the singleton methods are defined:</p>
<pre><code>irb(main):012:0> singleton_class = ( class << foo; self; end )
=> #<Class:#<Foo:0xb79fa724>>
irb(main):013:0> singleton_class.method_defined? :method1
=> true
irb(main):014:0> singleton_class.method_defined? :method2
=> true
irb(main):015:0> other_singleton_class = ( class << other_foo; self; end )
=> #<Class:#<Foo:0xb79f0ef4>>
irb(main):016:0> other_singleton_class.method_defined? :method1
=> true
irb(main):017:0> other_singleton_class.method_defined? :method2
=> false
</code></pre>
<p>So an alternative means of adding singleton methods to an object would be to define them with the object's singleton class open:</p>
<pre><code>irb(main):018:0> class << foo; def method3; puts 3; end; end
=> nil
irb(main):019:0> foo.method3
3
=> nil
irb(main):022:0> Foo.method_defined? :method3
=> false
</code></pre>
<p>In summary:</p>
<ul>
<li>methods must always belong to a class (or: be instance methods of some class)</li>
<li>normal methods belong to the class they're defined in (i.e. are instance methods of the class)</li>
<li>class methods are just singleton methods of a <code>Class</code></li>
<li>singleton methods of an object are not instance methods of the class of the object; rather, they are instance methods of the singleton class of the object.</li>
</ul>
|
<p>The most pragmatic/action-oreinted way to think of it (IMHO) is: as an inheritance chain, or method lookup/resolution order. This picture might help</p>
<p><a href="http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/" rel="nofollow noreferrer">http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/</a></p>
<p>This is r 1.9, contrasting builtin and user-defined classes: i'm still digesting this one.</p>
<p><a href="http://d.hatena.ne.jp/sumim/20080111/p1" rel="nofollow noreferrer">http://d.hatena.ne.jp/sumim/20080111/p1</a></p>
<p>Also, i htink a confusing use of the term is "Singleton object", which is different concept. A singleton object comes from a class which has its constructor/instantiator method overridden so that you can allocate only one of that class.</p>
| 26,106
|
<p>I'd love to know how Stack Overflow's tagging and search is architected, because it seems to work pretty well. </p>
<p>What is a good database/search model if I want to do all of the following:</p>
<ol>
<li>Storing Tags on various entities, (how normalized? i.e. Entity, Tag, and Entity_Tag tables?)
<ul>
<li>Searching for items with particular tags</li>
<li>Building a tag cloud of all tags that apply to a particular <strong>search result set</strong></li>
<li>How to show a tag list for each item in a search result?</li>
</ul></li>
</ol>
<p>Perhaps it makes sense to store the tags in a normalized form, but also as a space-delimited string for the purposes of #2, #4, and perhaps #3. Thoughts?</p>
<p>I have heard it said that Stack Overflow uses Lucene for search. Is that true? I've heard a couple of podcasts discussing SQL optimization, but nothing about Lucene. If they do use Lucene, I'm wondering how much of the search result comes from Lucene, and whether the "drill-down" tag cloud comes from Lucene.</p>
|
<p>Wow I just wrote a big post and SO choked and hung on it, and when I hit my back button to resubmit, the markup editor was empty. aaargh.</p>
<p>So here I go again...</p>
<p>Regarding Stack Overflow, it turns out that they use <a href="https://stackoverflow.com/questions/115831/what-is-the-search-engine-behind-stack-overflow">SQL server 2005 full text search</a>. </p>
<p>Regarding the OS projects recommended by @Grant:</p>
<ul>
<li><strong>*DotNetKicks</strong> uses the DB for tagging and Lucene for full-text search. There appears to be no way to combine a full text search with a tag search</li>
<li><strong>Kigg</strong> uses Linq-to-SQL for both search and tag queries. Both queries join Stories->StoryTags->Tags.</li>
<li>Both projects have a 3-table approach to tagging as everyone generally seems to recommend</li>
</ul>
<p>I also found some other questions on SO that I'd missed before:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/20856/how-do-you-recommend-implementing-tags-or-tagging">How Do You Recommend Implementing Tags or Tagging?</a></li>
<li><a href="https://stackoverflow.com/questions/185597/how-to-structure-data-for-searchability">How to structure data for searchability?</a></li>
<li><a href="https://stackoverflow.com/questions/48475/database-design-for-tagging">Database Design for Tagging</a></li>
</ul>
<p>What I'm currently doing for each of the items I mentioned:</p>
<ol>
<li>In the DB, 3 tables: Entity, Tag, Entity_Tag. I use the DB to:
<ul>
<li>Build site-wide tag clouds</li>
<li>browse by tag (i.e. urls like SO's <em>/questions/tagged/ASP.NET</em>)</li>
</ul></li>
<li>For search I use Lucene + NHibernate.Search
<ul>
<li>Tags are concat'd into a TagString that is indexed by Lucene
<ul>
<li>So I have the full power of the Lucene query engine (AND / OR / NOT queries)</li>
<li>I can search for text <em>and</em> filter by tags at the same time</li>
<li>The Lucene analyzer merges words for better tag searches (i.e. a tag search for "test" will also find stuff tagged "testing")</li>
</ul></li>
<li>Lucene returns a potentially enormous result set, which I paginate to 20 results</li>
<li>Then NHibernate loads the result Entities by Id, either from the DB or the Entity cache</li>
<li>So it's entirely possible that a search results in 0 hits to the DB</li>
</ul></li>
<li>Not doing this yet, but I think I will probably try to find a way to build the tag cloud from the TagString in Lucene, rather than take another DB hit</li>
<li>Haven't done this yet either, but I will probably store the TagString in the DB so that I can show an Entity's Tag list without having to make 2 more joins.</li>
</ol>
<p>This means that whenever an Entity's tags are modified, I have to:</p>
<ul>
<li>Insert any new Tags that do not already exist</li>
<li>Insert/Delete from the EntityTag table</li>
<li>Update Entity.TagString</li>
<li>Update the Lucene index for the Entity</li>
</ul>
<p>Given that the ratio of reads to writes is very big in my application, I think I'm ok with this. The only really time-consuming part is Lucene indexing, because Lucene can only <em>insert</em> and <em>delete</em> from its index, so I have to re-index the entire entity in order to update the TagString. I'm not excited about that, but I think that if I do it in a background thread, it will be fine.</p>
<p>Time will tell...</p>
|
<p>I don't know if they qualify as optimal, but both DotNetKicks and Kigg are open source digg clone implementations. You can look at how they're doing tags and search. </p>
<p>My best guesses without a lot of deliberation :)</p>
<ol>
<li>I never like the idea of serializing multiple values into a single field, so delimited strings stored in one field don't appeal to me... might work for adjacency paths with trees, but those are always ordered and tags need not be. This seems like it would tax the LIKE operator work you might do to find them.</li>
</ol>
<p>So my initial take is probably Entity -> EntityTag <- Tag.</p>
<ol start="2">
<li><p>This approach makes finding items via Tag pretty easy, join back through EntityTag, call it a day.</p></li>
<li><p>You need a secondary operation here to select the distinct tags for the result set. So a.) pull the result set, b.) normalize the tag space. I think you do this no matter what the answer is to #1 -- even stuffing tags into one field will still yield duplicate tags (and you have to deserialize them to perform this op--so more work, another argument for a fully relational approach).</p></li>
<li><p>Still easy. Here's one area where the serialized approach works better. No need to join for child tags, it's right there in the Entity. That said, pulling out 0..n tags via the two table join doesn't seem too challenging to me. If you're talking perf considerations, build it normalized first then optimize via cache or denorm.</p></li>
</ol>
<p>The other option is "do both". This feels like a premature optimization, but you could do the full normalized approach to support any tag-centric operations and serialize upon persist to have a denormalized version right there in the Entity. A bit more work, some potential to fall out of synch if not fully covered, but best of both worlds if there's real limitations to the fully normalized way in your use cases.</p>
<p>Lucene is interesting as well, you can declare specific metadata in the indices IIRC, so you could potentially leverage tag search this way as well. My suspicion is, if you go too far down this road, then you end up having some disconnects between what you store in the database and the index at some point. I can speak favorably about Lucene, it's very capable and easy to use--I believe .Text used it for it's search capabilities and it supported all of weblogs.asp.net prior to it switching over to Community Server. I'd stick to it for full-text search if MSSQL isn't in the picture/sufficient, solve the tag issues in the database imo.</p>
| 29,062
|
<p>I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with <a href="http://httpd.apache.org/docs/2.0/mod/core.html#serveralias" rel="noreferrer">ServerAlias</a>) or do I <a href="http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect" rel="noreferrer">Redirect</a> the request? </p>
<p>Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used?</p>
<p>Common vhost examples will have:</p>
<pre><code>ServerName example.net
ServerAlias www.example.net
</code></pre>
<p>Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site?</p>
<p>UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load.</p>
<p>UPDATE and ANSWER: Thanks Paul for finding the <a href="http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html" rel="noreferrer">Google link</a> which instructs us to "help your fellow webmasters by <strong>not</strong> perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."</p>
|
<p>Redirecting is better, then there is always one, canonical domain for your content. <strike>I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, <a href="http://www.searchenginejournal.com/duplicate-content-penalty-how-to-lose-google-ranking-fast/1886/" rel="noreferrer">here's one article</a>, but from 2005, which is ancient history in Internet years!)</strike> <em>(not correct, see edit below)</em></p>
<p>Here's some mod-rewrite rules to redirect to a canonical domain:</p>
<pre><code>RewriteCond %{HTTP_HOST} !^www\.foobar\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent]
</code></pre>
<p>That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain.</p>
<p><strong>Further Edit</strong>: <a href="http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html" rel="noreferrer">Here's an article straight from the horses mouth</a> - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in "www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black") and specifically says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."</p>
|
<p>Nowadays I doubt it matters. If you see both entries in google, then you know you're doing it wrong.</p>
| 16,922
|
<p>How can I print an embossed image in a concaved shape?</p>
<p>Like a big saucer. I will use this an a mold for a project.</p>
<p>So far I've found lots of software with huge spread of features. It's sort of overwhelming. There is lots of ways to create images into 3D printable objects but to add the extra step and concaving that image is harder to find out.</p>
<p>How would you do it? I'm open to suggestions.</p>
<p>I'm new to 3D printing and would really appreciate the help.</p>
|
<p>What you describe, sounds like you want to create a lithophane; a pattern etched or engraved on a thin translucent base material (in your case a bowl) that can only be seen clearly when backlit with a light source behind it. Apparently you want to use it for another purpose.</p>
<p>Special software and or scripts that transform the image to the base material exist. An example is e.g. <a href="https://www.thingiverse.com/thing:2770219" rel="nofollow noreferrer">this sphere which becomes a globe when lit from the inside</a>. Recommending a tool for creating such bowl is a little <a href="https://3dprinting.meta.stackexchange.com/questions/357/are-shopping-questions-on-topic-for-the-site">out of scope</a> as these types of questions become outdated very quickly as technology changes or tools cease to exist. With the provided information you should be able to find software that is able to provide what you want to do.</p>
|
<p>You may want to look up <a href="https://3dp.rocks/lithophane/" rel="nofollow noreferrer">https://3dp.rocks/lithophane/</a> it lets you do things like that</p>
| 1,349
|
<p>My question is similar to Engram's <a href="https://stackoverflow.com/questions/223149/how-do-you-handle-the-output-of-a-dynamically-generated-form-in-aspnet-mvc">here</a>, but my question goes a bit further. The way i intend it to work is I have a textbox asking how many entries a user is going to make. After they input the number, I need to create that many more textboxes to allow for entries (and then repeat the same process with those textboxes, but baby steps first...) I tried collecting the keys on the post, but it only returns the initial textbox asking for the number of entries. I'm still trying to get a grasp on MVC and the tutorials/videos so far don't delve this deep into it yet. Then again, I know this is probably something I could handle using JQuery, but I'd still be stuck in the same situation.</p>
<p>This is the controller I'm using:</p>
<pre><code>[AcceptVerbsAttribute("POST")]
public ActionResult Create(int tbxNumberOfExercises)
{
ViewData["number"] = tbxNumberOfExercises;
foreach (var key in Request.Form.Keys)
{
string keyString = key.ToString();
if (keyString.StartsWith("tbox_exercise", StringComparison.OrdinalIgnoreCase))
{
string recNum = keyString.Substring(13, keyString.Length - 13);
string approvedKey = Request.Form["tbox_exercise" + recNum];
int number;
int.TryParse(approvedKey, out number);
}
}
return View("Create");
}
</code></pre>
<p>And this is my aspx:</p>
<pre><code><form action="/CreateWorkout/Create" method="post">
Number of Exercises:
<%= Html.TextBox("tbxNumberOfExercises") %>
<br />
<br />
<input type="submit" value="Set Exercise Number" />
</form>
<% if (ViewData["number"] != null)%>
There are this many:<%=Html.Encode(ViewData["number"])%>
<br />
and this line should show up
<% if (ViewData["number"] != null)
{
int max = (int)ViewData["number"];
for (int i = 0; i < max; i++)
{%>
<br />
<br />
<%= Html.TextBox("tbox_exercise" + i) %>
<% }
} %>
<% if (ViewData["s"] != null) %>
<%=Html.Encode(ViewData["s"]) %>
</code></pre>
<p>Is there something I'm overlooking, not comprehending, or should I quit while I'm at it because it seems like I'll never get it?</p>
<p>Thanks in advance for any help -- I'm just trying to learn as most I can.</p>
|
<p>I'd break this up in stages, you'll need to add a "Save" view someplace depending on what you want.</p>
<p>Scott</p>
<pre><code><form action="/Demo01/Create" method="post">
Number of Exercises:
<%= Html.TextBox("tbxNumberOfExercises") %>
<br />
<br />
<input type="submit" value="Set Exercise Number" />
</form>
<% if (ViewData["number"] != null) {%>
<form action="/Demo01/Save" method="post">
There are this many:<%=Html.Encode(ViewData["number"])%>
<br />
and this line should show up
<% if (ViewData["number"] != null) {
int max = (int)ViewData["number"];
for (int i = 0; i < max; i++) {%>
<br />
<br />
<%= Html.TextBox("tbox_exercise" + i) %>
<% }
} %>
<% if (ViewData["s"] != null) %>
<%=Html.Encode(ViewData["s"]) %>
<input type="submit" value="Save Exercises" />
<% } %>
</form>
</code></pre>
<p>And then in your controller something like this:</p>
<pre><code>public class Demo01Controller : Controller {
public ActionResult Create() {
return View();
}
[AcceptVerbsAttribute("POST")]
public ActionResult Create(int tbxNumberOfExercises) {
ViewData["number"] = tbxNumberOfExercises;
return View("Create");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save() {
foreach (var key in Request.Form.Keys) {
string keyString = key.ToString();
if (keyString.StartsWith("tbox_exercise", StringComparison.OrdinalIgnoreCase)) {
string recNum = keyString.Substring(13, keyString.Length - 13);
string approvedKey = Request.Form["tbox_exercise" + recNum];
int number;
int.TryParse(approvedKey, out number);
}
}
return View(); // return/redirect to wherever you want
}
}
</code></pre>
|
<p>Thanks for the help guys. I realized at 5 this morning that my issue is that the form didn't include the new textboxes / I needed another form. I'll have to seriously look into Javascript and actually modifying the DOM as it would be better to keep it client side.</p>
<p>Thanks so much.</p>
| 38,591
|
<p>I have a message broker with some topics, and some set of applications running on it. Now I want to run a new set of the same applications (say for QA environment) on the same topics (on the same broker, if I could). What is the best way to do this. Creating a new broker and or creating a new set of topics is cumbersome, as our environments are under tight bureaucracy.</p>
|
<p>AFAIK EMS does not support anything like what you suggest. There are a few options to get what you are looking for. </p>
<p>Having independent EMS servers would be the <em>ideal</em> solution. This would allow your non-production environment to have some hickups without causing problems in your production environment. </p>
<p>Using the same server you can have an environment-specific prefix tacked onto all the queue/topic names. There would need to be some application level setting for which prefix to use (qa, dev, test, prod, ...). This would make for pretty good isolation of the environments, but would probably not work too well if any of the environments are really heavily loaded. </p>
<p>For topics you can use some JMS header property and messages subscriptions to determine which environment to route them to. I would not recommend this as it would be pretty easy to screw it up and corrupt both environments. </p>
|
<p>this requirement can be achieved by having as a qualifier in the message topics/queues or "subjects", so you can segregate the environment mode from DEV to TEST on the same server.Keep in mind that, flow of messages across environments are not recommended by using same EMS Server.</p>
<p>This particular requirement should be addressed in "Subject Naming Conventions", which is a classic task in SOA Architecture defining message formats, message excahange patterns and design of subjects etc.</p>
<p>For eg, your subject can be ..... where would be DEV or TEST or UAT etc</p>
| 11,042
|
<p>In my app I have these Hibernate-mapped types (general case):</p>
<pre><code>class RoleRule {
private Role role;
private PermissionAwareEntity entity; // hibernate-mapped entity for which permission is granted
private PermissionType permissionType; // enum
@ManyToOne
@JoinColumn(name = "ROLE_ID")
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
class Role {
private Set<RoleRule> rules = new HashSet<RoleRule>(0);
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="ROLE_ID")
public Set<RoleRule> getRules() {
return rules;
}
public void setRules(Set<RoleRule> rules) {
this.rules = rules;
}
}
</code></pre>
<p>All classes have <code>equals() & hashCode()</code> overrides.</p>
<p>My application allows tweaking of roles (by sysadmins only, don't worry), and among other fields, allows creation of new role rules. When a new rule is created I try to create a new <code>RoleRule</code> object and insert it into the role's field <code>rules</code>. I call <code>session.update(role)</code> to apply the changes to the database.</p>
<p>Now comes the ugly part... Hibernate decides to do the following when closing the transaction and flushing:</p>
<ol>
<li>Insert the new rule into the database. Excellent.</li>
<li>Update the other role fields (not collections). So far so good.</li>
<li>Update the existing rules, even if nothing has changed in them. I can live with this.</li>
<li>Update the existing rules <em>again</em>. Here's a paste from the log, including the automatic comment:<br></li>
</ol>
<pre>/* delete one-to-many row Role.rules */
update ROLE_RULE set ROLE_ID=null where ROLE_ID=? and ROLE_RULE_ID=?</pre>
<p>Of course, all fields are not-null, and this operation fails spectacularly.</p>
<p>Can anyone try to explain why Hibernate would do this??? And even more important, how the frak do I get around this???</p>
<p><strong>EDIT</strong>: I was so sure it was something to do with the mapping, and then my boss, on a whim, deleted the <code>equals()</code> and <code>hashCode()</code> in both classes, recreated them using Eclipse, and mysteriously this solved the problem.</p>
<p>I'm still very curious about my question though. Can anyone suggest why Hibernate would do this?</p>
|
<p>I've generally used two methods of updating a collection (the many side of a one-to-many) in Hibernate. The brute force way is to clear the collection, call save on the parent, and then call flush. Then add all of the collection members back and call save on the parent again. This will delete all and then insert all. The flush in the middle is key because it forces the delete to happen before the insert. It's probably best to only use this method on small collections since it does re-insert all of them.</p>
<p>The second way is harder to code, but more efficient. You loop through the new set of children and manually modify the ones that are still there, delete the ones that aren't, and then add the new ones. In pseudo-code that would be:</p>
<pre><code>copy the list of existing records to a list_to_delete
for each record from the form
remove it from the list_to_delete
if the record exists (based on equals()? key?)
change each field that the user can enter
else if the record doesn't exist
add it to the collection
end for
for each list_to_delete
remove it
end for
save
</code></pre>
<p>I've searched the Hibernate forums for many hours trying to find the right way to solve this problem. You should be able to just update your collection to make it accurate and then save the parent, but as you've found out, Hibernate tries to detach the children from the parent before deleting them and if the foreign key is not-null, it will fail.</p>
|
<p>Brian Deterling's answer helped me to overcome the phantom delete. I wish he had put a real code. Here is what I got from his suggestion 1. Posting for someone to use it or to comment my code.</p>
<pre><code>// snFile and task share many to many relationship
@PersistenceContext
private EntityManager em;
public SnFile merge(SnFile snFile) {
log.debug("Request to merge SnFile : {}", snFile);
Set<Task> tasks = taskService.findBySnFilesId(snFile.getId());
if(snFile.getTasks() != null) {
snFile.getTasks().clear();
}
em.merge(snFile);
em.flush();
if(tasks != null) {
if(snFile.getTasks() != null)
snFile.getTasks().addAll(tasks);
else
snFile.setTasks(tasks);
}
return em.merge(snFile);
}
</code></pre>
| 21,614
|
<p>It's big problem to convert mod_rewrite rules to lighttpd format</p>
|
<p>It is generally a case of just going through one by one and converting them. I don't know of any automated means,</p>
<p>The docs - <a href="http://redmine.lighttpd.net/projects/1/wiki/Docs:ModRewrite" rel="nofollow noreferrer">http://redmine.lighttpd.net/projects/1/wiki/Docs:ModRewrite</a> - has the regexes available, and some examples.</p>
<p>if there are any particularly problematical items, I'd edit the question to show them, and ask for the answers here.</p>
|
<p>url rewriting does not work within a $HTTP["url"] conditional. [<a href="http://forum.lighttpd.net/topic/1092#3028]" rel="nofollow noreferrer">http://forum.lighttpd.net/topic/1092#3028]</a></p>
| 8,777
|
<p>How do I add radio buttons as my parameter type in SSRS reports?</p>
<p>Thanks in advance,
Anna</p>
|
<p>If you are referring to the Reporting Services web interface, you can't. Selectable value lists appear as dropdown lists. You can configure to the ability to select multiple values, which are rendered as a dropdown list of checkboxes.</p>
|
<p>Not true, I am actually having a problem with 2 reports using the same parameter but displaying it differently. The parameter is boolean, and in one report it renders as a dropdown list and in the other it renders as a radio button list. Therefore, both are possible, the question is why is the same code being rendered differently by two different reports?
Boolean
True
true
Expand/Collapse All:
False
Expand All
True
Collapse All
</p>
| 39,804
|
<p>Here is the story. I was doing a program, every time the program is closed all the data(File links) created by the user is lost, so whenever the user reopen the program, he does have to do all the work again.</p>
<p>So I decided to use an xml file to store the data, because a dbms would take too long to load and code to handle a plain text file would be hard to maintain.</p>
<p>The data is mainly composed of Links that stores two file paths, one for the origin and one for the destination, one boolean that represent the state of the link before the program is closed, and a few other less important things.</p>
<p>When the program loads the data should be read restoring the previous state of the application.</p>
<p>So I made a xml file like this:</p>
<pre><code>...
<Directories>
<Directory id="0">
<FilePath>C:\Test1</FilePath>
<PathSeparator>\</PathSeparator>
</Directory>
...
</code></pre>
<p>And used a DataSet to get the data.</p>
<pre><code>Directory getDirectory()
{
ds = new DataSet();
ds.ReadXml(xmlPath);
DataRow[] myRow = ds.Tables["Directory"].
Select("id ="+id.ToString());// "id = id"
string temp = myRow[0]["FilePath"].ToString();
Directory result = new Directory();
result.path = temp;
temp = myRow[0]["PathSeparator"].ToString();
result.pathSeparator = temp[0];
return result;
}
</code></pre>
<p>All that works just fine, but then I tried to add new "rows" to the xml:</p>
<pre><code>public static int addDirectory(DataSet ds, char pathSeparator, string path)
{
DataRow myRow = ds.Tables["Directory"].NewRow();
myRow.ItemArray[0] = 8;
myRow.ItemArray[1] = path;
myRow.ItemArray[2] = pathSeparator.ToString();
myRow.ItemArray[3] = "lol";
ds.Tables["Directory"].Rows.Add(myRow);
ds.AcceptChanges();
ds.WriteXml(ApplicationDataManager.xmlPath);
return 8;
}
</code></pre>
<p>But all this writes is to a random place on the .xml</p>
<p>What am I doing wrong?</p>
<p>By the way if anyone have any suggestions about how I should store that data, I would be glad to hear(read).</p>
<p>Thanks in advance!</p>
<p>[Update]
File Links are used to create a connection between two directories, so they can be synchronized.</p>
|
<p>If LINQ is in your toolbox, I would highly recommend using that to read/write xml as opposed to a DataTable. It's much more fluent and intuitive and you can control where the nodes go... wherever you add them to the collection is where they appear in the resulting XML.</p>
<p>Here's a quick intro and there's a metric ton of information out there on the web about it if you search a bit:
<a href="http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx" rel="nofollow noreferrer">http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx</a></p>
|
<p>Your best option if you want a quick and dirty way is to load the users information into the dataset, call the "WriteXml" method to save and use "ReadXml" to pull it back in. The XML format that the DataSet uses on its own will come in and out in the same format.</p>
<p>You also have many other options, but the DataSet is the most quick and dirty way of doing it.</p>
| 29,547
|
<p>I've rewritten my family web site using JavaScript (JQuery) making Ajax calls to PHP on the back end. It's your standard "bunch of image thumbnails and one main image, and when you click on a thumbnail image the main image changes" kind of thing. Everything is working as expected when using Firefox, but on IE, when I click on a thumbnail, the main image changes to the one I clicked and then immediately changes back to the first one. I have tried MS Script Debugger to no avail; I set a breakpoint in the JavaScript code that starts the Ajax call, and when I click the thumbnail the breakpoint fires. Then I hit F5 and it continues but does not fire again. If I use Wireshark to watch the actual TCP packets over the network, I can see that we are definitely sending more than one request to the server. I cannot figure out where the second query (the one to revert back to the original image) comes from.</p>
<p>Any suggestions? One example of what I'm talking about is <a href="http://perrow.ca/gallery.php?tag=nicholas-1" rel="nofollow noreferrer">here</a>.</p>
|
<p>Debugging through your site here's what it looks is happening:</p>
<p>After the first image is pocessed, the resize event is being thrown, so this code gets called:</p>
<pre><code>$(window).bind("resize", function(){
ResizeWindow( 'nicholas-1' )
});
</code></pre>
<p>which as you know reloads your gallery. Now I can't tell you why this is occurring but this is where the trouble starts.</p>
<p>For future reference to debug this I used VS2008 to attach to IE. I then put a break in $ajax() at:</p>
<pre><code>// Send the data
try {
xhr.send(s.data);
} catch(e) {
jQuery.handleError(s, xhr, null, e);
}
</code></pre>
<p>Then I simply hit F5 which is run for the first two ajax calls, then I open up the call stack window when I found the rogue ajax call and walked the call stack back up to the function I posted earlier.</p>
<p>Good luck.</p>
|
<p>IE is a piece of work, isn't it? Have you tried something like this?</p>
<pre class="lang-js prettyprint-override"><code>var inProcess = 0;
function eventHandler() {
if (inProcess == 0) {
inProcess = 1;
// do stuff
setTimeout('inProcess = 0', 5000);
}
}
</code></pre>
<p>Cute kid, by the way.</p>
| 37,382
|
<p>I've seen SaaS applications hosted in many different ways. Is it a good idea to split features and modules across multiple databases? For example, putting things like the User table on one DB and feature/app specific tables on another DB and perhaps other commonly shared tables in another DB?</p>
|
<p>Start with one database. Split data/functionality when project requires it.</p>
<p>Here is what we can learn from LinkedIn:</p>
<ul>
<li>A single database does not work</li>
<li>Referential integrity will not be possible</li>
<li>Any data loss is a problem</li>
<li>Caching is good even when it's modestly effective</li>
<li>Never underestimate growth trajectory</li>
</ul>
<p>Source:</p>
<p><a href="http://www.slideshare.net/linkedin/linkedins-communication-architecture" rel="noreferrer">LinkedIn architecture</a></p>
<p><a href="http://www.slideshare.net/linkedin/linked-in-javaone-2008-tech-session-comm" rel="noreferrer">LinkedIn communication architecture</a></p>
|
<p>Keep it a natural design (denormalize as much as needed, normalize as less as required). Split the DB Model into its modules and keep the service oriented principles in mind by fronting data with a service (that owns the data). </p>
| 9,460
|
<p>I have an asp.net text form that contains numerous decimal fields that are optional. I want to selectively update the database but not inserting a "0" for fields that do not have data (maintaining the null status). </p>
<p>Typically, I would create multiple functions, each with a different signature to handle this. However, I am inserting the data through a webservice which does not allow a function with the same name to have multiple signatures. I can think of a couple ways to work around this, but none "pragmatically".</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/b3h38hb0(VS.80).aspx" rel="nofollow noreferrer">Nullable Types</a> are meant for the same purpose. They represent value types with the possibility of having no data in them. Presence of value can be checked using HasValue property of these types.</p>
<p>Pseudo code to read the fields:</p>
<pre><code>decimal? dValue; // default value is null
if(decimalValueExists)
{
dValue = <value read from text file>
}
</code></pre>
<p>When you say multiple methods - I assume these are overloaded methods to be able to add optional fields (so n optional fields means n more methods)</p>
<p>You can avoid writing those methods by writing single method. Suppose you have one required field and one optional field:</p>
<pre><code>public class MyFields
{
decimal req1;
decimal? opt1; // optional field 1
}
</code></pre>
<p>Then define the web service method to use it:</p>
<pre><code>[WebMethod]
void MyWSMethod(MyFields myFields)
{/* code here will ultimately call InsertMyFields */}
void InsertMyFields(MyFields myFields)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "AddMyFields";
command.CommandType = CommandType.StoredProcedure;
// Add the required input parameter
SqlParameter parameter1 = new SqlParameter();
parameter1.ParameterName = "@ReqField1";
parameter1.SqlDbType = SqlDbType.NVarChar;
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = myFields.req1;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter1);
// Add the optional parameter and set its properties.
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@OptField1";
parameter2.SqlDbType = SqlDbType.NVarChar;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter2);
//.. rest of the code
}
}
</code></pre>
<p>If the nullable type has a value, <a href="http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx" rel="nofollow noreferrer">Null Coalescing Operator</a> will set the value or else it will set the other value that you specify (DBNull.Value in our case).</p>
|
<p>You could use the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.dbnull" rel="nofollow noreferrer">DBNull class</a> to represent a null value on your web service code. </p>
<p>While you would still have to use a surrogate value (e.g., 0 or -1), and then just evaluate that value to convert it into the <code>DBNull</code> object.</p>
| 21,866
|
<p><em><strong>TL;DR</strong> - Please help me rebuild my CR-6 SE so that I can move on</em></p>
<hr />
<p>Here's a link to the latest issue that I had to make proof of in a video: <a href="https://youtu.be/9vChL7Il_9Y" rel="nofollow noreferrer">CR6-SE failed</a></p>
<p>Basically, it's failing to reach/maintain temperature (set point of 240 °C, fails to heat above 230 °C), issues start to happen at temps as low as 210 °C.
Creality support is evasive/dodgy. First, they want to see a video proof for the problem reported, and after a while and emails from me asking, suggested something obvious (set temp to 200 °C).</p>
<p>And without any video, they don't respond. Just like last time when I ran into the defective/burned power switch and failed bed leveling.</p>
<p><em>If you have some spare time, please quickly check the video and provide some feedback.</em></p>
<p>I already fixed the burned power switch and auto-leveling (Creality ignored me, so I got the parts from Amazon).</p>
<p>This is the last issue that I need to do a "mercy" fix, so that I can either repurpose it or, just give it away (but I still have to make it working again and safe!).
I already placed an order for an i3 MK3S+, should've bought this in the first place to help me study 3D modeling, <em>not working my degree towards fixing Creality printer failures</em> :)</p>
<p>Thanks in advance.</p>
<p>My troubleshooting steps so far after a screw fell off during print:</p>
<ul>
<li>Disassembled the hotend: found heater block loose, screws were bent and somewhat stripped</li>
<li>Heater resistor has a bad crimp</li>
<li>Thermistor is reading temp, but I don't know if it's accurate (don't have a multimeter+thermocouple)</li>
</ul>
<p>Ordered a hotend from AliExpress, hopefully, that's it</p>
|
<p>70 °C is a specialty filament. It is well below the <code>MIN_TEMP</code> defined in any sane firmware. In Marlin, you <strong>can't</strong> turn on the extruder in any way, while this is online.</p>
<p>You do need to define your firmware to allow such a print - either by dropping the value in the firmware or disabling Mintemp-protection and then <em>flashing that firmware</em>. That is quite invasive.</p>
<p>To <a href="https://marlinfw.org/docs/gcode/M302.html" rel="nofollow noreferrer">temporarily</a> disable the <code>MIN_TEMP</code>, you need to run the G-code <code>M302 P1</code> or <code>M302 S0</code> - <code>M302</code> on its own does nothing. However, some firmware distributions might explicitly prevent these two commands of <em>turning off</em> the check.</p>
<p>In that case, you might use <code>M302 S65</code> or similar to drop the <code>MIN_TEMP</code>.</p>
|
<p>In Cura Machine Settings, add <code>M302 S70</code>.</p>
<p>Apparently, <code>M302 P1</code> and <code>M302 S0</code> do nothing, you need to define a non-zero minimum, and in my case, 70. Thanks to 0scar and Trish for your help.</p>
| 1,850
|
<p>I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
</code></pre>
<p>How could I slice out:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234
</code></pre>
<p>Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.</p>
<p>Cheers</p>
|
<p>Use the <a href="http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit" rel="nofollow noreferrer">urlparse</a> module. Check this function:</p>
<pre><code>import urlparse
def process_url(url, keep_params=('CONTENT_ITEM_ID=',)):
parsed= urlparse.urlsplit(url)
filtered_query= '&'.join(
qry_item
for qry_item in parsed.query.split('&')
if qry_item.startswith(keep_params))
return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])
</code></pre>
<p>In your example:</p>
<pre><code>>>> process_url(a)
'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'
</code></pre>
<p>This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in:</p>
<pre><code>>>> url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1'
>>> process_url(url, ('CONTENT_ITEM_ID', 'other_value'))
'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'
</code></pre>
|
<pre><code>import re
url = 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3'
m = re.search('(.*?)&', url)
print m.group(1)
</code></pre>
| 32,306
|
<p>How do I determine the size of my array in C? </p>
<p>That is, the number of elements the array can hold?</p>
|
<p><strong>Executive summary:</strong></p>
<pre><code>int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
</code></pre>
<hr>
<p><strong>Full answer:</strong></p>
<p>To determine the size of your array in bytes, you can use the <code>sizeof</code>
operator:</p>
<pre><code>int a[17];
size_t n = sizeof(a);
</code></pre>
<p>On my computer, ints are 4 bytes long, so n is 68.</p>
<p>To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:</p>
<pre><code>int a[17];
size_t n = sizeof(a) / sizeof(int);
</code></pre>
<p>and get the proper answer (68 / 4 = 17), but if the type of
<code>a</code> changed you would have a nasty bug if you forgot to change
the <code>sizeof(int)</code> as well.</p>
<p>So the preferred divisor is <code>sizeof(a[0])</code> or the equivalent <code>sizeof(*a)</code>, the size of the first element of the array.</p>
<pre><code>int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
</code></pre>
<p>Another advantage is that you can now easily parameterize
the array name in a macro and get:</p>
<pre><code>#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
</code></pre>
|
<p><strong>Note:</strong> This one can give you undefined behaviour as <a href="https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c/37539#comment91048046_51392277">pointed out by M.M</a> in the comment.</p>
<pre><code>int a[10];
int size = (*(&a+1)-a);
</code></pre>
<p>For more details, see <a href="https://aticleworld.com/how-to-find-sizeof-array-in-cc-without-using-sizeof/" rel="nofollow noreferrer">here</a> and also <a href="https://www.geeksforgeeks.org/how-to-find-size-of-array-in-cc-without-using-sizeof-operator/" rel="nofollow noreferrer">here</a>.</p>
| 5,828
|
<p>I have the following database table created thus:</p>
<pre><code>CREATE TABLE AUCTIONS (
ARTICLE_NO VARCHAR(20),
ARTICLE_NAME VARCHAR(100),
SUBTITLE VARCHAR(20),
CURRENT_BID DECIMAL(5,2),
START_PRICE DECIMAL(5,2),
BID_COUNT VARCHAR(20),
QUANT_TOTAL VARCHAR(20),
QUANT_SOLD VARCHAR(20),
ACCESSSTARTS VARCHAR(20),
ACCESSENDS VARCHAR(20),
ACCESSORIGIN_END VARCHAR(20),
SELLER_ID VARCHAR(20),
BEST_BIDDER_ID VARCHAR(20),
FINISHED TINYINT,
WATCH TINYINT,
BUYITNOW_PRICE DECIMAL(5,2),
PIC_URL VARCHAR(20),
PRIVATE_AUCTION TINYINT,
AUCTION_TYPE VARCHAR(20),
ACCESSINSERT_DATE VARCHAR(20),
ACCESSUPDATE_DATE VARCHAR(20),
CAT_1_ID VARCHAR(20),
CAT_2_ID VARCHAR(20),
ARTICLE_DESC TEXT,
COUNTRYCODE VARCHAR(20),
LOCATION VARCHAR(20),
CONDITIONS VARCHAR(20),
REVISED TINYINT,
PAYPAL_ACCEPT TINYINT,
PRE_TERMINATED TINYINT,
SHIPPING_TO VARCHAR(20),
FEE_INSERTION DECIMAL(5,2),
FEE_FINAL DECIMAL(5,2),
FEE_LISTING DECIMAL(5,2),
PIC_XXL TINYINT,
PIC_DIASHOW TINYINT,
PIC_COUNT VARCHAR(20),
ITEM_SITE_ID VARCHAR(20),
STARTS DATETIME,
ENDS DATETIME,
ORIGIN_END DATETIME,
PRIMARY KEY ( `ARTICLE_NO` ));
</code></pre>
<p>Which is fine.</p>
<p>However when trying to input this row:</p>
<pre><code>5555555 This is the best ARticle in the world!!!!!! True 55.55 3232.2 6 5 5 8.7.2008 17:18:37 8.7.2008 17:18:37 8.7.2008 17:18:37 5454 7877 1 1 46.44 http//www.x.com 1 good 8.7.2008 17:18:37 8.7.2008 17:18:37 22 44 ANZTHINGcanogoherehihhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh 77 germanz none 1 1 1 446 everzwhere australia 22.2 22.2 22.2 1 1 5 1
</code></pre>
<p>As a tab delimited text file, there seems to be a problem around buy_it_nowprice</p>
<p>buy_it_nowprice shows correctly as 46.44 when doing select buy_it_nowprice from Auctions, but select pic_url from Auctions shows returns 1 instead of the website, and as a result all the subsequent records are out of place.</p>
<p>I am sure I have missed a field or something, but I can not work out what it is.</p>
|
<p>You have a space after 46.44, not a tab,</p>
|
<p>There is a space after the number. If you have the option of using another field delimiter from the application that creates the text file for you, that will probably make these kinds of problems easier to spot.</p>
| 34,291
|
<p>I have Eclipse PDT with Subclipse installed and currently have a PHP project drawing from a repository on my production server. I have VMWare Workstation installed with Linux and was hoping to use that as a debug server using XDebug. The problem is that when I update files, they are only committed to the repository on my production server. How can I test the setup on the VM linux? Is it possible to commit the changes to two repositories? Is there a better way of doing this?</p>
|
<p>I think you may be confusing the concept of a repository and a working copy. There should only be one repository for a project. The repository is basically just a central copy of your code base. You checkout the code from the repository to your debug server. When you make changes to your source code you will commit them and they go to the repository. You then run an svn update on the debug server working copy to get the latest changes to test with.</p>
|
<p>You can create a post-commit hook on the repository-machine, which tells the dev-machine to update its revision.</p>
| 35,387
|
<p>I have a polygon soup of triangles that I would like to construct a BSP tree for. My current program simply constructs a BSP tree by inserting a random triangle from the model one at a time until all the triangles are consumed, then it checks the depth and breadth of the tree and remembers the best score it achieved (lowest depth, lowest breadth).</p>
<p>By definition, the best depth would be log2(n) (or less if co-planar triangles are grouped?) where n is the number of triangles in my model, and the best breadth would be n (meaning no splitting has occurred). But, there are certain configurations of triangles for which this pinnacle would never be reached.</p>
<p>Is there an efficient test for checking the quality of my BSP tree? Specifically, I'm trying to find a way for my program to know it should stop looking for a more optimal construction.</p>
|
<p>Construction of an optimal tree is an NP-complete problem. Determining if a given tree is optimal is essentially the same problem.</p>
<p>From this <a href="http://www.faqs.org/faqs/graphics/bsptree-faq/" rel="nofollow noreferrer">BSP faq</a>:</p>
<blockquote>
<p>The problem is one of splitting versus
tree balancing. These are mutually
exclusive requirements. You should
choose your strategy for building a
good tree based on how you intend to
use the tree.</p>
</blockquote>
|
<ul>
<li>Try to pick planes that (could potentially) get split by the most planes as splitting planes. Splitting planes can't be split.</li>
<li>Try to pick a plane that has close to the same number of planes in front as in back.</li>
<li>Try to pick a plane that doesn't cause too many splits.</li>
<li>Try to pick a plane that is coplanar with a lot of other surfaces</li>
</ul>
<p>You'll have to sample this criteria and come up with a scoring system to decide which one is most likely to be a good choice for a splitting plane. For example, the further off balance, the more score it loses. If it causes 20 splits, then penalty is -5 * 20 (for example). Choose the one that scores best. You don't have to sample every polygon, just search for a pretty good one.</p>
| 19,731
|
<p>I am looking for a good primer or technical description of the <strong>System Call</strong> mechanism that is used by operating systems to transition from user space to the kernel to invoke functions such as "open", "read", "write", etc...</p>
<p>Is there anything other than the <a href="http://en.wikipedia.org/wiki/System_call" rel="nofollow noreferrer">Wikipedia</a> entry?
Websites, pdfs, books, source code, all are welcome :)</p>
|
<p>Well for source code, there are plenty of open source kernels to dive into. </p>
<p>As for books, <a href="https://rads.stackoverflow.com/amzn/click/com/0672327201" rel="nofollow noreferrer" rel="nofollow noreferrer">Robert Love's book</a> on the Linux kernel is very informative.</p>
|
<p>For a good explanation of system calls in Linux, look at the sample device drivers in <a href="http://lwn.net/Kernel/LDD3/" rel="nofollow noreferrer">Linux Device Drivers</a>.</p>
| 15,448
|
<p>I am battling regular expressions now as I type. </p>
<p>I would like to determine a pattern for the following example file: <code>b410cv11_test.ext</code>. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance. </p>
<p><strong><em>Further clarification of question:</em></strong></p>
<p>I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'</p>
|
<p>Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)</p>
<blockquote>
<p>must start with</p>
</blockquote>
<p>The caret (<code>^</code>) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.</p>
<blockquote>
<p>'b',</p>
</blockquote>
<p>Any non-special character in your re will match literally, so you just use "b" for this part: <code>^b</code>.</p>
<blockquote>
<p>followed by [...] digits,</p>
</blockquote>
<p>This depends a bit on which flavor of re you use:</p>
<p>The most general way of expressing this is to use brackets (<code>[]</code>). Those mean "match any one of the characters listed within. <code>[ASDF]</code> for example would match either <code>A</code> or <code>S</code> or <code>D</code> or <code>F</code>, <code>[0-9]</code> would match anything between 0 and 9.</p>
<p>Your re library probably has a shortcut for "any digit". In <code>sed</code> and <code>awk</code> you could use <code>[[:digit:]]</code> [sic!], in python and many other languages you can use <code>\d</code>.</p>
<p>So now your re reads <code>^b\d</code>.</p>
<blockquote>
<p>followed by three [...]</p>
</blockquote>
<p>The most simple way to express this would be to just repeat the atom three times like this: <code>\d\d\d</code>.</p>
<p>Again your language might provide a shortcut: braces (<code>{}</code>). Sometimes you would have to escape them with a backslash (if you are using sed or awk, read about "extended regular expressions"). They also give you a way to say "at least x, but no more than y occurances of the previous atom": <code>{x,y}</code>.</p>
<p>Now you have: <code>^b\d{3}</code></p>
<blockquote>
<p>followed by 'cv',</p>
</blockquote>
<p>Literal matching again, now we have <code>^b\d{3}cv</code></p>
<blockquote>
<p>followed by two digits,</p>
</blockquote>
<p>We already covered this: <code>^b\d{3}cv\d{2}</code>.</p>
<blockquote>
<p>then an underscore, followed by 'release', followed by .'ext'</p>
</blockquote>
<p>Again, this should all match literally, but the dot (<code>.</code>) is a special character. This means you have to escape it with a backslash: <code>^\d{3}cv\d{2}_release\.ext</code></p>
<p>Leaving out the backslash would mean that a filename like "b410cv11_test_ext" would also match, which may or may not be a problem for you.</p>
<p>Finally, if you want to guarantee that there is nothing else following ".ext", anchor the re to the end of the thing to match, use the dollar sign (<code>$</code>).</p>
<p>Thus the complete regular expression for your specific problem would be:</p>
<pre><code>^b\d{3}cv\d{2}_release\.ext$
</code></pre>
<p>Easy.</p>
<p>Whatever language or library you use, there has to be a reference somewhere in the documentation that will show you what the exact syntax in your case should be. Once you have learned to break down the problem into a suitable description, understanding the more advanced constructs will come to you step by step.</p>
|
<p>if the letters are unimportant, you could try \w\d\d\d\w\w\d\d_test.ext which would match the letter/number pattern, or b\d\d\dcv\d\d_test.ext or some mix of the two.</p>
| 39,969
|
<p>I am using link to sql, I have a connected set of objects.</p>
<p>I start out and do a linq statement like this</p>
<pre><code>Dim L= from II in context.InventoryItems select II
Dim L2 = L.tolist
</code></pre>
<p>The second line was so that I could narrow down where the problem was occuring. When the second line is hit I get an error "The EntitySet is already loaded and the source cannot be changed"</p>
<p>Any ideas what might be causing this?</p>
|
<p>Omer's comment brings up a very good point: is this DataContext being re-used from a previous operation? If so, you may want to check out Dino Esposito's <a href="http://weblogs.asp.net/despos/archive/2008/03/19/more-on-datacontext-in-hopefully-a-realistic-world.aspx" rel="nofollow noreferrer">blog post</a> regarding lifetime of the DataContext to make sure you're not keeping it around too long.</p>
<p>That error sounds like maybe you have already loaded data from the InventoryItems table using that DataContext and possibly made some changes to entities bound to the DataContext that you have not yet submitted. If you try your code with a brand new DataContext without specifying any special DataLoadOptions it should work.</p>
|
<p>Omer's comment brings up a very good point: is this DataContext being re-used from a previous operation? If so, you may want to check out Dino Esposito's <a href="http://weblogs.asp.net/despos/archive/2008/03/19/more-on-datacontext-in-hopefully-a-realistic-world.aspx" rel="nofollow noreferrer">blog post</a> regarding lifetime of the DataContext to make sure you're not keeping it around too long.</p>
<p>That error sounds like maybe you have already loaded data from the InventoryItems table using that DataContext and possibly made some changes to entities bound to the DataContext that you have not yet submitted. If you try your code with a brand new DataContext without specifying any special DataLoadOptions it should work.</p>
| 22,682
|
<p>I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.</p>
<p>Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File</p>
<p>However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?</p>
<pre><code><Menu>
<MenuItem>
<MenuItem.Header>
<UserControl>
<Image Source="..." />
<Label Text="_Open" />
</UserControl>
</MenuItem.Header>
</MenuItem>
...
</code></pre>
|
<p>I think the Icon property fits your needs.<br>
However to answer the original question, it is possible to retain the Accelerator functionality when you compose the content of your menuitem. <strong>If you have nested content in a MenuItem you need to define the AccessText property explicitly</strong> like in the first one below. When you use the inline form, this is automagically taken care of.</p>
<pre><code> <Menu>
<MenuItem>
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<Image Source="Images/Open.ico" />
<AccessText>_Open..</AccessText>
</StackPanel>
</MenuItem.Header>
</MenuItem>
<MenuItem Header="_Close" />
</Menu>
</code></pre>
|
<p>@a7an: Ah, I didn't notice the Icon property before. That's a good start.</p>
<p>However, specifically I wanted to add an extra 'button' to some MenuItems so I could have a 'Pin' feature (see the recently loaded Documents list in Office 2007 for the feature idea).</p>
<p>Since there needs to be code as well, will I probably need to subclass the control and add the code for the button? (Not affraid of messing with the MenuItem template, have already had to do it once and I'd do it again if I had to! ;) )</p>
| 8,406
|
<p>Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.</p>
<p>They print fine in IE7, even IE6.</p>
<p>We need these charts to print, but they also have dynamic content. I don't really want to draw them again as images when the user prints - the Flex component should do it.</p>
<p>We've found a <a href="http://www.anychart.com/blog/2007/09/23/solving-problem-with-printing-flash-content-in-firefox-browser/" rel="nofollow noreferrer">potential workaround</a>, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).</p>
<p>Anyone know a workaround?</p>
|
<p>Using the ACPrintManager I was able to get firefox 3 to print perfectly!</p>
<p>The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.</p>
<pre><code>private function initPrint():void {
//if we don't have a stage, wait until the next frame and try again
if ( stage == null ) {
callLater(initPrint);
return;
}
PrintManager.init(stage);
var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
data.draw(myDataGrid);
PrintManager.setPrintableContent(data);
}
</code></pre>
|
<p>Thanks. A load of <code>callLater</code>-s added to our custom chart code seems to have done it.</p>
| 3,066
|
<p>Does anyone know of an open source module or a good method for handling application errors and e-mailing them to an admin and/or saving to a database?</p>
|
<p><a href="http://code.google.com/p/elmah/" rel="nofollow noreferrer">ELMAH</a> is a great drop-in tool for this. DLL in the bin directory, and some markup to add to the web.config and you're done.</p>
|
<p>log4net is open source, fairly easy to learn, and can be configured to log to multiple sources (file, email, db, eventlog) very easily.</p>
| 11,012
|
<p>A co-worker asked me how the word "Nuke" relates to CMS? To be honest I never thought about it, and there wasn't any information on the web that I could find.</p>
<p>Francisco Burzi wrote that his Perl script that he used to manage content was called NUKE. His knowledge of that system fueled his adaptation of thatware to phpNuke. </p>
<p>Does anyone know what NUKE stands for and how it is related to content management?</p>
|
<p>the term Nuke originates with phpNuke and subsequent forks such as PostNuke. dotnetNuke just adopted the term from the php version. </p>
<p>I have no clue why phpNuke was named as such, but google to the rescue!</p>
<p><a href="http://74.125.95.132/search?q=cache:atpksHABV2AJ:www.uiarch.org/CMpro-v-p-36.htm+origins+of+name+NUKE+cms&hl=en&ct=clnk&cd=10&gl=us" rel="nofollow noreferrer">http://74.125.95.132/search?q=cache:atpksHABV2AJ:www.uiarch.org/CMpro-v-p-36.htm+origins+of+name+NUKE+cms&hl=en&ct=clnk&cd=10&gl=us</a></p>
<p>in short, "The name was taken from Francisco's user name of Nuke from the days when he was a cracker"</p>
|
<p>I'd heard that it relates to the slang term for using a microwave oven. Using a CMS adds convenience to updating a web site in a similar way that using a microwave is so much faster and simpler than using a real oven. But that's just hearsay.</p>
| 38,943
|
<p>I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.</p>
|
<pre><code>function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
</code></pre>
<p>And to use (I used swfObject as an example):</p>
<pre><code>var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
callbackMethod();
</code></pre>
|
<p>you can load script dynamically by adding <code><script src="..."></code> tag to DOM tree.</p>
| 40,019
|
<p>I'm building a traditional ASP.NET Web Service -- the style built using asmx. It's a pretty simple service. I started using the new Ado.NET Entity Framework for my persistence layer, and I'm running into some problems:</p>
<p>1) I don't like the WSDL that gets automatically generated -- the complex types were getting defined as so: </p>
<pre><code> <s:complexType name="TestObject">
<s:complexContent mixed="false">
<s:extension base="tns:EntityObject"> ...
</code></pre>
<p>So, I built my own WSDL and used the wsdl.exe tool to create a service definition, which includes a new type definition, so now the WSDL looks like, which I feel is a more cross-platform design:</p>
<pre><code><xsd:complexType name="TestObject">
<xsd:sequence>
<xsd:element minOccurs="0" name="created" type="xsd:dateTime"/> ...
</code></pre>
<p>I now have the ASPX generating a nice WSDL file. But now I'm not sure where I should take this. I have two types of basically the same type for TestObject:
1) that's used for entity persistence with the ADO.NET Entity Framework
2) and one that's used for defining data across the wire. </p>
<p>I'd like to figure out how to combine them into one. I'm a little nervous about modifying the .cs file that was automatically generated by the Ado.NEt Entity framework, as it seems like it might get over-written.</p>
<p>Anyone with much experience with the Ado.Net entity experience think it's worth using? While I like the idea of how quickly I was able to build persistence to my data layer, I need to define in a very custom manner how the entity object is transfered across the wire, so I'd need to modify the attributes associated with it's properties. Also, in my service implementation, I don't really want to by converting from EntityFramework.TestObject to WSDLDefenition.TestObject.</p>
<p>Thanks for any input.</p>
|
<p>You're facing the kind of wall many of us have faced when trying to use the Entity Framework in an SOA style architecture. </p>
<p>Version 1.0 of the Entity Framework doesn't work very well in the scenario you've described, as you end up in a world of hurt trying to manage object contexts (and likely
having to cache them).</p>
<p>I'd recommend a thorough read-through of the following (1) <a href="http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx" rel="nofollow noreferrer">article</a> posted by the EF team about the future of the Entity Framework. It also has the effect of capturing and discussing some of the current shortfalls.</p>
<p>In short, I'm not sure that the Entity Framework is quite the solution you want right now as there is no "clean" solution in handling EF entities across the wire (or outside service boundaries) at this stage. </p>
<p>Others may beg to differ...</p>
<p>P.S You're right about being wary of hand editing the generated code - any updates to the data model will overwrite any modifications (although you can extend it as they are within a partial class). Not helpful if you want to add attributes to properties though.</p>
<p>(a) <a href="http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/efdesign/archive/2008/11/20/n-tier-improvements-for-entity-framework.aspx</a></p>
|
<p>Thanks. This is what I was suspecting, but didn't want to spend a whole day researching. What I'm going to do for the time being is to keep my objects separate, this way I can keep the clean WSDL, and then in a data access layer, I'll convert between objects on the wire and the ADO.NET entity framework. </p>
<p>Probably not the most sound approach, but this will get me by for the demo.</p>
<p>Thanks for the link to the article, I think the key concept I was missing was Persistent Ignorance. I've worked on Java web services where you can define POJO (Plain old Java objects) and transfer them over the wire easily, as well as persist to the data source...</p>
<p>...and I see now why you're suggesting WCF, because of hte support for Persistent Ignorance.</p>
| 43,289
|
<p>I've recently inherited a fairly large web site. The project is set up as a web site in Visual studio, and not a Web Application. For a number of reasons, I would like to convert it to a web application.</p>
<p>I started converting the application using these directions from Scott Gu: <a href="http://webproject.scottgu.com/CSharp/Migration2/Migration2.aspx" rel="nofollow noreferrer">Migrating a VS 2005 Web Site Project to VS 2005 Web Application Project</a>.</p>
<p>While doing the conversion I discovered that this web site uses a ton of #include directives to include other .aspx files. The main problem with this is that currently each code-behind file directly calls controls (using this.) from the pages it is including. </p>
<p>This behavior seems to be allowed by the way that the compiler dynamically creates the .designer files in memory at compile time.</p>
<p>The problem is that since I'm converting the application to a Web Application, I'm creating physical versions of the .designer files. Now the same call to controls on the included pages (using this.), no longer work.</p>
<p>I've tried a few things to try and remedy this:</p>
<p>First, I noticed that the .aspx include files didn't have a @ Page directive, so I tried adding one. This prevented the app from compiling because the main page now had multiple @page directives.</p>
<p>Second, I tried to just rename the included .aspx files to .inc, but I still have the same problem of the main page no longer being able to access the controls as they could before.</p>
<p>Anyone ever done this before and have any thoughts on how to proceed without changing the entire structure of the web site?</p>
<p><em>edit: I decided not to go through with the conversion at this time simply because any benefits gained wouldn't be worth the trouble. Thanks for the help.</em></p>
|
<ul>
<li>You should convert included aspx files to classes, if they are used as code libraries in the old situation</li>
<li>You should convert aspx files, which contain html, server- and/or HTML-controls to usercontrols (ascx files)</li>
</ul>
<p>This should be a good starter for now. Later on you could refactor to your own taste.</p>
<p>Hope it helps. </p>
|
<p>You'll need to refactor the #included content into classes and controls that can be used in the main pages.</p>
<p>ASP.Net will <em>not</em> do #include.</p>
| 26,997
|
<p>Is there a good command-line UNIX charting / graphing / plotting tool out there? I'm looking for something that will plot xy points on an ASCII graph.</p>
<p>Just to clarify, I'm looking for something that will output a graph in ASCII (like ascii-art style), so I can use it over an interactive shell session without needing X.</p>
|
<p>Try <a href="http://www.gnuplot.info/" rel="noreferrer">gnuplot</a>. It has very powerful graphing possibilities.</p>
<p>It can output to your terminal in the following way:</p>
<pre><code>gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)
1 ++----------------**---------------+----**-----------+--------**-----++
+ *+ * + * * + sin(x) ****** +
0.8 ++ * * * * * * ++
| * * * * * * |
0.6 ++ * * * * * * ++
* * * * * * * |
0.4 +* * * * * * * ++
|* * * * * * * |
0.2 +* * * * * * * ++
| * * * * * * * |
0 ++* * * * * * *++
| * * * * * * *|
-0.2 ++ * * * * * * *+
| * * * * * * *|
-0.4 ++ * * * * * * *+
| * * * * * * *
-0.6 ++ * * * * * * ++
| * * * * * * |
-0.8 ++ * * * * * * ++
+ * * + * * + * * +
-1 ++-----**---------+----------**----+---------------**+---------------++
-10 -5 0 5 10
</code></pre>
|
<p>Here is my patch for eplot that adds a -T option for terminal output:</p>
<pre><code>--- eplot 2008-07-09 16:50:04.000000000 -0400
+++ eplot+ 2017-02-02 13:20:23.551353793 -0500
@@ -172,7 +172,10 @@
com=com+"set terminal postscript color;\n"
@o["DoPDF"]=true
- # ---- Specify a custom output file
+ when /^-T$|^--terminal$/
+ com=com+"set terminal dumb;\n"
+
+ # ---- Specify a custom output file
when /^-o$|^--output$/
@o["OutputFileSpecified"]=checkOptArg(xargv,i)
i=i+1
i=i+1
</code></pre>
<p>Using this you can run it as <code>eplot -T</code> to get ASCII-graphics result instead of a gnuplot window.</p>
| 15,011
|
<p>I was re-reading Effective Java (2nd edition) item 18, <a href="http://my.safaribooksonline.com/9780137150021/ch04lev1sec6" rel="nofollow noreferrer">prefer interfaces to abstract classes</a>. In that item Josh Bloch provides an example of a skeletal implementation of the <code>Map.Entry<K,V></code> interface:</p>
<pre><code>// Skeletal Implementation
public abstract class AbstractMapEntry<K,V>
implements Map.Entry<K,V> {
// Primitive operations
public abstract K getKey();
public abstract V getValue();
// ... remainder omitted
}
</code></pre>
<p>Two questions stem from this example:</p>
<ol>
<li>Why are getKey and getValue explicitly declared here as abstract methods? They are part of the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Map.Entry.html" rel="nofollow noreferrer">Map.Entry</a> interface, so I don't see a reason for the redundant declaration in the abstract class.</li>
<li><p>Why use the idiom of leaving these primitives methods, as Mr. Bloch refers to them, as abstract? Why not just do this:</p>
<p>// Skeletal Implementation
public abstract class AbstractMapEntry
implements Map.Entry {
private K key;
private V value;</p>
<pre><code> // Primitive operations
public K getKey() {return key;}
public V getValue() {return value;}
// ... remainder omitted
</code></pre>
<p>}</p></li>
</ol>
<p>The benefits of this are that each subclass doesn't have to define its own set of fields, and can still access the key and value by their accessors. If a subclass truly needs to define its own behavior for the accessors, it can implement the Map.Entry interface directly. The other downside is that in the equals method provided by the skeletal implementation, the abstract accessors are called:</p>
<pre><code>// Implements the general contract of Map.Entry.equals
@Override public boolean equals(Object o) {
if (o == this)
return true;
if (! (o instanceof Map.Entry))
return false;
Map.Entry<?,?> arg = (Map.Entry) o;
return equals(getKey(), arg.getKey()) &&
equals(getValue(), arg.getValue());
}
</code></pre>
<p>Bloch warns against calling overridable methods (item 17) from classes designed for inheritance as it leaves the superclass vulnerable to changes made by subclasses.
Maybe this is a matter of opinion, but I was hoping to determine whether there's more to the story, as Bloch doesn't really elaborate on this in the book.</p>
|
<ol>
<li>I would say it helps emphasize what the concrete class is intended to deal with, instead of just leaving it up to the compiler to tell you (or you having to compare both to see what is missing). Kind of self-documenting code. But it certainly isn't necessary, it is more of a style thing, as far as I can see.</li>
<li>There is more significant logic in returning these values than simple getter and setting. Every class I spot checked in the standard JDK(1.5) did something non-simple on at least one of the methods, so I would guess that he views such an implementation as too naive and it would encourage subclasses to use it instead of thinking through the problem on their own.</li>
</ol>
<p>Regarding the issue with equals, nothing would change if the abstract class implemented them because the issue is overrid<strong>able</strong>. In this case I would say that the equals is attempting to be carefully implemented to anticipate implementations. Normally equals in general should not be implemented to return true between itself and its subclass (although there are plenty that do) due to covariance issues (the superclass will think it equals the subclass, but the subclass won't think it equals the superclass), so this type of implementation of equals is tricky no matter what you do.</p>
|
<p>One reason that <code>AbstractMapEntry#getKey</code> and <code>getValue</code> are abstract (i.e. unimplemented) is that <code>Map.Entry</code> is an inner interface to <code>Map</code>. Using nested classes/interfaces is how Java implements composition. The idea in composition is that the composed part is not a first-class concept. Rather, the composed part only make sense if it is contained in the whole. In this case, the composed part is <code>Map.Entry</code> and the root object of the composite is <code>Map</code>. Obviously the concept expressed is that a <code>Map</code> has many <code>Map.Entry</code>s. </p>
<p>Therefore the semantics of <code>AbstractMapEntry#getKey</code> and <code>getValue</code> will depend essentially on the implementation of <code>Map</code> that we're talking about. A plain old getter implementation as you've written will work just fine for <code>HashMap</code>. It won't work for something like <code>ConcurrentHashMap</code> which demands thread-safety. It's likely that <code>ConcurrentHashMap</code>'s implementation of <code>getKey</code> and <code>getValue</code> make defensive copies. (Recommend checking the source code for yourself).</p>
<p>Another reason not to implement <code>getKey</code> and <code>getValue</code> is that the characters that implement <code>Map</code> are radically different ranging from ones that should have never belonged (i.e. <code>Properties</code>) to completely different universes from an intuitive impls of <code>Map</code> (e.g. <code>Provider</code>, <code>TabularDataSupport</code>).</p>
<p>In conclusion, <em>not</em> implementing <code>AbstractMapEntry#getKey</code> and <code>getValue</code>, because of this golden rule of API design:</p>
<blockquote>
<p>When in doubt, leave it out (see <a href="http://www.artima.com/intv/blochP.html" rel="nofollow noreferrer">here</a>)</p>
</blockquote>
| 29,346
|
<p>I am trying to set the background color of a DataGridView row to red. I tried with the following line:</p>
<p>dgvActiveCalls.Rows[1].DefaultCellStyle.BackColor = Color.Red;</p>
<p>but it doesn't work. Then just to see if something is wrong with update I tried to paint the column instead of row:</p>
<p>dgvActiveCalls.Columns[1].DefaultCellStyle.BackColor = Color.Red;</p>
<p>and it worked fine. I would be really thankful if anyone could show the way to paint the DataGridView row.</p>
<p>Thanks!</p>
|
<p>Make sure that the default style isn't being overriden by another of the styles. Interesting quirk of DGV in 2.0: Seems like the inheritence chain is almost upside down from what you'd expect. If you are dynamically adding columns, your DefaultCellStyle can be ignored and be overridden by the RowsDefaultCellStyle. Sorting can also override styles you've set. </p>
<p>You might want to check in which order you're setting these styles and google for some articles regarding style inheritence.</p>
<p>P.S. Interestingly enough, I googled to find a link to provide, and came across this blog with an almost identical explanation: </p>
<p><a href="http://yakkowarner.blogspot.com/2008/06/datagridview-style-inheritance.html" rel="nofollow noreferrer">http://yakkowarner.blogspot.com/2008/06/datagridview-style-inheritance.html</a></p>
|
<p>I tested that on my machine and it worked fine. Are you sure that line isn't highlighted? If it's highlighted you'll see the highlighted color, not the red.</p>
| 32,902
|
<p>We've added performance measures to our application and are exposing them using
JMX. Now we would like to gather and store performance data for analysis, in files or in a database.</p>
<p>Does anyone know of a JMX client, open source or commercial, that can persist gathered information?</p>
|
<p><a href="http://www.oracle.com/technology/products/jrockit/missioncontrol/index.html" rel="nofollow noreferrer">JRockit Mission Control</a> can persist JMX data to log-rotated XML-files that you can open up and view in the gui. </p>
|
<p>you can attach logging functionality to jconsole itself and log mbean output etc.</p>
| 43,340
|
<p>I have just installed the Platform SDK for Windows Server 2008 and .NET 3.5 on my new system, and for the first time tried to compile a project for WIN64. The Unicode Release version of that program, built for 32 bit (using the optimizing compiler from the no longer available Free Toolkit), comes in at about 2.8 MB. Using the amd64 compiler from the latest PSDK the program is more than 5 MB big.</p>
<p>I'm most concerned with program size, so everything is built with /O1 switch. I was expecting the program to become larger when built for 64 bit, but not that much. The size is more in line with a build from the Express version, where (some) optimizations are not available.</p>
<p>Do the compiler in the PSDK and the compiler from MSVC 2008 Professional create programs of very different sizes? Does the compiler in the PSDK optimize in the same way, or even at all?</p>
<p>Thanks for any insight.</p>
<p><strong>Edit:</strong></p>
<p>The program and all linked libraries are built using the same makefile.vc on the command line, so differences in compilation settings are not likely. I basically just used another command file to start a shell with proper environment for 64 bit compilation.</p>
<p>Here are the sizes for the application:</p>
<pre>
VC++ Toolkit 2003 32 bit cl.exe: 13.10.3052 for 80x86 2.916.352
Platform SDK 32 bit cl.exe: 15.00.30729.01 for 80x86 2.881.536
Platform SDK 64 bit cl.exe: 15.00.21022.08 for x64 5.138.432
</pre>
<p>So the 64 bit version is 78% larger :-(</p>
|
<p>A 64-bit binary will be larger than a 32-bit binary due to code side differences, static data, etc. Our project comes in at 7.1MB (x86) vs 10.7MB (x64), and that is for a significant amount of code. Nearly doubling sounds excessive, unless you have a lot of pointer sized static data.</p>
<p>Make sure you are linking with /OPT:REF to discard any unreferenced symbols.</p>
|
<p>I highly doubt that it's the optimizer. The difference in program size probably has to with debugging information and/or static libraries being linked in. Make sure you're not linking against any static libraries you don't need.</p>
| 43,925
|
<p>The code below always return an empty array from <code>GetModifiedMembers(object)</code>
but <code>dx.GetChangeSet().Updates.Contains( foo )</code> returns true.</p>
<pre><code>DataContext dx = new DataContext( string.Empty );
MockLinqDataObject foo = new MockLinqDataObject();
dx.GetTable( foo.GetType() ).Attach( foo );
foo.PK = Guid.NewGuid();
// always returns empty array
ModifiedMemberInfo[] arr_Result = dx.GetTable( foo.GetType() ).GetModifiedMembers( foo );
bool isOk = ( arr_Result.Length == 1 );
return isOk;
</code></pre>
<p>Does anyone know what there is wrong?</p>
<p>Thanks in advance?</p>
|
<p>Homework?</p>
<pre><code>set RootObject to the current object.
while the parent of RootObject is not undefined, set RootObject to its parent.
Finally, return RootObject.
</code></pre>
|
<p>Why you have difficulty in locating the root? go from parent to parent until parent is not set.</p>
<p>BTW Are you talking about B+ trees? They auto balance using blocks of children that get split when a threshold is exceeded look at this image in wikipedia <a href="https://web.archive.org/web/20100305054914/http://upload.wikimedia.org:80/wikipedia/commons/f/fe/Btree.svg" rel="nofollow noreferrer"><img src="https://web.archive.org/web/20100305054914/http://upload.wikimedia.org:80/wikipedia/commons/f/fe/Btree.svg" alt="image"></a></p>
| 38,243
|
<p>Is there any way to change the default datatype when importing an Excel file into Access? (I'm using Access 2003, by the way).</p>
<p>I know that I sometimes have the freedom to assign any datatype to each column that is being imported, but that could only be when I'm importing non-Excel files. </p>
<p><strong>EDIT:</strong> To be clear, I understand that there is a step in the import process where you are allowed to change the datatype of the imported column. </p>
<p>In fact, that's what I'm asking about. For some reason - maybe it's always Excel files, maybe there's something else - I am sometimes not allowed to change the datatype: the dropdown box is grayed out and I just have to live with whatever datatype Access assumes is correct.</p>
<p>For example, I just tried importing a large-ish Excel file (<strong>12000+ rows, ~200 columns</strong>) in Access where column #105 (or something similar) was filled with mostly numbers (codes: <code>1=foo, 2=bar</code>, etc), though there are a handful of alpha codes in there too (A=boo, B=far, etc). Access assumed it was a <code>Number</code> datatype (even after I changed the <code>Format</code> value in the Excel file itself) and so gave me errors on those alpha codes. If I had been allowed to change the datatype on import, it would have saved me some trouble.</p>
<p>Am I asking for something that Access just won't do, or am I missing something? Thanks.</p>
<p><strong>EDIT:</strong> There are two answers below that give useful advice. Saving the Excel file as a CSV and then importing that works well and is straightforward like <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122588">Chris OC</a> says. The advice for saving an import specification is very helpful too. However, I chose the registry setting answer by <a href="https://stackoverflow.com/questions/122422/change-datatype-when-importing-excel-file-into-access#122504">DK</a> as the "Accepted Answer". I liked it as an answer because it's a <em>one-time-only step</em> that can be used to solve my major problem (having Access incorrectly assign a datatype). In short, this solution doesn't allow me to change the datatype myself, but it makes Access accurately guess the datatype so that there are fewer issues.</p>
|
<p>This <em>may</em> be caused by Excel Jet driver default settings. Check out the following registry key and change it's value from default 8 to 0, meaning "guess column data type based on all values, not just first 8 rows."</p>
<pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel]
"TypeGuessRows"=dword:00000000
</code></pre>
<p>Please, tell if this works.</p>
|
<p>Access will do this.</p>
<p>In your import process you can define what the data type of each column is.</p>
| 14,892
|
<p>Given an object:</p>
<pre><code>let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
</code></pre>
<p>How do I remove the property <code>regex</code> to end up with the following <code>myObject</code>?</p>
<pre><code>let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
</code></pre>
|
<p>To remove a property from an object (mutating the object), you can do it like this:</p>
<pre><code>delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
</code></pre>
<p>Demo
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
delete myObject.regex;
console.log(myObject);</code></pre>
</div>
</div>
</p>
<p>For anyone interested in reading more about it, Stack Overflow user <a href="https://stackoverflow.com/users/130652/kangax">kangax</a> has written an incredibly in-depth blog post about the <code>delete</code> statement on their blog, <em><a href="http://perfectionkills.com/understanding-delete" rel="noreferrer">Understanding delete</a></em>. It is highly recommended.</p>
<p>If you'd like a <em>new</em> object with all the keys of the original except some, you could use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring" rel="noreferrer">destructuring</a>.</p>
<p>Demo
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
// assign the key regex to the variable _ indicating it will be unused
const {regex: _, ...newObj} = myObject;
console.log(newObj); // has no 'regex' key
console.log(myObject); // remains unchanged</code></pre>
</div>
</div>
</p>
|
<p>We can remove using</p>
<ol>
<li>using delete object.property</li>
<li>using delete object['property']</li>
<li>using rest, remove multiple property</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*",
"regex1": "^http://.*",
"regex2": "^http://.*",
"regex3": "^http://.*",
"regex4": "^http://.*"
};
delete myObject.regex; // using delete object.property
// Or
delete myObject['regex1']; // using delete object['property']
const { regex2, regex3, regex4, ...newMyObject } = myObject;
console.log(newMyObject);</code></pre>
</div>
</div>
</p>
| 25,526
|
<p>I added the ModalPopupExtender to an existing ASP.NET application. At runtime I get the following error</p>
<p>Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. </p>
<p>Compiler Error Message: BC32206: Indirect reference is being made to assembly System.Web.Extensions version 3.5.0.0, which contains 'AjaxControlToolkit.ModalPopupExtender'. This Project references a prior version of System.Web.Extensions version 1.0.61025.0. To use 'AjaxControlToolkit.ModalPopupExtender', you must replace the reference to System.Web.Extensions with version 3.5.0.0 or higher.</p>
<p>Source Error:</p>
<p>Line 29: <br />
Line 30:<br>
Line 31: </p>
<p>How do I fix this. </p>
|
<p>You're trying to compile a .NET 3.5 application with a reference to a .NET 1.1 module. Make sure you have the .NET 3.5 framework installed, and if you do, make sure you're trying to build it in .NET 3.5.</p>
<p>You may also want to see <a href="https://stackoverflow.com/questions/43939/targeting-multiple-versions-of-net-framework">this post</a>.</p>
|
<p>You're trying to compile a .NET 3.5 application with a reference to a .NET 1.1 module. Make sure you have the .NET 3.5 framework installed, and if you do, make sure you're trying to build it in .NET 3.5.</p>
<p>You may also want to see <a href="https://stackoverflow.com/questions/43939/targeting-multiple-versions-of-net-framework">this post</a>.</p>
| 37,581
|
<p>I am using Direct3D to display a number of I-sections used in steel construction. There could be hundreds of instances of these I-sections all over my scene.</p>
<p>I could do this two ways:</p>
<p><img src="https://i.stack.imgur.com/Eu1Lr.png" alt="I-Sections"></p>
<p>Using method A, I have fewer surfaces. However, with backface culling turned on, the surfaces will be visible from only one side. If backface culling is turned off, then the flanges (horizontal plates) and web (vertical plate) may be rendered in the wrong order.</p>
<p>Method B seems correct (and I could keep backface culling turned on), but in my model the thickness of plates in the I-section is of no importance and I would like to avoid having to create a separate triangle strip for each side of the plates.</p>
<p>Is there a better solution? Is there a way to switch off backface culling for only certain calls of DrawIndexedPrimitives? I would also like a platform-neutral answer to this, if there is one.</p>
|
<p>From <a href="http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>:</p>
<blockquote>
<p>The Elapsed event is raised on a
ThreadPool thread. If processing of
the Elapsed event lasts longer than
Interval, the event might be raised
again on another ThreadPool thread.
Thus, the event handler should be
reentrant.</p>
</blockquote>
|
<p>Well my most basic instinct would be that somehow you actually have two event wireups to the Elapsed event - resulting in two events firing. I've been caught out through this, sometimes because I've added the event wireup manually when it has already been added in the designer, or there is some inheritance aspect here where the wireup is already in a base class and you are repeating it in a derived class.</p>
<p>Of course if there are multiple threads then that is a whole different ball game!</p>
| 29,616
|
<p>I have an idea for a 3D printed project, but I'm a total noob in this area and need someone to reality check it for me.</p>
<p>Basically what I want to do is a tricopter frame made of a <a href="https://en.wikipedia.org/wiki/Tetragonal_disphenoid_honeycomb" rel="nofollow noreferrer">tetrahedral honeycomb</a>.</p>
<p>The whole model would be within 30 * 30 * 10 cm, the honeycomb edges would be approximately 1mm thick and about 15mm long and it would be printed out of nylon with SLS.</p>
<p>I have found Shapeways' design guidelines and my idea seems to fit it, but still it feels slightly more extreme use than what they had in mind.</p>
<p>Is this doable? Does anyone else use a similar method? Is there some software that I can use to generate honeycombs like this, or do I have to write it myself?</p>
<p>Edit:</p>
<p>This is how two layers of the honeycomb look like:
<a href="https://i.stack.imgur.com/ttIZ6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ttIZ6.jpg" alt="honeycomb"></a></p>
<p>In the actual model there would be several layer of this on top of each other and the shape would be kind of carved out of the honeycomb (+ some finishing to avoid spiky surface)</p>
|
<p>For designing your part, especially considering the repetitive mathematics involved, I would consider to learn to use OpenSCAD. I've learned the program and it fits your modeling requirement quite well. I feel it's easy to learn and is somewhat easier for folks who have a programming background. I don't have one, but it's still a logical progression to learn this program.</p>
<p>Regarding the SLS aspect, that also jumped out at me as a suitable answer. Solid shapes require to have "drain holes" to reduce the amount of powder consumed by the process.</p>
<p>I am assembling a Sintratec SLS printer and your model is the sort of thing I would enjoy to create with the printer. I've not yet listed my Sintratec printer on 3dhubs to solicit business, simply because it's not yet a fully assembled printer!</p>
<p>I did a quick Google search for "openscad tetrahedral honeycomb" and found this link:</p>
<p><a href="http://forum.openscad.org/Beginner-Honeycomb-advice-needed-td4556.html" rel="nofollow noreferrer">http://forum.openscad.org/Beginner-Honeycomb-advice-needed-td4556.html</a></p>
<p>The result is more a polygonal honeycomb, not a true 3d tetrahedron, but it's a start. The file that created it is fewer than a few dozen lines of code.</p>
<p>The post is old enough that the internal links no longer work but the OP posted his module code and that does work:</p>
<p><a href="https://i.stack.imgur.com/rO5Je.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rO5Je.png" alt="enter image description here"></a></p>
<p>I'm not sure how personal contact works in stackexchange, but I'd be willing to work with you regarding creating your code and if the printer ever gets assembled, printing out your part.</p>
<p><a href="https://i.stack.imgur.com/hohRb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hohRb.png" alt="enter image description here"></a></p>
<p>Adding a picture again, to show the latest revision, based on the updated information:</p>
<p><a href="https://i.stack.imgur.com/Gna6W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gna6W.png" alt="enter image description here"></a></p>
|
<p>In short, I don't think printing the full tetrahedral honeycomb design is a good approach considering the application of the part. Here are few things to note when attempting to 3D print the tetrahedral honeycomb:</p>
<p>I wouldn't recommend trying to 3D print this with a an FDM/FFF printer as you will most likely need supports and there would not be enough strength laterally. You may be able to <em>print</em> the design using SLA, but handling would be very difficult before post-processing as the part is very brittle post-print until a heat treat or curing process is done to chemically solidify. The post-process of the SLA could determine how strong the part is (ie. stainless steel powder, infused with bronze in a heat treat process would be good for such a part).</p>
<p>While SLS may be the best method for 3D printing this type of design, for that size part (30x30x10cm) you're looking at an expensive print regardless of whether or not you print it yourself.</p>
<p>Instead, I would highly recommend finding (or designing your own) a joint connector that would allow you to join wood/plastic dowels in the tetrahedral honeycomb shape. Not only will this be cheaper for you in the long run (easier to replace a few broken segments than an entire 3D printed model), but it could provide more structural strength for something that could potentially get banged around, like a tricopter.</p>
<p>For example, <a href="http://www.thingiverse.com/thing:176263" rel="nofollow noreferrer">this model</a> on Thingiverse (not my model) shows an example of how you can utilize 3D printing complex or custom joints that allow you to connect dowels in the shape you're looking for. It'd kind of be like building with <a href="https://www.google.com/search?q=k'nex&hl=en&biw=1920&bih=918&site=webhp&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjurNmd2fzLAhVL1mMKHZ9RA44Q_AUIBygC" rel="nofollow noreferrer">K'Nex</a>.</p>
<p>As far as designing said joint, you could model a single "inner" joint that has 18 connectors (8 on XY plane, 6 on YZ plane, and 4 on XZ plane). Below is a crude example of what I mean drawn in Google SketchUp:
<a href="https://i.stack.imgur.com/dlTMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dlTMG.png" alt="enter image description here"></a></p>
| 246
|
<p>I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily?</p>
|
<p>Just add a new Winform, add the following code to your <code>Main</code>:</p>
<pre><code> Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
</code></pre>
<p>Also, be sure the <code>[STAThread]</code> attribute is declared above your <code>Main</code> function to indicate the COM threading model your Windows application will use (more about STAThread <a href="https://www.youtube.com/watch?v=S0jPzb9kk3o" rel="noreferrer">here</a>). </p>
<p>Then right click your project and select properties and change the "Output type" to Windows application and you're done.</p>
<p><strong>EDIT :</strong></p>
<p>In VS2008 the property to change is Application type</p>
<p><img src="https://i.stack.imgur.com/luhTN.jpg" alt="enter image description here"></p>
|
<p>For completeness - and for other newbs like me - you also need to add:</p>
<p>using System.Windows.Forms;</p>
<p>... to the top of Program.cs</p>
| 17,450
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.