instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I recently got a Dell XPS 64-bit Vista for myself. Eclipse doesn't have their 64-bit version, but I've read on forums that they download Eclipse and work with Java 1.5 on the Vista with only some problems. I have Java 1.6 and Netbeans was easily downloadable.</p>
<p>What's the basic/big difference that I'll notice if I shift to Netbeans from Eclipse now?</p>
|
<p>What is the difference between Coke and Pepsi?</p>
<p>Ok, it's not really that similar, but a lot of the differences are in qualitative ways. Speaking of Netbeans 6.1 and 6.5:</p>
<ul>
<li><p>Netbeans has a very different UI and
workflow. There are no perspectives,
but toolbars and such will auto
appear/hide as needed (i.e.
debugging). Build process is
different. Managing projects is
different.</p></li>
<li><p>Netbeans focuses on a smooth,
integrated experience sometimes at
the expense of features. The
Profiler is fully integrated into
the editor (context menu's let you
quickly manipulate the profiler),
but is lacking some featuers of
Eclipse profilers.</p></li>
<li><p>Netbeans has a tightly integrated
JSP/Servlet/JSF development
environment. The whole workflow
connects together from development,
debugging, deployment. This is more
of a "feel" than anything else.</p></li>
<li><p>Netbeans editor is missing several
Eclipse features. Spell check being
one prominent one. Quick complete
(Ctrl-K, Ctrl-J) is an underused
Netbeans feature. Snippets being
another (though they have an
auto-complete template which fills a
different, but similar niche).</p></li>
<li><p>Less choice. If you don't like one
of the included tools, it's unlikely
you will find a good alternative
plug-in.</p></li>
<li><p>Matisse. Eclipse GUI editors have
started to catch up, but they are
simply no comparison to Matisse.
Superficially, they seem
equivalent...</p></li>
<li><p><code><sarcasm></code>Your friends will make
fun of you.<code></sarcasm></code></p></li>
</ul>
|
<p>The build system is different. Eclipse has an internal build mechanism whilst NetBeans relies on ant.</p>
| 42,753
|
<p>I'm considering using reporting services 05 SP2 with share point integration on a new reporting project. </p>
<p>In this project's reports users can only see records they own. I was thinking a simple userId parameter on the report would allow me to filter the report's results to only these "owned" records. </p>
<p>I'm curious: Can I pass the current share point user's ID to the report some how? Can it be done in such a way that its not possible for the user to somehow alter it? How would I do this if possible?</p>
|
<p>The sharepoint UserID = the one RS will use and detect.
This is defined by UserID global in RS and picked up form the login token.</p>
<p>You can hide the parameter (Report) or just specify it at the dataset level (SQL).</p>
|
<p>Have you tried getting row level security happening at the database end?</p>
<p>You project then only needs to pass the users credentials through as it does anyway and you can then let SQL server security handle the issue?</p>
| 22,494
|
<p>I need to do some communications over a serial port in Ruby. From my research, it appears that there aren't many modern libraries for serial communications and the newest material I can find is from 2006. Are there any gems that I'm not aware of?</p>
<p>I ultimately need to maintain communications with a serial device attached to USB (I can figure out the port no problem) for back and forth communications like so (somewhat Ruby-esque pseudo code).</p>
<pre><code>def serial_write_read
if serial.read == "READY"
serial.write "1"
until serial.read == "OK"
serial.write "5"
end
return when serial.read == "DONE"
end
end
</code></pre>
|
<p>The serial port specification has not changed in forever, I wouldn't worry about how old the libraries are.</p>
<p>I'm assuming you saw <a href="http://www.rubyinside.com/cross-platform-ruby-serial-port-library-328.html" rel="nofollow noreferrer">this</a> article from 2006 about ruby and serial ports </p>
<p><a href="http://www.openlogic.com/blogs/2008/04/access-serial-ports-through-ruby/" rel="nofollow noreferrer">Here's</a> someone who got the <a href="http://rubyforge.org/projects/ruby-serialport/" rel="nofollow noreferrer">Ruby-SerialPort</a> library mentioned there to work on macs this year.</p>
<p>There's also <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/35355" rel="nofollow noreferrer">this old post</a> from ruby talk, about interfacing to the Win32 Serial API.</p>
|
<p>While the serial standard has not changed, the way Ruby Gems interact with Ruby C extensions changed enough over the years so that the RubyForge serial port extension would not play well. There have been some patches over the years on RubyForge to fix that, but it hasn't been pretty. The great news is that Github has allowed an incredible acceleration in the activity to clean up the Ruby serial port extension. At least three different people are cross-branching their serial port code on Github. You can search on Github, but I believe that Toholio has the latest code, which recodes and repackages the Ruby serial port as a Ruby Gem. (Yea!)</p>
<p><a href="http://github.com/toholio/ruby-serialport/tree/master" rel="nofollow noreferrer">http://github.com/toholio/ruby-serialport/tree/master</a></p>
<p>It works great for me on Linux, solving the earlier conflict with the latest Ruby Gems release. On Windows, I'm still having a problem getting it working. Compiling Ruby extensions on Windows is never very easy, but that is a whole 'nuther can of worms. I'm just happy that people are working on the Ruby serial port support again. I've asked Toholio to generate a Windows binary gem, which would solve everyone's problems, and he says it's on his list to do.</p>
| 20,275
|
<p>I'm writing a GUI application in Python using wxPython and I want to display an image in a static control (<code>wx.StaticBitmap</code>).</p>
<p>I can use <a href="http://www.wxpython.org/docs/api/wx-module.html#ImageFromStream" rel="nofollow noreferrer"><code>wx.ImageFromStream</code></a> to load an image from a file, and this works OK:</p>
<pre><code>static_bitmap = wx.StaticBitmap(parent, wx.ID_ANY)
f = open("test.jpg", "rb")
image = wx.ImageFromStream(f)
bitmap = wx.BitmapFromImage(image)
static_bitmap.SetBitmap(bitmap)
</code></pre>
<p>But, what I really want to be able to do is create the image from data in memory. So, if I write</p>
<pre><code>f = open("test.jpg", "rb")
data = f.read()
</code></pre>
<p>how can I create a <code>wx.Image</code> object from <code>data</code>?</p>
<p>Thanks for your help!</p>
|
<p>You should be able to use <code>StringIO</code> to wrap the buffer in a memory file object.</p>
<pre><code>...
import StringIO
buf = open("test.jpg", "rb").read()
# buf = get_image_data()
sbuf = StringIO.StringIO(buf)
image = wx.ImageFromStream(sbuf)
...
</code></pre>
<p><code>buf</code> can be replaced with any data string.</p>
|
<p>Since in Python you use Duck Typing you can write your own stream class and hand an instance of that class to ImageFromStream. I think you only need to implement the read method and make it return your data.</p>
| 49,178
|
<p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p>
|
<p>Try JVM option <strong>-XX:-UsePerfData</strong></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html" rel="noreferrer">more info</a></p>
<p>The following might be helpful that is from link <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html" rel="noreferrer">https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html</a></p>
<pre><code>-XX:+UsePerfData
Enables the perfdata feature. This option is enabled by default
to allow JVM monitoring and performance testing. Disabling it
suppresses the creation of the hsperfdata_userid directories.
To disable the perfdata feature, specify -XX:-UsePerfData.
</code></pre>
|
<p><em>EDIT: Cleanup info and summarize</em></p>
<p>Summary:</p>
<ul>
<li>Its a feature, not a bug</li>
<li>It can be turned of with -XX:-UsePerfData which might hurt performance</li>
</ul>
<p>Relevant info:</p>
<ul>
<li><a href="http://forums.sun.com/thread.jspa?threadID=587299&messageID=4257939" rel="nofollow noreferrer">Sun forum</a></li>
<li><a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5012932" rel="nofollow noreferrer">Bugreport</a></li>
</ul>
| 10,194
|
<p>Using Visual Studio 2005 with default install of Crystal Reports.</p>
<p>When I create a report, Crystal asks for the database, and I give it my development db. In the app, I create a DataTable and pass it to the report, which is then handed to the CR Viewer. At runtime, neither the report object, nor the viewer need to see the db since I have already retrieved the table.</p>
<p>When the app is handed to the users, everything works fine. They cannot see the development db.</p>
<p>Once, in the production office, I created a report at the production site, and instead of creating the Crystal Report by specifying the development db, I gave it the production db. Back in my own office, running in VS, the report tries to connect to the development db, and fails. (It's not visible.)</p>
<p>So, it's not a problem that they can't see my development database, but it is a problem that I can't see the production database. </p>
<p>Questions are: Does this arise because running in VS is different from running the installed app? Why does the report try to connect to the DB anyway? How do I control it?</p>
|
<p>I think I'm following...</p>
<p>When you are looking at the .rpt in VS, right-click on Database Fields in the Field Explorer window and go to 'Set Datasource Location'. What does it show for your connection? Is it pointing to the Production db server? This setting will be stored in the .rpt file so this might explain your issue.</p>
|
<p>Questions are: Does this arise because running in VS is different from running the installed app? Why does the report try to connect to the DB anyway? How do I control it?</p>
<p>you can control it according to your report content</p>
<p>if your report contain one table and and you passed this table to your report using DataTable , report will work normally </p>
<p>but
report try to connect to the original DB location when your data table don't provide all report data, usually when your report contain 2 or more table </p>
<p>in this case you need to pass DATASET to report contain all tables </p>
<p>here my code using 2 tables form authors and titleauthor </p>
<pre><code>'Build a SQL statement to query for the authors table
Dim sqlString As String = "SELECT * FROM authors"
'Retrieve the data using the SQL statement
adoOleDbDataAdapter = New OleDbDataAdapter(sqlString, adoOleDbConnection)
'Build a SQL statement to query for the titleauthor table
sqlString = "SELECT * FROM titleauthor"
'Retrieve the data using the SQL statement
adoOleDbDataAdapter2 = New OleDbDataAdapter(sqlString, adoOleDbConnection)
'Create a instance of a Dataset
DataSet1 = New DataSet()
'Fill the dataset with the data with author information
adoOleDbDataAdapter.Fill(DataSet1, "authors")
'Fill the dataset with the data with titleauthor information.
'The table name used in the Fill method must be identical to the name
'of the table in the report.
adoOleDbDataAdapter2.Fill(DataSet1, "titleauthor")
'Pass the dataset to the report
crReportDocument.Database.Tables(0).SetDataSource(DataSet1)
'View the report
CrystalReportViewer1.ReportSource = crReportDocument
</code></pre>
| 48,691
|
<p>What is the difference between the following types of endianness?</p>
<ul>
<li>byte (8b) invariant big and little endianness</li>
<li>half-word (16b) invariant big and little endianness</li>
<li>word (32b) invariant big and little endianness</li>
<li>double-word (64b) invariant big and little endianness</li>
</ul>
<p>Are there other types/variations?</p>
|
<p>There are two approaches to endian mapping: <em>address invariance</em> and <em>data invariance</em>.</p>
<h2>Address Invariance</h2>
<p>In this type of mapping, the address of bytes is always preserved between big and little. This has the side effect of reversing the order of significance (most significant to least significant) of a particular datum (e.g. 2 or 4 byte word) and therefore the interpretation of data. Specifically, in little-endian, the interpretation of data is least-significant to most-significant bytes whilst in big-endian, the interpretation is most-significant to least-significant. In both cases, the set of bytes accessed remains the same.</p>
<p><strong>Example</strong></p>
<p>Address invariance (also known as <em>byte invariance</em>): the byte address is constant but byte significance is reversed.</p>
<pre><code>Addr Memory
7 0
| | (LE) (BE)
|----|
+0 | aa | lsb msb
|----|
+1 | bb | : :
|----|
+2 | cc | : :
|----|
+3 | dd | msb lsb
|----|
| |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xaa (preserved)
Read 2 bytes: 0xbbaa 0xaabb
Read 4 bytes: 0xddccbbaa 0xaabbccdd
</code></pre>
<h2>Data Invariance</h2>
<p>In this type of mapping, the relative byte significance is preserved for datum of a particular size. There are therefore different types of data invariant endian mappings for different datum sizes. For example, a 32-bit word invariant endian mapping would be used for a datum size of 32. The effect of preserving the value of particular sized datum, is that the byte addresses of bytes within the datum are reversed between big and little endian mappings.</p>
<p><strong>Example</strong></p>
<p>32-bit data invariance (also known as <em>word invariance</em>): The datum is a 32-bit word which always has the value <code>0xddccbbaa</code>, independent of endianness. However, for accesses smaller than a word, the address of the bytes are reversed between big and little endian mappings.</p>
<pre><code>Addr Memory
| +3 +2 +1 +0 | <- LE
|-------------------|
+0 msb | dd | cc | bb | aa | lsb
|-------------------|
+4 msb | 99 | 88 | 77 | 66 | lsb
|-------------------|
BE -> | +0 +1 +2 +3 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xdd
Read 2 bytes: 0xbbaa 0xddcc
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
</code></pre>
<p><strong>Example</strong></p>
<p>16-bit data invariance (also known as <em>half-word invariance</em>): The datum is a 16-bit
which always has the value <code>0xbbaa</code>, independent of endianness. However, for accesses smaller than a half-word, the address of the bytes are reversed between big and little endian mappings.</p>
<pre><code>Addr Memory
| +1 +0 | <- LE
|---------|
+0 msb | bb | aa | lsb
|---------|
+2 msb | dd | cc | lsb
|---------|
+4 msb | 77 | 66 | lsb
|---------|
+6 msb | 99 | 88 | lsb
|---------|
BE -> | +0 +1 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xbb
Read 2 bytes: 0xbbaa 0xbbaa (preserved)
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
</code></pre>
<p><strong>Example</strong></p>
<p>64-bit data invariance (also known as <em>double-word invariance</em>): The datum is a 64-bit
word which always has the value <code>0x99887766ddccbbaa</code>, independent of endianness. However, for accesses smaller than a double-word, the address of the bytes are reversed between big and little endian mappings.</p>
<pre><code>Addr Memory
| +7 +6 +5 +4 +3 +2 +1 +0 | <- LE
|---------------------------------------|
+0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb
|---------------------------------------|
BE -> | +0 +1 +2 +3 +4 +5 +6 +7 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0x99
Read 2 bytes: 0xbbaa 0x9988
Read 4 bytes: 0xddccbbaa 0x99887766
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
</code></pre>
|
<p>the basic concept is the ordering of bits:</p>
<pre><code>1010 0011
</code></pre>
<p>in little-endian is the same as</p>
<pre><code>0011 1010
</code></pre>
<p>in big-endian (and vice-versa).</p>
<p>You'll notice the order changes by grouping, not by individual bit. I don't know of a system, for example, where</p>
<pre><code>1100 0101
</code></pre>
<p>would be the "other-endian" version of the first version.</p>
| 4,161
|
<p>Is there any reason something like this would not work?</p>
<p>This is the logic I have used many times to update a record in a table with LINQ:</p>
<pre><code> DataClasses1DataContext db = new DataClasses1DataContext();
User updateUser = db.Users.Single(e => e.user == user);
updateUser.InUse = !updateUser.InUse;
db.Log = new System.IO.StreamWriter(@"c:\temp\linq.log") { AutoFlush = true };
db.SubmitChanges();
</code></pre>
<p>(updateUser.InUse is a bit field) </p>
<p>For some reason it isn't working. When I check the linq.log it is completely blank.</p>
<p>Could there be a problem with my .dbml? Other tables seem to work fine but I've compared properties in the .dbml and they all match.</p>
<p>It's as if the <code>db.SubmitChanges()</code>; does not detect any updates being required.</p>
|
<p>The table could not be updated properly because it had no primary key. (Actually it had the column but the constraint was not copied when I did a SELECT INTO my dev table). <strong>The DataContext class requires a primary key for updates.</strong> </p>
|
<p>Is the InUse property a "normal" one as far as LINQ is concerned? (e.g. it's not autogenerated or anything funky like that?)</p>
<p>Alternatively, I don't suppose it's a Nullable<bool> is it, with a current value of null? If so, your update line isn't actually doing anything - for nullable Booleans, !null = null.</p>
| 25,302
|
<p>What is the difference between the value and itemValue attribute of the radiobutton in Jsf?</p>
|
<p>The value is meant to send in a SelectItem object and not a String like itemValue is. The itemValue is the items value, which is passed to the server as a request parameter, but the value is a value binding expression that points to a SelectItem instance.</p>
<p>If you look at this JSF:</p>
<pre><code> <h:selectOneRadio value="">
<f:selectItem itemValue="TestValue" itemLabel="TestLabel" />
</h:selectOneRadio>
</code></pre>
<p>which turns into this HTML:</p>
<pre><code><table>
<tr>
<td>
<input type="radio" name="j_id_id9" id="j_id_id9:0" value="TestValue" />
<label for="j_id_id9:0"> TestLabel</label>
</td>
</tr>
</table>
</code></pre>
<p>So value = valueBinding pointing to a SelectItem in your managed bean, and itemValue = the value that is being submitted. If you decided to add a value="#{TestBean.mySelectItem}" it would not change the outputted HTML in any way, but the JSF implementation would know that the getter property for the mySelectItem field should be used on this.</p>
<p><strong>Edit:</strong> To clarify the answer a bit more. The value property of the SelectItem binds the SelectItem to an SelectItem field in the managed bean via getter and setter properties. If you set the value like this:</p>
<pre><code> <h:selectOneRadio value="">
<f:selectItem itemValue="TestValue" itemLabel="TestLabel" value="#{TestBean.mySelect}"/>
</h:selectOneRadio>
</code></pre>
<p>it will invoke the getMySelectItem() method in the TestBean. As you can see this has nothing to do with the itemValue as the itemValue is resposible of setting the value of what goes in the request when the user submits the form. The itemValue will then be stored in the h:selectOneRadio's value which hopefully you have bound up to a String field like this:</p>
<pre><code><h:selectOneRadio value="#{TestBean.selectedRadioValue}">
<f:selectItem itemValue="1" itemLabel="1. radio one" />
<f:selectItem itemValue="2" itemLabel="2. radio two" />
</h:selectOneRadio>
</code></pre>
<p>Now if the user checks the radio which to him looks like: "<em>1. radio one</em>" the value "1" will be stored in the TestBean's variable called selectedRadioValue</p>
|
<p>From this IBM article <a href="http://www.ibm.com/developerworks/rational/library/05/1213_he/" rel="nofollow noreferrer">Adding row selection to a JSF datatable using radio buttons</a>:</p>
<p>The <strong>attribute id</strong> is for the component value of the Radio Button Group. It will be bound to the Value field </p>
<p><img src="https://i.stack.imgur.com/QxTc0.jpg" alt="attributeid"></p>
<p>The attribute selectedRowId is for the <strong>item value</strong> of the radio button, and will be bound to the item value field</p>
<p><img src="https://i.stack.imgur.com/lbkjf.jpg" alt="Item Value"></p>
| 42,173
|
<p>I just finish building a Graber i3 printer from mixed parts (a MDF clone of Prusa i3 MK2). For the hotend, I've bought the Greetech MK8 extruder. However, the temperature sensor is driving me up the wall.</p>
<p>I've already checked the wires and connections, but the darn thing keeps showing a steady 500 degrees Celsius. In Marlin, it shows it right up (I'm using the 1st option for a 100k thermistor), in Repetier Firmware (using the same one), it shows 0.00°C, until I tell the printer to heat up, when it shoots to 500°C just like before with Marlin. The documentation for this extruder only lists it as a "100K NTC Thermistor", so I tried to select one of the NTC options on the list for both Marlin and Repetier and the temp sensor reads steady 3.600°C!!!</p>
<p>Measuring it with the multimeter, it shows around 60k, it's 31°C outside.</p>
<p>Is it broken or am I selecting the wrong thermistor type?</p>
<p><a href="http://www.geeetech.com/assembled-mk8-extruder-p-857.html" rel="nofollow noreferrer">Documentation for MK8</a></p>
|
<p>A brand new thermistor shows about 95-105k ohm (depends on the multimeter quality), so it looks like that one is out of the range.
To be sure that it is a thermistor, you could connect a 100k potentiometer, play with it and see readings on the lcd. If the readings are OK, then mainboard is good so replace the thermistor.</p>
<p><a href="https://arduino.stackexchange.com/a/36420/26303">A 100k thermistor curve</a> </p>
|
<p>If your printer is a cheap one that uses a ribbon cable or other combined cables, verify your thermal sensor's polarity. I know, I know - it's a resistor (in most cases) and that means there's no such thing as polarity. Bear with me - I just helped a friend diagnose his printer (Geeetech, for the record) for showing 500C on one sensor and 'def' on the other, after replacing the mainboard with a different/more capable model. Turns out, they SHARE PINS, which suddenly makes polarity important. Swap the pins in the connector, and it might just work. First time I've run into this. We swapped only the Ext0 sensor and left the bed disconnected - Ext0 read normal, so we swapped both, and everything's been perfect since.</p>
| 850
|
<p>I have a SQL query (MS Access) and I need to add two columns, either of which may be null. For instance:</p>
<pre><code>SELECT Column1, Column2, Column3+Column4 AS [Added Values]
FROM Table
</code></pre>
<p>where Column3 or Column4 may be null. In this case, I want null to be considered zero (so <code>4 + null = 4, null + null = 0</code>).</p>
<p>Any suggestions as to how to accomplish this?</p>
|
<p>Since ISNULL in Access is a boolean function (one parameter), use it like this:</p>
<pre><code>SELECT Column1, Column2, IIF(ISNULL(Column3),0,Column3) + IIF(ISNULL(Column4),0,Column4) AS [Added Values]
FROM Table
</code></pre>
|
<p>Use COALESCE.</p>
<pre><code>SELECT
Column1,
Column2,
COALESCE(Column3, 0) + COALESCE(Column4, 0) AS [Added Values]
FROM Table
</code></pre>
| 16,619
|
<p>I'm looking for a way to easily load test and benchmark some of our SQL (using ADO.NET, nothing fancy using LINQ or PLINQ) that has to be performant when running under high parallel load.</p>
<p>I've thought of using the new parallel extensions CTP and specifically <code>Parallel.For</code> / <code>Parallel.ForEach</code> to simply run the SQL over 10k iterations or so - but I've not been able to find any data on what these have been optimized for.</p>
<p>Essentially I'm worried that because database access is inherently I/O bound, it won't create sufficient load. Does anyone know if Parallel. For is intelligent enough to use > x threads (where x = # of CPUs) if the tasks it is executing are not totally CPU bound? I.e. does it behave in a similar manner to the managed thread pool?</p>
<p>Would be rather cool if it was so!</p>
<p><b>EDIT: As @CVertex has kindly referred to below, you can set the number of threads independently. Does anyone know if the parallel libraries by default are intelligent enough to keep adding threads if a job is I/O bound?</b></p>
|
<p>Sure can!</p>
<p>You can specify the max number of threads per CPU you want.</p>
<p>Before you Parallel.For whatever you're doing, you'll have to instantiate your own TaskManager from the System.Threading.Tasks namespace.
Look at the ctor parameters to see how you can customize a task manager for your own purposes.</p>
<p>There should be an overload for Parallel.For that takes a task manager instance.</p>
|
<p>Another way is to define the PLINQ_DOP environment variable. From the docs:</p>
<pre><code>PLINQ_DOP
DOP stands for degree of parallelism. Setting this environment variable defines the number of threads for PLINQ to use.
E.g. PLINQ_DOP=1 means single-threaded, while PLINQ_DOP=8 means PLINQ should use 8 threads.
If this is set to a value greater than the number of procs*cores available on the system,
PLINQ will use more threads than processors. If one of them blocks, for instance,
this allows other threads to make forward progress.
</code></pre>
| 45,473
|
<p>In a Flex <code>AdvancedDatGrid</code>, we're doing a lot of grouping. Most of the columns are the same for the parents and for the children, so I'd like to show the first value of the group as the summary rather than the MAX, MIN or AVG</p>
<p>This code works on numerical but not textual values (without the commented line you get NaN's):</p>
<pre><code>private function firstValue(itr:IViewCursor,field:String, str:String=null):Object
{
//if(isNaN(itr.current[field])) return 0 //Theory: Only works on Numeric Values?
return itr.current[field]
}
</code></pre>
<p>The XML:</p>
<pre><code>(mx:GroupingField name="Offer")
(mx:summaries)
(mx:SummaryRow summaryPlacement="group")
(mx:fields)
(mx:SummaryField dataField="OfferDescription" label="OfferDescription" summaryFunction="firstValue"/)
(mx:SummaryField dataField="OfferID" label="OfferID" summaryFunction="firstValue"/)
(/mx:fields)
(/mx:SummaryRow)
(/mx:summaries)
(/mx:GroupingField)
</code></pre>
<p><code>OfferID</code>'s work Correctly, <code>OfferDescription</code>s don't.</p>
|
<p>It looks like the summaryFunction has to return a number. According to the <a href="https://bugs.adobe.com/jira/browse/FLEXDOCS-431" rel="nofollow noreferrer">Adobe bug tracker</a>, it is a bug in the documentation:</p>
<blockquote>
<p>Comment from Sameer Bhatt:</p>
<p>In the documentation it is mentioned that -
The built-in summary functions for SUM, MIN, MAX, AVG, and COUNT all return a Number containing the summary data.</p>
<p>So people can get an idea but I agree with you that we should clearly mention that the return type should be a Number.</p>
<p>We kept it as an Object so that it'll be easy in the future to add more things in it.</p>
</blockquote>
|
<p>It looks like the summaryFunction has to return a number. According to the <a href="https://bugs.adobe.com/jira/browse/FLEXDOCS-431" rel="nofollow noreferrer">Adobe bug tracker</a>, it is a bug in the documentation:</p>
<blockquote>
<p>Comment from Sameer Bhatt:</p>
<p>In the documentation it is mentioned that -
The built-in summary functions for SUM, MIN, MAX, AVG, and COUNT all return a Number containing the summary data.</p>
<p>So people can get an idea but I agree with you that we should clearly mention that the return type should be a Number.</p>
<p>We kept it as an Object so that it'll be easy in the future to add more things in it.</p>
</blockquote>
| 9,134
|
<p>Here is a problem I've struggled with ever since I first started learning object-oriented programming: how should one implement a logger in "proper" OOP code?</p>
<p>By this, I mean an object that has a method that we want every other object in the code to be able to access; this method would output to console/file/whatever, which we would use for logging--hence, this object would be the logger object.</p>
<p>We don't want to establish the logger object as a global variable, because global variables are bad, right? But we also don't want to have the pass the logger object in the parameters of every single method we call in every single object.</p>
<p>In college, when I brought this up to the professor, he couldn't actually give me an answer. I realize that there are actually packages (for say, Java) that might implement this functionality. What I am ultimately looking for, though, is the knowledge of how to properly and in the OOP way implement this myself.</p>
|
<p>You <em>do</em> want to establish the logger as a global variable, because global variables are <em>not</em> bad. At least, they aren't inherently bad. A logger is a great example of the proper use of a globally accessible object. Read about the Singleton design pattern if you want more information.</p>
|
<p>You could look at the Singleton pattern.</p>
| 11,217
|
<p>I am prototyping some C# 3 collection filters and came across this.
I have a collection of products:</p>
<pre><code>public class MyProduct
{
public string Name { get; set; }
public Double Price { get; set; }
public string Description { get; set; }
}
var MyProducts = new List<MyProduct>
{
new MyProduct
{
Name = "Surfboard",
Price = 144.99,
Description = "Most important thing you will ever own."
},
new MyProduct
{
Name = "Leash",
Price = 29.28,
Description = "Keep important things close to you."
}
,
new MyProduct
{
Name = "Sun Screen",
Price = 15.88,
Description = "1000 SPF! Who Could ask for more?"
}
};
</code></pre>
<p>Now if I use LINQ to filter it works as expected:</p>
<pre><code>var d = (from mp in MyProducts
where mp.Price < 50d
select mp);
</code></pre>
<p>And if I use the Where extension method combined with a Lambda the filter works as well:</p>
<pre><code>var f = MyProducts.Where(mp => mp.Price < 50d).ToList();
</code></pre>
<p><strong>Question:</strong> What is the difference, and why use one over the other?</p>
|
<p>LINQ turns into method calls like the code you have.</p>
<p>In other words, there should be no difference.</p>
<p>However, in your two pieces of code you are not calling .ToList in the first, so the first piece of code will produce an enumerable data source, but if you call .ToList on it, the two should be the same.</p>
|
<p>Other than the ToList difference, #2 is a lot more readable and natural IMO</p>
| 2,717
|
<p>I was curious if anyone had any hard numbers around the performance difference between annotating Entities using private fields instead of public getter methods. I've heard people say that fields are slower because they're called "through reflection" but then again so are the getter methods, no? Hibernate needs to set the accessibility of the field to true before it tries to read it which I can see having some <em>slight</em> overhead. However wouldn't that be done at the Class-level in the scope of a Session or perhaps only once when the Configuration is read and SessionFactory is built?</p>
<p>Just curious if this is a myth or if there's really truth to it; I personally find annotating the fields to be a bit more readable.</p>
|
<p>Loaded 5000 records into a simple 3 column table. Mapped two classes to that table, one using annotated private fields and another using annotated public getters. Ran 30 runs of Spring's HibernateTemplate.loadAll() followed by a HibernateTemplate.clear() to purge the Session cache. Results in ms below...</p>
<p>methods total: 6510, average: 217</p>
<p>fields total: 6586, average: 219</p>
<p>I should probably take another stab at it after adding more properties to each class but right now the difference doesn't appear to be statistically significant.</p>
|
<p>Generally use annotation in above of getter methods, Because when class is loaded in JVM ath that hibernate model or entity class is also loaded then if you use annotation above of field or peroperty then it will execute only once at time of each request. whereas if you placing above getter then in reflaction or any other layer when it will caled this class then getter method called then this become very useful</p>
| 43,090
|
<p>What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.</p>
|
<p>The best approach I think is to compare <a href="http://en.wikipedia.org/wiki/Unit_in_the_last_place" rel="noreferrer">ULPs</a>.</p>
<pre><code>bool is_nan(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0;
}
bool is_finite(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000;
}
// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)
// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other
#define UNEQUAL_NANS 1
// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)
// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX
#define INFINITE_INFINITIES 1
// test whether two IEEE floats are within a specified number of representable values of each other
// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers
bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)
{
#ifdef UNEQUAL_NANS
if(is_nan(lhs) || is_nan(rhs))
{
return false;
}
#endif
#ifdef INFINITE_INFINITIES
if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))
{
return false;
}
#endif
signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs));
// transform signed magnitude ints into 2s complement signed ints
if(left < 0)
{
left = 0x80000000 - left;
}
signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs));
// transform signed magnitude ints into 2s complement signed ints
if(right < 0)
{
right = 0x80000000 - right;
}
if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference)
{
return true;
}
return false;
}
</code></pre>
<p>A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are.</p>
<p>I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then.</p>
|
<p>Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.</p>
| 4,149
|
<p>I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a number and collection of digits. What would be awesome is if there was some indexable form of a floating point number, but I have been unable to find such a solution. I am throwing this question out there to see if there is something obvious I am missing or if I should just roll my own.</p>
<hr>
<p>Thanks for the advice! I was hoping for a solution that wouldn't convert from float -> string -> int, but I <em>think</em> that is the best way to get away from floating point quantization issues. I ended up going with boost::format and just referencing the individual characters of the string. I can't see that being a huge performance difference compared to using combinations of modf and fmod to attempt to get a digit out of a float (It probably does just that behind the scenes, only more robustly than my implementation). </p>
|
<p>Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng.</p>
<p>To cast, do this:</p>
<pre><code>char string[99];
sprintf(string,"%f",floatValue);
</code></pre>
<p>Or see this : <a href="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1" rel="noreferrer">http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1</a></p>
<p>The wikipedia article can explain more on the representation: <a href="http://en.wikipedia.org/wiki/Floating_point" rel="noreferrer">http://en.wikipedia.org/wiki/Floating_point</a></p>
|
<p>You can cast between string and float only by using boost::lexical_cast. However, you can't directly index the float form - it's internally not stored as decimal digits. This is probably not that much of an issue. For your UI, you will most likely keep a string form of the number anyway, with conversions to and from float in the getter/setter.</p>
| 44,040
|
<p>What C++ HTTP frameworks are available that will help in adding HTTP/SOAP serving support to an application?</p>
|
<p>Well, gSOAP of course. :)</p>
<p><a href="http://www.cs.fsu.edu/~engelen/soap.html" rel="nofollow noreferrer">http://www.cs.fsu.edu/~engelen/soap.html</a></p>
|
<p><a href="http://code.google.com/p/yield/updates/list" rel="nofollow noreferrer">Yield</a> a high performance server framework, IIRC SOAP is supported. </p>
| 48,035
|
<p>I am writing my own Joomla component (MVC), its based heavily on the newsflash module, because I want to display the latest 5 content items in a sliding tabbed interface, all the hard work is done, but I am having real difficult getting content out of the for loop.</p>
<p>Here is the code I have so far
default.php</p>
<pre><code><ul id="handles" class="tabs">
<?php for ($i = 0, $n = count($list); $i < $n; $i ++) :
modSankeSlideHelper::getTabs($list[$i]);
endfor; ?>
<li class="end"></li>
</ul>
</code></pre>
<p>helper.php</p>
<pre><code>function getTabs(&$item)
{
global $mainframe;
$item->created = $item->created;
list($year, $month, $day) = split("-", $item->created);
$tabdate = date('d\/m\/y', mktime(0, 0, 0, $month, $day, $year));
require(JModuleHelper::getLayoutPath('mod_sankeslide', '_tab'));
}
</code></pre>
<p>_tab.php</p>
<pre><code><li><a href="#tab"><span><?php echo 'Shout ' . $tabdate; ?></span><b></b></a></li>
</code></pre>
<p>The first item needs to have different value and a class item added to the a: item, so I need to be able to identify which is the first item and do something during that loop.</p>
<p>I tried to use if $i = 0 else statement in the default.php, but it resulted in a page timeout for some reason!</p>
<p>Any ideas?</p>
|
<p>You said, you tried <code>if $i = 0</code>, the <a href="http://www.php.net/operators.comparison" rel="nofollow noreferrer">comparison operator</a> in PHP is <code>==</code>, with your if you have an endless loop, because in each iteration you assign 0 to $i, and it never reaches $n, you should do inside your loop:</p>
<pre><code>if ($i == 0){
// First Item here...
}else{
// Other Items...
}
</code></pre>
|
<p>If you're using a plain <code>for</code> loop, I'd recommend just acting on the 1st item and then looping through the rest as <a href="https://stackoverflow.com/users/12950/tvanfosson">tvanfosson</a> <a href="https://stackoverflow.com/questions/238376/getting-the-first-item-out-of-a-for-loop#238392">said</a>. It's slightly faster and potentially easier to read...</p>
<pre><code>doSomethingWithFirst($list[0]);
for ($i = 1; $i < count($list); $i++) {
doSomethingWithTheRest($list[$i]);
}
</code></pre>
<p>I tend to use <code>foreach</code> over <code>for</code> to loop over arrays, in which case, I would use a "firstDone" var, like so:</p>
<pre><code>$bFirstTime = true;
foreach($list as $item) {
if ($bFirstTime) {
doSomethingWithFirst($item);
$bFirstTime = false;
} else {
doSomethingWithTheRest($item);
}
}
</code></pre>
| 29,477
|
<p>I'm not looking so much for language-specific answers, just general models for implementing a plugin system (if you want to know, I'm using Python). I have my own idea (register callbacks, and that's about it), but I know others exist. What's normally used, and what else is reasonable?</p>
<blockquote>
<p>What do you mean by a plugin system? Does Dependency Injection and IOC containers sounds like a good solution?</p>
</blockquote>
<p>I mean, uh, well, a way to insert functionality into the base program without altering it. I didn't intend to define it when I set out. Dependency Injection doesn't <em>look</em> particularly suitable for what I'm doing, but I don't know much about them.</p>
|
<p>A simple plugin architecture can define a plugin interface with all the methods the plugin ought to implement. The plugin handles event from the application, and can use the application's standard code, model objects, etc. to get things done. Basically the same as an ASP.NET Form does, except that you're overriding rather than implementing.</p>
<p>Nobody taught me this part, and I'm no expert, but I feel: In general a plugin will be less stable than its application, so the application should always be in control and only give the plugin periodic opportunities to act. If a plugin can register an Observer, then calls to the delegate should be tried/caught.</p>
|
<p>How about <a href="http://www.dofactory.com/Patterns/PatternAbstract.aspx" rel="nofollow noreferrer">abstract factory</a>? Your base program defines how the abstract concepts interact with each other, but the caller has to provide the implementation.</p>
| 12,470
|
<p>I have a large table (more than 10 millions records). this table is heavily used for search in the application. So, I had to create indexes on the table. However ,I experience a slow performance when a record is inserted or updated in the table. This is most likely because of the re-calculation of indexes. </p>
<p>Is there a way to improve this.</p>
<p>Thanks in advance</p>
|
<p>You could try reducing the number of page splits (in your indexes) by reducing the fill factor on your indexes. By default, the fill factor is 0 (same as 100 percent). So, when you rebuild your indexes, the pages are completely filled. This works great for tables that are not modified (insert/update/delete). However, when data is modified, the indexes need to change. With a Fill Factor of 0, you are guaranteed to get page splits.</p>
<p>By modifying the fill factor, you should get better performance on inserts and updates because the page won't ALWAYS have to split. I recommend you rebuild your indexes with a Fill Factor = 90. This will leave 10% of the page empty, which would cause less page splits and therefore less I/O. It's possible that 90 is not the optimal value to use, so there may be some 'trial and error' involved here. </p>
<p>By using a different value for fill factor, your select queries may become slightly slower, but with a 90% fill factor, you probably won't notice it too much.</p>
|
<p>This is a classic engineering trade-off... you can make the shovel lighter or stronger, never both... (until a breakthrough in material science. )</p>
<p>More index mean more DML maintenance, means faster queries.</p>
<p>Fewer indexes mean less DML maintenance, means slower queries.</p>
<p>It could be possible that some of your indexes are redundant and could be combined.</p>
<p>Besides what Joel wrote, you also need to define the SLA for DML. Is it ok that it's slower, you noticed that it slowed down but does it really matter vs. the query improvement you've achieved... IOW, is it ok to have a light shovel that weak?</p>
| 36,143
|
<p>I'm working on a simple ASP.Net page (handler, actually) where I check the value of the LOGON_USER server variable. This works using Visual Studio's built-in web server and it works in other sites deployed to the live intranet site. But it doesn't work on the IIS instance on my local XP machine. How can I fix it, or what's going on if I can't?</p>
|
<p>What authentication do you have enabled in IIS? Anonmyous, Basic, Digest, Integrated Windows? Sounds to me like anonymous access is enabled/allowed, and nothing else. This would means that LOGON_USER is not populated. </p>
<p>When you access your local IIS, trying using <a href="http://127.0.0.1" rel="nofollow noreferrer">http://127.0.0.1</a> in particular if you use IE. IE will recognize "localhost" as being in your local trusted zone and will automatically pass your XP login credentials through when Integrated Windows auth is enabled.</p>
|
<p>In addition to Jon's answer, IIRC even if you have Integrated Authentication enabled, if Anonymous Authentication is enabled it will take precedence...</p>
| 8,473
|
<p>According to the answers to <a href="https://stackoverflow.com/questions/151250/how-do-i-embed-a-file-version-in-an-msi-file-with-visual-studio">this</a> question, I cannot embed a file version in my .msi file. </p>
<p>The installer that I give the client needs to have a file version. </p>
<p>So, what I want to do is create a self-extracting executable containing the msi file and the setup.exe generated by Visual Studio, and put the file version on this self-extracting executable instead.</p>
<p>Therefore, I need a utility to create self-extracting executables which supports embedding a file version in its output. It also needs to support automatically running a file after extraction, so I can start the real installer automatically. It would be nice if it was scriptable.</p>
<p>All I could find was <a href="http://www.gdgsoft.com/pb/customize-package.aspx" rel="nofollow noreferrer">this</a>, which looks great, but I would much prefer a free alternative.</p>
<p>Does anyone have any suggestions?</p>
<p><strong>Edit:</strong> To clarify, I'm not really looking to create an installer - I already have a VS setup project. I just want a self-extractor (like WinZip can create). So, the user mouses over Setup-Blorgbeard2008.exe, sees "Version: 1.0.0.0". User doubleclicks it, it silently extracts setup.exe and setup.msi to a temp folder, then runs setup.exe. User then sees normal installer screen and proceeds as normal.</p>
<p><strong>Another Edit:</strong> Yay, I don't need a self-extractor anymore, since my other question has now been answered. That makes this whole question pretty much irrelevant. It <em>would</em> still be nice to be able to distribute only one file, rather than setup.exe and setup.msi.</p>
|
<p>NSIS can do this.</p>
<p>Part of our build environment is a script that outputs version information to a "header" file that our NSIS script sources. You should be able to use something similar to embed your version information and you can certainly get NSIS to run a file after extraction.</p>
<p>In fact, as NSIS creates the installer package... you may be able to simplify your approach a great deal.</p>
|
<p>FYI using a DotNetZip self-extractor does not make sense if you are using the bootstrapper setup.exe to verify .NET is installed (DotNetZip self-extractor requires .NET 2.0).</p>
| 18,248
|
<p>I'm using the appengine webapp framework (<a href="http://code.google.com/appengine/docs/webapp/" rel="nofollow noreferrer">link</a>). Is it possible to add Django middleware? I can't find any examples. I'm currently trying to get the FirePython middleware to work (<a href="http://github.com/woid/firepython/tree/master" rel="nofollow noreferrer">link</a>).</p>
|
<p>It's easy: You create the WSGI application as per normal, then wrap that application in your WSGI middleware before executing it.</p>
<p>See <a href="http://github.com/Arachnid/bloog/blob/bb777426376d298765d5dee5b88f53964cc6b5f3/main.py#L71" rel="noreferrer">this code</a> from Bloog to see how firepython is added as middleware.</p>
|
<p>The GAE webapp framework does not map one to one to the Django framework. It would be hard to do what you want without implementing some kind of adapter yourself, I do not know of any third party handler adapters to do this.</p>
<p>That said, I generally use the app-engine-patch so I can use the latest 1.0.2 Django release with AppEngine, and then you can just include the Django middleware the normal way with the setup.py file. If you needed to, you could probably look through the app-engine-patch's adapter to see how they do it, and start with that as a framework.</p>
| 45,848
|
<p>I am trying to write a C program that uses <code>dlysm</code>, and I keep getting an undefined reference to dlysm. I think I need to set my <code>-ldl</code> flags but I have no idea how to do this. </p>
<p>I am very new to linux and setting variables. If this is what I need to do can someone help me out with the commands?</p>
|
<p><code>-l</code> library options are used at link time.</p>
<p>If you compile just one source file (<code>gcc -o program program.c</code>), then you both compile and link in one go. Just add the <code>-ldl</code>.</p>
<p>If you compile multiple object (<code>*.o</code>) files, and then link them together, specify the <code>-ldl</code> option to the linker (<code>ld</code>).</p>
<p>See also <code>man ld</code> and <code>man cc</code></p>
|
<p>Pass <code>-ldl</code> as a parameter to the compiler.</p>
<p>Example:</p>
<pre><code>gcc myprog.c -o app -ldl
</code></pre>
| 35,364
|
<p>I think the file that is produced is an .asm file, any idea how to produce this in Visual Studio when you do a build?</p>
|
<ol>
<li>Open the Properties page for a project </li>
<li>Select the <code>Configuration Properties -> C/C++ -> Output Files</code> branch </li>
<li>Change the Assembler Output option to something other than <code>No Listing</code> </li>
<li>Make sure ASM List Location is set to a valid path or sub-path</li>
<li>Build.</li>
</ol>
|
<p>Or if using the Visual Studio command line, </p>
<p>cl.exe /Fa[assembler code filename]</p>
<p>If you just want to view the assembler code in the IDE you can start the debugger and then select the Go To Dissassembly choice on the right click menu.</p>
| 5,494
|
<p>The span element seems to be exactly like a div, but at the in-line level rather than at the block level. However, I can't seem to think of any beneficial logical divisions that the span element can provide. </p>
<p>A single sentence, or word if not contained in a sentence, seems to be the smallest logical part. Ignoring CSS, since CSS is only for layout and not for semantic meaning, <strong>when does span provide additional semantic value by chopping up a sentence or string of words</strong>? </p>
<p>It seems that in all cases, other elements are better suited to adding semantic value, making span a purely layout element. Is this true?</p>
|
<p>Span can be used to add semantic meaning that falls outside the scope of HTML. This can be done by using classes which identify certain attributes. For example, if you are writing a science-fiction novel you can use span to identify made-up words, because you may want to format those differently, or because you may want the spell-checker to ignore them:</p>
<blockquote>
<p>Then the wizard called upon the <span class="wizardword">gravenwist</span> and bade it attack the approaching army. The <span class="wizardword">gavenwist</span> resisted but the wizard's <span class="wizardword">wistwand</span> was too powerful.</p>
</blockquote>
<p>This could render as </p>
<blockquote>
<p>Then the wizard called upon the <em>gravenwist</em> and bade it attack the approaching army. The <em>gavenwist</em> resisted but the wizard's <em>wistwand</em> was too powerful.</p>
</blockquote>
<p>Another good example of this sort of thing are <a href="http://microformats.org/" rel="noreferrer">microformats</a>, which allow the creation of arbitrary structure within HTML:</p>
<pre><code><span class="tel">
<span class="type">home</span>:
<span class="value">+1.415.555.1212</span>
</span>
</code></pre>
<p>The advantage of span, versus div, is that spans can appear almost everywhere because they are inline content, and divs are block elements, so they can only occur inside certain other elements.</p>
|
<p>I think he's asking about the difference between a div and a span, and there really isn't one, other than the default behavior.</p>
<p>It's a matter of convention. When using styling, <code>div</code> is typically used to demarcate divisions of content, while <code>span</code> is used to demarcate inline text. You could just as easily use <code>div</code> everywhere or use <code>span</code> everywhere, but it's helpful to think of them as different, even if it's only by convention.</p>
| 35,223
|
<p>Is the firts time that I saw this movement after the printing has finishig and causes the nozzle crashes to the printed part and I noticed due the part is 14x8 and the nozzle is to near and below to the border of the shape. I supposed that some scripts has changed but, seems to be everything ok.</p>
<p>this is the end script:</p>
<pre><code>G92 E0
G1 E-1.5000 F1800
; layer end
M104 S0 ; turn off extruder
M140 S0 ; turn off bed
G28 X0 ; home X axis
M84 ; disable motors
; Build Summary
; Build time: 3 hours 9 minutes
; Filament length: 12689.1 mm (12.69 m)
; Plastic volume: 30520.78 mm^3 (30.52 cc)
; Plastic weight: 38.15 g (0.08 lb)
</code></pre>
<p>Z axis moves down 4mm after finishing going to X0, why? I don't want the nozzle crashes the part on going to zero.</p>
|
<p>You can use:</p>
<pre><code>G91
G1 Z10
</code></pre>
<p><code>G91</code> make the printer use ralative positioning, while <code>G1 Z10</code> would move the gantry up of 10mm, reagrdless of its actual position.</p>
<p>In order to understand what's going on, you could experiment with the position of those lines in the script.</p>
<p>The safest bet it to insert them at the very top, but you could insert them straight after the homing of the X axis to understand if the drop you are seeing is caused by the homing command itself or by the ´M84´ one.</p>
<p>My <em>guess</em> is that the drop is actually caused by the latter. <code>M84</code> doesn't really "disable motors", rather it stops using energy to keep them still (i.e.: it stops the <em>idle hold</em>). What I believe is happening in your case is that when you stop the idle hold, the weight and mechanical play of the X gantry causes it to move slightly (a bit like when you relax your body on the sofa and you "sink" in it a bit more).</p>
|
<p>There is something fundamentally wrong with your z-motor drive if both screws are dropping the gantry at all.</p>
<p>Try a couple experiments.<br>
Write a quick script to move the head somewhere up high, then terminate without the X-homing command. See if the z-axis moves. Ditto for X-home but not motor disable. </p>
<p>Write any script, and while the gantry is up high, pull power and see what happens.</p>
<p>That will at least help narrow down the list of possible problems. In the meantime, please post your printer, the motors, and the driver board/firmware in use.</p>
| 828
|
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p>
<p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p>
<p>The returned list looks something like this:</p>
<pre><code>print MyList
[{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}]
</code></pre>
<p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p>
<p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p>
<p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
|
<pre><code>>>> mysets = (set(x.items()) for x in MyList)
>>> reduce(lambda a,b: a.intersection(b), mysets)
set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])
</code></pre>
<p>First, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a list comprehension here but this way doesn't convert your entire list into yet another list, useful if you don't know how big it will be.</p>
<p>Then I've used reduce to apply a function that finds the common values between each set. It finds the intersection of set 1 & set 2, which is itself a set, then the intersection of that set & set 3 etc. The mysets generator will happily feed each set on demand to the reduce function until its done.</p>
<p>I believe reduce has been deprecated as a built-in in Python 3.0, but should still be available in functools.</p>
<p>You could of course make it a one-liner by replacing mysets in the reduce with the generator expression, but that reduces the readability IMO. In practice I'd probably even go one step further and break the lambda out into its own line as well:</p>
<pre><code>>>> mysets = (set(x.items()) for x in MyList)
>>> find_common = lambda a,b: a.intersection(b)
>>> reduce(find_common, mysets)
set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])
</code></pre>
<p>And if you need the end result to be a dict, just wrap it like so:</p>
<pre><code>>>> dict(reduce(find_common, mysets))
{'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'}
</code></pre>
<p>dict can accept any iterator of key,value pairs, such as the set of tuples returned at the end.</p>
|
<p>Sorry, yes, 'type':'Purchase' is also one of the common values.Should have logged in to edit the question.</p>
| 40,597
|
<p>By default, .NET application's configuration file is named after "exe file name".config. I'm wondering whether it is possible to have one application's configuration specified dynamically.</p>
<p>For example, the built application is "foo.exe". At runtime, the config file is "foo.exe.config". Is it possible to have it accept command line arguments to use other config file. So, the application can use other configuration like below.</p>
<blockquote>
<p>foo.exe /config:bar.config</p>
</blockquote>
<p>bar.config is used as config file insteand of foo.exe.config.</p>
|
<p>All of the above work well if you need to replace only AppSettings section. </p>
<p>In case you have to run with different config files (all sections) you might want to consider launching application using a host, that creates app domain for your main application and sets different config file depending on parameters you passed in.</p>
<p>Here's the code that worked for me:</p>
<pre><code> AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "file://" + System.Environment.CurrentDirectory;
setup.DisallowBindingRedirects = true;
setup.DisallowCodeDownload = true;
if (args.Length != 0 && args[0].Equals("-test"))
{
setup.ConfigurationFile = "PATH_TO_YOUR_TEST_CONFIG_FILE";
}
else {
setup.ConfigurationFile = "PATH_TO_YOUR_LIVE_CONFIG_FILE";
}
AppDomain domain = AppDomain.CreateDomain("FRIENDLY_NAME", null, setup);
domain.ExecuteAssembly("YourMainApp.exe");
</code></pre>
|
<p>Yes you will need use ExeConfigurationFileMap</p>
| 30,024
|
<p>I now own the Prusa3D MMU2. The benefits, costs, and experience others have had is well documented. I am interested in rebuilding my large, home-designed delta machine to be multi-material, and don't want to overlook strategies I haven't considered.</p>
<p>My original implementation used an E3D Kraken as the hot-end, and handled the inevitable delta tilt by adding two additional degrees of freedom to the head to lower the selected nozzle to the bed. I've been through three generations of mechanisms, and I think the third will work.</p>
<p>But, I feel that I am not seeing obvious and better alternatives.</p>
<p>So, the question: Through what methods and mechanisms can a multi-material (different polymers, different temperatures) FDM printer operate, and are there available designs or examples of best practices for those methods?</p>
|
<p>Let's look at various methods:</p>
<h2>Multiple Hotends</h2>
<p>The oldest version and one of the best to print materials at vastly different print temperatures (like printing a cheaper PLA infill into a Polycarbonate shell - the print temperature difference is 60-100 °C) is to have 2 or more hotends. This way also avoids the need for purging towers. It does, however, limit the maximum size of the used printbed and few 2-printhead machines are cheap.</p>
<h2>Y-Coupler</h2>
<p>Using a bowden setup, a Y-coupler could be used to feed the filament from 2 extruders into one hotend. On the switching tool command, E0 would pull the filament back some couple millimeters beyond the coupler and then E1 would push forward back into the meltzone. One will need a purging tower/object.</p>
<h2>Special, multi-entry hotend</h2>
<p>Some Hotends had been concieved that have 2 or more ways into the meltzone and the multiple extruders push along them. They generally are quite complex and hard to clean, but they allow to seamlessly blend between two filaments of the same material and create pretty much a controlled fade by precisely directing how much of either side is used on any layer. For clean cuts, a purging tower is necessary.</p>
<h2>Splicing filament</h2>
<p>This is what the <a href="https://www.mosaicmfg.com/products/palette-2" rel="nofollow noreferrer">Palette 2</a> and the Prusa MMU do: they push pieces of filament into a feeder tube that then are consumed by the printer via its own extruder. If they melt the filaments together like in the PAlette, it's proper splicing, if they just line up the next filament piece without merging into a spliced filament it's more like instant color switching.</p>
<p>This method is good for multi-color prints or using materials that have the same or similar<sup>1</sup> melting temperatures. It might or might not need a purge tower/object to get rid of the residue in the zones between the filaments.</p>
<p>This could btw also be done manually but should be avoided.</p>
<p><sup>1 - or rather not too dissimilar, if the slicer is set up to do it right. By setting up the slicer cleverly, one can have the extruder retract the filament, then adjust the heat over the purge tower and then resume extruding in the purge object at the changed temperature. PLA/PVA from a Prusa MMU is known and advertised to be doable, PLA/ABS might be possible this way. For extreme dissimilarities like PLA/PC (60-100 °C) I have my doubts though. </sup></p>
<h2>Usability</h2>
<p>All of these variants are basically viable, but some have benefits over others. Service is in this comparison meant as <em>repairing</em> a broken extruder, <em>maintaining</em> as the operations needed to keep it in printing order.</p>
<ul>
<li>multiple <em>fully independent</em> hotends is among the easiest to services. It could be direct drive (good for flexible filaments) or bowden. It is however heavy and usually not an option for delta printers. It has a downside that you have to perfectly level two hotend nozzles to be exactly on the same height, putting it in the hard to maintain category.
<ul>
<li><em>multiple hotends on the same carrier</em> is harder to service and maintain in comparison to multiple <em>independent</em> hotends as the components are very close together. Especially nozzle height adjustments can be more finicky.</li>
</ul></li>
<li>Y-Coupler needs to be a bowden and has problem with materials that are very stringy. That makes it especially bad for flexible materials. Maintaining is like a normal hotend and servicing is almost the same.</li>
<li>Special hotends are hard to come by but could be available for direct drive, making them possible for flexible filaments. They are, as already noticed, very hard to service.</li>
<li>Splicing filament can be done with either direct drive or bowden setups. It is probaby the most convenient to use after setup and has the maintenance and serviceability of a single hotend and a fully separate machine. Their biggest downside is price and setup time needed.</li>
</ul>
|
<p>Another way to combine the simpler geometry of a single nozzle, and to get the reduced mass of a single extrusion tool would be to make it like a CNC machine with a tool changer. One material is printed, then the hot end, extruder, and feed tube are swapped out for another which is primed and ready with the next material.</p>
<p>Lots of mechanical precision problems exist for arranging for the nozzles to be in the very same place, plus or minus a small tolerance. This is worsened by the presence of filament bits and strings which seem to eventually pollute the workspace.</p>
<p>If that could be worked out, one could have a plethora of extrusion tools, nozzle sizes, materials, multi-material mixing chambers, and other complexities.</p>
<p>E3D was talking about such a printer, but I haven't seen a product... only an invitation to send money as a show of interest in such a printer.</p>
| 1,334
|
<p>I have to include Groovy classes into existing Java apps, and include Groovy into Ant's <code>build.xml</code> file.</p>
<p>What is the best way to configure Ant's <code>build.xml</code> for it? </p>
<p>Update: Are there more specifics in combining Java and Groovy compilations? Sequence of tasks?</p>
|
<p>@VonC is correct about including Groovy scripting in your Ant build.</p>
<p>To expand a bit:</p>
<p>To compile <code>.groovy</code> and <code>.java</code> sources <em>together</em> for use in the same application, use the <a href="http://groovy.codehaus.org/The+groovyc+Ant+Task" rel="nofollow noreferrer"><code><groovyc></code></a> Ant task.</p>
<p>See <a href="http://groovy.codehaus.org/Ant+Integration+with+Groovy" rel="nofollow noreferrer">Ant Integration with Groovy</a> for the reference.</p>
|
<p>You should define javac inside groovyc, like this.</p>
<pre><code><groovyc srcdir="${testSourceDirectory}" destdir="${testClassesDirectory}">
<classpath>
<pathelement path="${mainClassesDirectory}"/>
<pathelement path="${testClassesDirectory}"/>
<path refid="testPath"/>
</classpath>
<javac source="1.4" target="1.4" debug="on" />
</groovyc>
</code></pre>
<p>For more info have a look here: <a href="http://groovy.codehaus.org/The+groovyc+Ant+Task" rel="nofollow">http://groovy.codehaus.org/The+groovyc+Ant+Task</a> at section Joint Compilation.</p>
| 37,242
|
<p>I have an nmake-based project which in turn calls the asp compiler, which can throw an error, which nmake seems to recognize:</p>
<pre><code>NMAKE : fatal error U1077: 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe' : return code '0x1'
</code></pre>
<p>However, when I call nmake from within a batch file, the environment variable %ERRORLEVEL% remains set at zero:</p>
<pre><code>nmake /NOLOGO
echo BUILD RETURNING: %ERRORLEVEL%
</code></pre>
<p>If I control-c the nmake task, I do end up getting a non-zero ERRORLEVEL (it's set to 2) so my assumption is that I'm able to catch errors okay, but nmake isn't bubbling up the non-zero exit code from it's task. Or, at least, I'm mis-trapping it. Any help would be appreciated.</p>
|
<p>First thing, please post your batch file so we can see how you trap the error.<br>
Also comment this post so I can read it again.<br>
As a first git, i'd guess something like: </p>
<p><strong>nmakebatch.cmd</strong> <em>usual nmake arguments, without /NOLOGO</em></p>
<pre><code>@echo off
rem Args[x]: nmake arguments
echo.>> %~n0.log
echo %date% %time%>> %~n0.log
echo nmake /NOLOGO %*>> %~n0.log
nmake /NOLOGO %*
echo %errorlevel%>> %~n0.log
</code></pre>
<p>Is a start for trapping all situations, into a incrementing log, while building.</p>
|
<p>you should use <code>exit /b %errorlevel%</code> in your batch script this will pass the return code back to nmake</p>
| 40,819
|
<p>I can display and select a single file in windows explorer like this:</p>
<pre><code>explorer.exe /select, "c:\path\to\file.txt"
</code></pre>
<p>However, I can't work out how to select more than one file. None of the permutations of select I've tried work.</p>
<p>Note: I looked at these pages for docs, neither helped.</p>
<p><a href="https://support.microsoft.com/kb/314853" rel="nofollow noreferrer">https://support.microsoft.com/kb/314853</a><br />
<a href="http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm" rel="nofollow noreferrer">http://web.archive.org/web/20100716112458/http://www.infocellar.com:80/Win98/explorer-switches.htm</a></p>
|
<p>This should be possible with the shell function <a href="http://msdn.microsoft.com/en-us/library/bb762232(VS.85).aspx" rel="noreferrer"><code>SHOpenFolderAndSelectItems</code></a></p>
<p><strong>EDIT</strong></p>
<p>Here is some sample code showing how to use the function in C/C++, without error checking:</p>
<pre><code>//Directory to open
ITEMIDLIST *dir = ILCreateFromPath(_T("C:\\"));
//Items in directory to select
ITEMIDLIST *item1 = ILCreateFromPath(_T("C:\\Program Files\\"));
ITEMIDLIST *item2 = ILCreateFromPath(_T("C:\\Windows\\"));
const ITEMIDLIST* selection[] = {item1,item2};
UINT count = sizeof(selection) / sizeof(ITEMIDLIST);
//Perform selection
SHOpenFolderAndSelectItems(dir, count, selection, 0);
//Free resources
ILFree(dir);
ILFree(item1);
ILFree(item2);
</code></pre>
|
<p>I suppose you can use <code>FindWindowEx</code> to get the SysListView32 of Windows Explorer, then use <code>SendMessage</code> with <code>LVM_SETITEMSTATE</code> to select the items. The difficulty being to know the position of the items... Perhaps <code>LVM_FINDITEM</code> can be used for this.</p>
| 3,079
|
<p>I'm a newbie to swing development.</p>
<p>I have a swing app that needs to access data from a remote sql database. The users of the app are all located in our office.</p>
<p>Is it bad practice to access the database directly from the swing app? </p>
<p>Should I put database facing code into an rmi server?</p>
|
<p>Not necessarily, but you'll want to 'layer out' the data access code in your application to make it easier to do later. It will also tend to make the rest of the application more maintainable.</p>
|
<p>Do you have a plan for dealing with concurrent access to the same records in the database? It is something you will have to deal with, so if not from within the code, having all instances of the Swing application accessing the data via a central (i.e. your RMI server) location would make this much easier.</p>
| 32,968
|
<p>In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), <code>public</code>, <code>protected</code> and <code>private</code>, while making <code>class</code> and <code>interface</code> and dealing with inheritance?</p>
|
<p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="noreferrer">The official tutorial</a> may be of some use to you.</p>
<hr />
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th></th>
<th>Class</th>
<th>Package</th>
<th>Subclass<br/>(same pkg)</th>
<th>Subclass<br/>(diff pkg)</th>
<th>World</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>public</code></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
</tr>
<tr>
<td><code>protected</code></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td></td>
</tr>
<tr>
<td><em>no modifier</em></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td></td>
<td></td>
</tr>
<tr>
<td><code>private</code></td>
<td>+</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>+ : accessible<br/>
blank : not accessible</p>
|
<ul>
<li><p>public</p>
<p>If a class member is declared with public then it can be accessed from anywhere</p></li>
<li><p>protected</p>
<p>If a class member is declared with keyword protected then it can be accessed from same class members, outside class members within the same package and inherited class members. If a class member is protected then it can NOT be accessed from outside package class unless the outside packaged class is inherited i.e. extends the other package superclass. But a protected class member is always available to same package classes it does NOT matter weather the same package class is inherited or NOT</p></li>
<li><p>default</p>
<p>In Java default is NOT an access modifier keyword. If a class member is declared without any access modifier keyword then in this case it is considered as default member. The default class member is always available to same package class members. But outside package class member can NOT access default class members even if outside classes are subclasses unlike protected members</p></li>
<li><p>private</p>
<p>If a class member is declared with keyword protected then in this case it is available ONLY to same class members</p></li>
</ul>
| 26,485
|
<p>What software do you use to manage Scrum software development ? </p>
<p>We've tried Tackle and VersionOne (both free) so far and they are good except for the fact that it's difficult to track work in progress. For example, if I have a task that I estimate will take me 8 hours to complete, I've done 4 hours of work with 4 hours remaining, the task is always reported as 8 hours remaining until it is marked complete, at which time it falls to zero. </p>
<p>I'd like to use a tool that will allow me to take an accurate work at the teams WIP at the end of each week and see how much impact that work has had towards a deadline along with completed tasks. </p>
<p>Thanks for your input!</p>
|
<p>I recommend a white board and excel spreadsheets. The whiteboard has story cards (index cards) , where the work in progress is tracked. The story card starts out with say 8 hours, and as the work progresses decrement the number on the card. At the end of the day, put the numbers in the cards to a spreadsheet.</p>
<p>The whiteboard is visible all the time, and gives the whole team visibility on how the work is progressing.</p>
|
<p>ScrumWorks is nice for small teams. And free, too, for the basic version. We have about 30 developers with multiple projects/iterations/etc. Some basic burn-down charts, good for "yesterday's weather", etc.</p>
<p>Check it out at:</p>
<p><a href="http://danube.com/scrumworks/basic" rel="nofollow noreferrer">http://danube.com/scrumworks/basic</a></p>
| 18,495
|
<p>I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?</p>
|
<p>I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a <code>lock</code>:</p>
<pre><code>void AddItemToList(object o)
{
lock(myBindingList)
{
myBindingList.Add(o);
}
}
</code></pre>
<p>Look at the <a href="http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx" rel="nofollow noreferrer">lock statement docs</a> for more info.</p>
|
<p>Only just found this post... do you mean <a href="http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/f12a3c5980567f06" rel="nofollow noreferrer">like this</a>?</p>
| 17,899
|
<p>I am writing a sort of screen-recording app for Windows and wish to know when and which regions of the screen/active window have changed.</p>
<p>Is there a Windows API I can hook to get notified of screen changes?</p>
<p>Or would I need to manually write something like <a href="https://stackoverflow.com/questions/76651/">this</a>? :(</p>
<p>I always figured that Remote Desktop used some sort of API to detect what regions of the screen had changed and only sent back those images - this is exactly the behavior that I need.</p>
|
<p>I don't think there is an API in Windows that can tell you which parts of the screen have changed.</p>
<p>One possible way is using a <a href="http://www.uvnc.com/features/driver.html" rel="nofollow noreferrer">video mirror driver</a> like UltraVNC uses.</p>
|
<p>Thanks for your help everyone. I ended up writing an image differencing class which seems to calculate the changed rectangles suprisingly quick. I've posted the gist of how it works <a href="https://stackoverflow.com/questions/76651/dirty-rectangles#322354">here</a>.</p>
<p>At the moment I'm just doing it in a timer but planning to do it after input events too.</p>
<p>Thanks heaps for your links Boost - I've only just looked at this thread again so I'll check them out soon.</p>
| 35,519
|
<p>Is there an easy way to convert between color models in Java (RGB, HSV and Lab). </p>
<p>Assuming RGB color model:</p>
<ul>
<li>How do I calculate black body spectrum color palette? I want to use it for a heatmap chart.</li>
<li>How about single-wavelength spectrum?</li>
</ul>
<p><strong>Edit:</strong> I found that the <a href="http://java.sun.com/javase/6/docs/api/java/awt/color/ColorSpace.html" rel="nofollow noreferrer">ColorSpace</a> class can be used for conversions between RGB/CIE and many other color models.</p>
|
<p>Java has built-in RGB to HSB conversion. Whenever I need a quick pallet of colors in Java I just do this:</p>
<pre><code>public Color[] generateColors(int n)
{
Color[] cols = new Color[n];
for(int i = 0; i < n; i++)
{
cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f);
}
return cols;
}
</code></pre>
<p>It is a quick and dirty hack (I would tweak the 'magic' numbers for your app), but for my simple uses it generates a nice bright pleasant pallet.</p>
|
<p>This is a nice way to make a HSL color square in AS3.</p>
<pre><code>/**
* Generate a BitmapData HSL color square (n x n) of hue
* At a low n dimension you get cool blocky color palettes (e.g. try n=10)
*/
function generateColorSquare(n:uint, hue:uint):BitmapData
{
var bd:BitmapData = new BitmapData(n, n, false, 0xFFFFFF);
for (var i:uint=n*n; i > 0; i--)
{
bd.setPixel(i % n, Math.floor(i / n), HSBColor.convertHSBtoRGB(hue, i / (n*n), (1/n) * (i % n) ));
}
return bd;
}
</code></pre>
| 27,664
|
<p>Here's something I haven't been able to fix, and I've looked <strong>everywhere</strong>. Perhaps someone here will know!</p>
<p>I have a table called dandb_raw, with three columns in particular: dunsId (PK), name, and searchName. I also have a trigger that acts on this table:</p>
<pre><code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dandb_raw_searchNames]
ON [dandb_raw]
FOR INSERT, UPDATE
AS
SET NOCOUNT ON
select dunsId, name into #magic from inserted
UPDATE dandb
SET dandb.searchName = company_generateSearchName(dandb.name)
FROM (select dunsId, name from #magic) i
INNER JOIN dandb_raw dandb
on i.dunsId = dandb.dunsId
--Add new search matches
SELECT c.companyId, dandb.dunsId
INTO #newMatches
FROM dandb_raw dandb
INNER JOIN (select dunsId, name from #magic) a
on a.dunsId = dandb.dunsId
INNER JOIN companies c
ON dandb.searchName = c.searchBrand
--avoid url matches that are potentially wrong
AND (lower(dandb.url) = lower(c.url)
OR dandb.url = ''
OR c.url = ''
OR c.url is null)
INSERT INTO #newMatches (companyId, dunsId)
SELECT c.companyId, max(dandb.dunsId) dunsId
FROM dandb_raw dandb
INNER JOIN
(
select
case when charindex('/',url) <> 0 then left(url, charindex('/',url)-1)
else url
end urlMatch, * from companies
) c
ON dandb.url = c.urlMatch
where subsidiaryOf = 1 and isReported = 1 and dandb.url <> ''
and c.companyId not in (select companyId from #newMatches)
group by companyId
having count(dandb.dunsId) = 1
UPDATE cd
SET cd.dunsId = nm.dunsId
FROM companies_dandb cd
INNER JOIN #newMatches nm
ON cd.companyId = nm.companyId
GO
</code></pre>
<p>The trigger causes inserts to fail:</p>
<pre><code>insert into [dandb_raw](dunsId, name)
select 3442355, 'harper'
union all
select 34425355, 'har 466per'
update [dandb_raw] set name ='grap6767e'
</code></pre>
<p>With this error:</p>
<pre><code>Msg 213, Level 16, State 1, Procedure companies_contactInfo_updateTerritories, Line 20
Insert Error: Column name or number of supplied values does not match table definition.
</code></pre>
<p>The most curious thing about this is that each of the individual statements in the trigger works on its own. It's almost as though inserted is a one-off table that infects temporary tables if you try to move inserted into one of them.</p>
<p>So what causes the trigger to fail? How can it be stopped?</p>
|
<p>I think David and Cervo combined have hit on the problem here.</p>
<p>I'm pretty sure part of what was happening was that we were using #newMatches in multiple triggers. When one trigger changed some rows, it would fire another trigger, which would attempt to use the connection scoped #newMatches.</p>
<p>As a result, it would try to, find the table already existed with a different schema, die, and produce the message above. One piece of evidence that would be in favor: Does inserted use a stack style scope (nested triggers have their own inserteds?)</p>
<p>Still speculating though - at least things seem to be working now!</p>
|
<p>Trigger code (because it must run everytime the data is updated) must be efficient and must account for multiple record inserts. You've succeeded at the second but not the first. You have made this overly complicated and have used things such as Not in statements that are usually less efficeint than using a left join. Temp tables are unnecessary here (I would never consider using one in a trigger) as they add to the inefficiency of the trigger. There is not reason not to write
From inserted i
instead of
FROM (select dunsId, name from #magic) i</p>
<p>The first is likely to be faster and is simpler to read and maintain.</p>
<p>Here:
JOIN ( select case when charindex('/',url) <> 0 then left(url, charindex('/',url)-1) else url end urlMatch, * from companies ) c ON dandb.url = c.urlMatch</p>
<p>You are selecting all the fields in the table even though you only appear to be using one. Why? You are also running that case stament on all the records in company even though after you join you may not need all of them.</p>
<p>Also in general I would avoid using select * but especially in a trigger. Suppose you are inserting into another table and you used select * from some table joined to inserted or deleted. Adding a column to that table would cause the trigger to fail and stop all data changes until it was fixed.</p>
<p>You've also used a function in the trigger. This coudl be painfully slow if you havea large insert. I suggest you test this by updating a large group of records and see what happens. All data changes do not happen just from the user interface, one record at a time. There will be times when one field is updated from an ad-hoc query in management studio (when all prices need to be adjusted by 10% as the simplest example that comes to mind.) Your trigger needs to be able to handle those types if updates as well as the ones you are expecting. I would run a test case updating 100000 rows and see how much this trigger slows things down.</p>
<p>Maybe this isn't really answering your problem, but the trigger just is so far from optimal, I had to say it.</p>
| 12,084
|
<p>I have a table of data, and I allow people to add meta data to that table.</p>
<p>I give them an interface that allows them to treat it as though they're adding extra columns to the table their data is stored in, but I'm actually storing the data in another table.</p>
<pre><code>Data Table
DataID
Data
Meta Table
DataID
MetaName
MetaData
</code></pre>
<p>So if they wanted a table that stored the data, the date, and a name, then I'd have the data in the data table, and the word "Date" in metaname, and the date in MetaData, and another row in the meta table with "Name" in metaname and the name in metadata. </p>
<p>I now need a query that takes the information from these tables and presents it as though coming from a single table with the two additional columns "Data" and "Name" so to the customer it would look like there's a single table with their custom columns:</p>
<pre><code>MyTable
Data
Date
Name
</code></pre>
<p>Or, in other words, how do I go from here:</p>
<pre><code>Data Table
DataID Data
1 Testing!
2 Hello, World!
Meta Table
DataID MetaName MetaData
1 Date 20081020
1 Name adavis
2 Date 20081019
2 Name mdavis
</code></pre>
<p>To here:</p>
<pre><code>MyTable
Data Date Name
Testing! 20081020 adavis
Hello, World! 20081019 mdavis
</code></pre>
<p>Years ago when I did this in MySQL using PHP, I did two queries, the first to get the extra meta data, the second to join them all together. I'm hoping that modern databases have alternate methods of dealing with this.</p>
<p>Related to option 3 of <a href="https://stackoverflow.com/questions/218848/design-decision-dynamically-adding-data-question#218872">this question</a>.</p>
<p>-Adam</p>
|
<p>You want to pivot each of your name-value pair rows in the MyTable... Try this sql:</p>
<pre><code>DECLARE @Data TABLE (
DataID INT IDENTITY(1,1) PRIMARY KEY,
Data VARCHAR(MAX)
)
DECLARE @Meta TABLE (
DataID INT ,
MetaName VARCHAR(MAX),
MetaData VARCHAR(MAX)
)
INSERT INTO @Data
SELECT 'Data'
INSERT INTO @Meta
SELECT 1, 'Date', CAST(GetDate() as VARCHAR(20))
UNION
SELECT 1, 'Name', 'Joe Test'
SELECT * FROM @Data
SELECT * FROM @Meta
SELECT
D.DataID,
D.Data,
MAX(CASE MetaName WHEN 'Date' THEN MetaData ELSE NULL END) as Date,
MAX(CASE MetaName WHEN 'Name' THEN MetaData ELSE NULL END) as Name
FROM
@Meta M
JOIN @Data D ON M.DataID = D.DataID
GROUP BY
D.DataID,
D.Data
</code></pre>
|
<p>AFAIK, you can do this on the server-side only with a dynamic <code>SQL</code> stored procedure. </p>
<p>Effectively the code you want to generate dynamically is:</p>
<pre><code>SELECT [Data Table].*
,[MyTable Date].MetaData
,[MyTable Name].MetaData
FROM [Data Table]
LEFT JOIN [MyTable] AS [MyTable Date]
ON [MyTable Date].DataID = [Data Table].DataID
AND [MyTable Date].MetaName = 'Date'
LEFT JOIN [MyTable] AS [MyTable Name]
ON [MyTable Name].DataID = [Data Table].DataID
AND [MyTable Name].MetaName = 'Name'
</code></pre>
<p>And here's code to do it:</p>
<pre><code>DECLARE @sql AS varchar(max)
DECLARE @select_list AS varchar(max)
DECLARE @join_list AS varchar(max)
DECLARE @CRLF AS varchar(2)
DECLARE @Tab AS varchar(1)
SET @CRLF = CHAR(13) + CHAR(10)
SET @Tab = CHAR(9)
SELECT @select_list = COALESCE(@select_list, '')
+ @Tab + ',[MyTable_' + PIVOT_CODE + '].[MetaData]' + @CRLF
,@join_list = COALESCE(@join_list, '')
+ 'LEFT JOIN [MyTable] AS [MyTable_' + PIVOT_CODE + ']' + @CRLF
+ @Tab + 'ON [MyTable_' + PIVOT_CODE + '].DataID = [DataTable].DataID' + @CRLF
+ @Tab + 'AND [MyTable_' + PIVOT_CODE + '].MetaName = ''' + PIVOT_CODE + '''' + @CRLF
FROM (
SELECT DISTINCT MetaName AS PIVOT_CODE
FROM [MyTable]
) AS PIVOT_CODES
SET @sql = 'SELECT [DataTable].*' + @CRLF
+ @select_list
+ 'FROM [DataTable]' + @CRLF
+ @join_list
PRINT @sql
--EXEC (@sql)
</code></pre>
<p>You could use a similar dynamic technique using the <code>CASE</code> statement example to perform the pivot.</p>
| 27,026
|
<p>I'm doing a webapp and need a backup plan. Here's what I've got so far:</p>
<ul>
<li>nightly encrypted backup of the SQL database to Amazon S3 and my external drive (incremental if possible, not overly familiar with PostgreSQL yet, but that's another thread) </li>
<li>nightly backup of my Mercurial repo (which includes Apache configs, deploy scripts, etc) to S3 (w/ local backups via Time Machine)</li>
</ul>
<p>Should I add anything else, or will this cover it? For a gauge of how critical the data is/would be, it's a project management app along the lines of Basecamp.</p>
|
<p>Weekly full backup of your database as well as nightly incremental ones as well perhaps?</p>
<p>It means that if one of your old incremental backups gets corrupted then you have lost less than a week of data.</p>
<p>Also, ensure you have a backup test plan to ensure your backups work. There are a lot of horror stories going around about this, from companies that have been doing backups for years, never testing them and then finding out none of them are any good once they need them. (I've also been at a company like this. Thankfully I spotted the backups weren't working before they were required and fixed the problems).</p>
|
<p>I would if you can change from a incremental back up to a differential. If you have a incremental then you would have to apply the weekly full backup and then every incremental following that. If one of your incrementals fails early in the week, then all your subsequent backups will fail too.</p>
<p>However if you use a differential then each differential contains all the changes since the last back up. so even if one of the back ups failed earlier in the week you would still be able to recover fully if you have a sucessful recent backup.</p>
<p>I hope i am explaining this well!</p>
<p>:)</p>
| 17,981
|
<p>Here is my scenario. For the example lets say that I need to return a list of cars based on a search criteria. I would like to have a single View to display the results since the output will be the same, but I need several ways of getting there. For instance, I may have a Form with a textbox to search by year. I may have another separate page that contains a hyperlink for all red, Toyota cars. How do I handle these multiple scenarios in the same View and Controller. My dilemma is that the search could contain several options… year, make, model, etc but I don’t know where to put them.</p>
<p>What is the best approach for this? Should I define the parameters in the routing or go with query strings, etc?</p>
|
<p><strong>Option 1</strong></p>
<p>Of course you always can choose the way of /car/search/?vendor=Toyota&color=Red&model=Corola and I think it will be good for you.</p>
<pre><code>routes.MapRoute(
"CarSearch",
"car/search",
new { controller = "car", action = "search" }
);
</code></pre>
<p>You can get params from Request.Params in action in this case.</p>
<p><strong>Option 2</strong></p>
<p>Or you can define params in the routing table, but AFAIK it will be required to make a set of rules for all possible combinations, because an order of the params matter, for example:</p>
<pre><code> routes.MapRoute(
"CarSearch1",
"car/search/vendor/{vendor}/color/{color}/model/{model}",
new {controller = "car", action = "search"}
);
routes.MapRoute(
"CarSearch2",
"car/search/color/{color}/vendor/{vendor}/model/{model}",
new {controller = "car", action = "search"}
);
routes.MapRoute(
"CarSearch3",
"car/search/model/{model}/color/{color}/vendor/{vendor}",
new {controller = "car", action = "search"}
);
</code></pre>
<p>... an so on. It's true if you are going with the standard MvcRouteHandler.</p>
<p>But it was an easy ways :)</p>
<p><strong>Option 3</strong></p>
<p>The hard, but, I think, most elegant way, is to make your own IRouteHandler implementation - it will give you much more flexibility in params order. But again, its a hard way, dont go with it if you have a simple app.
So, just for example of how to make it this way (very simple example):</p>
<p>Add new route to the list of routes:</p>
<pre><code>routes.Add
(
new Route
(
"car/search/{*data}",
new RouteValueDictionary(new {controller = "car", action = "search", data = ""}),
new MyRouteHandler()
)
);
</code></pre>
<p>Add classes that will tweak the standard request processing chain:</p>
<pre><code>class MyRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHttpHandler(requestContext);
}
}
class MyHttpHandler : MvcHandler
{
public MyHttpHandler(RequestContext requestContext) : base(requestContext)
{
}
protected override void ProcessRequest(HttpContextBase httpContext)
{
IController controller = new CarController();
(controller as Controller).ActionInvoker = new MyActionInvoker();
controller.Execute(RequestContext);
}
}
class MyActionInvoker : ControllerActionInvoker
{
protected override ActionResult InvokeActionMethod(MethodInfo methodInfo, IDictionary<string, object> parameters)
{
// if form of model/{model}/color/{color}/vendor/{vendor}
var data = ControllerContext.RouteData.GetRequiredString("data");
var tokens = data.Split('/');
var searchParams = new Dictionary<string, string>();
for (var i = 0; i < tokens.Length; i++)
{
searchParams.Add(tokens[i], tokens[++i]);
}
parameters["searchParams"] = searchParams;
return base.InvokeActionMethod(methodInfo, parameters);
}
}
</code></pre>
<p>In controller:</p>
<pre><code>public ActionResult Search(IDictionary<string, string> searchParams)
{
ViewData.Add
(
// output 'model = Corola, color = red, vendor = Toyota'
"SearchParams",
string.Join(", ", searchParams.Select(pair => pair.Key + " = " + pair.Value).ToArray())
);
return View();
}
</code></pre>
<p>And it will work with any search parameters order:</p>
<pre><code>/car/search/vendor/Toyota/color/red/model/Corola
/car/search/color/red/model/Corola/vendor/Toyota
/car/search/model/Corola/color/red/vendor/Toyota
</code></pre>
<p>But also dont forget to make a link generation logic, because Html.ActionLink and Html.RenderLink will not give you url in pretty form of /car/search/model/Corola/color/red/vendor/Toyota, so you'll need to make a custom link generator.</p>
<p>So, if you need a really flexible routing - you'd better go with this hard way :)</p>
|
<p>Each method (action) on the controller would take different parameters, but create the same collection of search results. Then, each would </p>
<pre><code>return View("SearchResult", searchResultCollection);
</code></pre>
<p>They all use the same view, SearchResult.aspx.</p>
| 49,729
|
<p>What materials, available as filaments for use in FDM printing, are known to be the most physically and chemically inert? In particular, stability (not necessarily simultaneously) in the presence of the following should be assumed:</p>
<ul>
<li>pH 0-14</li>
<li>oxidizing agents (ozone, permanganates, dichromates, acidic hydrogen
peroxide)</li>
<li>organic solvents (particularly acetone, methanol, toluene, formamide)</li>
<li>temperature up to 160 degrees Celsius</li>
<li>pressures between ~10^-7 torr and ~2 bar</li>
<li>oxygen or argon plasma</li>
</ul>
|
<p>PEEK, a plastic known for its superior chemical and physical resilience (<a href="http://www.zeusinc.com/materials/peek/chemical-resistance-chart-peek" rel="nofollow">http://www.zeusinc.com/materials/peek/chemical-resistance-chart-peek</a>), has been successfully used for filament-based printing (<a href="https://3dprint.com/52713/indmatec-peek-fdm-printing-filament/" rel="nofollow">https://3dprint.com/52713/indmatec-peek-fdm-printing-filament/</a>). However, it is unlikely to be an option on most existing printers given its high melting temperature (around 343 degrees Celsius, <a href="https://en.wikipedia.org/wiki/PEEK" rel="nofollow">https://en.wikipedia.org/wiki/PEEK</a>). Though it does not meet all the criteria proposed (for instance, its glass transition temperature is around 143 degrees Celsius), overall it is a fairly good choice.</p>
<p>Teflon, an obvious choice, unfortunately has a decomposition temperature very close to its melting temperature, and appears to be unsuitable for extrusion.</p>
|
<p>PEEK, a plastic known for its superior chemical and physical resilience (<a href="http://www.zeusinc.com/materials/peek/chemical-resistance-chart-peek" rel="nofollow">http://www.zeusinc.com/materials/peek/chemical-resistance-chart-peek</a>), has been successfully used for filament-based printing (<a href="https://3dprint.com/52713/indmatec-peek-fdm-printing-filament/" rel="nofollow">https://3dprint.com/52713/indmatec-peek-fdm-printing-filament/</a>). However, it is unlikely to be an option on most existing printers given its high melting temperature (around 343 degrees Celsius, <a href="https://en.wikipedia.org/wiki/PEEK" rel="nofollow">https://en.wikipedia.org/wiki/PEEK</a>). Though it does not meet all the criteria proposed (for instance, its glass transition temperature is around 143 degrees Celsius), overall it is a fairly good choice.</p>
<p>Teflon, an obvious choice, unfortunately has a decomposition temperature very close to its melting temperature, and appears to be unsuitable for extrusion.</p>
| 398
|
<p>I'm working with a JavaScript API where most of the functions are asynchronous. The API is the <a href="http://webkit.org/blog/126/webkit-does-html5-client-side-database-storage/" rel="noreferrer">WebKit JavaScript Database API</a> which is a binding to a subset of functionality to manipulate SQLite3 databases. I understand the design decision to make things async as to not block and provide a responsive user interface. In my situation I know that my usage of the async API calls will execute fast. Since this is the case I'd like to provide my developers a cleaner and easier to use wrapper API that forces synchronous calls.</p>
<p>Here's the async call</p>
<pre><code>db.executeSql(sqlStatement, function(result) {
// do something with result
});
</code></pre>
<p>And here's what I'd like to be able to do</p>
<pre><code>var result = dbWrapper.executeSql(sqlStatement);
// do something with result
</code></pre>
<p>Is there a design pattern/way to do this? A written or linked to code example is preferred. The target platform/broswer is Mobile Safari on the iPhone.</p>
<p>Thank you</p>
|
<p>Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.</p>
<p>You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.</p>
<p>So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.</p>
<p>*: except in some obscure situations which wouldn't help you and are generally considered bugs</p>
|
<p>This doesn't actually implement synchronous operation of the db query, but this was my solution for easy management. Basically use the calling function as the callback function, and test for the results argument. If the function receives results, it parses them, if not, it sends itself as a callback to the query method.</p>
<pre><code> render: function(queryResults){
if (typeof queryResults != 'undefined'){
console.log('Query completed!');
//do what you will with the results (check for query errors here)
} else {
console.log('Beginning query...');
this.db.read(this.render); //db.read is my wrapper method for the sql db, and I'm sending this render method as the callback.
}
}
</code></pre>
| 26,363
|
<p>I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.</p>
<p>I <em>could</em> sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already.</p>
<p>What I need is something like:</p>
<pre><code>int get_bits(char* data, unsigned bitOffset, unsigned numBits);
</code></pre>
<p>so I could get the 7th 6-bit character in the data by calling:</p>
<pre><code>const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
</code></pre>
|
<p>This may not work for sizes greater than 8, depending on endian system. It's basically what Marco posted, though I'm not entirely sure why he'd gather one bit at a time.</p>
<pre><code>int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {
numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course
data += bitOffset/8;
bitOffset %= 8;
return (*((int*)data) >> bitOffset) & numBits; //little endian
//return (flip(data[0]) >> bitOffset) & numBits; //big endian
}
//flips from big to little or vice versa
int flip(int x) {
char temp, *t = (char*)&x;
temp = t[0];
t[0] = t[3];
t[3] = temp;
temp = t[1];
t[1] = t[2];
t[2] = temp;
return x;
}
</code></pre>
|
<p>I think something in the line of the following might work.</p>
<pre><code>int get_bit(char *data, unsigned bitoffset) // returns the n-th bit
{
int c = (int)(data[bitoffset >> 3]); // X>>3 is X/8
int bitmask = 1 << (bitoffset & 7); // X&7 is X%8
return ((c & bitmask)!=0) ? 1 : 0;
}
int get_bits(char* data, unsigned bitOffset, unsigned numBits)
{
int bits = 0;
for (int currentbit = bitOffset; currentbit < bitOffset + numBits; currentbit++)
{
bits = bits << 1;
bits = bits | get_bit(data, currentbit);
}
return bits;
}
</code></pre>
<p>I've not debugged nor tested it, but you can use it as a start point.</p>
<p>Also, take into account bit order. You might want to change </p>
<pre><code> int bitmask = 1 << (bitoffset & 7); // X&7 is X%8
</code></pre>
<p>to</p>
<pre><code> int bitmask = 1 << (7 - (bitoffset & 7)); // X&7 is X%8
</code></pre>
<p>depending on how the bit array has been generated.</p>
| 33,140
|
<p>I’m writing pl/sql procedure that exports data from Oracle to Excel. I need data formatting so I can’t use CSV. I’ve already tried with XML but it generates too large files when I want to export e.g. 70000 rows with 50 columns (almost 300 MB!!!). </p>
<p>That’s why I decided to use HTML tags to generate XLS file – it is smaller than XML and I must directly define format of only some special columns (strings, numbers and dates are formatted automatically by Excel).
It’s very simple and convenient but I can’t define more than one worksheet.</p>
<p>Do you know how to add/define more than one worksheet in excel file written using HTML? I’ve tried to use VBScript formula like <% ActiveWorkbook.Worksheet.Add %>, but it doesn’t work.</p>
|
<p>Instead of creating Excel or HTML files on Oracle server, you can fetch Oracle data to existing Excel document via ODBC or OLEDB. The shortcoming is, that you should be careful with user permissions.</p>
<p><a href="https://www.youtube.com/watch?v=Adz0zZFePf8" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Adz0zZFePf8</a></p>
|
<p>You could save a (small) Excel sheet as html in Excel, and then reproduce that format.</p>
| 38,238
|
<p>Why not use partial class to build the ViewModel?</p>
<p>Since the definition of viewmodel classes have some definition of the data classes of datamodel, why not try to reduce some work, extending or making partial classes of the datamodel, completing them with command and etc.</p>
|
<p>In some cases this may be useful, but generally the ViewModel (or PresentationModel) has a different set of concerns that would muddle the rest of the model.</p>
<p>For example, imagine that you have an object model that represents an order processing workflow (everybody's favorite example.) This same model might be underlying a WPF, a web site, and perhaps even other services.
Within the WPF application there will be WPF-specific concerns for presentation. Adding these concerns to primary model (even as partial classes) results in a violation of SRP. Ultimately, it would obscure the intent of model and make it difficult for consumers of the model to know which parts of it where essential and which were incidental.</p>
|
<p>I agree but there are also extensions that seem to belong in a partial class as well. For example, a calculated field (say an invoice total), useful on the client and perhaps the viewmodel exposes it for data binding to the UI, however it's really a property of the entity. It may not be represented in the model itself because it can be derrived from the entity's other properties, and IMO better represented by using a partial class to extend the domain entity.</p>
| 40,975
|
<p>Sometimes software installers force you to scroll to the end of the EULA before the “I agree” box is enabled. How can I produce the same effect on a web page?</p>
|
<pre><code><html>
<head>
<script type="text/javascript">
function setupPage() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
if (scrollableHeight > visibleHeight) {
var checkbox = document.getElementById("agreebox");
checkbox.checked=false;
checkbox.disabled=true;
agreement.onscroll = handleScroll;
}
}
function handleScroll() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
var position = agreement.scrollTop;
if (position + visibleHeight == scrollableHeight) {
document.getElementById("agreebox").disabled=false;
}
}
</script>
</head>
<body>
<form>
<textarea id="agreetext" rows="8" cols="40">Long agreement</textarea>
<br/><br/>
<input type="checkbox" id="agreebox" value="true"/> <label id="agreelabel" for="agreebox">I agree</label>
<br/><br/>
<input type="submit" value="Continue"/>
</form>
<script type="text/javascript">
// We put this at the end of the page rather than in an document.onload
// because the document.onload event doesn't fire until all images have loaded.
setupPage();
</script>
</body>
</html>
</code></pre>
|
<p>Excellent bit of code, if you also want to change the color in the label next to the checkbox, just modify the code as follows: </p>
<pre><code>function setupPage() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
if (scrollableHeight > visibleHeight) {
var checkbox = document.getElementById("agreebox");
checkbox.checked=false;
checkbox.disabled=true;
document.getElementById("agreelabel").style.color = "#777";
agreement.onscroll = handleScroll;
}
}
function handleScroll() {
var agreement = document.getElementById("agreetext");
var visibleHeight = agreement.clientHeight;
var scrollableHeight = agreement.scrollHeight;
var position = agreement.scrollTop;
if (position + visibleHeight == scrollableHeight) {
document.getElementById("agreebox").disabled=false;
document.getElementById("agreelabel").style.color = "black";
}
}
</code></pre>
| 41,103
|
<p>During my last print I noticed this jumpy behavior during heat up (blue is bed, red is hotend):</p>
<p><a href="https://i.stack.imgur.com/KlD2K.png" rel="nofollow noreferrer" title="Graph of heatbed and hotend temperature over time"><img src="https://i.stack.imgur.com/KlD2K.png" alt="Graph of heatbed and hotend temperature over time" title="Graph of heatbed and hotend temperature over time"></a></p>
<p>So I am wondering about the jumps. What could cause this? I do not think that it is a defunct sensor (it is in both sensors) and I also don't think it is real. Could this pose some sort of hazard as temperature might not properly be controlled?</p>
<p>I use an Anet A8 printer with Marlin 1.1.9 and Octoprint</p>
|
<p>Since the terminal temperatures never exceed the setpoints, there's no apparent potential for disaster. Whether it's due to missing readings or to some sequencing of power (current) applied to the bed vs. the hotend, it really doesn't matter. </p>
<p>If you have a similar graph of the temperatures over an hour of printing and you see signifcant anomalies there, that might be of interest. </p>
|
<p>It looks like everything is ok with the real temperature, and it is just Octoprint missing some readings, like Oscar said.
But I think it is unlikely the USB cables fault, the whole print would fail in that case. I think the PI is to busy, maybe due to a Webcam streaming at high rate (try reducing the framerate). Another reason might be if you use a PI Zero W, especially if you transfer data over the Wifi at the same time, since Wifi and USB cause bottlenecks for each other on that board.</p>
<p>PS. I'd comment, but don't have privilege yet.</p>
| 1,278
|
<p>I am currently working on a project and my goal is to locate text in an image. OCR'ing the text is not my intention as of yet. I want to basically obtain the bounds of text within an image. I am using the AForge.Net imaging component for manipulation. Any assistance in some sense or another?</p>
<p>Update 2/5/09:
I've since went along another route in my project. However I did attempt to obtain text using MODI (Microsoft Office Document Imaging). It allows you to OCR an image and pull text from it with some ease.</p>
|
<p>This is an active area of research. There are literally oodles of academic papers on the subject. It's going to be difficult to give you assistance especially w/o more deatails. Are you looking for specific types of text? Fonts? English-only? Are you familiar with the academic literature? </p>
<p>"Text detection" is a standard problem in any OCR (optical character recognition) system and consequently there are lots of bits of code on the interwebs that deal with it. </p>
<p>I could start listing piles of links from google but I suggest you just do a search for "text detection" and start reading :). There is ample example code available as well.</p>
|
<p>If you're ok with using an online API for this, the API at <a href="http://www.wisetrend.com/wisetrend_ocr_cloud.shtml" rel="nofollow noreferrer">http://www.wisetrend.com/wisetrend_ocr_cloud.shtml</a> can do text detection in addition to just OCR.</p>
| 2,411
|
<p>I have plsql procedure which accepts certain parameters e.g. v_name, v_country, v_type.</p>
<p>I wish to have a cursor with a select statement like this:</p>
<pre><code>select column from table1 t1, table2 t2
where t1.name = v_name
and t1.country = v_country
and t1.id = t2.id
and t2.type = v_type
</code></pre>
<p>If certain parameters are empty can I only add the relevant where clauses to the cursor? Or is there a better way to accomplish this?</p>
|
<p>The best way to use this is with DBMS_SQL.</p>
<p>You create a string that represents your SQL statement. You still use bind variables. It's painful.</p>
<p>It goes something like this (I haven't compiled this, but it should be close) :-</p>
<pre><code>CREATE OR REPLACE FUNCTION find_country( v_name t1.country%TYPE,
v_type t2.type%TYPE) /* Hmm, column called type? */
DECLARE
v_SQL varchar2(2000);
v_select INTEGER; /* "Pointer" to a DBMS_SQL select statement */
v_execute INTEGER;
BEGIN
v_SQL := 'select column from table1 t1, table2 t2 ||
'where t1.id = t2.id';
IF v_name IS NOT NULL THEN
v_SQL := v_SQL || ' AND t1.country = :v_name'
END IF;
IF v_type IS NOT NULL THEN
v_SQL := v_SQL || ' AND t2.type = :v_type';
END IF;
/* Setup Cursor */
v_select := dbms_sql.open_cursor;
dbms_sql.parse( v_select, v_SQL, DBMS_SQL.native);
IF v_name IS NOT NULL THEN
dbms_sql.bind_variable( v_select, ':v_name', v_name );
END IF;
IF v_type IS NOT NULL THEN
dbms_sql.bind_variable( v_select, ':v_type', v_type );
END IF;
DBMS_SQL.DEFINE_COLUMN(v_select, 1, v_column); /* This is what we have selected */
/* Return value from EXECUTE is undefined for a SELECT */
v_execute := DBMS_SQL.EXECUTE( v_select );
IF DBMS_SQL.FETCH_ROWS( v_select ) > 0 THEN
/* A row was found
DBMS_SQL.COLUMN_VALUE( v_select, 1, v_column);
/* Tidy Up */
DBMS_SQL.CLOSE_CURSOR(v_select);
RETURN v_ID_address;
ELSE
DBMS_SQL.CLOSE_CURSOR(v_select);
/* No row */
RETURN NULL;
END IF;
EXCEPTION
WHEN OTHERS THEN
IF DBMS_SQL.IS_open(v_select) THEN
DBMS_SQL.CLOSE_CURSOR(v_select);
END IF;
RAISE;
END;
</code></pre>
<p>This approach is so painful compared to just writing the SQL inline that unless you have heaps of columns sometimes it's just easier writing a couple of different versions using this syntax:</p>
<pre><code>FOR r IN (SELECT blah FROM blah WHERE t1 = v_t1) LOOP
func( r.blah );
END LOOP;
</code></pre>
|
<p>One way would be to build up your query as a string then use <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/executeimmediate_statement.htm" rel="nofollow noreferrer">execute immediate</a></p>
| 49,428
|
<p>I've read <a href="https://stackoverflow.com/questions/41354/is-the-stackoverflow-login-situation-bearable">https://stackoverflow.com/questions/41354/is-the-stackoverflow-login-situation-bearable</a> and must agree to a certain point that openid (for me) makes it more difficult to log in. Not a show stoper but I'm used to opening the front page of the site, there's a small login form, firefox' password manager already filled in the correct values, submit, done. One click.
Here - and it's currently the only site with openid I use - the password/form manager doesn't even fill in my "login id". I often close all browser windows and all cookies are erased - and I would like to keep it this way.</p>
<p>Are there any firefox plugins you would recommend that make the login process easier? Maybe something that checks my status at myOpenId and performs the login if necessary.</p>
<p>Edit:
Unfortunately RichQ is right and I can't use Seatbelt. And Sxipper ...not quite what I had in mind ;) Anyway, both solutions would take away some of the "pain", so upvotes for both of you.</p>
<p>I've also tried the ssl certificate. But that only adds more steps. Hopefully I did something wrong and some of those steps can be eliminated:</p>
<ul>
<li>Click "login" at stackoverflow
<li>Click on the "select provider" Button.
<li>Click on MyOpenId
<li>Enter Username
<li>Click "Login" (Sxipper could reduce the previous 4 steps to a single mouseclick)
<li>MyOpenId login page is loaded
<li>Click "Sign in with an SSL certificate"
<li>Choose Certificate (grrr)
<li>Click "Login" (GRRR)
<li>Back to stackoverflow, finally.
</ul>
<p>What I really would like is:
<ul>
<li>Click "login" at stackoverflow
<li>My (only) LoginId is filled in
<li>Click "Login"
<li>If necessary the certificate is chosen automagically, ssl login performed
<li>Back to stackoverflow without any further user interaction.
</ul>That would be more or less what I'm used to - and I'm a creature of habit :)</p>
|
<p>VeriSign (ick)'s SeatBelt plugin: <a href="https://pip.verisignlabs.com/seatbelt.do" rel="noreferrer">https://pip.verisignlabs.com/seatbelt.do</a></p>
<p>Ideally, the plugin would allow a higher-level of authentication. I know something like this was planned for the OLPC.</p>
|
<p>You could try <a href="http://www.sxipper.com" rel="nofollow noreferrer">Sxipper</a>. It provides intelligent automatic form-fill, including auto-login. </p>
<p>From the Sxipper FAQ:</p>
<blockquote>
<p><em>How does Sxipper support OpenID?</em><br>
Sxipper remembers your OpenIDs and presents an overlay. You choose the one you want to use and login with one click. Sxipper also helps protect you against phishing.</p>
</blockquote>
| 7,077
|
<p>Saw this question here : <a href="http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx" rel="noreferrer">What Great .NET Developers Ought To Know (More .NET Interview Questions)</a></p>
|
<p>It will show processes that have loaded modules (usaully .DLL files) hosting the .NET runtime. The same technique can be used to search for other DLLs that have been loaded.</p>
<p>On a related note, <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">Process Explorer</a> is a Microsoft task manager replacement that will show .NET processes highlighted. I cannot recommend it enough. It is well worth investigating along with the rest of the <a href="http://technet.microsoft.com/en-us/sysinternals/0e18b180-9b7a-4c49-8120-c47c5a693683.aspx" rel="noreferrer">Sysinternals Suite</a>.</p>
|
<p>It would seem to list all processes using modules like mscoree.dll, mscorwks.dll, etc. This would be .NET processes and possibly processes hosting .NET plug-ins.</p>
| 18,402
|
<p>We are developing large ASP.NET applications with lot of dynmically created pages containing ASCX controls. We use a lot of jQuery everywhere.</p>
<p>I have been reading that it would make sense to move the inline JavaScript code to the bottom of the page as it could delay the loading of the page when it's included "too early".</p>
<p>My question is now: <strong>Does this still make sense when working with jQuery?</strong> </p>
<p>Most of the code is executed in the ready handler, so I would expect that is does not slow down the loading of the page.
In my case the multiple Usercontrols <strong>ASCX have all their own jQuery</strong> bits and pieces, and it would not be easy to move that all down in the rendered page.</p>
|
<p>You could model the different ways of ordering the JavaScript in <a href="http://stevesouders.com/cuzillion/" rel="noreferrer">Cuzillion</a> to see how it affects page loading.</p>
<p>See the <a href="http://stevesouders.com/cuzillion/help.php#examples" rel="noreferrer">examples</a> and <a href="http://www.stevesouders.com/blog/2008/04/25/cuzillion/" rel="noreferrer">this blog post</a> for examples of how ordering of page elements can affect speed.</p>
|
<p>Most of the time, the reason to move your JavaScript to the bottom of the page is to ensure that any DOM elements the JavaScript might reference have been created before the JavaScript is run. This also ensures that the page has time to render before running any JavaScript.</p>
<p>In this case, I wouldn't worry about moving the JavaScript down lower on the page.</p>
| 40,689
|
<p>We have a customer that is trying to call our web service written in C# from PHP code. The web service call takes a long as parameter.</p>
<p>This call works fine for other customers calling from C# or Java but this customer is getting an error back from the call. I haven't debugged their specific call but I am guessing that the 64bit integer is getting truncated somehow from PHP. The customer says they are just making the web service call with a string but is there a wrapper in PHP that does type conversion. Could this be losing the number information?</p>
<p>Thanks for any info.</p>
|
<p>Most PHP installations won't support 64 bit integers - 32 is the max. You can check this by reading the PHP_INT_SIZE constant (4 = 32bit, 8 = 64bit) or read the PHP_INT_MAX value.</p>
<pre><code><?php
echo PHP_INT_SIZE, "\n", PHP_INT_MAX;
?>
</code></pre>
<p>If the web service class he is using is trying to type-convert a string representation of a 64 bit integer, then yes, it's mostly likely being truncated or converted into a float. You can sort of see this behavior with this simple test</p>
<pre><code><?php
echo intval( "12345678901234567890" );
// prints 2147483647, the max value for a 32 bit signed int.
</code></pre>
<p>Without knowing the details of his implementation, it's difficult to postulate on what a good solution/workaround might be.</p>
|
<p>If you absolutely must take a big number like that, make it a string, and convert it to long in your web service. </p>
<p>This will bother your other users a little bit, but would make it more friendly to your PHP-using costumers.</p>
| 24,766
|
<p>I need to do a LINQ2DataSet query that does a join on more than one field (as</p>
<pre><code>var result = from x in entity
join y in entity2
on x.field1 = y.field1
and
x.field2 = y.field2
</code></pre>
<p>I have yet found a suitable solution (I can add the extra constraints to a where clause, but this is far from a suitable solution, or use <a href="https://stackoverflow.com/questions/345427/linq-to-sql-join-multiple-columns-from-the-same-table">this</a> solution, but that assumes an equijoin).</p>
<p>Is it possible in LINQ to join on multiple fields in a single join?</p>
<p><strong>EDIT</strong></p>
<pre><code>var result = from x in entity
join y in entity2
on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
</code></pre>
<p>is the solution I referenced as assuming an equijoin above.</p>
<p>Further <strong>EDIT</strong></p>
<p>To answer criticism that my original example was an equijoin, I do acknowledge that, My current requirement is for an equijoin and I have already employed the solution I referenced above.</p>
<p>I am, however, trying to understand what possibilities and best practices I have / should employ with LINQ. I am going to need to do a Date range query join with a table ID soon, and was just pre-empting that issue, It looks like I shall have to add the date range in the where clause.</p>
<p>Thanks, as always, for all suggestions and comments given</p>
|
<p>The solution with the anonymous type should work fine. LINQ <em>can</em> only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.</p>
<p>If you don't like the version with the anonymous type for some specific reason, you should explain that reason.</p>
<p>If you want to do something other than what you originally asked for, please give an example of what you <em>really</em> want to do.</p>
<p>EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.</p>
<p>Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something <em>similar</em> - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a <code>where</code> clause (after a second <code>from</code> clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.</p>
|
<pre><code>from d in db.CourseDispatches
join du in db.DispatchUsers on d.id equals du.dispatch_id
join u in db.Users on du.user_id equals u.id
join fr in db.Forumreports on (d.course_id + '_' + du.user_id) equals (fr.course_id + '_'+ fr.uid)
</code></pre>
<p>this works for me</p>
| 48,853
|
<p>I need to setup a blog using wordpress engine but i need it support multi languages (3 languages), currently i am thinking of using custom field to identify the language of current post though i knew thats not a best practices, does anyone has better suggestions?</p>
|
<p>I've tested 2 plugins that both looked very promising: <a href="http://wordpress.org/extend/plugins/qtranslate/" rel="nofollow noreferrer">qTranslate</a> and <a href="http://wordpress.org/extend/plugins/gengo/" rel="nofollow noreferrer">Gengo</a></p>
<p>qTranslate works by adding inputs for all used languages for each post, Gengo used separate posts and links them in a "post Y is a translation of post X" way, which I preferred much (because it allowed me to not translate everything) and it worked fine for me.</p>
|
<p>I have used the xlanguage plugin and I am happy with it.
<a href="http://hellosam.net/project/xlanguage" rel="nofollow noreferrer">xlanguage site</a></p>
| 20,746
|
<p>What is the advantage of doing a logical/soft delete of a record (i.e. setting a flag stating that the record is deleted) as opposed to actually or physically deleting the record?</p>
<p>Is this common practice?</p>
<p>Is this secure?</p>
|
<p>Advantages are that you keep the history (good for auditing) and you don't have to worry about cascading a delete through various other tables in the database that reference the row you are deleting. Disadvantage is that you have to code any reporting/display methods to take the flag into account.</p>
<p>As far as if it is a common practice - I would say yes, but as with anything whether you use it depends on your business needs.</p>
<p>EDIT: Thought of another disadvantange - If you have unique indexes on the table, deleted records will still take up the "one" record, so you have to code around that possibility too (for example, a User table that has a unique index on username; A deleted record would still block the deleted users username for new records. Working around this you could tack on a GUID to the deleted username column, but it's a very hacky workaround that I wouldn't recommend. Probably in that circumstance it would be better to just have a rule that once a username is used, it can never be replaced.)</p>
|
<p>Soft Delete is a programming practice that being followed in most of the application when data is more relevant. Consider a case of financial application where a delete by the mistake of the end user can be fatal.
That is the case when soft delete becomes relevant. In soft delete the user is not actually deleting the data from the record instead its being flagged as IsDeleted to true (By normal convention).</p>
<p>In EF 6.x or EF 7 onward Softdelete is Added as an attribute but we have to create a custom attribute for the time being now.</p>
<p><strong>I strongly recommend SoftDelete In a database design and its a good convention for the programming practice.</strong></p>
| 49,550
|
<p>I'm wondering what's a reasonable size for iPhone Apps. Right now I'm working on an iPhone game, and of course it loads fast into my device since I'm connected directly to it through a USB cable, but I've no idea how long it would actually take to download from the App Store.</p>
<p>In my case it's about 2mb in size, which is reasonable for a desktop or even a flash game, but I've no idea if this is reasonable size for the iPhone.</p>
<p>My other concern is what's the non-wifi download limit of the App Store? Occasionally there are Apps that won't download unless you've got a wifi connection. And personally I've never downloaded such apps, since it gives me a bad impression. So I'd definitely want to stay below that limit.</p>
<p>Also since I'm already asking about app sizes, it would be probably be useful to collect good sizes for other types of apps as well.</p>
<p>Thanks!</p>
|
<p>Looking through some of the games i have on my phone they weigh in around 7 or 8 mb a pop. I think your 2mb will be fine.</p>
<p>One thing i can tell you for sure is that if you want to be distributable over the cell network your application has to be under 50 mb. If you exceed this it will have to be downloaded using wifi or itunes on a computer. </p>
|
<p>I would try and keep it as small as possible. The app-store could probably support, say, a 100MB application, but it wont be nice to install for users.</p>
<p>The problem is installing via the phone - all you get is a simple progress bar, and most people have their phone auto-lock after 1 minute.. So, ideally the app would download in under a minute on an average connection..</p>
| 20,513
|
<p>I wonder how many of you have implemented one of computer science's "<strong><a href="http://www.cs.virginia.edu/~luebke/cs332/" rel="nofollow noreferrer">classical algorithms</a></strong>" like <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="nofollow noreferrer">Dijkstra's algorithm</a> or <strong>data structures</strong> (e.g. binary search trees) in a <strong>real world</strong>, not academic project?</p>
<p>Is there a benefit to our dayjobs in knowing these algorithms and data structures when there are tons of libraries, frameworks and APIs which give you the same functionality?</p>
|
<blockquote>
<p>Is there a benefit to our dayjobs in knowing these algorithms and data structures when there are tons of libraries, frameworks and APIs which give you the same functionality?</p>
</blockquote>
<p>The library doesn't know what your problem domain is and won't be able to chose the correct algorithm to do the job. That is why I think it is important to know about them: then YOU can make the correct choice of algorithms to solve YOUR problem.</p>
|
<p>Classical algorithms are usually associated with something glamorous, like games, or Web search, or scientific computation. However, I had to use some of the classical algorithms for a mere enterprise application. </p>
<p>I was building a metadata migration tool, and I had to use topological sort for dependency resolution, various forms of graph traversals for queries on metadata, and a modified variation of Tarjan's union-find datastructure to partition forest-like structured metadata to trees.</p>
<p>That was a really satisfying experience. Most of those algorithms were implemented before, but their implementations lacked something that I would need for my task. That's why It's important to understand their internals. </p>
| 42,603
|
<p>Suppose you have two seperate ASP.NET Web Application projects that both need to use a common MasterPage.</p>
<p>What's the best way to share the MasterPage across projects without having to duplicate code? Preferably without having to resort to source control or file system hacks.</p>
|
<p>I have trying to accomplish the same thing. I look into a couple of solutions but I think using a virtual directory is probably the best way to share master pages. </p>
<p>Here are a couple sources that you can look at. </p>
<ul>
<li><a href="https://blogs.msdn.microsoft.com/shahpiyush/2007/03/09/sharing-master-pages-amongst-applications-by-embedding-it-in-a-dll/" rel="nofollow noreferrer">Sharing Master Pages amongst
Applications by Embedding it in a
Dll</a></li>
<li><a href="https://msdn.microsoft.com/en-us/library/aa992039.aspx" rel="nofollow noreferrer">Sharing Master Pages in Visual Studio</a></li>
<li><a href="http://www.odetocode.com/articles/450.aspx" rel="nofollow noreferrer">ASP.Net 2.0 - Master Pages: Tips, Tricks, and Traps </a></li>
</ul>
<p>The third bullets near the end the article tells you of possible ways you can share Masterpages also.</p>
|
<p>Use <a href="http://msdn.microsoft.com/en-us/library/aa365680%28VS.85%29.aspx" rel="nofollow noreferrer">a symbolic link</a>:</p>
<blockquote>
<p>A symbolic link is a file-system object that points to another file
system object. The object being pointed to is called the target.
Symbolic links are transparent to users; the links appear as normal
files or directories, and can be acted upon by the user or application
in exactly the same manner.</p>
</blockquote>
| 5,075
|
<p>I have a .Net 1.1 web application sitting in a folder called C:\inetpub\wwwroot\MyTestApp, where 'MyTestApp' is a virtual directory and is configured to be on ASP.Net version 1.1.4322 in IIS 5.1.</p>
<p>In the root directory (C:\inetpub\wwwroot) there is a web.config file for a .Net2.0 application, because the root folder contains some web pages written in .Net2.0.</p>
<p>Whenever I try to access 'MyTestApp' though I get an error...</p>
<pre><code>Parser Error Message: Unrecognized configuration section 'connectionStrings'
Source File: c:\inetpub\wwwroot\web.config Line: 17
</code></pre>
<p>The .Net1.1 application in the MyTestApp folder is trying to access the web.config file in the root folder, and getting upset because it is on a different version. How can I tell the MyTestApp folder NOT to use the web.config file in the root folder, but instead just use the web.config in its own folder?</p>
<p>Is such a thing possible, or is nesting a .Net 1.1 application in a sub-folder under a .Net 2.0 application a no-no?</p>
|
<p>I think you need to configure your virtual directory for your 1.1 app as a "application" directory.</p>
<p>I am on IIS7, so I am providing this from memory!</p>
<p>If you right click it in IIS, and then click "<strong>Create Application</strong>" that should do the trick.</p>
<p><code>Web.config</code> is always read based on proximity (closest to application first, up through folder structure, right up to <code>Machine.config</code>).</p>
<p>Hope this helps.</p>
<h3>Edit</h3>
<p>Checkout the <a href="http://support.microsoft.com/kb/172138" rel="nofollow noreferrer">guide on MSDN</a> on creating Virtual Directories. It also touches on creating Applications.</p>
|
<p>You want to use the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.inheritinchildapplications(VS.80).aspx" rel="nofollow noreferrer">InheritInChildApplications</a> setting in the root web.config and set this to false.</p>
| 39,745
|
<p>I had this question in mind and since I just discovered this site I decided to post it here.</p>
<p>Let's say I have a table with a timestamp and a state for a given "object" (generic meaning, not OOP object); is there an optimal way to calculate the time between a state and the next occurrence of another (or same) state (what I call a "trip") with a single SQL statement (inner SELECTs and UNIONs aren't counted)?</p>
<p>Ex: For the following, the trip time between Initial and Done would be 6 days, but between Initial and Review it would be 2 days. </p>
<blockquote>
<p>2008-08-01 13:30:00 - Initial<br>
2008-08-02 13:30:00 - Work<br>
2008-08-03 13:30:00 - Review<br>
2008-08-04 13:30:00 - Work<br>
2008-08-05 13:30:00 - Review<br>
2008-08-06 13:30:00 - Accepted<br>
2008-08-07 13:30:00 - Done</p>
</blockquote>
<p>No need to be generic, just say what <a href="https://stackoverflow.com/questions/980813/what-is-sgbd">SGBD</a> your solution is specific to if not generic.</p>
|
<p>Here's an Oracle methodology using an analytic function.</p>
<pre><code>with data as (
SELECT 1 trip_id, to_date('20080801 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Initial' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080802 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080803 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080804 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Work' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080805 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Review' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080806 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Accepted' step from dual UNION ALL
SELECT 1 trip_id, to_date('20080807 13:30:00','YYYYMMDD HH24:mi:ss') dt, 'Done' step from dual )
select trip_id,
step,
dt - lag(dt) over (partition by trip_id order by dt) trip_time
from data
/
1 Initial
1 Work 1
1 Review 1
1 Work 1
1 Review 1
1 Accepted 1
1 Done 1
</code></pre>
<p>These are very commonly used in situations where traditionally we might use a self-join.</p>
|
<p>I don't think you can get that answer with one SQL statement as you are trying to obtain one result from many records. The only way to achieve that in SQL is to get the timestamp field for two different records and calculate the difference (datediff). Therefore, UNIONS or Inner Joins are needed.</p>
| 10,872
|
<p><a href="http://dl.getdropbox.com/u/240752/stars.gif" rel="nofollow noreferrer">My screenshot http://dl.getdropbox.com/u/240752/stars.gif</a></p>
<p>I want to have it so that only the text is underlined. The only way I can see of doing this is this:</p>
<pre><code>.no-underline {
text-decoration:none;
}
.underline {
text-decoration:underline;
}
<a href="#" class="no-underline"><span class="underline">Average customer review rating</span><img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /></a>
</code></pre>
<p>Is this the best way? or does someone know a leaner way? Thanks.</p>
|
<p>No other solution really. Though you can shorten it a little:</p>
<pre><code><a href="#" class="imgLink"><span>Link Text</span> <img src="..."></a>
a.imgLink { text-decoration: none; }
a.imgLink span { text-decoration: underline; }
</code></pre>
<p>That way you only need to specify one class.</p>
|
<p>In which browser do you have a problem with this? Most browsers do not apply text-decoration to images since it makes no sence.</p>
<p>othersize, just do like this:</p>
<p><code><a class="imgLink" href="">some text<img src="" /></a></code></p>
<pre>
.imgLink {
text-decoration: underline;
}
.imgLink img {
text-decoration: none;
}
</pre>
| 34,175
|
<p>I'm aware that in Vim I can often repeat a command by simply adding a number in front of it. For example, one can delete 5 lines by:</p>
<pre><code>5dd
</code></pre>
<p>It's also often possible to specify a range of lines to apply a command to, for example</p>
<pre><code>:10,20s:hello:goodbye:gc
</code></pre>
<p>How can I perform a 'vertical edit'? I'd like to, for example, insert a particular symbol, say a comma, at the beggining (skipping whitespace, i.e. what you'd get if you type a comma after Shift-I in command mode) of every line in a given range. How can this be achieved (without resorting to down-period-down-period-down-period)?</p>
|
<p><code>:10,20s/^/,/</code></p>
<p>Or use a macro, record with:</p>
<p><code>q a i , ESC j h q</code></p>
<p>use with:</p>
<p><code>@ a</code></p>
<p>Explanation: <code>q a</code> starts recording a macro to register <code>a</code>, <code>q</code> ends recording. There are registers <code>a</code> to <code>z</code> available for this.</p>
|
<p>Apart from the macros, as already answered, for the specific case of inserting a comma in a range of lines (say from line 10 to 20), you might do something like: </p>
<pre><code>:10,20s/\(.*\)/,\1
</code></pre>
<p>That is, you can create a numbered group match with \( and \), and use \1 in the replacement string to say "replace with the contents of the match".</p>
| 46,395
|
<p>I am in charge of a website at work and recently I have added ajaxy requests to make it faster and more responsive. But it has raised an issue.</p>
<p>On my pages, there is an index table on the left, like a menu. Once you have clicked on it, it makes a request that fills the rest of the page. At anytime you can click on another item of the index to load a different page.</p>
<p>Before adding javascript, it was possible to middle click (open new tabs) for each item of the index, which allowed to have other pages loading while I was dealing with one of them.
But since I have changed all the links to be ajax requests, they now execute some javascript instead of being real links. So they are only opening empty tabs when I middle click on them.</p>
<p>Is there a way to combine both functionalities: links firing javascript when left clicked or new tabs when middle clicked?
Does it have to be some ugly javascript that catches every clicks and deal with them accordingly?</p>
<p>Thanks.</p>
|
<p>Yes. Instead of:</p>
<pre><code><a href="javascript:code">...</a>
</code></pre>
<p>Do this:</p>
<pre><code><a href="/non/ajax/display/page" id="thisLink">...</a>
</code></pre>
<p>And then in your JS, hook the link via it's ID to do the AJAX call. Remember that you need to stop the click event from bubbling up. Most frameworks have an event killer built in that you can call (just look at its Event class).</p>
<p>Here's the event handling and event-killer in jquery:</p>
<pre><code>$("#thisLink").click(function(ev, ob) {
alert("thisLink was clicked");
ev.stopPropagation();
});
</code></pre>
<p>Of course you can be a lot more clever, while juggling things like this but I think it's important to stress that this method is <em>so</em> much cleaner than using <code>onclick</code> attributes.</p>
<h1>Keep your JS in the JS!</h1>
|
<p>Possibly, I could provide two links each time, one firing the javascript and another being a real link that would allow for middle click.
I presume, one of them would have to be an image to avoid overloading the index.</p>
| 18,369
|
<p>Below is my stored procedure. I want use stored procedure select all row of date from tbl_member and insert 2 table. But it's not work. Some one can help me?</p>
<pre><code>Create PROCEDURE sp_test
AS
BEGIN
SET NOCOUNT ON;
Declare @A Varchar(255), @B Varchar(255), @C Varchar(255), @D int
Declare Table_Cursor Cursor
For select A, B, C from tbl_Member Open Table_Cursor
Fetch Next From Table_Cursor
Into @A, @B, @C While(@@Fetch_Status=0)
Begin Exec(
'insert into NewMember (A, B, C, D) values (@A, @B, @C, @D)
set @D = @@IDENTITY
Insert into MemberId (Mid) VALUES(@D)
)
Fetch Next From Table_Cursor Into @A, @B, @C End Close Table_Cursor
Deallocate Table_Cursor
END
GO
</code></pre>
|
<p>The first thing I can see here is that you are using a cursor when you don't need to. You can rewrite the first query as:</p>
<pre><code>INSERT INTO NewMember(A, B, C, D)
SELECT A, B, C, D
FROM tbl_member
</code></pre>
<p>Then, I would have an INSERT trigger against NewMember that inserted the identity column.</p>
<pre><code>create trigger myInsertTrigger
on newmember
for insert
as
insert into memberid(mid)
select <<identity_column>> from inserted
</code></pre>
<p>BTW - it's a bad idea to use @@IDENTITY to get the identity of an insert. Use the SCOPE_IDENTITY function instead.</p>
|
<p>Please pay particular attention to what Pete said about @@identity. The reason it is bad to ever use @@identity is that if a trigger is ever added to the table that inserts to another table with an identity, that is the identity that is returned not the one you just inserted. This can lead to massive data integrity problems that may not be caufght for months. </p>
<p>Even if you kept the cursor (which I do not recommend, cursors are a very bad way to do inserts as they are very slow compared to the set-based solution that Pete gave), your code could not do the insert to the first table if column D is the identity column (which I would guess it is since you later try to assign D to the identity value). That is because you are trying to put a value into a column that cannot accept a value as it is autogenerated. If D is the identity then do not use it inthe insert at all, just define the columns you need to insert into. This would be true of Pete's solution as well, if D is in fact your identity column.</p>
| 48,014
|
<p>All I want is to update an ListViewItem's text whithout seeing any flickering.</p>
<p>This is my code for updating (called several times):</p>
<pre><code>listView.BeginUpdate();
listViewItem.SubItems[0].Text = state.ToString(); // update the state
listViewItem.SubItems[1].Text = progress.ToString(); // update the progress
listView.EndUpdate();
</code></pre>
<p>I've seen some solutions that involve overriding the component's <code>WndProc():</code></p>
<pre><code>protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WM.WM_ERASEBKGND)
{
m.Msg = (int)IntPtr.Zero;
}
base.WndProc(ref m);
}
</code></pre>
<p><strong>They say it solves the problem, but in my case It didn't</strong>. I believe this is because I'm using icons on every item.</p>
|
<p>To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to "Brian Gillespie" for giving the solution.</p>
<pre><code>public enum ListViewExtendedStyles
{
/// <summary>
/// LVS_EX_GRIDLINES
/// </summary>
GridLines = 0x00000001,
/// <summary>
/// LVS_EX_SUBITEMIMAGES
/// </summary>
SubItemImages = 0x00000002,
/// <summary>
/// LVS_EX_CHECKBOXES
/// </summary>
CheckBoxes = 0x00000004,
/// <summary>
/// LVS_EX_TRACKSELECT
/// </summary>
TrackSelect = 0x00000008,
/// <summary>
/// LVS_EX_HEADERDRAGDROP
/// </summary>
HeaderDragDrop = 0x00000010,
/// <summary>
/// LVS_EX_FULLROWSELECT
/// </summary>
FullRowSelect = 0x00000020,
/// <summary>
/// LVS_EX_ONECLICKACTIVATE
/// </summary>
OneClickActivate = 0x00000040,
/// <summary>
/// LVS_EX_TWOCLICKACTIVATE
/// </summary>
TwoClickActivate = 0x00000080,
/// <summary>
/// LVS_EX_FLATSB
/// </summary>
FlatsB = 0x00000100,
/// <summary>
/// LVS_EX_REGIONAL
/// </summary>
Regional = 0x00000200,
/// <summary>
/// LVS_EX_INFOTIP
/// </summary>
InfoTip = 0x00000400,
/// <summary>
/// LVS_EX_UNDERLINEHOT
/// </summary>
UnderlineHot = 0x00000800,
/// <summary>
/// LVS_EX_UNDERLINECOLD
/// </summary>
UnderlineCold = 0x00001000,
/// <summary>
/// LVS_EX_MULTIWORKAREAS
/// </summary>
MultilWorkAreas = 0x00002000,
/// <summary>
/// LVS_EX_LABELTIP
/// </summary>
LabelTip = 0x00004000,
/// <summary>
/// LVS_EX_BORDERSELECT
/// </summary>
BorderSelect = 0x00008000,
/// <summary>
/// LVS_EX_DOUBLEBUFFER
/// </summary>
DoubleBuffer = 0x00010000,
/// <summary>
/// LVS_EX_HIDELABELS
/// </summary>
HideLabels = 0x00020000,
/// <summary>
/// LVS_EX_SINGLEROW
/// </summary>
SingleRow = 0x00040000,
/// <summary>
/// LVS_EX_SNAPTOGRID
/// </summary>
SnapToGrid = 0x00080000,
/// <summary>
/// LVS_EX_SIMPLESELECT
/// </summary>
SimpleSelect = 0x00100000
}
public enum ListViewMessages
{
First = 0x1000,
SetExtendedStyle = (First + 54),
GetExtendedStyle = (First + 55),
}
/// <summary>
/// Contains helper methods to change extended styles on ListView, including enabling double buffering.
/// Based on Giovanni Montrone's article on <see cref="http://www.codeproject.com/KB/list/listviewxp.aspx"/>
/// </summary>
public class ListViewHelper
{
private ListViewHelper()
{
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam);
public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle)
{
ListViewExtendedStyles styles;
styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);
styles |= exStyle;
SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);
}
public static void EnableDoubleBuffer(Control control)
{
ListViewExtendedStyles styles;
// read current style
styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);
// enable double buffer and border select
styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect;
// write new style
SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);
}
public static void DisableDoubleBuffer(Control control)
{
ListViewExtendedStyles styles;
// read current style
styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0);
// disable double buffer and border select
styles -= styles & ListViewExtendedStyles.DoubleBuffer;
styles -= styles & ListViewExtendedStyles.BorderSelect;
// write new style
SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles);
}
}
</code></pre>
|
<p>If you only want to update the text, simply set the changed SubItem's text directly rather than updating the entire ListViewItem (you've not said how you're doing your updates).</p>
<p>The override you show is equivalent to simply overriding OnPaintBackground, which would be a "more correct" managed way to do that task, and it's not going to help for a single item.</p>
<p>If you still have problems, we'll need clarification on what you've actually tried.</p>
| 11,338
|
<p>I'm in the process of building my own head unit / stereo prototype for a car, which will have a 3D-printed enclosure.</p>
<p>My concern is that cars can get quite hot in the sun, and even more so if you live in hot climates. Some estimations put the interior of cars getting up to 50-60 °C, sometimes even in only 20 °C weather due to the 'greenhouse' effect created in the car. I live in a fairly temperate climate, but the summers can still get up to 20-29 °C (80-85 °F), and my car might get up to 60 °C/150 °F on a hot day.</p>
<p>The part won't be exposed <em>directly</em> to the sun, but will obviously be exposed to heat both from the interior of the car when in the sun, and potentially from the engine radiating heat through the firewall, though the latter factor will differ from car to car.</p>
<p>Should I be concerned using PLA for my part? If not, what material, if any, would be better suited for these possible temperatures (other than metal)?</p>
|
<p>No, PLA cannot be used in cars standing in the sun. Temperatures can locally get over 50 °C (122 °F).</p>
<p>I have printed sun visor hinge pins from PLA for a car (not exposed to direct sunlight either), but after one day in the sun (it usually doesn't get over 29 °C or about 85 ˚F here too) the pin deformed (only printed it for form fitting). The actual pin was eventually printed in PETG, and even with PETG the part deformed a little when it got really hot in the car.</p>
<p>Your part might not get that hot as it is lower in the car, but you could best print parts in Nylon (Polyamide, PA), ABS or any other high temperature resistant Co-Polymer (e.g. made from Amphora HT5300), there are lots to choose from nowadays.</p>
<p>If it is a non load bearing component that is not stressed (e.g. a cover or a bushing) it could be printed in PLA, but I would not take a change and would print it directly in a more temperature resistant material.</p>
<hr />
<p>Downloading some of the technical data sheets from various filaments will give you for <a href="https://ultimaker.com/en/resources/49911-pla#technical" rel="nofollow noreferrer">PLA</a>:</p>
<blockquote>
<p><strong>Not suitable for</strong> long term outdoor usage or applications where the
printed part is exposed to temperatures higher than 50 °C (122 °F).</p>
</blockquote>
<p>similar for <a href="https://ultimaker.com/en/resources/49913-nylon#technical" rel="nofollow noreferrer">Nylon</a>:</p>
<blockquote>
<p><strong>Not suitable for</strong> applications where the printed part is exposed to
temperatures higher than 80 °C (176 °F).</p>
</blockquote>
<p>To complete the overview, generally, materials should not be exposed prolonged periods of time above (give or take):</p>
<ul>
<li>70 °C (158 °F) for basic Co-Polymers</li>
<li>85 °C (185 °F) for ABS</li>
<li>100 °C (212 °F) for enhanced Co-Polymers and ASA</li>
<li>105 °C (221 °F) for Polypropylene (PP)</li>
<li>110 °C (230 °F) for Polycarbonate (PC)</li>
</ul>
|
<p>If you put PLA parts in a sealed plastic bag (or two to keep it dry) and simmer in water (212 °F or 100 °C), the part "anneals". The time taken varies with the part shape, but for small parts should be about 15-30 minutes. You can simmer longer if unsure, but it provides no additional benefit once the part is annealed. When you remove and cool the annealed part, it will feel harder and more compact. You may also notice a slight hazing or color change.</p>
<p>Annealed parts become a bit more resistant to heat warp. The annealing process shrinks and hardens your part (I've annealed gears) so you need to account for the shrinkage by making the unannealed part slightly larger. I do this for stepper mounts or gears as needed. Putting your part in the passenger compartment of a car can work depending on your climate. My daughter-in-law has a camera mount on her dashboard showing significant warp, but she still uses it.</p>
<p>Here's <a href="https://rigid.ink/blogs/news/how-to-anneal-your-3d-prints-for-strength" rel="nofollow noreferrer">more information</a> and I'm sure you can find more...</p>
| 925
|
<p>I'm trying to run Selenium RC against my ASP.NET code running on a Cassini webserver.</p>
<p>The web application works when i browse it directly but when running through Selenium I get </p>
<p>HTTP ERROR: 403<br>
Forbidden for Proxy</p>
<hr>
<p>Running Selenium i interactive mode I start a new session with: </p>
<pre>cmd=getNewBrowserSession&1=*iexplore&2=http://localhost:81/
cmd=open&1=http://localhost:81/default.aspx&sessionId=199578
</pre>
<p>I get the above error in the Selenium browser, the command window tells me OK.</p>
<hr>
<p>Any input?</p>
|
<p>I think the problem is that both Selenium and the webserver is running on localhost.<br>
It works if I run with the "iehta" instead of "iexplore".</p>
|
<p>Have you tried running RC with the -proxyInjection flag? </p>
| 14,589
|
<p>I'm having problems with my application receiving low memory warnings while the user is deep within a navigation controller stack of views. After the user browses through a bunch of hierarchical options in subsequent UITableViews, he can open a PDF document in a UIWebView (in a different view controller).</p>
<p>Everything works fine, the PDF loads and the user can flip through the pages. However, when the document is a bit large, or has several pages, and the user taps on the "Back" button in the navigation controller, he app crashes as the previous view controller in the navigation controller stack has been deallocated.</p>
<p>After searching around for ways to deal with low memory warnings, and dealing with this type of problem, I found several posts that just advise people to release the objects that can be released, and then lazy-load them later on when the user tries to load a view that has been deallocated. One of these posts is Craig Hockenberry's <a href="http://furbo.org/2008/08/27/dealing-with-memory-loss-the-cleanup/" rel="nofollow noreferrer">Dealing with memory loss: the cleanup</a> post.</p>
<p>While that's a bit helpful, it doesn't give me much information to work from.</p>
<p>Can someone provide a simple guide on how to deal with low memory warnings, and how to implement "lazy loading" of objects?</p>
|
<p>When memory is low, the system sends out a series of memory-related messages. Any instantiated view controllers will get the -didReceiveMemoryWarning message. If you don't implement this, the default action (assuming the view controller is not front-most) is to release the controller's view member. If you've got hooks into it, or perhaps into its subviews, that could cause issues when your controller gets returned to the top of the stack. </p>
|
<p>Your first task is to figure out what <em>exactly</em> is causing the problem. Which object is being deallocated? Usually, fixing this is simply a matter of making sure the object is retained properly. </p>
<p>I suggest you use NSZombiesEnabled to try and track down the object you're having trouble with. Once you have that, you can make sure you're retaining it properly.</p>
| 42,943
|
<p>Are there any methods/systems that you have in place to incentivize your development team members to write "good" code and add comments to their code? I recognize that "good" is a subjective term and it relates to an earlier question about <a href="https://stackoverflow.com/questions/127360/is-there-a-rating-system-for-the-maintainability-of-source-code">measuring the maintainability of code</a> as one measurement of good code.</p>
|
<p>While most people respond that code reviews are a good way to ensure high quality code, and rightfully so, they don't seem to me to be a direct incentive to getting there. However, coming up with a positive incentive for good code is difficult because the concept of good code has large areas that fall in the realm of opinion and almost any system can be gamed.</p>
<p>At all the jobs I have had, the good developers were intrinsically motivated to write good code. Chicken and egg, feedback, catch 22, call it what you will, the best way to get good code is to hire motivated developers. Creating an environment where good developers want to work is probably the best incentive I can think of. I'm not sure which is harder, creating the environment or finding the developers. Neither is easy, but both are worth it in the long term.</p>
<p>I have found that one part of creating an environment where good developers want to work includes ensuring situations where developers talk about code. I don't know a skilled programmer that doesn't appreciate a good critique of his code. This helps the people that like to be the best get better. As a smaller sub-part of this endeavor, and thus an indirect incentive to create good code, I think code reviews work wonderfully. And yes, your code quality should gain some direct benefit as well.</p>
<p>Another technique co-workers and I have used to communicate good coding habits is a group review in code. It was less formal and allowed people to show off new techniques, tools, features. Critiques were made, kudos were given publicly, and most developers didn't seem to mind speaking in front of a small developer group where they knew everyone. If management cannot see the benefit in this, spring for sammiches and call it a brown bag. Devs will like free food too.</p>
<p>We also made an effort to get people to go to code events. Granted, depending on how familiar you all are with the topic, you might not learn too much, but it keeps people thinking about code for a while and gets people talking in an even more relaxed environment. Most devs will also show up if you offer to pick up a round or two of drinks afterwards.</p>
<p>Wait a second, I noticed another theme. Free food! Seriously though, the point is to create an environment where people that already write good code and those that are eager to learn want to work.</p>
|
<p>Hm.</p>
<p>Maybe the development team should do code-reviews of each other codes. That could motivate them to write better, commented code. </p>
| 15,649
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/bb384061.aspx" rel="noreferrer">var</a> keyword does away with the need for an explicit type declaration and I have read with interest the <a href="https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c">SO discussion</a> of when it might be appropriate.</p>
<p>I have also read about (but not used) <a href="https://github.com/boo-lang/boo" rel="noreferrer">Boo</a> which seems to take things a step further by making it <a href="https://github.com/boo-lang/boo/wiki/Type-Inference" rel="noreferrer">optional to declare a local variable</a>. With Boo, both the type and the declaration can be implied.</p>
<p>Which leads me to wonder, why did the C# language designers bother to include a var keyword at all? </p>
<p><strong>Update</strong>: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...</p>
<pre><code>var anon = new { Name = "Terry", Age = 34 };
</code></pre>
<p>versus</p>
<pre><code>anon = new { Name = "Terry", Age = 34 };
</code></pre>
|
<p><strong>Update:</strong> There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?</p>
<p>The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:</p>
<p>As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:</p>
<pre><code>SomeGeneric<VeryLongTypename<NestedTypename>> thing = new
SomeGeneric<VeryLongTypename<NestedTypename>>();
</code></pre>
<p>Verbose and error-prone, right? So now they let you do this:</p>
<pre><code>var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();
</code></pre>
<p>By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.</p>
|
<p>For anonymous types, which amongst other things support LINQ.</p>
<p><a href="http://www.blackwasp.co.uk/CSharpAnonTypes.aspx" rel="nofollow noreferrer">http://www.blackwasp.co.uk/CSharpAnonTypes.aspx</a></p>
| 25,669
|
<p>My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.</p>
<p>I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:</p>
<pre><code>from ctypes import cast, CFUNCTYPE, c_char_p, c_long
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long))
print fptr(1234)
</code></pre>
<p>Now, why does this script keeps doing segmentation fault whenever I run it?</p>
<p>I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text</p>
<p>But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?</p>
|
<p>As <a href="https://stackoverflow.com/questions/275207/python-ctypes-and-function-calls#275333">vincent</a> mentioned, this is due to the allocated page being marked as non executable. Newer processors support this <a href="http://en.wikipedia.org/wiki/NX_bit" rel="nofollow noreferrer">functionality</a>, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.</p>
<p>To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:</p>
<pre><code>libc = CDLL('libc.so')
# Some constants
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4
def executable_code(buffer):
"""Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.
The pointer should be freed with libc.free() when finished"""
buf = c_char_p(buffer)
size = len(buffer)
# Need to align to a page boundary, so use valloc
addr = libc.valloc(size)
addr = c_void_p(addr)
if 0 == addr:
raise Exception("Failed to allocate memory")
memmove(addr, buf, size)
if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):
raise Exception("Failed to set protection on buffer")
return addr
code_ptr = executable_code(buffer)
fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))
print fptr(1234)
libc.free(code_ptr)
</code></pre>
<p>Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. </p>
<p>Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).</p>
|
<p>Does python even allow such usage? I should learn it then...</p>
<p>I think the interpreter doesn't expect any register to be changed. Try saving the registers that you use inside the function if you plan to use your assembler output like this.</p>
<p>Btw, call convention of x86_64 is different than regular x86. You may have trouble if you lose stack pointer alignment and mix external objects generated with other tools.</p>
| 34,685
|
<p>Which techniqes would you use to implement a search for contents in a column on a very big table in MySql? Say for instance that you have 10.000.000 emails stored in a table in the database and would like to implement a subject search, that would enable me to search for one or more words that was present in the email subject. If the user searched for "christmas santa" you should find a emails with subjects like "Santa visits us this christmas" and "christmas, will santa ever show".</p>
<p>My idea is to process all the words in the subjects (strip all numbers, special signs, commas etc) and save each word in an index table, where I have a unique index on the word column. Then I would link that to the email table by a many to many relationship table.</p>
<p>Is there a better way to perform wildcard searches on very big tables ?</p>
<p>Is there databases that natively supports this kind of searches ?</p>
|
<p>You could use FULLTEXT indexes if you are using MyISAM as the storage engine. However, MySQL in general is not very good with text search.</p>
<p>A much better option would be to go with a dedicated text indexing solution such as <a href="http://lucene.apache.org/java/docs/" rel="noreferrer">Lucene</a> or <a href="http://www.sphinxsearch.com/" rel="noreferrer">Sphinx</a>. Personally I'd recommend Sphinx - it has great integration with PHP and MySQL and is very, very fast (can be used to speed up even ordinary queries - performs very fast grouping and ordering).</p>
<p>Wikipedia has a nice list of different indexing engines - <a href="http://en.wikipedia.org/wiki/Free_text_search#Text_retrieval_software" rel="noreferrer">here</a>.</p>
|
<p>This sounds like a a full text search, which SQL Server supports.</p>
<p>But your idea is generally sound. You're effectively computing an "index" on your table in advance to speed up searches.</p>
| 48,772
|
<p>What's the general consensus?</p>
<p>If you need to change the database after a given action, do you use an observer pattern and let the framework / application handle the update for you? Or do you bypass the application and delegate the update to a database trigger?</p>
<p>Obviously the trigger is faster, but is it worth it?</p>
|
<p>I use triggers, but triggers are typically database-specific. If you plan on supporting multiple database servers, certainly find a way to cover it in code. If you're sure you'll be using a specific DB server, then your data-integrity will love you for your triggers.</p>
|
<p>As we use LINQ2SQL this task is quite easy to be acoomplished overriding the SubmitChanges() method. Our main goal is to do auditing in our tables. The code would like this:</p>
<pre><code> /// <summary>
/// Sends changes that were made to retrieved objects to the underlying database,
/// and specifies the action to be taken if the submission fails.
/// NOTE: Handling this event to easily perform Audit tasks whenever a table gets updated.
/// </summary>
/// <param name="failureMode">The action to be taken if the submission fails.
/// Valid arguments are as follows:<see cref="F:System.Data.Linq.ConflictMode.FailOnFirstConflict"/>
/// <see cref="F:System.Data.Linq.ConflictMode.ContinueOnConflict"/></param>
public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
//Updates
for (int changeCounter = 0; changeCounter < this.GetChangeSet().Updates.Count; changeCounter++)
{
object modifiedEntity = this.GetChangeSet().Updates[changeCounter];
SetAuditStamp(this, modifiedEntity, ChangeType.Update);
}
//Inserts
for (int changeCounter = 0; changeCounter < this.GetChangeSet().Inserts.Count; changeCounter++)
{
object modifiedEntity = this.GetChangeSet().Inserts[changeCounter];
SetAuditStamp(this, modifiedEntity, ChangeType.Insert);
}
base.SubmitChanges(failureMode);
</code></pre>
<p>We particulary don't like using triggers as they are always hidden into you DB and it makes hard to work out problems that may occur ... with having that into your code you just need to start debugging it to find out why something has failed for instance ...</p>
| 39,571
|
<p>The situation is, I have a website where the users get a sub domain. eg: client.mydomain.com. If the client fails to meet certain condition (eg. payment default), I want the above site to be pointing to a different web site. The way we want to do it is by creating a dns record with the appropriate redirection.</p>
<p>I use a win 2003 server, and program in .Net. any inputs on how I can programmatically do this?</p>
<p>I do control the website, however the reason is there are a lot of users (and hence sub domains) and also there is no physical website for (client.mydomain.come), it's like a wordpress/blogger where a user has blog.wordpress.com (and I assume they don't create a new website for each user).</p>
|
<p>Shouldn't it be possible to map *.domain.com to your server-ip and then from your app configure the host-binding? that way you will use the same app for all users. Otherwise, you can always check the host yourself and redirect, switch webroot etc or whatever you want. </p>
|
<p>If you control the website, I think that best would be to setup redirections instead of changing DNS records. The redirection could be as simple as renaming the current document index (say, index.htm) for one of your own that'll do a meta redirect to the destination.</p>
<p>DNS changes are slow to propagate, so there will be delays in the disabling and also in the enabling, even with small TTL. The other change is easier and immediate.</p>
| 35,436
|
<p>I'm not much of a coder, but I need to write a simple <em>preg_replace</em> statement in PHP that will help me with a WordPress plugin. Basically, I need some code that will search for a string, pull out the video ID, and return the embed code with the video id inserted into it. </p>
<p>In other words, I'm searching for this: </p>
<pre><code>[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]
</code></pre>
<p>And want to replace it with this (keeping the video id the same): </p>
<pre><code>param name="movie" value="http://www.youtube.com/v/VIDEO_ID_HERE&hl=en&fs=1&rel=0
</code></pre>
<p>If possible, I'd be forever grateful if you could explain how you've used the various slashes, carets, and Kleene stars in the search pattern, i.e. translate it from grep to English so I can learn. :-)</p>
<p>Thanks!<br>
Mike</p>
|
<p>BE CAREFUL! If this is a BBCode-style system with user input, these other two solutions would leave you vulnerable to XSS attacks. </p>
<p>You have several ways to protect yourself against this. Have the regex explicitly disallow the characters that could get you in trouble (or, allow only those valid for a youtube video id), or actually sanitize the input and use preg_match instead, which I will illustrate below going off of RoBorg's regex.</p>
<pre><code><?php
$input = "[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]";
if ( preg_match('/\[youtube=.*?v=(.*?)&.*?\]/i', $input, $matches ) )
{
$sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );
echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';
} else {
// Not valid input
}
</code></pre>
<p>Here's an example of this type of attack in action</p>
<pre><code><?php
$input = "[youtube=http://www.youtube.com/watch?v=\"><script src=\"http://example.com/xss.js\"></script>&hl=en&fs=1]";
// Is vulnerable to XSS
echo preg_replace('/\[youtube=.*?v=(.*?)&.*?\]/i', 'param name="movie" value="http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $input );
echo "\n";
// Prevents XSS
if ( preg_match('/\[youtube=.*?v=(.*?)&.*?\]/i', $input, $matches ) )
{
$sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );
echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0';
} else {
// Not valid input
}
</code></pre>
|
<pre><code>$embedString = 'youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1';
preg_match('/v=([^&]*)/',$embedstring,$matches);
echo 'param name="movie" value="http://www.youtube.com/v/'.$matches[1].'&hl=en&fs=1&rel=0';
</code></pre>
<p>Try that.</p>
<p>The regex <code>/v=([^&]*)/</code> works this way:</p>
<ul>
<li>it searches for <code>v=</code></li>
<li>it then saves the match to the pattern inside the parentheses to <code>$matches</code></li>
<li><code>[^&]</code> tells it to match any character <em>except</em> the ampersand ('&')</li>
<li><code>*</code> tells it we want anywhere from 0 to any number of those characters in the match</li>
</ul>
| 23,362
|
<p>If I set temperature say 220 °C, printer heats up to it and it only varies +/- 0.5 °C under non operating condition. But if I start a print, there's a shift of +/- 15 °C.</p>
<p>I've already auto tuned PID parameters and when I run <code>M503</code>, the printer shows the updated PID values.</p>
<p><a href="https://i.stack.imgur.com/w8SCE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8SCE.png" alt="Octoprint temperature graph showing hotend temperature drops" /></a></p>
<p>What could be the reason?</p>
<p>Electronics details:</p>
<ul>
<li>Firmware used: Marlin</li>
<li>Controller board: Printrboard rev D</li>
</ul>
|
<p>There could be a number of reasons for that behaviour:</p>
<p>Please check following items:</p>
<ol>
<li>part blower/fan cools down the nozzle - stop the fan</li>
<li>material is extruded at high speed and takes the heat</li>
<li>loose thermistor (when the move occurs as it moves a bit internally) </li>
<li>the power supply unit voltage varies - so temperature reading varies as well - measure voltage and see if there are significant drops</li>
<li>nozzle heater and thermistor cables can be loose as well (check screw terminals)</li>
<li>bed heater connection cables having not a good connection (check screw terminals)</li>
</ol>
|
<p>Can you also show a "power output" graph (or something like that, which show PWD duty cycle output to the hot end)?</p>
<p>Have you noted any relation between temperature raise and fall and the printing position?</p>
<p>Looking at graph I can only suggest the heating is suddenly stops and then the same sudden resumes.
It looks like you have a loose wire connection to the heater. When head is starting to move, it makes disturbance for the wiring, so heater occasionally stops to work.
There are usual two weak points: first it is where cable is connected to the board. Check is connector heated? Are any noises/sparks from there?
Another part: it is just at the point where wires going into the hot end. If wires are not secured to the printing head, then during printing those place experiences a lot of bending, which makes it weaker over the time.</p>
| 917
|
<p>What are some good links for diving into Erlang and functional programming in general?</p>
|
<p>Here's <a href="http://www.erlang.org/download/erlang-book-part1.pdf" rel="noreferrer">the first half of Concurrent Programming in Erlang</a> [PDF], free.</p>
|
<p>Let me suggest that Erlang is not necessarily typical of "functional programming in general". If you want a good balance, I'd combine reading some of the Erlang-specific sources already cited (or <a href="https://rads.stackoverflow.com/amzn/click/com/193435600X" rel="nofollow noreferrer" rel="nofollow noreferrer">Joe Armstrong's book, <em>Programming Erlang: Software for a Concurrent World</em></a>) with some of the tutorial links from <a href="http://www.haskell.org/" rel="nofollow noreferrer">the Haskell web site</a>.</p>
| 49,179
|
<p>I'd like to create a progress bar to indicate the status of an a batch job in <code>Ruby</code>. </p>
<p>I've read some <a href="http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/" rel="noreferrer" title="NCURSES Programming HOWTO">tutorials</a> / <a href="http://ncurses-ruby.berlios.de/" rel="noreferrer" title="ncurses-ruby">libraries</a> on using <em>(n)curses</em>, none of which were particularly helpful in explaining how to create an <em>"animated"</em> progress bar in the terminal or using curses with <code>Ruby</code>. </p>
<p>I'm already aware of using a separate thread to monitor the progress of a given job, I'm just not sure how to proceed with drawing a progress bar. </p>
<hr>
<p><strong>Update</strong> </p>
<p><a href="http://0xcc.net/ruby-progressbar/" rel="noreferrer" title="ruby-progressbar">ProgressBar</a> class was incredibly straight-forward, perfectly solved my problem.</p>
|
<p>You might be able to get some implementation ideas from the <a href="http://0xcc.net/ruby-progressbar/" rel="noreferrer" title="Ruby/ProgressBar">Ruby/ProgressBar library</a>, which generates text progress bars. I stumbled across it a couple of months back but haven't made any use of it.</p>
|
<p>On windows, curses works out of the box, ncurses doesn't, and for a progress bar curses should be sufficient. So, use curses instead of ncurses.</p>
<p>Also, both curses and ncurses are wafer-thin wrappers around the c library - that means you don't really need Ruby-specific tutorials.</p>
<p>However, on the <a href="http://www.pragprog.com/titles/ruby/source_code" rel="nofollow noreferrer">site for the PickAxe</a> you can download all the code examples for the book. The file "ex1423.rb" contains a curses demo which plays Pong - that should give you plenty of material to get you going.</p>
| 2,371
|
<p>What is the best way to send HTTP requests from Windows Powershell?</p>
|
<p>Found one way:</p>
<pre><code>$page = (New-Object System.Net.WebClient).DownloadString("http://localhost/")
</code></pre>
<p>Thanks to Steven Murawski for his comment:</p>
<blockquote>
<p>The best way really depends on what
task you are trying to accomplish as
the two answers below have noted.
<strong>WebClient</strong> is the simplest, but
<strong>HttpWebRequest</strong> is the most flexible.</p>
</blockquote>
|
<p>System.Net.WebClient is the easiest way to do it for simple GET request. However if you need to do a POST request for a form then you will need to use System.Net.HttpWebRequest.</p>
| 44,251
|
<p>Ok, I'm a newbie to ASP.NET web apps... and web apps in general. I'm just doing a bit of a play app for an internal tool at work.</p>
<p>given this tutorial... </p>
<p><a href="http://www.asp.net/learn/mvc-videos/video-395.aspx" rel="nofollow noreferrer">http://www.asp.net/learn/mvc-videos/video-395.aspx</a></p>
<p>The example basically has a global tasklist. </p>
<p>So if I wanted to do the same thing, but now I want to maintain tasks for projects. So I now select a project and I get the task list for that project. How do I keep the context of what project I have selected as I interact with the tasks? Do I encode it into the link somehow? or do you keep it in some kind of session data? or some other way?</p>
|
<p>As it sounds like you are having multiple projects with a number of tasks each, it would be best practise to let the project be set in the URL. This would require a route such as <code>"/projects/{project}/tasks"</code>. It follows the RESTful URL principle (i.e. the URL describes the content).</p>
<p>Using session state will not work if a user possibly have different projects open in multiple browser windows. Let's say I am logging into your system and a selecting two projects opening in two tabs. First the session is set to the project of the first opened tab, but as soon the second tab has loaded, the session will be overwritten to this project. If I then do anything in the first tab, it will be recorded for the second project.</p>
|
<p>ok, From what I can tell, the best option seems to be to save it into the Session data</p>
| 14,513
|
<p>I'm building a database that will store information on a range of objects (such as scientific papers, specimens, DNA sequences, etc.) that all have a presence online and can be identified by a URL, or an identifier such as a <a href="http://www.doi.org/" rel="noreferrer" title="DOI">DOI</a>. Using these GUIDs as the primary key for the object seems a reasonable idea, and I've followed <a href="http://delicious.com/" rel="noreferrer" title="delicious">delicious</a> and <a href="http://www.connotea.org" rel="noreferrer" title="Connotea">Connotea</a> in using the md5 hash of the GUID. You'll see the md5 hash in your browser status bar if you mouse over the edit or delete buttons in a delicious or Connotea book mark. For example, the bookmark for <a href="http://stackoverflow/" rel="noreferrer">http://stackoverflow/</a> is </p>
<pre><code>http://delicious.com/url/e4a42d992025b928a586b8bdc36ad38d
</code></pre>
<p>where e4a42d992025b928a586b8bdc36ad38d ais the md5 hash of <a href="http://stackoverflow/" rel="noreferrer">http://stackoverflow/</a>.</p>
<p>Does anybody have views on the pros and cons of this approach?</p>
<p>For me an advantage of this approach (as opposed to using an auto incrementing primary key generated by the database itself) is that I have to do a lot of links between objects, and by using md5 hashes I can store these links externally in a file (say, as the result of data mining/scraping), then import them in bulk into the database. In the same way, if the database has to be rebuilt from scratch, the URLs to the objects won't change because they use the md5 hash.</p>
<p>I'd welcome any thoughts on whether this sounds sensible, or whether there other (better?) ways of doing this.</p>
|
<p>It's perfectly fine. </p>
<p>Accidental collision of MD5 is impossible in all practical scenarios (to get a 50% chance of collision you'd have to hash 6 <em>billion</em> URLs <em>per second</em>, every second, for 100 years). </p>
<p>It's such an improbable chance that you're trillion times more likely to get your data messed up due to an undetected hardware failure than due to an actual collision.</p>
<p>Even though there is a known collision attack against MD5, intentional malicious collisions are currently impossible against hashed URLs.</p>
<ul>
<li><p>The type of collision you'd need to intentionally collide with a hash of another URL is called a <strong>pre-image</strong> attack. There are no known pre-image attacks against MD5. As of 2017 there's no research that comes even close to feasibility, so even a determined well-funded attacker can't compute a URL that would hash to a hash of any existing URL in your database.</p></li>
<li><p>The only known collision attack against MD5 is not useful for attacking URL-like keys. It works by generating a pair of binary blobs that collide <em>only with each other</em>. The blobs will be relatively long, contain NUL and other unprintable bytes, so they're extremely unlikely to resemble anything like a URL.</p></li>
</ul>
|
<p>md5 hash is almost unique, but is not totally unique unique so don't use it as primary key. It is depreciated for cryptographic use. There is less chance of key collision, but if you have pretty big database with billions of rows, there is still some chance of collision. If you insist using hash as primary key use other better hash. You cannot use non unique values for Primary Key.
If you have pretty big table, don't use it. If you have small table, you might use it, but not recommended.</p>
| 27,247
|
<p>I coded a Mancala game in Java for a college class this past spring, and I used the <a href="https://www.eclipse.org" rel="nofollow noreferrer" title="Eclipse">Eclipse</a> IDE to write it. One of the great (and fairly simple) visual aids in Eclipse is if you select a particular token, say a declared variable, then the IDE will automatically highlight all other references to that token on your screen. <a href="https://notepad-plus-plus.org/" rel="nofollow noreferrer">Notepad++</a>, my preferred Notepad replacement, also does this.</p>
<p>Another neat and similar feature in Eclipse was the vertical "error bar" to the right of your code (not sure what to call it). It display little red boxes for all of the syntax errors in your document, yellow boxes for warnings like "variable declared but not used", and if you select a word, boxes appear in the bar for each occurrence of the word in the document.</p>
<p>A screenshot of these features in action:
<img src="https://i.stack.imgur.com/XZeTy.jpg" alt="screenshot"></p>
<p>After a half hour of searching, I've determined that Visual Studio cannot do this on its own, so my question is: does anyone know of any add-ins for 2005 or 2008 that can provide either one of the aforementioned features?</p>
<p>Being able to highlight the current line your cursor is on would be nice too. I believe the add-in ReSharper can do this, but I'd prefer to use a free add-in rather than purchase one.</p>
|
<p>In a different question on SO (<a href="https://stackoverflow.com/questions/41908/customizing-visual-studio">link</a>), someone mentioned the VS 2005 / VS 2008 add-in "RockScroll". It seems to provide the "error bar" feature I was inquiring about in my question above.</p>
<p><a href="http://www.hanselman.com/blog/IntroducingRockScroll.aspx" rel="nofollow noreferrer">RockScroll</a></p>
<p>EDIT: RockScroll also does the identical token highlighting that I was looking for! Great!</p>
|
<p>The "error bar" functionality is provided in JetBrains ReSharper. I'm not sure if it does highlighting of references to the currently selected identifier.</p>
| 5,243
|
<p>This is just a general question - I was sitting and waiting for a bit of software to compile (we use Incredibuild here but can still take 10/15 mins) and it got me wondering, does anyone know how long it took to compile Windows XP or Vista? </p>
<p>I did some googling but didn't really find any useful information</p>
|
<p>OP is asking about <em><strong>Windows</strong></em>:</p>
<blockquote>
<p>"There are no other software projects
like this," <a href="http://en.wikipedia.org/wiki/Mark_Lucovsky" rel="nofollow noreferrer">Lucovsky</a> said, "but the
one thing that's remained constant
[over the years] is how long it takes
to build [Windows]. <em><strong>No matter which
generation of the product, it takes 12
hours to compile and link the system.</strong></em>"
Even with the increase in processing
horsepower over the years, Windows has
grown to match, and the development
process has become far more
sophisticated, so that Microsoft does
more code analysis as part of the
daily build. "The CPUs in the build
lab are pegged constantly for 12
hours," he said. "We've adapted the
process since Windows 2000. Now, we
decompose the source [code] tree into
independent source trees, and use a
new build environment. It's a
multi-machine environment that lets us
turn the crank faster. But because of
all the new code analysis, it still
takes 12 hours."</p>
</blockquote>
<p><a href="http://web.archive.org/web/20100712104930/http://www.winsupersite.com/reviews/winserver2k3_gold2.asp" rel="nofollow noreferrer">SOURCE</a></p>
<p>Also see Mark Lucovsky classic <a href="http://www.usenix.org/events/usenix-win2000/invitedtalks/lucovsky_html/sld001.htm" rel="nofollow noreferrer">presentation</a> on developing Windows NT/2000.</p>
<p>I don't work at Microsoft, so I don't know for sure...</p>
|
<p>I don't know how long is taking to compile XP, but 10/15 minutes is not so big at all.
Our project that include Linux kernel as one of the components (not the biggest) was taking about a hour to compile. We improved this by using <a href="http://ccache.samba.org/" rel="nofollow noreferrer">ccache</a> and now it's taking only few minutes. </p>
<p>Not exactly the answer to your question but i though it's might be relevant/useful. </p>
| 27,989
|
<p>I have a Tomcat Filter that delegates requests to the a handling object depending on the URL. This is the only filter in the <code>FilterChain</code>. I have an Ajax app that hammers this filter with lots of requests.</p>
<p>Recently I noticed an issue where the filter's <code>doFilter</code> method is often called with a committed response as a parameter (Internally, it is the coyote response that is marked committed).</p>
<p>It seems to me that the only way that this can happen is if the <code>recycle()</code> method is not called on this coyote response. I have checked to make sure that I am not keeping references to any of the request, response, outputStream, or writer objects. Additionally, I made sure to close the outputStream in a finally block. However, this doesn't resolve this issue.</p>
<p>This sounds like I am doing something to abuse the servlet container but I am having trouble tracking it down.</p>
|
<p>I have tried using Tomcat 6.16 and 6.18. This is definitely is the only filter in the chain.</p>
<p>It seems that something is keeping a reference to the servlet outputStream. I wrapped the ServletOutputStream in my own OutputStream and then made sure the reference is destroyed. This fixed the issue so that I no longer see a committed response passed in.</p>
<p>This is an odd side effect of holding a reference. But I don't think it qualifies as a Tomcat bug. More likely a bug in ImageIO.createImageOutputStream() that I suspect is holding the reference.</p>
|
<p>What version of Tomcat are you using? To me this sounds like a bug in Tomcat, I can't think of any reason why your doFilter method should be called with a response that's already been committed (if that filter is the only one in the chain, are you sure about this?). </p>
| 6,721
|
<p>I have a bunch of servlets running under the Tomcat servlet container. I would like to separate test code from production code, so I considered using a test framework.
JUnit is nicely integrated into Eclipse, but I failed to make it run servlets using a running Tomcat server. Could you please recommend a unit testing framework that supports testing Tomcat servlets? Eclipse integration is nice but not necessary. </p>
|
<p>Check out <a href="http://httpunit.sourceforge.net/doc/servletunit-intro.html" rel="noreferrer">ServletUnit</a>, which is part of HttpUnit. In a nutshell, ServletUnit provides a library of mocks and utilities you can use in ordinary JUnit tests to mock out a servlet container and other servlet-related objects like request and response objects. The link above contains examples.</p>
|
<p>Updated Feb 2018: <a href="https://closingbraces.net/openbrace/" rel="nofollow noreferrer">OpenBrace Limited has closed down</a>, and its ObMimic product is no longer supported.</p>
<p>If you want a newer alternative to ServletUnit for JUnit testing of Servlets, you might find my company's <a href="http://www.openbrace.com" rel="nofollow noreferrer">ObMimic</a> library useful. It's available for free from the website's <a href="http://www.openbrace.com/main/pages/download/download-current.html" rel="nofollow noreferrer">downloads</a> page.</p>
<p>As with ServletUnit, it provides a library of classes that you can use in normal JUnit or TestNG tests outside of any servlet container to simulate the Servlet API.</p>
<p>Its Servlet API objects have no-argument constructors, are fully configurable and inspectable for all relevant Servlet API data and settings, and provide a complete simulation of all of the behaviour specified by the Servlet API's javadoc. To help with testing there's support for selective recording of Servlet API calls, control over any container-dependent behaviour, checks for any ambiguous calls (i.e. where the Servlet API behavour isn't fully defined), and an in-memory JNDI simulation for any servlet code that relies on JNDI lookups.</p>
<p>For full details, example code, "how to" guides, Javadoc etc, see the website.</p>
| 7,703
|
<p>Whenever I type a (, [, or {, Notepad++ completes it with the corresponding closing bracket. I find this 'feature' annoying and would like to disable it. It doesn't seem to be listed in the Preferences dialog and a search of the online documentation didn't yield any useful result.
Does anybody here know where the option for this is hidden?
I'm currently using Notepad++ 5.0.3.</p>
|
<p>From version 6.6.8 onward:</p>
<p>Go to Settings -> Preferences -> Auto-Completion</p>
<p>In the second grouping called "Auto-Insert", check/un-check the appropriate auto completion/inserts.</p>
|
<p>If none of the above helps (as in my case), there's also a plugin called Xbrackets Lite. </p>
<p>Plugins -> XBrackets Lite -> Uncheck Autocomplete brackets. </p>
<p>I seem to recall installing this because the other two (settings/auto-complete and TextFX .. AutoClose) did not work. </p>
<p>Notepad++ 7.3.3. </p>
| 14,517
|
<p>We use PVCS for source control for all our code. We have 7 Servers across the EU covering 17 countries. PVCS mimics our folder structure in production:</p>
<pre><code>folderA
|
|--folderB
| |
| | -- folderC
| |
| | -- folder
| --folderD
| |
| | -- folderE
| |
| | -- folderF
</code></pre>
<p>Our projects can be dependant on files in multiple folders so we can just copy one folder out to deploy a new project. Also multiple programs can live in the same folder.</p>
<p>We have a DEV, UAT and Production server. Files will be developed on the DEV server, put onto UAT (well they are supposed to, this is part of the problem, too many human hands involved and some of them don't want to play ball), for testing by the user. When UAT is approved they are put back into PVCS with the appropriate version label and assigned a development level, (they can be put back into PVCS earlier with a development version label).</p>
<p>When all the relevant approvals have been done a change control request is raised and the support team will deploy the code to production.</p>
<p>Our biggest problem is the process is so bitty and there are too many people that have to do certain things at certain times and tell people stuff in the right order.</p>
<p>What we would like is a program that would automate the deployment of projects. You would need to be able to assign different files from different folders in PVCS a project label and then be able to progress that label and deploy all the files as needed.</p>
<p>Does this exist?</p>
<p>I hope that made sense.</p>
<p>Thanks</p>
<p>Jon</p>
<p><strong>EDIT:</strong></p>
<p>We would be creating new projects all the time. A project would relate to a deployment. I.e. project 1234 would have files 1,2,5,6 project 2345 would use files, 2,5,8. So to this end we would need a quick and easy way to add and manage projects.</p>
<p>If anyone can suggest a better way of dealing with this sort of automation that would be great as well.</p>
<p>We are not interested in compiling the code and testing as there are a number of languages and I believe that would be way out of our scope at this point.</p>
|
<p>Check out <a href="http://nant.sourceforge.net/" rel="nofollow noreferrer">nAnt</a> and <a href="http://cruisecontrol.sourceforge.net/index.html" rel="nofollow noreferrer">Cruise Control</a></p>
<p><strong>edit:</strong>
With Cruise Control you can always write your own plug ins to better handle your environment. </p>
|
<p>In order to automate our deployment process i had to create a tool using pcli and python. Where the pcli script get the code ( using inputs from the user ( Labels ) ) and python to deploy to our servers. </p>
<p>Check for the pcli documentation which is under VM_Install_Dir\books\vm\vmbooks\pcli.pdf </p>
| 38,292
|
<p>I have an SSRS report where I need to collapse data into a summary column like so:<br>
+Program<br>
-Program2<br>
Program2DataElement1 | Program2DataElement2 | etc.</p>
<p>How does one doe this? I see it in other reports, but can't for the life of me find the area to set it up. When I put in a group, I get something like this on all records: <br>
Program<br>
ProgramDataElement | ProgramDataElement | ...</p>
<p>What am I mising? Thanks in advance!</p>
|
<p>I believe these are the steps:</p>
<ol>
<li>Edit group</li>
<li>Click on Visibility Tab</li>
<li>For Initial Visibility, select the "hidden" radio button.</li>
</ol>
|
<p>For SSRS 2008 - We have:</p>
<ol>
<li>Select Group Properties for Program2DataElement at Row Groups</li>
<li>Select option Visibility</li>
<li>When the report is initially run: <strong>Hide</strong></li>
<li>Check Display can be toggled by this report item: <strong>Program2</strong></li>
</ol>
| 35,221
|
<p>We are getting an error in a VB6 application that sends data back and forth over TCP sockets. We get a runtime error "out of string space". Has anyone seen this or have any thoughts on why this would happen? It seems like we are hitting some VB6 threshhold so any other thoughts would be helpful as well.</p>
|
<p>As others have pointed out, every string concatenation in VB will allocate a new string and then copy the data over and then de-allocate the original once it can. In a loop this can cause issues.</p>
<p>To work around this you can create a simple StringBuilder class like this one:</p>
<pre><code>Option Explicit
Private data As String
Private allocLen As Long
Private currentPos As Long
Public Function Text() As String
Text = Left(data, currentPos)
End Function
Public Function Length() As Long
Length = currentPos
End Function
Public Sub Add(s As String)
Dim newLen As Long
newLen = Len(s)
If ((currentPos + newLen) > allocLen) Then
data = data & Space((currentPos + newLen))
allocLen = Len(data)
End If
Mid(data, currentPos + 1, newLen) = s
currentPos = currentPos + newLen
End Sub
Private Sub Class_Initialize()
data = Space(10240)
allocLen = Len(data)
currentPos = 1
End Sub
</code></pre>
<p>This class will minimize the number of string allocations by forcing the string to be built with spaces in it and then overwriting the spaces as needed. It re-allocates to roughly double its size when it finds that it does not have enough space pre-initialized. The Text method will return the portion of the string that is actually used.</p>
|
<p>Assuming that you are appending data in a loop, ensure that it's not being appended to itself, which will eat memory extremely quickly.</p>
<p>Example and description of error meaning:
<a href="http://msdn.microsoft.com/en-us/library/aa264524.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa264524.aspx</a></p>
| 11,956
|
<p>Is anyone writing applications specifically to take advantage of google chrome?<br>
Are there any enterprise users who are considering using it as the standard browser? </p>
|
<p>Yes, I have started to pay very good attention to Google Chrome for my applications. Recent analytics show that between 6%-15% of my users are accessing my applications (varies between 6 to 15 in different applications) on Chrome. And, this number looks on an upward trend.</p>
<p>Thus, I can't really ignore it for testing right now.</p>
<p>As far as taking it as a standard goes, thats a long way off. I still have to test for IE6! :( Though, we have been planning to start using features like Gears (inbuilt in Chrome - downloadable elsewhere) once Chrome crosses the 25% mark. Thats when I believe that we will be looking at Chrome to be our preferred browser. I hope that we have Chrome 1.0+ by then! ;) </p>
|
<p>I am using Google Chrome, so far all the web apps I have work fine in it with no modifications.</p>
| 12,849
|
<p>What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?</p>
|
<p>By an "anonymous class", I take it you mean <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html" rel="noreferrer">anonymous inner class</a>.</p>
<p>An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.</p>
<p>I tend to use it as a shortcut for attaching an event listener:</p>
<pre><code>button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
</code></pre>
<p>Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements <code>ActionListener</code> -- I can just instantiate an anonymous inner class without actually making a separate class.</p>
<p>I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.</p>
|
<p>The best way to optimize code. also, We can use for an overriding method of a class or interface. </p>
<pre><code>import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
</code></pre>
| 46,288
|
<p>I am writing one web chat program using AJAX (a little bit). It is working when both users open a chat page, but I want to open a window when one user send data to others.</p>
|
<p>Unless both users have a common web page (that you control) open, then this wouldn't be possible. However for the sake of providing a solution, let's agree on some assumptions: </p>
<ol>
<li>Both of the visitors are on your home page</li>
<li>One of the visitors opens a chat window and enters a message.</li>
</ol>
<p>Once that message is entered, you use AJAX to send the message to the server. At this point it would probably be best to go ahead and save the message into a database (just my two cents worth on that part). The home page would have to be set up to poll for any messages every so often also using AJAX (I'd suggest every 30 seconds or so, depending on the purpose of this application). If a new message is received, then it would respond by opening a chat window (<code>window.open(url)</code>) and the discussion can commence.</p>
|
<p>Sounds like you need to write some javascript to open a new window when a message is received. How are you sending the message - <a href="http://en.wikipedia.org/wiki/Reverse_Ajax" rel="nofollow noreferrer">reverse Ajax</a>?</p>
<p>Presumably both users will need to have your chat applications web page open so that you have somewhere to put the reverse ajax hook code.</p>
| 27,215
|
<p>G'day!</p>
<p>I have one million different words which I'd like to query for in a table with 15 million rows. The result of synonyms together with the word is getting processed after each query.</p>
<p>table looks like this:</p>
<pre><code> synonym word
---------------------
ancient old
anile old
centenarian old
darkened old
distant far
remote far
calm gentle
quite gentle
</code></pre>
<p>This is how it is done in Java currently:</p>
<pre><code>....
PreparedStatement stmt;
ResultSet wordList;
ResultSet syns;
...
stmt = conn.prepareStatement("select distinct word from table");
wordList = stmt.executeQuery();
while (wordList.next()) {
stmt = conn.prepareStatement("select synonym from table where word=?");
stmt.setString(1, wordList.getString(1));
syns = stmt.executeQuery();
process(syns, wordList.getString(1));
}
...
</code></pre>
<p>This is incredible slow. What's the fastest way to do stuff like this?</p>
<p>Cheers,
Chris</p>
|
<p>Two ideas:</p>
<p>a) How about making it one query:</p>
<pre><code>select synonym from table where word in (select distinct word from table)
</code></pre>
<p>b) Or, if you <code>process</code> method needs to deal with them as a set of synonyms of one word, why not sort them by <code>word</code> and start <code>process</code> anew each time <code>word</code> is different? That query would be:</p>
<pre><code>select word, synonym
from table
order by word
</code></pre>
|
<p>The problem is solved. The important point is, that the table can be sorted by word. Therefore, I can easily iterate through the whole table. Like this:</p>
<pre><code>....
Statement stmt;
ResultSet rs;
String currentWord;
HashSet<String> syns = new HashSet<String>();
...
stmt = conn.createStatement();
rs = stmt.executeQuery(select word, synonym from table order by word);
rs.next();
currentWord = rs.getString(1);
syns.add(rs.getString(2));
while (rs.next()) {
if (rs.getString(1) != currentWord) {
process(syns, currentWord);
syns.clear();
currentWord = rs.getString(1);
}
syns.add(rs.getString(2));
}
...
</code></pre>
| 36,078
|
<p>I have a Silverlight 2 app that sends a byte array to a Silverlight-enabled WCF service. However, (unless I try to upload a .txt file) the service's <code>SaveFile()</code> method is never reached and I get an error: "The remote server returned an error: NotFound"</p>
<p>Am I missing something really obvious? Why can't I upload .doc files? Why only .txt?</p>
<p>UPDATE: I've tried attaching debugger for CLR exceptions, but that didn't help. I am still not able to see any errors besides the 404. Here's my code:</p>
<p><strong>in Page.xaml.cs:</strong></p>
<pre><code>OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog().Value)
{
byte[] fileContent = new byte[dlg.File.Length];
using (FileStream fs = dlg.File.OpenRead())
{
fs.Read(fileContent, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
Service1.Service1Client srv = new SL1.Service1.Service1Client();
srv.SaveFileCompleted += (sender1, e1) =>
{
foo.Text = "Uploaded!";
};
srv.SaveFileAsync(dlg.File.Name, fileContent);
}
</code></pre>
<p><strong>in Service1.svc.cs:</strong></p>
<pre><code>[OperationContract]
public string SaveFile(string fileName, byte[] fileContent)
{
string ret = String.Empty;
try
{
string target = @"c:\debug123\" + fileName;
if (File.Exists(target))
{
File.Delete(target);
}
File.WriteAllBytes(target, fileContent);
ret = "OK";
}
catch (Exception ex)
{
ret = ex.ToString();
}
return ret;
}
</code></pre>
<p>Anyone see anything wrong with this?</p>
|
<p>FYI, I figured out my problem and <a href="http://michaelsync.net/2008/03/27/uploading-with-silveright-2-beta-1-and-wcf" rel="nofollow noreferrer">this article</a> solved it. "By default the largest message that can be sent to a service from the client is 8124 bytes." So I had to increase the limit via the bindings config settings.</p>
<p>But now my main issue is how to get an appropriate error message, instead of the 404. I'll have to research that some more, but hope someone else can come up with a good answer (unfortunately breaking on CLR exceptions didn't help me).</p>
<p>UPDATE: Upon further reading of <a href="http://michaelsync.net/2008/03/27/uploading-with-silveright-2-beta-1-and-wcf" rel="nofollow noreferrer">the same article</a>, I discovered that the WCF Service Configuration Utility that is included in the Windows SDK can help determine the underlying problem.</p>
|
<p>This sounds like your issue Check out <a href="http://www.yoda.arachsys.com/csharp/readbinary.html" rel="nofollow noreferrer">http://www.yoda.arachsys.com/csharp/readbinary.html</a> and <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/ea40b542-c7e1-4a4f-b974-7ecc03cbd475/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/ea40b542-c7e1-4a4f-b974-7ecc03cbd475/</a></p>
| 37,636
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.