instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I need a Linux text editor to replace Textpad 4.7.3 (a Windows nagware app), but all the alternatives I've tried are either bloated or incomplete. Here are the features I find most important, in descending order:</p>
<ul>
<li>Regex search, mark, and replace (across all open files, even), regex search in directory trees</li>
<li>Tabbed editor with <strong>proper</strong> keyboard shortcuts ([ctrl]+[tab] should work on the <em>exact same model</em> as [alt]+[tab])</li>
<li>Auto-indent, indent preservation, and indent manipulation (tab, shift-tab)</li>
<li>Smart navigation keys: [home] toggles between start of line and start of non-whitespace, [F2] seeks to next bookmark, <em>hitting the up and down arrow keys take you to the column where you last navigated, not where you last typed</em> (I think Textpad's the only place I've seen this)</li>
<li>Syntax highlighting (bonus: mixed-language highlighting, which TextPad lacked)</li>
<li>Block select mode</li>
<li>Run user-defined commands from program (such as compilers), have interactive command results (Textpad would let you define regexes to match filenames and line numbers so you could double-click on an error and be taken to that line in that file.)</li>
<li>Workspaces (collections of files to be open at the same time)</li>
</ul>
<p>Here's what I've found distasteful in the editors I've tried:</p>
<ul>
<li>Vim and emacs <s>do not take full advantage of my screen, mouse, and keyboard. Also, there's</s> have quite a learning curve -- you have to learn an <em>entirely new</em> way of interacting with the keyboard. (Of course, if they had everything I wanted, I would learn them.)</li>
<li>Gedit is almost perfect, but it (like most of them) has crappy tabbing, which is <em>intolerable</em></li>
<li>Eclipse is a monstrosity, and I won't touch it unless I'm doing Java</li>
<li><strong>Regex capability</strong> is frighteningly rare</li>
<li>Almost nothing has <strong>last-seen</strong> tab traversal</li>
<li>I've not seen anything with last-navigation-column cursor traversal. (Once I started using it I found I couldn't do without.)</li>
</ul>
<p>I don't have the time or the specific knowledge required to build my "ideal editor", so I'm hoping someone out there with the same taste in editors might have stumbled across a gem.</p>
<p>ETA: Please <strong>don't recommend</strong> an editor you haven't <strong>personally used</strong>. I've heard of SciTE, Eclipse, gedit, medit, nedit, GVim, Gemacs, Kate, Geany, Gnotepad, ozeditor, etc. I'm sure that most of them have some of the features I mentioned. If you're not sure if it has an essential feature (e.g. ctrl-tab works just like alt-tab), then you're not really helping, are you?</p>
|
<p><em>Vim and emacs do not take full advantage of my screen, mouse, and keyboard.</em> </p>
<p>Have you looked at gvim? I'm a console guy myself, but I'm pretty sure it's GUIlicious.</p>
|
<p>Have you tried <a href="http://kate-editor.org/" rel="nofollow noreferrer">Kate</a>? I'm not sure it complies with all your requirements, but it may. Also, for a more development oriented tool, you could try <a href="http://www.kdevelop.org/" rel="nofollow noreferrer">KDevelop</a>, whose default editor is Kate (but you can change for any other editor implementing the KTextEditor interface)</p>
| 27,170
|
<p>I've isolated the behaviour into the following test case. I'd be grateful to anyone who can tell me how to expect/verify a property set for a <code>List<T></code> property - it appears there's something going on inside <code>It.Is<T>(predicate)</code> that isn't making a whole lot of sense to me right now. Sample code will run as a console app from VS2008 - you'll need to add a reference to Moq 2.6 (I'm on 2.6.1014.1) - please try uncommenting the different ExpectSet statements to see what's happening...</p>
<pre><code>using System;
using Moq;
using System.Collections.Generic;
namespace MoqDemo {
public interface IView {
List<string> Names { get; set; }
}
public class Controller {
private IView view;
public Controller(IView view) {
this.view = view;
}
public void PopulateView() {
List<string> names = new List<string>() { "Hugh", "Pugh", "Barney McGrew" };
view.Names = names;
}
public class MyApp {
public static void Main() {
Mock<IView> mockView = new Mock<IView>();
// This works - and the expectation is verifiable.
mockView.ExpectSet(mv => mv.Names);
// None of the following can be verified.
// mockView.ExpectSet(mv => mv.Names, It.Is<Object>(o => o != null));
// mockView.ExpectSet(mv => mv.Names, It.Is<List<string>>(names => names.Count == 3));
// mockView.ExpectSet(mv => mv.Names, It.IsAny<IList<String>>());
Controller controller = new Controller(mockView.Object);
controller.PopulateView();
try {
mockView.VerifyAll();
Console.WriteLine("Verified OK!");
} catch (MockException ex) {
Console.WriteLine("Verification failed!");
Console.WriteLine(ex.Message);
}
Console.ReadKey(false);
}
}
}
}
</code></pre>
|
<p>I'm not using the very latest version of Moq, so I don't have an overload of ExpectSet that takes two parameters, but I've had some success with this pattern:</p>
<pre><code>mockView.ExpectSet(mv => mv.Names).Callback(n => Assert.That(n != null));
</code></pre>
<p>The Assert (from NUnit) call in the callback will throw an exception if the value assigned to .Names doesn't match the predicate. It does make it hard to trace when a test fails, though. I agree that the ability to pass an It.Is or It.IsAny as the second parameter would be handy.</p>
|
<p>Moq doesn't provide an overload receiving It.IsAny as it's effectively the same as calling ExpectSet without passing an expected value ;)</p>
| 46,704
|
<p>Is it possible to add a "metadata"-like description or comments to a table in Microsoft SQL 2000 and above? </p>
<p>How would you do this through the CREATE TABLE statement?</p>
<p>Is it possible to add a description or comment to fields?</p>
<p>How do you query this info back in MSSQL 2000? 2005?</p>
|
<p>Use extended properties. For example to add an extended property to a table in the dbo schema you can use:</p>
<pre><code>EXEC sys.sp_addextendedproperty @name=N'<NameOfProp>',
@value=N'<Value>' , @level0type=N'SCHEMA',@level0name=N'dbo',
@level1type=N'TABLE',@level1name=N'<Table>'
</code></pre>
<p>You can update them:</p>
<pre><code>EXEC sys.sp_updateextendedproperty
@name=N'MS_Description', @value=N'My Description' ,
@level0type=N'SCHEMA',@level0name=N'dbo',
@level1type=N'TABLE'
,@level1name=N'<YOUR TABLE NAME>'
</code></pre>
<p>You can read them like:</p>
<pre><code>SELECT *
FROM fn_listextendedproperty (NULL, 'schema','dbo', 'table', '<yourtable>', default, default);
</code></pre>
<p>or</p>
<pre><code>SELECT
p.name AS [Name],p.value
FROM
sys.tables AS tbl
INNER JOIN sys.extended_properties AS p ON p.major_id=tbl.object_id AND p.minor_id=0 AND p.class=1
WHERE
(tbl.name=N'<yourtablename>' and SCHEMA_NAME(tbl.schema_id)=N'dbo')
ORDER BY
[Name] ASC
</code></pre>
|
<p>Most tools and people use the Extended Properties for supporting this. The common name used by SSMS is MS_Description</p>
<p>There are several built in stored procedures for creating these properties as well as reading them, they procs changed over time so there will be compat differences between SQL versions.</p>
| 49,609
|
<p>Consider the following simple C program that read a file into a buffer and displays that buffer to the console:</p>
<pre><code>#include<stdio.h>
main()
{
FILE *file;
char *buffer;
unsigned long fileLen;
//Open file
file = fopen("HelloWorld.txt", "rb");
if (!file)
{
fprintf(stderr, "Unable to open file %s", "HelloWorld.txt");
return;
}
//Get file length
fseek(file, 0, SEEK_END);
fileLen=ftell(file);
fseek(file, 0, SEEK_SET);
//Allocate memory
buffer=(char *)malloc(fileLen+1);
if (!buffer)
{
fprintf(stderr, "Memory error!");
fclose(file);
return;
}
//Read file contents into buffer
fread(buffer, fileLen, 1, file);
//Send buffer contents to stdout
printf("%s\n",buffer);
fclose(file);
}
</code></pre>
<p>The file it will read simply contains: </p>
<blockquote>
<p>Hello World!</p>
</blockquote>
<p>The output is:</p>
<blockquote>
<p>Hello World!²²²²▌▌▌▌▌▌▌↔☺</p>
</blockquote>
<p>It has been a while since I did anything significant in C/C++, but normally I would assume the buffer was being allocated larger than necessary, but this does not appear to be the case. </p>
<p>fileLen ends up being 12, which is accurate.</p>
<p>I am thinking now that I must just be displaying the buffer wrong, but I am not sure what I am doing wrong. </p>
<p>Can anyone clue me in to what I am doing wrong?</p>
|
<p>You need to NUL-terminate your string. Add</p>
<pre><code>buffer[fileLen] = 0;
</code></pre>
<p>before printing it.</p>
|
<p>You can use <code>calloc</code> instead of <code>malloc</code> to allocate memory that is already initialised. <code>calloc</code> takes on extra argument. It's useful for allocating arrays; the first parameter of <code>calloc</code> indicates the number of elements in the array that you would like to allocate memory for, and the second argument is the size of each element. Since the size of a <code>char</code> is always 1, we can just pass <code>1</code> as the second argument:</p>
<pre><code> buffer = calloc (fileLen + 1, 1);
</code></pre>
<p>In C, there is no need to cast the return value of <code>malloc</code> or <code>calloc</code>. The above will ensure that the string will be null terminated even if the reading of file ended prematurely for whatever reason. <code>calloc</code> does take longer than <code>malloc</code> because it has to zero out all the memory you asked for before giving it to you.</p>
| 32,522
|
<p>My father died recently and I've inherited his Mac. I'd love to put it to use in my own life, but I don't want to wipe its brains out just so I can reconfigure it to use in my network, etc. His old files are historically important to me—I trust you can understand my desire to keep them.</p>
<p>I can log in as I had an account on the machine before he passed, but that's about it.</p>
|
<p>Sincere condolences.</p>
<p>Try this: <a href="http://kb.wisc.edu/helpdesk/page.php?id=3853" rel="nofollow noreferrer">Mac OS X - Resetting a Forgotten Account Password</a></p>
<p>The link shows a walk-through of starting up from the Mac OS X installation DVD and using its Reset Password functionality to reset the administrator account's password.</p>
<p>There's further information here: <a href="http://support.apple.com/kb/HT1274" rel="nofollow noreferrer">Mac OS X: Changing or resetting an account password</a></p>
|
<p>If you can access the files in question, then the first thing to do would be to back them up...</p>
| 23,784
|
<p>What would you suggest for the following scenario: </p>
<p>A dozen of developers need to build and design a complex system. This design needs to be documented for future developers and the design decisions must be noted. These reports need to be made about every two months. My question is how this project should be documented. </p>
<p>I see two possibilities. Each developer writes about the things they helped design and integrate and then one person combines each of these documents together. The final document will probably be incoherent or redundant at times since the person tasked of assembling everything won't have much time to adjust every part. </p>
<p>Assume that the documentation parts from each developer arrive just a few days before deadline. A collaborative system (i.e. wiki) wouldn’t work properly since there wouldn’t be anything to read until a few days before deadline. </p>
<p>Or should a few people (2-3) be tasked with writing the documentation while the rest of the team works on actually developing the system? The developers would need a way to transfer their design choices and conclusions to the technical writers. How could this be done efficiently?</p>
|
<p>We approach this from 2 sides, using a RUP style approach. In the first case, you'll have a domain expert who is responsible for roughing out the design of what you're going to deliver - with developers chipping in as necessary. In the second case, we use a technical author - they document the application, so they should have a good idea of how it hangs together, and you involve them right through the design and development process. In this case, they can help to polish the design, and to make sure that it matches what they thought was being developed.</p>
|
<p>I think you can use Sand Castle to document your project.</p>
<p>Check it out</p>
<p><a href="http://www.codeplex.com/DocProject/Wiki/View.aspx?title=How%20To%20Configure%20Visual%20Studio%202005%20For%20DocProject&referringTitle=Home" rel="nofollow noreferrer">Sand Castle from Microsoft</a></p>
| 47,744
|
<p>Is there a way to print all methods of an object in JavaScript?</p>
|
<p>Sure:</p>
<pre><code>function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
</code></pre>
<p>Using it:</p>
<pre><code>alert(getMethods(document).join("\n"));
</code></pre>
|
<p>Since methods in JavaScript are just properties that are functions, the for..in loop will enumerate them with an exception - it won't enumerate built-in methods. As far as I know, there is no way to enumerate built-in methods. And you can't declare your own methods or properties on an object that aren't enumerable this way.</p>
| 18,400
|
<p>Have done fft (see earlier posting if you are interested!) and got a result, which helps me. Would like to analyse the noisiness / spikiness of an array (actually a vb.nre collection of single). Um, how to explain ...</p>
<p>When signal is good, fft power results is 512 data points (frequency buckets) with low values in all but maybe 2 or 3 array entries, and a decent range (i.e. the peak is high, relative to the noise value in the nearly empty buckets. So when graphed, we have a nice big spike in the values in those few buckets.</p>
<p>When signal is poor/noisy, data values spread (max to min) is low, and there's proportionally higher noise in many more buckets.</p>
<p>What's a good, computationally non-intensive was of analysing the noisiness of this data set? Would some kind of statistical method, standard deviations or something help ? </p>
|
<p>The key is defining what is noise and what is signal, for which modelling assumptions must be made. Often an assumption is made of white noise (constant power per frequency band) or noise of some other power spectrum, and that model is fitted to the data. The signal to noise ratio can then be used to measure the amount of noise.</p>
<p>Fitting a noise model depends on the nature of your data: if you know that the real signal will have no power in the high frequency components, you can look there for an indication of the noise level, and use the model to predict what the noise will be at the lower frequency components where there is both signal and noise. Alternatively, if your signal is constant in time, taking multiple FFTs at different points in time and comparing them to get a standard deviation for each frequency band can give the level of noise present.</p>
<p>I hope I'm not patronising you to mention the issues inherent with windowing functions when performing FFTs: these can have the effect of introducing spurious "noise" into the frequency spectrum which is in fact an artifact of the periodic nature of the FFT. There's a tradeoff between getting sharp peaks and 'sideband' noise - more here <a href="http://www.ee.iitm.ac.in/~nitin/_media/ee462/fftwindows.pdf" rel="nofollow noreferrer">www.ee.iitm.ac.in/~nitin/_media/ee462/fftwindows.pdf</a></p>
|
<p>calculate the signal to noise ratio
<a href="http://en.wikipedia.org/wiki/Signal-to-noise_ratio" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Signal-to-noise_ratio</a></p>
<p>you could also check the stdev for each point and if it's under some level you choose then the signal is good else it's not.</p>
| 18,438
|
<p>I'm building a group calendar application that needs to support recurring events, but all the solutions I've come up with to handle these events seem like a hack. I can limit how far ahead one can look, and then generate all the events at once. Or I can store the events as repeating and dynamically display them when one looks ahead on the calendar, but I'll have to convert them to a normal event if someone wants to change the details on a particular instance of the event.</p>
<p>I'm sure there's a better way to do this, but I haven't found it yet. What's the best way to model recurring events, where you can change details of or delete particular event instances?</p>
<p>(I'm using Ruby, but please don't let that constrain your answer. If there's a Ruby-specific library or something, though, that's good to know.)</p>
|
<p>I would use a 'link' concept for all future recurring events. They are dynamically displayed in the calendar and link back to a single reference object. When events have taken place the link is broken and the event becomes a standalone instance. If you attempt to edit a recurring event then prompt to change all future items (i.e. change single linked reference) or change just that instance (in which case convert this to a standalone instance and then make change). The latter cased is slightly problematic as you need to keep track in your recurring list of all future events that were converted to single instance. But, this is entirely do-able.</p>
<p>So, in essence, have 2 classes of events - single instances and recurring events.</p>
|
<blockquote>
<p>What if you have a recurring appointment with no end date? As cheap as space is, you don't have infinite space, so Solution 2 is a non-starter there... </p>
</blockquote>
<p>May I suggest that "no end date" can be resolved to an end date at the end of the century. Even for a dayly event the amount of space remains cheap.</p>
| 11,122
|
<p>Would anyone know why MSVC++ 2008 always returns error 5 on GetLastError() when I try to call OpenProcess with PROCESS_ALL_ACCESS as my desired access? PROCESS_VM_READ works just fine. I'm an administrator on this computer and it is working fine in Dev C++.</p>
<p>Do I need to set an option somewhere?</p>
|
<p>Opening a process with full access rights can be a highly privileged operation if it's not a process running under you credentials or in your logon session - you'll need to follow this bit of documentation from MSDN:</p>
<blockquote>
<p>To open a handle to another process
and obtain full access rights, you
must enable the SeDebugPrivilege
privilege. For more information, see
Changing Privileges in a Token.</p>
</blockquote>
<p>Remember that even if you have a privilege, in most cases the privilege is not enabled - it has to be specifically enabled in the code that's attempting to use the privilege.</p>
|
<p>Which process is it? Opening a service or a process in another user session is likely to return Access Denied (5). A process in another session will open for read but you wouldn't be able to debug it. It's one reason why Windbg has the non-intrusive attach. It works across user sessions. You're not actually debugging. It suspends all the threads and is reading the memory.</p>
| 20,444
|
<p>The workflow is like this:</p>
<ol>
<li>I receive a scan of a coupon with data (firstname, lastname, zip, city + misc information) on it.</li>
<li>Before I create a new customer, I have to search the database if the customer might exist already.</li>
</ol>
<p>Now my question: What's the best way to find an existing customer, when there is no unique ID available?</p>
<p>PS: I do have a unique ID in the database, just not on the coupons we receive ;)</p>
|
<p>We are using the <a href="http://en.wikipedia.org/wiki/Levenshtein_distance" rel="nofollow noreferrer">Levenshtein distance</a> algorithm to check users for duplication. However we have quite strict rules to enter the data itself, so we have to check only for misstyping, case differences and such.</p>
|
<p>You query the database for all customers that match the given data, e.g.</p>
<pre><code>SELECT ID FROM tbl_customers WHERE
first_name LIKE 'JOHN'
AND last_name LIKE 'Doe'
AND zip_code=12345
AND city LIKE 'Ducktown'
</code></pre>
<p>If the number of rows returned is 0, create a new entry in the database. If it is 1, the query will give you the ID. If it is > 1 you may have several customers of the same name living in the same area, need to find a way to deal with this situation. But that would justify a new question here ;-)</p>
<hr>
<p>p.s.: If you have no unique ID at all, redesign your database.</p>
| 18,968
|
<p>In the Delphi IDE, you can hold control and click on a method to jump to its definition. In VS2008, you have to right-click and select "Go To Definition".</p>
<p>I use this function quite often, so I'd really like to get VS to behave like Delphi in this regard - its so much quicker to ctrl+click.</p>
<p>I don't think there's a way to get this working in base VS2008 - am I wrong? Or maybe there's a plugin I could use?</p>
<p><strong>Edit</strong>: Click then F12 does work - but isn't really a good solution for me.. It's still way slower than ctrl+click.
I might try AutoHotkey, since I'm already running it for something else.</p>
<p><strong>Edit</strong>: <a href="http://www.autohotkey.com" rel="nofollow noreferrer">AutoHotkey</a> worked for me. Here's my script:</p>
<pre><code>SetTitleMatchMode RegEx
#IfWinActive, .* - Microsoft Visual Studio
^LButton::Send {click}{f12}
</code></pre>
|
<p>You could create an Autohotkey script that does that. When you ctrl-click a word, send a doubleclick then a F12.</p>
<p>I don't have AHK handy so I can't try and sketch some code but it should be pretty easy; the AHK recorder should have enough features to let you create it in a point 'n' click fashion and IIRC it is smart enough to let you limit this behaviour to windows of a certain class only.</p>
<p>When you have your script ready just run the script in the background while you code. It takes just an icon in the Notify bar.</p>
|
<p>Put the mouse cursor on the method name or any identifier, and press <kbd>F12</kbd></p>
| 10,643
|
<p>ASP.NET 2.0 provides the <code>ClientScript.RegisterClientScriptBlock()</code> method for registering JavaScript in an ASP.NET Page.</p>
<p>The issue I'm having is passing the script when it's located in another directory. Specifically, the following syntax does not work:</p>
<pre><code>ClientScript.RegisterClientScriptBlock(this.GetType(), "scriptName", "../dir/subdir/scriptName.js", true);
</code></pre>
<p>Instead of dropping the code into the page like <a href="http://msdn.microsoft.com/en-us/library/aa479390.aspx#javawasp2_topic7" rel="nofollow noreferrer">this page</a> says it should, it instead displays <code>../dir/subdir/script.js</code> , my question is this:</p>
<p>Has anyone dealt with this before, and found a way to drop in the javascript in a separate file? Am I going about this the wrong way?</p>
|
<p>What you're after is: </p>
<pre><code>ClientScript.RegisterClientScriptInclude(this.GetType(), "scriptName", "../dir/subdir/scriptName.js")
</code></pre>
|
<p>Your script value has to be a full script, so put in the following for your script value.</p>
<pre><code><script type='text/javascript' src='yourpathhere'></script>
</code></pre>
| 11,198
|
<p>I've just bought <strong>Anycubic i3 Mega</strong> printer and trying to level it.
So far I've printed test object and 2 others but looks like there are problems with leveling.</p>
<p>I want to make image of 5 small one layer squares(one in each corner and one in center). Looking for recommendations of <strong>simple</strong> software/tutorials/approaches to do it. I tried zbrush but found that it kind of complicated.</p>
|
<p>You are probably looking for something like <a href="https://www.thingiverse.com/thing:2479352" rel="nofollow noreferrer">this</a>:</p>
<p><img src="https://cdn.thingiverse.com/renders/0f/68/62/46/9f/646e9a4ee9ff75a7f0cacb396a0b7ed4_preview_featured.jpg" alt="leveling print object"></p>
<p>Note this is for large beds (300 x 300 mm), so you would have to X, Y scale this in your slicer.</p>
<p>This is a simple part that is very easily generated with <a href="http://www.openscad.org" rel="nofollow noreferrer">OpenSCAD</a> 3D design software (very good modeller if you are familiar with software coding), but could easily been designed in any <a href="https://en.m.wikipedia.org/wiki/List_of_3D_modeling_software" rel="nofollow noreferrer">other tool</a>.</p>
<p>Another leveling and centering print that is created with OpenSCAD is <a href="https://www.thingiverse.com/thing:2280529" rel="nofollow noreferrer">this</a>, and could be a start for you to create your own design:</p>
<p><a href="https://i.stack.imgur.com/mH73a.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mH73a.jpg" alt="leveling and centering print object"></a></p>
<p>Note that the file with the design is located in the "files" section.</p>
<p><strong>Edit</strong>:
Some code for OpenSCAD made within 5 minutes (I don't type fast so it could have been faster if I did not use the constants, but if you go OpenSCAD, making parametric designs is almost a must ;) ):</p>
<pre><code>// Set constants as you like
width = 30;
depth = 30;
layer_height = 0.2;
first_layer_height = 0.2;
nr_of_layers = 2;
box_size = 180;
// Calculated parameters
height = first_layer_height + (nr_of_layers - 1) * layer_height;
// Draw the test object
translate([-width/2, -depth/2,0]){
// Draw the center square
cube(size = [width, depth, height], center = false);
// Draw the corner squares
for (x=[-1:2:1]){
for (y=[-1:2:1]){
translate([x * (box_size-width)/2, y * (box_size-depth)/2, 0])
cube(size = [width, depth, height], center = false);
}
}
}
</code></pre>
<p>Rendered figure:
<a href="https://i.stack.imgur.com/bVNru.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bVNru.png" alt="rendered image of the 5 square level test print"></a></p>
|
<p>One of the most accessible modelling tools has to be <a href="https://www.tinkercad.com/" rel="nofollow noreferrer">tinkercad</a>. Everything is done in the browser, and it even works (to an extent) on a tablet. </p>
<p>I wouldn't recommend getting too attached to it, since it is fairly limited. As an introduction to modeling in 3D, and some of the spatial concepts that you will need to get used to, it works very well.</p>
| 995
|
<p>Our development process is highly automated via a raft of bash and php scripts (including subversion hook scripts.) These scripts do a number of things to integrate with our Bugzilla 3.0 installation.</p>
<p>But the current integration approach is a bunch of SQL calls which update the bugzilla database directly - which obviously has a number of downsides - including making me nervous about upgrading to 3.2 in case the database schema has changed!</p>
<p>For example, to add a comment to a bug, I'm doing an INSERT into the longdescs table.</p>
<p>So my (slightly long-winded) question is:</p>
<ul>
<li>should I be using Bugzilla WebServices (and if so, is there any good documentation other than the Bugzilla API docs which aren't getting me up to speed quickly)</li>
<li>or, should I be using some other Bugzilla API (direct perl calls?) - and, again, is there any decent doco on this?</li>
<li>or, should I just keep doing what I'm doing (direct SQL calls) because the db doesn't change that much and it "does the job"</li>
</ul>
|
<p>According to the Bugzilla WebServices API, some of the features needed (e.g. changing a bug status) are not yet available, so for the time being, direct SQL calls seem the most appropriate option.</p>
<p>The database schema has not changed significantly between version 3.0 and 3.2 so this is a practical way forward.</p>
|
<p>Be careful! Some database changes imply other changes as well. Adding a comment to a bug by adding a row to longdescs works, but you should also be updating delta_ts in table bugs.</p>
<p>Until web services are available, here's what I would do: perform the action using the UI that you want to do from the shell. (Assuming MySQL) Go look at the binary log for the database using 'mysqlbinlog' and you'll see what statements Bugzilla usually executes when doing whatever.</p>
<p>If you want the comment you added to be mailed the next time someone makes a change, leave bugs.last_diffed alone. If you don't want the comment you added to be mailed out, update bugs.last_diffed as you are doing to bugs.delta_ts.</p>
<p>Bugzilla has a number of subtle dependencies in the database that you must respect, or you're likely to get some unexpected results.</p>
| 44,237
|
<p>I have a <code><div></code> that I want to be on a line by itself. According to <a href="http://www.w3schools.com/Css/pr_class_clear.asp" rel="nofollow noreferrer">W3Schools</a>, this rule:</p>
<pre><code>div.foo {
clear: both;
}
</code></pre>
<p>...should mean this:</p>
<blockquote>
<p>"No floating elements allowed on either the left or the right side."</p>
</blockquote>
<p>However, if I float two <code><div></code> elements left, and apply the rule above to the first one, the second one does not budge.</p>
<p>On the other hand, if I apply <code>"clear: left"</code> to the second <code><div></code>, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this.</p>
<p>Is the W3Schools description above poorly stated, or am I missing something? <strong>Is a clearing rule only able to move the element to which it is applied?</strong></p>
<h2>Answer</h2>
<p>Thanks Michael S and John D for the good explanations. Warren pointed to <a href="http://www.w3.org/TR/REC-CSS2" rel="nofollow noreferrer">the CSS2 spec</a>, and that's where I found this answer (emphasis mine):</p>
<blockquote>
<p>This property indicates which sides of an element's box(es) may not be adjacent to an <strong>earlier</strong> floating box.</p>
</blockquote>
<p>So: <code>clear</code> only affects the position of the element to which it is applied, relative to elements that appear before it the code.</p>
<p>Disappointing that I can't tell my <code><div></code> to make other divs move down, but them's the breaks. :)</p>
|
<p>When you apply clear to an element, it will move THAT element so that it doesn't have items left or right of it. It does not re-position any of the other elements, it simply moves the element to a position where nothing is around it.</p>
<p><strong>Edit</strong></p>
<p>Items above the item cleared are not moved, items below the element COULD be moved. Also note the additional comment in the comments</p>
|
<p>I generally do the following for that effect:</p>
<pre><code>float: left;
clear: right;
</code></pre>
<p>I don't know if it applies merely to the element to which it is applied, though it makes sense.</p>
<p>The specs are available here, though: <a href="http://www.w3.org/TR/REC-CSS2/" rel="nofollow noreferrer">http://www.w3.org/TR/REC-CSS2/</a></p>
| 26,141
|
<p>Just curious, did I overlook somewhere in the API to display a chat bubble type image as found in the iPhone's SMS application? There's a few applications out there that use bubbles that look verbatim to the iPhone's and I'm wondering if they're using a native widget or their own image.</p>
<p>This is also seen in the Tweetie application where the content of the tweets are.</p>
|
<p>I suggest using the stretch method they recommend for button images.</p>
<pre><code>[UIImage stretchableImageWithLeftCapWidth:15 topCapHeight:13]
</code></pre>
<p>You can see a working example by downloading <a href="http://twitterfon.net/" rel="noreferrer">Twitterfon</a>'s source(it's on the FAQ page). You can see how they code a reusable control for it as well as example images for creating your own bubble.</p>
<p>Edit - Source is no longer available(NDA, possibly)</p>
<p>I put the image up <a href="http://drop.io/jibschx" rel="noreferrer">here</a>. You should be able to figure out the rest :) </p>
|
<p>Many of our applications have chat or messaging facility, and many of the clients are asking to build chat "similar to that iPhone's SMS chat, with bubbles".</p>
<p>Unfortunately, Cocoa SDK does not provide convenient and easy way to display chat bubbles, and numerous code snippets that we've googled were not perfect either - some of them were simply ugly, some displayed bubbles of the same size regardless of text length, some did not alter bubble width, some were good, but barely customizable, etc.</p>
<p>Eventually, Alex - our leading iOS architect (who also happens to be the CTO at Stex) - went ahead and wrote this code from scratch. Main features are:</p>
<ul>
<li>easily (really easily!) customizable and embeddable. The code is based on the UITableView subclassing approach, so once you need to add the chat facility to the app - consider this as simply adding the UITableView, where each cell is a messag</li>
<li>easily customizable bubble's color and style - there's 2 pictures, that can be easily tweaked in Photoshop</li>
<li>time grouping</li>
<li>flexible bubble height and witdh</li>
</ul>
<p>The code can be downloaded from GitHub, <a href="https://github.com/AlexBarinov/UIBubbleTableView" rel="nofollow">https://github.com/AlexBarinov/UIBubbleTableView</a></p>
| 45,782
|
<p>I know this sounds very basic but I just started with visual studio and I am looking for instructions on the basic control functions. In general, what the different options do. I am just trying to get familiar with some of the functions and I am not completely understanding how to manipulate the data. For example, how to trigger information in a textbox after hitting the return button instead of any input change in the window. I know this sounds simple but its very frustrating getting started with the basics. I am looking for a good book or online support forum that gets me over some of the simple hurdles. Also, is there a clock function that I can use as a count down in a program that someone has done.</p>
<p>Thanks</p>
<p>Killing Myself</p>
|
<p><a href="http://www.learnvisualstudio.net/" rel="nofollow noreferrer">http://www.learnvisualstudio.net/</a></p>
<p>excellent tutorial videos, a very good place to start</p>
|
<p>There are some video tutorials about programming in Visual Studio on the Internet. If you like books - take for a start something like lessons in VS.</p>
<p>To handle return button in textbox just handle KeyPressed event and in parameter e you have all necessary information.</p>
<p>To do something like clock you can use Timer component. It fires an event based on the timer interval period.</p>
| 43,111
|
<p>Delphi 2009 complains with an E2283 error: [DCC Error] outputcode.pas(466): E2283 Too many local constants. Use shorter procedures</p>
<p>Delphi 2007 compiles just fine. I can't find an abundance of local constants, it's a short (500 line) unit. Do you see any abundance of constants or literals I can address?</p>
<pre><code>procedure TOutputCodeForm.FormCreate(Sender: TObject);
var
poParser : TStringStream;
begin
if ( IsWindowsVista() ) then
begin
SetVistaFonts( self );
end;
poParser := TStringStream.Create( gstrSQLParser );
SQLParser := TSyntaxMemoParser.Create( self );
SQLParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
SQLParser.UseRegistry := True;
SQLParser.CompileFromStream( poParser );
FreeAndNil( poParser );
poParser := TStringStream.Create( gstrCPPParser );
cppParser := TSyntaxMemoParser.Create( self );
cppParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
cppParser.UseRegistry := True;
cppParser.CompileFromStream( poParser );
FreeAndNil( poParser );
poParser := TStringStream.Create( gstrPasParser );
pasParser := TSyntaxMemoParser.Create( self );
pasParser.RegistryKey := '\Software\Advantage Data Architect\SQLSyntaxMemo';
pasParser.Script := ExtractFilePath( Application.ExeName ) + 'pasScript.txt';
pasParser.CompileFromStream( poParser );
{* Free the stream since we are finished with it. *}
FreeAndNil( poParser );
poCodeOutput := TSyntaxMemo.Create( self );
poCodeOutput.Parent := Panel1;
poCodeOutput.Left := 8;
poCodeOutput.Top := 8;
poCodeOutput.Width := Panel1.Width - 16;
poCodeOutput.Height := Panel1.Height - 16;
poCodeOutput.ClipCopyFormats := [smTEXT, smRTF];
poCodeOutput.Font.Charset := ANSI_CHARSET;
poCodeOutput.Font.Color := clWindowText;
poCodeOutput.Font.Height := -11;
poCodeOutput.Font.Name := 'Courier New';
poCodeOutput.Font.Style := [];
poCodeOutput.GutterFont.Charset := DEFAULT_CHARSET;
poCodeOutput.GutterFont.Color := clWindowText;
poCodeOutput.GutterFont.Height := -11;
poCodeOutput.GutterFont.Name := 'MS Sans Serif';
poCodeOutput.GutterFont.Style := [];
poCodeOutput.HyperCursor := crDefault;
poCodeOutput.IndentStep := 1;
poCodeOutput.Margin := 2;
poCodeOutput.Modified := False;
poCodeOutput.MonoPrint := True;
poCodeOutput.Options := [smoSyntaxHighlight, smoPrintWrap, smoPrintLineNos, smoPrintFilename, smoPrintDate, smoPrintPageNos, smoAutoIndent, smoTabToColumn, smoWordSelect, smoShowRMargin, smoShowGutter, smoShowWrapColumn, smoTitleAsFilename, smoProcessDroppedFiles, smoBlockOverwriteCursor, smoShowWrapGlyph, smoColumnTrack, smoUseTAB, smoSmartFill, smoOLEDragSource];
poCodeOutput.ReadOnly := False;
poCodeOutput.RightMargin := 80;
poCodeOutput.SaveFormat := sfTEXT;
poCodeOutput.ScrollBars := ssBoth;
poCodeOutput.SelLineStyle := lsCRLF;
poCodeOutput.SelStart := 3;
poCodeOutput.SelLength := 0;
poCodeOutput.SelTextColor := clWhite;
poCodeOutput.SelTextBack := clBlack;
poCodeOutput.TabDefault := 4;
poCodeOutput.TabOrder := 0;
poCodeOutput.VisiblePropEdPages := [ppOPTIONS, ppHIGHLIGHTING, ppKEYS, ppAUTOCORRECT, ppTEMPLATES];
poCodeOutput.WrapAtColumn := 0;
poCodeOutput.OnKeyDown := FormKeyDown;
poCodeOutput.ActiveParser := 3;
poCodeOutput.Anchors := [akLeft, akTop, akRight, akBottom];
poCodeOutput.Parser1 := pasParser;
poCodeOutput.Parser2 := cppParser;
poCodeOutput.Parser3 := SQLParser;
SQLParser.AttachEditor( poCodeOutput );
cppParser.AttachEditor( poCodeOutput );
pasParser.AttachEditor( poCodeOutput );
poCodeOutput.Lines.AddStrings( poCode );
if ( CodeType = ctCPP ) then
poCodeOutput.ActiveParser := 2
else if ( CodeType = ctPascal ) then
poCodeOutput.ActiveParser := 1
else
poCodeOutput.ActiveParser := 3;
MainForm.AdjustFormSize( self, 0.95, 0.75 );
end;
</code></pre>
|
<p>Is Win32 defined, could the constants be from all the included units.</p>
<p>i would do a binary search: keep tearing half the unit out until it compiles, then add stuff back in.</p>
<p>Yes it sucks, but that's one of the features of trying to debug BorlandCodeGaembarcadero's internal compiler errors.</p>
|
<p>I've found the method (FormCreate) that is the problem and have been refactoring but no matter how small I make the chunks the compiler still has a problem unless I delete some of the code. </p>
<p>François thanks, but I did refactor the code and still get the error. If it built with D2007, and doesn't with D2009, that seems fishy to me.</p>
<pre><code>procedure TOutputCodeForm.FormCreate(Sender: TObject);
begin
if ( IsWindowsVista() ) then
begin
SetVistaFonts( self );
end;
SetupParser( SQLParser, gstrSQLParser, '' );
// unresolved jmu - have to comment this out for now or delphi will complain
// that there are too many literals in this file. Seems like a delphi bug
// since this builds in older versions, and I've already refactored it.
//SetupParser( cppParser, gstrCPPParser, '' );
SetupParser( pasParser, gstrPasParser, ExtractFilePath( Application.ExeName ) + 'pasScript.txt' );
SetupCodeOutput( poCodeOutput );
SQLParser.AttachEditor( poCodeOutput );
cppParser.AttachEditor( poCodeOutput );
pasParser.AttachEditor( poCodeOutput );
poCodeOutput.Lines.AddStrings( poCode );
if ( CodeType = ctCPP ) then
poCodeOutput.ActiveParser := 2
else if ( CodeType = ctPascal ) then
poCodeOutput.ActiveParser := 1
else
poCodeOutput.ActiveParser := 3;
MainForm.AdjustFormSize( self, 0.95, 0.75 );
end;
</code></pre>
| 30,253
|
<p>I've spent a good amount of time coming up with solution to this problem, so in the spirit of <a href="https://stackoverflow.com/questions/21245/questions-vs-conveying-information">this post</a>, I'm posting it here, since I think it might be useful to others. </p>
<p>If anyone has a better script, or anything to add, please post it.</p>
<p>Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.</p>
|
<p>I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).</p>
<pre><code>
select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from sysobjects so
cross apply
(SELECT
' ['+column_name+'] ' +
data_type + case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'xml' then ''
when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', '
from information_schema.columns where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
</code></pre>
<p><strong>Update:</strong> Added handling of the XML data type</p>
<p><strong>Update 2:</strong> Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name</p>
|
<p>If you are using management studio and have the query analyzer window open you can drag the table name to the query analyzer window and ... bingo! you get the table script.
I've not tried this in SQL2008</p>
| 4,168
|
<p>Lets say I have a Dictionary object:</p>
<pre><code>Dictionary myDictionary<int, SomeObject> = new Dictionary<string, SomeObject>();
</code></pre>
<p>Now I want to iterate through the dictionary in reverse order. I can't use a simple for loop because I don't know the keys of the dictionary. A <em>foreach</em> is easy:</p>
<pre><code>foreach (SomeObject object in myDictionary.Values)
{
// Do stuff to object
}
</code></pre>
<p>But how can I perform this in reverse?</p>
|
<p>A dictionary or any other form of hashtable has no ordering. So what you are trying to do is pointless :)</p>
|
<pre><code>foreach (Sample in Samples)
try the following:
Int32 nEndingSample = Samples.Count - 1;
for (i = nEndingSample; i >= 0; i--)
{
x = Samples[i].x;
y = Samples[i].y;
}
</code></pre>
| 10,855
|
<p>Is it possible to deploy a website using <code>git push</code>? I have a hunch it has something to do with using <a href="http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks" rel="noreferrer">git hooks</a> to perform a <code>git reset --hard</code> on the server side, but how would I go about accomplishing this?</p>
|
<p>I found <a href="https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030">this script</a> on <a href="http://git.or.cz/gitwiki/GitFaq#head-b96f48bc9c925074be9f95c0fce69bcece5f6e73" rel="noreferrer">this site</a> and it seems to work quite well.</p>
<ol>
<li>Copy over your .git directory to your web server</li>
<li><p>On your local copy, modify your .git/config file and add your web server as a remote:</p>
<pre><code>[remote "production"]
url = username@webserver:/path/to/htdocs/.git
</code></pre></li>
<li><p>On the server, replace .git/hooks/post-update with <a href="https://stackoverflow.com/questions/279169/deploy-php-using-git/3387030#3387030">this file</a> (in the answer below)</p></li>
<li><p>Add execute access to the file (again, on the server):</p>
<pre><code>chmod +x .git/hooks/post-update
</code></pre></li>
<li><p>Now, just locally push to your web server and it should automatically update the working copy:</p>
<pre><code>git push production
</code></pre></li>
</ol>
|
<p>Given an environment where you have multiple developers accessing the same repository the following guidelines may help.</p>
<p>Ensure that you have a unix group that all devs belong to and give ownership of the .git repository to that group.</p>
<ol>
<li><p>In the .git/config of the server repository set sharedrepository = true. (This tells git to allow multiple users which is needed for commits and deployment.</p></li>
<li><p>set the umask of each user in their bashrc files to be the same - 002 is a good start </p></li>
</ol>
| 35,263
|
<p>I am using the <strong>System.Messaging.MessageQueue</strong> to send and receive multicast <strong>System.Messaging.Messag</strong>e’s on my LAN – this works fine.</p>
<p>However, I have a requirement to receive the msgs without using a message queue.</p>
<p>As the <strong>MessageQueue</strong> uses the PGM protocol (113) to send messages I am trying to build a type that listens on PGM (protocol 113) using a socket (e.g. new <strong>Socket(AddressFamily.InterNetwork, SocketType.Rdm, (ProtocolType)113);</strong>). The type is receiving message data but it is in a text format (with a soap formatter section -see example this example on msdn <a href="http://msdn.microsoft.com/en-us/library/cc219170.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc219170.aspx</a>)</p>
<p>I obviously want binary data so i can cast it into a <strong>System.Messaging.Message</strong> and get at the real data.</p>
<p>Any ideas on how i can do this are greatly appreciated . </p>
|
<p>If you are looking purely for PGM use on MS Windows then <a href="http://code.google.com/p/emcaster/" rel="nofollow noreferrer">Emcaster</a> is very good info source with example how to use it.</p>
<p>But if you are looking for more mature solution with broader range of capability then <a href="http://www.nservicebus.com/Default.aspx" rel="nofollow noreferrer">nServiceBus</a> framework should be your choice. </p>
|
<p>You can just peek at them? The MSMQ supports that functionality. Or are you just trying to read messages on queues you don't typically listen on?</p>
| 29,217
|
<p>How do I multiply 10 to an <code>Integer</code> object and get back the <code>Integer</code> object?</p>
<p>I am looking for the neatest way of doing this.</p>
<p>I would probably do it this way:
Get int from <code>Integer</code> object, multiply it with the other int and create another Integer object with this int value.</p>
<p>Code will be something like ... </p>
<pre><code>integerObj = new Integer(integerObj.intValue() * 10);
</code></pre>
<p>But, I saw a code where the author is doing it this way: Get the <code>String</code> from the <code>Integer</code> object, concatenate "0" at the end and then get <code>Integer</code> object back by using <code>Integer.parseInt</code></p>
<p>The code is something like this:</p>
<pre><code>String s = integerObj + "0";
integerObj = Integer.parseInt(s);
</code></pre>
<p>Is there any merit in doing it either way?</p>
<p>And what would be the most efficient/neatest way in general and in this case?</p>
|
<p>With Java 5's <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html" rel="nofollow noreferrer">autoboxing</a>, you can simply do:</p>
<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;
a *= 10;
System.out.println(a);
</code></pre>
|
<p>toolkit's answer above is correct and the best way, but it doesn't give a full explanation of what is happening.
Assuming Java 5 or later:</p>
<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;
a *= 10;
System.out.println(a); // will output 20
</code></pre>
<p>What you need to know is that this is the exact same as doing:</p>
<pre><code>Integer a = new Integer(2); // or even just Integer a = 2;
a = a.intValue() * 10;
System.out.println(a.intValue()); // will output 20
</code></pre>
<p>By performing the operation (in this case *=) on the object 'a', you are not changing the int value inside the 'a' object, but actually assigning a new object to 'a'.
This is because 'a' gets auto-unboxed in order to perform the multiplication, and then the result of the multiplication gets auto-boxed and assigned to 'a'.</p>
<p>Integer is an immutable object. (All wrapper classes are immutable.)</p>
<p>Take for example this piece of code:</p>
<pre><code>static void test() {
Integer i = new Integer(10);
System.out.println("StartingMemory: " + System.identityHashCode(i));
changeInteger(i);
System.out.println("Step1: " + i);
changeInteger(++i);
System.out.println("Step2: " + i.intValue());
System.out.println("MiddleMemory: " + System.identityHashCode(i));
}
static void changeInteger(Integer i) {
System.out.println("ChangeStartMemory: " + System.identityHashCode(i));
System.out.println("ChangeStartValue: " + i);
i++;
System.out.println("ChangeEnd: " + i);
System.out.println("ChangeEndMemory: " + System.identityHashCode(i));
}
</code></pre>
<p>The output will be:</p>
<pre><code>StartingMemory: 1373539035
ChangeStartMemory: 1373539035
ChangeStartValue: 10
ChangeEnd: 11
ChangeEndMemory: 190331520
Step1: 10
ChangeStartMemory: 190331520
ChangeStartValue: 11
ChangeEnd: 12
ChangeEndMemory: 1298706257
Step2: 11
MiddleMemory: 190331520
</code></pre>
<p>You can see the memory address for 'i' is changing (your memory addresses will be different).</p>
<p>Now lets do a little test with reflection, add this onto the end of the test() method:</p>
<pre><code>System.out.println("MiddleMemory: " + System.identityHashCode(i));
try {
final Field f = i.getClass().getDeclaredField("value");
f.setAccessible(true);
f.setInt(i, 15);
System.out.println("Step3: " + i.intValue());
System.out.println("EndingMemory: " + System.identityHashCode(i));
} catch (final Exception e) {
e.printStackTrace();
}
</code></pre>
<p>The additional output will be:</p>
<pre><code>MiddleMemory: 190331520
Step2: 15
MiddleMemory: 190331520
</code></pre>
<p>You can see that the memory address for 'i' did not change, even though we changed its value using reflection.<br>
(DO NOT USE REFLECTION THIS WAY IN REAL LIFE!!)</p>
| 6,799
|
<p>Does any one know as to why Java does not allow you to switch on numbers larger than integers? Is there any technical reason behind this?</p>
|
<p>As said <a href="http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html" rel="noreferrer">here</a>, switch works with the byte, short, char, and int primitive data types. It also works with enumerated types and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer. </p>
<p>The Java switch statement is compiled into the <a href="http://www.artima.com/underthehood/flowP.html" rel="noreferrer">JVM bytecode tableswitch or lookupswitch</a>. Both of these bytecodes require that the case values be unique, 32-bit, integer, compile-time constants.</p>
<p>The tableswitch and lookupswitch instructions both include one default branch offset and a variable-length set of case value/branch offset pairs.<br>
Both instructions pop the key (the value of the expression in the parentheses immediately following the switch keyword) from the stack.<br>
The key is compared with all the case values:</p>
<ul>
<li>If a match is found, the branch offset associated with the case value is taken. </li>
<li>If no match is found, the default branch offset is taken. </li>
</ul>
<p>Even though the above represents implementation details, I believe <strong>the types used for switch are the one compatible with an efficient bytecode for control flow</strong>, and it may have been an important part for the reason of this choice.</p>
<p>As said in this <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4276296" rel="noreferrer">Java Bug</a>:</p>
<blockquote>
<p>I suppose you could allow Java switch statement cases to include other types of values, and compile a switch statement that uses one of those kinds of values into other bytecode, such as a sequence of ifs and gotos. But then we'd have to examine all switch statements carefully in order to determine if it will be compiled into a fast switch bytecode or a slow sequence of if-elses.</p>
</blockquote>
<p>As said in this other <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4401321" rel="noreferrer">Java bug</a></p>
<blockquote>
<p>'switch' statements can use function-table dispatch and/or binary-tree search to match the case statements faster than just testing them one by one in order.</p>
</blockquote>
|
<p>Maybe because it's really bad programming to have more than integer max cases in a switch?</p>
<p>If you want to switch over long variables, just projet them in the interger space.</p>
| 39,696
|
<p>A lot of times in code on the internet or code from my co-workers I see them creating an Object with just one method which only gets used once in the whole application. Like this:</p>
<pre><code> class iOnlyHaveOneMethod{
public function theOneMethod(){
//loads and loads of code, say 100's of lines
// but it only gets used once in the whole application
}
}
if($foo){
$bar = new iOnlyHaveOneMEthod;
$bar->theOneMethod();
}
</code></pre>
<p>Is that really better then:</p>
<pre><code>if($foo){
//loads and loads of code which only gets used here and nowhere else
}
</code></pre>
<p>?<br>
For readability it makes sense to move the loads and loads of code away, but shouldn't it just be in a function?</p>
<pre><code>function loadsAndLoadsOfCode(){
//Loads and loads of code
}
if($foo){ loadsAndLoadsOfCode(); }
</code></pre>
<p>Is moving the code to a new object really better then just creating a function or putting the code in there directly?<br>
To me the function part makes more sense and seems more readible then creating an object which hardly is of any use since it just holds one method.</p>
|
<p>The problem is not whether it's in a function or an object. </p>
<p>The problem is that you have hundreds of lines in one blob. Whether that mass of code is in a method of an object or just a class seems more or less irrelevant to me, just being minor syntatic sugar. </p>
<p>What are those hundreds of lines doing? That's the place to look to implement object oriented best practice. </p>
<p>If your other developers really think using an object instead of a function makes it significantly more "object oriented" but having a several-hundred line function/method isn't seen as a code smell, then I think organisationally you have some education to do.</p>
|
<p>yes, the presences of loads and loads of code is a <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">Code Smell</a>.</p>
| 47,835
|
<p>My company releases a small software product for which I've recently been taking over the development side. It is a C# Windows Forms application.</p>
<p>One of the things I've noticed is that much of the information about how the software is used is filtered through my superiors and I get the feeling that I'm missing important detail in some of the messages.</p>
<p>I realise I'll have to work on the management issues with this situation, however in order to give another view on the problem I've been considering a technological solution. Perhaps something similar to the "Microsoft Customer Experience Improvement Program".</p>
<p>I was wondering if anyone out there had any experience or advice monitoring and reporting on user behaviour in their applications?</p>
|
<p>I would suggest you get your application to write its "usage information" somewhere and then, <em>with the users permission</em>, transmit it electronically every so often.</p>
<p>Note the emphasis above. Depending on your jurisdiction, you could get into serious trouble transmitting any sort of data from someone else's computer without permission.</p>
<p>You're more likely to get permission if:</p>
<p>1/ You make it clear, on install or update, that your program will collect information and transmit it only with permission.</p>
<p>2/ You explain clearly what the information is and that it only holds "usage information", nothing that can be traced back to the user of the software (NO serial numbers, etc).</p>
<p>3/ You request permission to transmit infrequently. If I had an obnoxious program that asked me daily, I'd soon stop using it altogether.</p>
|
<p>I believe that you've already received a good answer to your question re the privacy aspect of the technological solution.</p>
<p>I would also like to mention that you should try to use HTTP or HTTPS over normal 80/443 ports - these are the least likely to cause problems with the firewalls and proxy. Use MS IE proxy settings as they are usually set properly.</p>
<hr>
<p>From a totally different prospective I would like to say that the best way to learn about the usage of your software is to check if you have any 'friendly' users in your install base and interview them.
It could be some partner company or people who are your 'pilot group' for the betas of new release. Talk to them. Grap your manager and spend a day going to their site if possible and just seeing for yourself how and then they click the buttons. Make notes. Listen to the feedback. Establish personal relationship so next time they talk to you directly.</p>
<p>If your application is small and your company is no Microsoft its much better to be close to your userbase than to collect anonymous usage data which takes significant effort to collect and process and then even more effort to understand.</p>
| 17,336
|
<p>I am using SQL Advantage and need to know what the SQL is to identify the triggers associated with a table. I don't have the option to use another tool so the good old fashioned SQL solution is the ideal answer.</p>
|
<p>I also found out that </p>
<pre><code>sp_depends <object_name>
</code></pre>
<p>will show you a lot of information about a table, including all triggers associated with it. Using that, along with Ray's query can make it much easier to find the triggers. Combined with this query from Ray's linked article:</p>
<pre><code>sp_helptext <trigger_name>
</code></pre>
<p>and you can see the definition of the trigger:</p>
<pre><code>sp_depends <trigger_name>
</code></pre>
<p>will also show you all tables related to a trigger</p>
|
<ol>
<li>Open Sybase Central and navigate to the triggers view.</li>
<li>Click on the "Object Name" column to sort. </li>
</ol>
<p>The "Object Name" column apparently shows the table associated with the trigger. Scroll down to the table you're interested in.</p>
| 41,165
|
<p>I knew ActionScript and ActionScript2 inside out, but I've been away from Flash for a couple years. What's the magnitude of becoming fluent in ActionScript3 and the new Flash functionality? From Colin Moock's blog, I heard that some of the fundamental movieclip methods have changed...</p>
|
<p>You've probably already seen the <a href="http://livedocs.adobe.com/flex/3/langref/migration.html" rel="noreferrer">as2 -> as3 migration doc</a>?</p>
<p>Sure, some syntax has changed but if you know as2 well writing as3 won't be a problem at all. Some weird things may come up in the beginning with the syntax, but that's just checking the documentation for the new way of doing it. If you're hacking yourself through as1 & as2, as3 may cause some headaches since it's much stricter (doesn't allow you to do stuff you shouldn't do anyway) ;)</p>
<p>You'll probably be fine with as3 in less than a week.</p>
|
<p>Actionscript3 is indeed far different in many ways, but it is important to realize that you are merely memorizing built-in packages, classes, properties, and methods as similar to learning prior versions. Some of the larger hurdles to get over are the Display list and events (event flow > Example: Bubbling). Much of the language has been changed to the developers advantage, such as a unified way of loading dynamic assets with the Loader class for display objects or the URLLoader class for loading data such as XML and CSS, or calling a php script. Once you feel confident with some of these new aspects of the language you can begin extending prior classes or creating new ones. Actionsscript3 may have a steep learning curve, but the opposite side of the hill is almost equally as steep!. After you have your eye opening, "OH, I GET IT!" moment, it is an addictive and thrilling ride. The possibilities become seemingly limitless and soon your developing whatever comes to mind!</p>
<p>I suggest that anyone that wants to learn proper techniques, conventions, and workflow, please head to <a href="http://www.gotoandlearn.com" rel="nofollow noreferrer">http://www.gotoandlearn.com</a> where Lee Brimelow does an excellent job displaying leading edge techniques and effects. Lee also authors <a href="http://theflashblog.com" rel="nofollow noreferrer">http://theflashblog.com</a> which I personally check daily.</p>
| 12,559
|
<p>Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?</p>
<p>It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.</p>
<pre>
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.3 -> 1.3.1
drwxr-xr-x 3 root wheel 102 Jan 14 2008 1.3.1
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.4 -> 1.4.2
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 1.4.1 -> 1.4
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.4.2
lrwxr-xr-x 1 root wheel 5 Feb 21 2008 1.5 -> 1.5.0
drwxr-xr-x 8 root wheel 272 Feb 21 2008 1.5.0
lrwxr-xr-x 1 root wheel 5 Jun 14 15:49 1.6 -> 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 1.6.0
drwxr-xr-x 8 root wheel 272 Jun 14 15:49 A
lrwxr-xr-x 1 root wheel 1 Jun 14 15:49 Current -> A
lrwxr-xr-x 1 root wheel 3 Jun 14 15:49 CurrentJDK -> 1.5
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions $
</pre>
<p>and the contents of A</p>
<pre>
-rw-r--r-- 1 root wheel 1925 Feb 29 2008 CodeResources
drwxr-xr-x 34 root wheel 1156 Jun 14 15:49 Commands
drwxr-xr-x 3 root wheel 102 Mar 6 2008 Frameworks
drwxr-xr-x 16 root wheel 544 Jun 14 15:49 Headers
-rwxr-xr-x 1 root wheel 236080 Feb 29 2008 JavaVM
drwxr-xr-x 29 root wheel 986 Jun 14 15:49 Resources
steve-mbp /System/Library/Frameworks/JavaVM.framework/Versions/A $
</pre>
|
<p>The (<code>A</code>, <code>Current</code> symbolic-linked to <code>A</code>) is part of the structure of a Mac OS X framework, which <code>JavaVM.framework</code> is. This framework may have C or Objective-C code in it, in addition to the actual JVM installations. Thus it could potentially be linked against from some C or Objective-C code in addition to containing the JVM alongside that.</p>
<p>Note that you <strong>should not</strong> change the <code>CurrentJDK</code> link to point at anything but what it is set to by Mac OS X. Unlike on other platforms, the Java virtual machine is an operating system service on Mac OS X, and changing it in this way would put you in an unsupported (and potentially untested, unstable, etc.) configuration.</p>
|
<p>If you want to revert to an older JVM (here, 1.5), you can put the following in your <code>~/.profile</code> (or paste it into a specific Terminal window):</p>
<pre><code>export JAVA_HOME="/System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/"
export PATH=$JAVA_HOME/bin/:$PATH
</code></pre>
| 18,251
|
<p>I am creating a component and want to expose a color property as many flex controls do, lets say I have simple component like this, lets call it foo_label:</p>
<pre>
<code>
<mx:Canvas>
<mx:Script>
[Bindable] public var color:uint;
</mx:Script>
<mx:Label text="foobar" color="{color}" />
</mx:Canvas>
</code>
</pre>
<p>and then add the component in another mxml file, something along the lines of:</p>
<pre>
<code>
<foo:foo_label color="red" />
</code>
</pre>
<p>When I compile the compiler complains: cannot parse value of type uint from text 'red'. However if I use a plain label I can do</p>
<pre><code><mx:Label text="foobar" color="red"></code></pre>
<p>without any problems, and the color property is still type uint. </p>
<p>My question is how can I expose a public property so that I can control the color of my components text? Why can I use the string "red" as a uint field for the mx controls but cannot seem to do the same in a custom component, do I need to do something special?</p>
<p>Thanks.</p>
|
<p>Color is not a property, it is a style. You need to define the style like this:</p>
<pre><code>[Style(name="labelColor", type="uint", format="Color" )]
</code></pre>
<p>(enclose it in tag if you define it directly in MXML). You then need to add some ActionScript to handle this style and apply it to whichever control you need, please refer to <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html" rel="noreferrer">http://livedocs.adobe.com/flex/3/html/help.html?content=skinstyle_1.html</a> for more information.</p>
|
<p>Here you are 2 of my utils functions:</p>
<pre><code> public static function convertUintToString( color:uint ):String {
return color.toString(16);
}
public static function convertStringToUint(value:String, mask:String):uint {
var colorString:String = "0x" + value;
var colorUint:uint = mx.core.Singleton.getInstance("mx.styles::IStyleManager2").getColorName( colorString );
return colorUint;
}
</code></pre>
| 15,913
|
<p>What is the best was to evaluate an expression like the following:
<br />
(A And B) Or (A And C) Or (Not B And C)<br />
or<br />
(A && B) || (A && C) || (!B && C)<br /></p>
<p>At runtime, I was planning on converting the above expressions to the following:<br />
(True And False) Or (True And False) Or (Not False And True)<br />
or<br />
(True && False) || (True && False) || (! False && True)<br /></p>
<p>Conditions:
1) The logical expression is not known until runtime.
2) The number variable and their values are not known until runtime.
3) Variable values are never null.</p>
<p>I know I could create a simple assemble with a class and a method that I generate at runtime based on the inputs, but is there a better way.
I have done this before. Use a string builder to write the code, then call the compiler. After that, you load the assembly and call the method. </p>
<p>Suggestions?</p>
<p>Thanks.</p>
|
<p>If you're using .NET3.5 then you can parse the text and create an abstract sytax tree using the Expression classes. Then create a suitable LambdaExpression instance and compile it into a delegate, which you can then execute.</p>
<p>Constructing a parser and syntax tree builder for this kind of fairly simple grammer is quite an interesting exercise, and will execute somewhat faster than invoking the compiler (and it's neater in my view as well).</p>
<p>If you're not using .NET3.5, then it's also not complicated to implement an interpreted abstract syntax tree yourself.</p>
|
<p>You can write a simple interpreter/parser. Use something like <a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> and reuse existing grammars.</p>
| 45,575
|
<p>I am working with a PC based automation software package called Think'n'Do created by <a href="http://www.phoenixcontact.com" rel="nofollow noreferrer">Phoenix Contact</a> It does real time processing, read inputs/ control logic / write outputs all done in a maximum of 50ms. We have an OPC server that is reading/writing tags from a PLC every 10ms. There is a long delay in writing a tag to the PLC and reading back the written value (Think'n'Do (50ms) > OPC Server (10ms) > PLC (10ms) > OPC Server (10ms) > Think'n'Do (50ms) ) that process takes up to 6 seconds to complete when it should by my math only take 130ms.</p>
<p>Any ideas of where to look or why it might be taking so much longer would be helpful.</p>
|
<p>It depends on how you have your OPC client configured to pull data. When you subscribe to a group in OPC, you get to specify a refresh rate. This might default to 1s or even 5s, depending on the OPC client. There's also a limit the OPC server might put on the frequency of updated data. This only applies if you have your OPC client subscribing to data change events.</p>
<p>The other way you can go is to do async or sync reads / writes to the OPC server. There are several reading modes as well. Since you are using OPC, you can use any OPC compatible client to test your server, this will tell you if the problem is with a setting in Think'n'Do or is it something with the PLC / server.</p>
<p>The best general purpose OPC client I've used is OPC Quick Client. You can get it with TOP Server here: <a href="http://www.toolboxopc.com/Features/Demo/demo.shtml" rel="noreferrer">http://www.toolboxopc.com/Features/Demo/demo.shtml</a>. Just grab the TOP Server demo and install the OPC Quick Client. You can use it to connect to your OPC server and browse the tags and see what the data looks like. The second best OPC client I've used is from ICONICS (called OPC Data Spy) available here: <a href="http://www.iconics.com/support/free_tools.asp" rel="noreferrer">http://www.iconics.com/support/free_tools.asp</a>.</p>
<p>Use the OPC client to see how fast you can read the data. Make sure you set the group refresh rate correctly. I think the tools might provide some timing information for you as well (but you'll be able to figure out a 6 second delay pretty easily).</p>
|
<p>Here are a few places to look: OPC Client configuration, OPC Client itself, OPC Server, or the PLC itself. </p>
<p>Here are things you should check:</p>
<ol>
<li>OPC Client configuration - The OPC Group you've added the OPC tags to should have a fast scan rate (ie. 100 ms to 1 sec depending on what you use it for). With the act of writing values, do you notice if the values come in faster? If not, then there might be a DCOM or network configuration issue.</li>
<li>OPC Client - Download a free OPC Client software(probably from the OPC Foundation website or major OPC Server software vendors) to see if you get the values back faster. If so, there might be a problem with your client.</li>
<li>OPC Server - Some OPC Server have diagnostic tools. Turn those on and see what is the time the writes actually occur and what time the reads actually take place. If you can answer those questions, you can probably identify whether the culprit of the delay is from the PLC or the OPC Server. Also observe the CPU usage of the OPC Server, if you notice it is using more CPU than normal, it probably means that the OPC Server is loaded down which might deteriorate performance.</li>
<li>Others - Finally check PLC, network are working properly.</li>
</ol>
| 6,118
|
<p>I am still very new to Ruby (reading through the Pickaxe and spending most of my time in <code>irb</code>), and now that I know it's possible to patch classes in Ruby, I'm wondering when it's acceptable to do so, specifically whether it's acceptable to patch Ruby's base classes. For example: I answered another Ruby question <a href="https://stackoverflow.com/questions/238684/subtract-n-hours-from-a-datetime-in-ruby#238718">here</a> where the poster wanted to know how to subtract hours from a <code>DateTime</code>. Since the <code>DateTime</code> class doesn't seem to provide this functionality, I posted an answer that patches the <code>DateTime</code> and <code>Fixnum</code> classes as a possible solution. This is the code I submitted:</p>
<pre><code>require 'date'
# A placeholder class for holding a set number of hours.
# Used so we can know when to change the behavior
# of DateTime#-() by recognizing when hours are explicitly passed in.
class Hours
attr_reader :value
def initialize(value)
@value = value
end
end
# Patch the #-() method to handle subtracting hours
# in addition to what it normally does
class DateTime
alias old_subtract -
def -(x)
case x
when Hours; return DateTime.new(year, month, day, hour-x.value, min, sec)
else; return self.old_subtract(x)
end
end
end
# Add an #hours attribute to Fixnum that returns an Hours object.
# This is for syntactic sugar, allowing you to write "someDate - 4.hours" for example
class Fixnum
def hours
Hours.new(self)
end
end
</code></pre>
<p>I patched the classes because I thought in this instance it would result in a clear, concise syntax for subtracting a fixed number of hours from a <code>DateTime</code>. Specifically, you could do something like this as a result of the above code:</p>
<pre><code>five_hours_ago = DateTime.now - 5.hours
</code></pre>
<p>Which seems to be fairly nice to look at and easy to understand; however, I'm not sure whether it's a good idea to be messing with the functionality of <code>DateTime</code>'s <code>-</code> operator.</p>
<p>The only alternatives that I can think of for this situation would be:</p>
<p><strong>1. Simply create a new <code>DateTime</code> object on-the-fly, computing the new hour value in the call to <code>new</code></strong>
<br/></p>
<pre><code>new_date = DateTime.new(old_date.year, old_date.year, old_date.month, old_date.year.day, old_date.hour - hours_to_subtract, date.min, date.sec)
</code></pre>
<p><br/>
<strong>2. Write a utility method that accepts a <code>DateTime</code> and the number of hours to subtract from it</strong>
<br/></p>
<p>Basically, just a wrapper around method (1):</p>
<pre><code>def subtract_hours(date, hours)
return DateTime.new(date.year, date.month, date.day, date.hour - hours, date.min, date.sec)
end
</code></pre>
<p><br/>
<strong>3. Add a new method to <code>DateTime</code> instead of changing the existing behavior of <code>#-()</code></strong></p>
<p>Perhaps a new <code>DateTime#less</code> method that could work together with the <code>Fixnum#hours</code> patch, to allow syntax like this:</p>
<pre><code>date.less(5.hours)
</code></pre>
<hr/>
<p>However, as I already mentioned, I took the patching approach because I thought it resulted in a much more expressive syntax.</p>
<p>Is there anything wrong with my approach, or should I be using one of the 3 alternatives (or another one I haven't thought of) in order to do this? I have the feeling that patching is becoming my new 'hammer' for problems in Ruby, so I'd like to get some feedback on whether I'm doing things the "Ruby way" or not.</p>
|
<p>My personal answer, in a nutshell: <a href="http://avdi.org/devblog/2008/02/25/full-disclosure/" rel="noreferrer">the core-class patching hammer should be at the bottom of your toolbox</a>. There are a lot of other techniques available to you, and in almost all cases they are sufficient, cleaner, and more <a href="http://avdi.org/devblog/2008/03/25/sustainable-development-in-ruby-introduction/" rel="noreferrer">sustainable</a>.</p>
<p>It really depends on the environment in which you are coding, though. If it's a personal project - sure, patch to your heart's content! The problems begin to arise when you are working on a large codebase over a long period of time with a large group of programmers. In the organization I work for, which has Ruby codebases of over 100KLOC and and twenty or so developers, we have started to crack down pretty hard on monkey patching, because we've seen it lead to head-scratching, man-hour wasting behavior far too often. At this point we pretty much only tolerate it for temporarily patching third-party code which either hasn't yet incorporated or won't incorporate our source patches.</p>
|
<p>I think its like this: If you honestly feel that most other programmers would agree with your patches, then fine. If not, perhaps you should instead be implementing a code library?</p>
| 29,549
|
<p>I've recently embarked upon the <em>grand voyage</em> of Wordpress theming and I've been reading through the Wordpress documentation for how to write a theme. One thing I came across <a href="http://codex.wordpress.org/Theme_Development" rel="nofollow noreferrer">here</a> was that the <code>style.css</code> file must contain a specific header in order to be used by the Wordpress engine. They give a brief example but I haven't been able to turn up any formal description of what must be in the <code>style.css</code> header portion. Does this exist on the Wordpress site? If it doesn't could we perhaps describe it here?</p>
|
<p>Based on <a href="http://codex.wordpress.org/Theme_Development" rel="nofollow noreferrer">http://codex.wordpress.org/Theme_Development</a>:</p>
<p>The following is an example of the first few lines of the stylesheet, called the style sheet header, for the Theme "Rose":</p>
<pre><code>/*
Theme Name: Rose
Theme URI: the-theme's-homepage
Description: a-brief-description
Author: your-name
Author URI: your-URI
Template: use-this-to-define-a-parent-theme--optional
Version: a-number--optional
Tags: a-comma-delimited-list--optional
.
General comments/License Statement if any.
.
*/
</code></pre>
<p>The simplest Theme includes only a style.css file, plus images if any. To create such a Theme, you must specify a set of templates to inherit for use with the Theme by editing the Template: line in the style.css header comments. For example, if you wanted the Theme "Rose" to inherit the templates from another Theme called "test", you would include Template: test in the comments at the beginning of Rose's style.css. Now "test" is the parent Theme for "Rose", which still consists only of a style.css file and the concomitant images, all located in the directory wp-content/themes/Rose. (Note that specifying a parent Theme will inherit all of the template files from that Theme — meaning that any template files in the child Theme's directory will be ignored.)</p>
<p>The comment header lines in style.css are required for WordPress to be able to identify a Theme and display it in the Administration Panel under Design > Themes as an available Theme option along with any other installed Themes. </p>
<p>The Theme Name, Version, Author, and Author URI fields are parsed by WordPress and used to display that data in the Current Theme area on the top line of the current theme information, where the Author's Name is hyperlinked to the Author URI. The Description and Tag fields are parsed and displayed in the body of the theme's information, and if the theme has a parent theme, that information is placed in the information body as well. In the Available Themes section, only the Theme Name, Description, and Tags fields are used.</p>
<p>None of these fields have any restrictions - all are parsed as strings. In addition, none of them are required in the code, though in practice the fields not marked as optional in the list above are all used to provide contextual information to the WordPress administrator and should be included for all themes.</p>
|
<p>You are probably thinking about this:</p>
<pre><code>/*
THEME NAME: Parallax
THEME URI: http://parallaxdenigrate.net
VERSION: .1
AUTHOR: Martin Jacobsen
AUTHOR URI: http://martinjacobsen.no
*/
</code></pre>
<p>If I'm not way off, Wordpress uses this info to display in the "Activate Design" dialog in the admin backend.</p>
| 11,234
|
<p>In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.</p>
<p>My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles.</p>
<pre><code>#include <fstream>
#include <sstream>
using namespace std;
int main() {
ifstream is;
is.open (sFilename.c_str(), ios::binary );
// get length of file:
is.seekg (0, std::ios::end);
long length = is.tellg();
is.seekg (0, std::ios::beg);
// allocate memory:
char *buffer = new char [length];
// read data as a block:
is.read (buffer,length);
// create string stream of memory contents
// NOTE: this ends up copying the buffer!!!
istringstream iss( string( buffer ) );
// delete temporary buffer
delete [] buffer;
// close filestream
is.close();
/* ==================================
* Use iss to access data
*/
}
</code></pre>
|
<p><code>std::ifstream</code> has a method <code>rdbuf()</code>, that returns a pointer to a <code>filebuf</code>. You can then "push" this <code>filebuf</code> into your <code>stringstream</code>:</p>
<pre><code>#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
// operations on the buffer...
}
}
</code></pre>
<p>EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the <code>stringstream</code>'s <code>operator<<</code> will read the filebuf character by character. You might want to check his answer, where he uses the <code>ifstream</code>'s <code>read</code> method as you used to do, and then set the <code>stringstream</code> buffer to point to the previously allocated memory.</p>
|
<p>This seems like premature optimization to me. How much work is being done in the processing. Assuming a modernish desktop/server, and not an embedded system, copying a few MB of data during intialization is fairly cheap, especially compared to reading the file off of disk in the first place. I would stick with what you have, measure the system when it is complete, and the decide if the potential performance gains would be worth it. Of course if memory is tight, this is in an inner loop, or a program that gets called often (like once a second), that changes the balance. </p>
| 16,049
|
<p>I want to change the behavior of a JavaScript used to display a banner, coming from a central source.</p>
<p>Today I include a script-tag inline in code, like this:</p>
<pre><code><script type="text/javascript" src="http://banner.com/b?id=1234"></script>
</code></pre>
<p>But what that returns is code which uses <code>document.write</code>, like this:</p>
<pre><code>if(condition) {
document.write('<a href="..."><img src="..." /></a>')
}
</code></pre>
<p>I want to somehow override this <code>document.write</code> and maybe evaluate the returned code and instead use a JavaScript-framework to bind code to a div-element at DOM ready.</p>
<p>Is there a way to do that? Something like this?:</p>
<pre><code>OnDOMReady() {
BindBanner(1234);
}
BindBanner(bannerId) {
var divTag = document.getElementById('banner_' + bannerId);
divTag.innerHtml = ManipulatedReturenedCode(bannerId);
}
</code></pre>
<p>Can JavaScript's prototyping handle something like this?</p>
<p><strong>Edit</strong>: It has to be somewhat waterproof cross-platform, cross-browser-compatible, so I don't know if changing <code>document.write</code> is ok.</p>
|
<p>Yes, you can override document.write. Prototyping is not necessary, you can do it directly on the document object itself. I do this commonly for analysing malware, but it could certainly be used to capture ad script output, as long as the ad script doesn't do any particularly convoluted processing that would turn up the difference between document.write and whatever you replaced it with.</p>
<p>Here's a wrapper that loads an ad onload (slightly later than DOMReady):</p>
<pre><code><div id="advertgoeshere"></div>
<script type="text/javascript">
function rewrite(w) {
document.getElementById('advertgoeshere').innerHTML+= w;
}
window.onload= function() {
document.write= rewrite;
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://externalsite/ads.js';
document.body.appendChild(script);
}
</script>
</code></pre>
|
<p>Why not use jQuery? It has a DOM ready function:</p>
<pre><code>$.ready(function() {
});
</code></pre>
<p>Then you can easily manipulate an element using</p>
<pre><code>$("#div_id").html
</code></pre>
| 40,924
|
<p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p>
<p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p>
<p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p>
<p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>
|
<p>You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow. </p>
<pre><code> using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
class ExampleEventArgs : EventArgs
{
public int IntArg {get; set;}
}
class EventRaiser
{
public event EventHandler SomethingHappened;
public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg;
public void RaiseEvents()
{
if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);
if (SomethingHappenedWithArg!=null)
{
SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});
}
}
}
class Handler
{
public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");}
public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg); }
}
static class EventProxy
{
//void delegates with no parameters
static public Delegate Create(EventInfo evt, Action d)
{
var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, EventArgs x1) => d()
var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x"));
var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"));
var lambda = Expression.Lambda(body,parameters.ToArray());
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
//void delegate with one parameter
static public Delegate Create<T>(EventInfo evt, Action<T> d)
{
var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg)
var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")).ToArray();
var arg = getArgExpression(parameters[1], typeof(T));
var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg);
var lambda = Expression.Lambda(body,parameters);
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
//returns an expression that represents an argument to be passed to the delegate
static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)
{
if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int))
{
//"x1.IntArg"
var memberInfo = eventArgs.Type.GetMember("IntArg")[0];
return Expression.MakeMemberAccess(eventArgs,memberInfo);
}
throw new NotSupportedException(eventArgs+"->"+handlerArgType);
}
}
static class Test
{
public static void Main()
{
var raiser = new EventRaiser();
var handler = new Handler();
//void delegate with no parameters
string eventName = "SomethingHappened";
var eventinfo = raiser.GetType().GetEvent(eventName);
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));
//void delegate with one parameter
string eventName2 = "SomethingHappenedWithArg";
var eventInfo2 = raiser.GetType().GetEvent(eventName2);
eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg));
//or even just:
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine("!")));
eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+"!")));
raiser.RaiseEvents();
}
}
</code></pre>
|
<p>Do you mean something like:</p>
<pre><code>//reflect out the method to fire as a delegate
EventHandler eventDelegate =
( EventHandler ) Delegate.CreateDelegate(
typeof( EventHandler ), //type of event delegate
objectWithEventSubscriber, //instance of the object with the matching method
eventSubscriberMethodName, //the name of the method
true );
</code></pre>
<p>This doesn't do the subscription, but will give to the method to call.</p>
<p>Edit: </p>
<p>Post was clarified after this answer, my example won't help if you don't know the type. </p>
<p>However all events in .Net should follow the default event pattern, so as long as you've followed it this will work with the basic EventHandler.</p>
| 6,777
|
<p>I'm trying to set up an enclosed (custom enclosure) Prusa i3 style printer for ABS, but having a fair amount of difficulty preventing the part corners from curling.</p>
<p><a href="https://i.stack.imgur.com/k9YT6.png" rel="nofollow noreferrer" title="Example of curling at part corners"><img src="https://i.stack.imgur.com/k9YT6.png" alt="Example of curling at part corners" title="Example of curling at part corners"></a></p>
<p>Detailed specs:</p>
<ul>
<li>Geetech A10 (generic Prusa clone) w/ PEI heatbed</li>
<li>Custom enclosure</li>
<li>Slic3r software</li>
<li>ABS filament (obviously!)</li>
<li>247 °C hotend temp</li>
<li>115 °C heated bed first layer, 110 °C for others</li>
<li>Fan on for layer 3 and above</li>
</ul>
<p>Verified heatbed temperature with calibrated IR imager.</p>
<p>Thus far I have been unable to prevent parts from separating from the heatbed during print, primarily at the corners where stress is concentrated. I've tried various heatbed temperatures from 90 °C to 115 °C, lower hotend temperatures (which just made the problem worse and caused complete print failure), cleaning the PEI surface with alcohol, etc. to no avail. I'm even seeing this to some extent with Benchy, it shows up as a lift to the stern and bow (slight bend parallel to the keel) -- the print is otherwise basically perfect.</p>
<p>I've attached an image of the more extreme curling -- yes, I should probably be using mouse ears on a part like this, but I see the same thing on parts that shouldn't require mouse ears.</p>
<p>What is the best way to fix this particular problem? Temperature adjustments, brims, rafts, something else?</p>
|
<p>Adding 20mm mouse ears was sufficient to resolve the problem using the original extrusion / heatbed settings. I did not expect mouse ears to be required on the Benchy model, but given the lack of better advice it seems this may be a poorly documented "feature" of ABS.</p>
<p>Results on the original worst-case test model:</p>
<p><a href="https://i.stack.imgur.com/aBOso.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aBOso.jpg" alt="Properly bonded mouse ear"></a></p>
<p>Note that the brims will not help if the bed is insufficiently leveled -- the brim has to actually merge with / melt into the base part layer, so the extruder height has to be perfect at the brim to part interface.</p>
<p>Example of extruder too far away from bed:</p>
<p><a href="https://i.stack.imgur.com/CAoV3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CAoV3.png" alt="Failed mouse ear"></a></p>
|
<p>A tall skirt (like 1 cm tall or more, even as tall as the part) few millimetres from the part would shield the corners and the outer parts from colder air and keep the part temperature high, reducing curling. </p>
<p>It is in principle better than mouse ears, because these just pull the corners, which will still have a lot of internal stress when cooled, but if you keep the part warm as I suggest, the corner will stay flat(ter) by themselves, resulting in a stronger and better print with less internal stresses.</p>
| 1,280
|
<p>We are currently evolving our development processes in an effort to become CMMI compliant (we will start with level 2, and move up from there). We are trying to locate a tool that is inexpensive (or free) that will allow us to develop requirements in the spirit of CMMI. In other words, we need to be able to enter our requirements, track changes to them, provide alerts to individuals when requirements change, perform traceability, etc. Our projects are typically small (typically 3 - 7 developers and a tester or two).</p>
<p>We have looked at many of the commercial tools, but they cost more than we are able to afford. We looked at a few on SourceForge (OSRM and others) but could not find anything that was sufficiently mature that also had the features that we needed.</p>
<p>We are looking for suggestions for a tool that meets the above requirements.</p>
|
<p>INCOSE is an excellent resource for this sort of question. They maintain a <a href="http://www.incose.org/ProductsPubs/products/toolsdatabase.aspx" rel="nofollow noreferrer">Tools Database</a> that indexes COTS and GOTS System Engineering tools. Some of the tools that perform requirements management also have high-level System Eng functionality (CORE, for example) whereas others are more narrowly-focused (i.e. RequistePro).</p>
<p>Most of these tools will cost money, but may provide some limited free functionality. <a href="http://www.workspace.com" rel="nofollow noreferrer">Workspace.com</a>, for example, provides some free functionality. I would recommend against rolling your own solution, or adapting a tool that is not specifically intended for requirements management, because the hidden cost of getting it going, as well as inefficiency at the intended task could become burdensome.</p>
<p>If you absolutely can't afford to spend any money on a requirements tool, it would be better to use the free functionality from a commercial tool. But don't do that... pony up the cash for RequisitePro and sleep better knowing that you're getting the right tool for the job.</p>
|
<p>We're heavily into CMMI at our company, but all of our tools are developed in-house.</p>
<p>All I can recommend is to develop your own tools. You will at least have the advantage that it will reflect your business process.</p>
<p>In general, for a new tool, we start off with a tool developed on a project, which is then shared with the rest of the company, if it has been successful. Don't be afraid to use Excel to trace your requirements along with a statuts, which along with a good change control system, such as subversion, gives you a lot of traceability.</p>
| 23,547
|
<p>I am trying this:</p>
<pre><code>Provider=MSDASQL.1;Persist Security Info=False;User ID=sys;Password=pwd;Initial Catalog=DATABASE;Data Source=OdbcDataSource;DBA Privilege=SYSDBA
</code></pre>
<p>But I get the error:</p>
<pre><code>[Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed
</code></pre>
<p>I'm using Delphi, but answers in any language are welcome.</p>
<p><strong><em>Clarification:
I am able to connect as a normal user. I run into trouble when I try to connect AS SYSDBA.</em></strong></p>
|
<p>You can't connect as SYSDBA using standard System.Data.OracleClient, as stated by this post : <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2245591&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2245591&SiteID=1</a>.</p>
<p>You can do that using ODP .NET (Oracle Data Provider for .NET), or other third parties library. If you're planning to build serious Oracle Application on .NET, I suggest you at least look at ODP.NET</p>
|
<p>Oracle Connection string sample</p>
<p>You must have your Oracle SID defined in your TNSNames file. Which is the data source.</p>
<pre><code>Data Source=oracl;User Id=userID;Password=password;Integrated Security=no
</code></pre>
<p>If you are using Visual Studios you can add a data source in the Sever Explore and it will give you the connection string.</p>
| 21,628
|
<p>What's the best practice for making sure that certain ajax calls to certain pages are only accepted from authenticated users?</p>
<p>For example:</p>
<p>Let's say that I have a main page called <strong>blog.php</strong> (I know, creativity abounds). Let's also say that there is a page called <strong>delete.php</strong> which looks for the parameter <strong>post_id</strong> and then deletes some entry from a database.</p>
<p>In this very contrived example, there's some mechanism on blog.php which sends a request via ajax to delete.php to delete an entry. </p>
<p>Now this mechanism is only going to be available to authenticated users on blog.php. But what's to stop someone from just calling delete.php with a bunch of random numbers and deleting everything in site?</p>
<p>I did a quick test where I set a session variable in blog.php and then did an ajax call to delete.php to return if the session variable was set or not <strong><em>(it wasn't)</em></strong>.</p>
<p>What's the accepted way to handle this sort of thing?</p>
<hr>
<p>OK. I must have been crazy the first time I tried this.</p>
<p>I just did another test like the one I described above and it worked perfectly.</p>
|
<p>You were correct in trying to use session variables. Once your user authenticates, you should store that information in their session so that each subsequent page view will see that. Make sure you are calling <code>session_start()</code> on both pages (blog.php and delete.php) before accessing $_SESSION. Also make sure you have cookies enabled -- and if not, you should pass an additional parameter in the query string, usually PHPSESSID=<<code>session_id()</code>>.</p>
|
<p>It is not recommended that you rely on sessions for authentication without taking additional actions.
<a href="http://shiflett.org/articles/the-truth-about-sessions" rel="nofollow noreferrer">Read more on</a>.</p>
| 3,618
|
<p>I think it would be interesting to get a programmers viewpoint on UI design.</p>
<p>What is your favorite User Interface that you have come across in a web application?</p>
<p>If possible, say a little bit about why you like it.</p>
|
<p><a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a> is my favorite. Can be considered a "lack of UI" ;)</p>
|
<p>The new Yahoo Mail UI blew me away when I first saw it. The keyboard shortcuts, drag 'n' drop, tabs, etc. really make it look and feel like a desktop app. Admittedly this quality of UI has become a lot more common on the web in the last few years, but for me at least, Yahoo Mail was the first web app in my experience to bring this kind of usability to the web.</p>
| 27,945
|
<p>I have a code sample that gets a <code>SEL</code> from the current object, </p>
<pre><code>SEL callback = @selector(mymethod:parameter2);
</code></pre>
<p>And I have a method like </p>
<pre><code> -(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
}
</code></pre>
<p>Now I need to move <code>mymethod</code> to another object, say <code>myDelegate</code>.</p>
<p>I have tried:</p>
<pre><code>SEL callback = @selector(myDelegate, mymethod:parameter2);
</code></pre>
<p>but it won't compile. </p>
|
<p>SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:</p>
<pre><code>-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
</code></pre>
<p>Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:</p>
<pre><code>-(void)someMethod:(NSTimer*)timer;
</code></pre>
<p>So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:</p>
<pre><code>@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
</code></pre>
<p>In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds. </p>
|
<p>Beyond what's been said already about selectors, you may want to look at the NSInvocation class.</p>
<blockquote>
<p><em>An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.</em></p>
<p><em>An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.</em></p>
</blockquote>
<p>Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.</p>
| 38,097
|
<p>I know this isn't really what XPath is for but if I have a HashMap of XPath expressions to values how would I go about building an XML document. I've found dom-4j's
DocumentHelper.makeElement(branch, xpath) except it is incapable of creating attributes or indexing. Surely a library exists that can do this?</p>
<pre><code>Map xMap = new HashMap();
xMap.put("root/entity/@att", "fooattrib");
xMap.put("root/array[0]/ele/@att", "barattrib");
xMap.put("root/array[0]/ele", "barelement");
xMap.put("root/array[1]/ele", "zoobelement");
</code></pre>
<p>would result in:</p>
<pre><code><root>
<entity att="fooattrib"/>
<array><ele att="barattrib">barelement</ele></array>
<array><ele>zoobelement</ele></array>
</root>
</code></pre>
|
<p>Here's a slightly different example, one with final reference-type fields rather than final value-type local variables:</p>
<pre><code>public class MyClass {
public final MyOtherObject obj;
}
</code></pre>
<p>Every time you create an instance of MyClass, you'll be creating an outgoing reference to a MyOtherObject instance, and the GC will have to follow that link to look for live objects.</p>
<p>The JVM uses a mark-sweep GC algorithm, which has to examine all the live refereces in the GC "root" locations (like all the objects in the current call stack). Each live object is "marked" as being alive, and any object referred to by a live object is also marked as being alive.</p>
<p>After the completion of the mark phase, the GC sweeps through the heap, freeing memory for all unmarked objects (and compacting the memory for the remaining live objects).</p>
<p>Also, it's important to recognize that the Java heap memory is partitioned into a "young generation" and an "old generation". All objects are initially allocated in the young generation (sometimes referred to as "the nursery"). Since most objects are short-lived, the GC is more aggressive about freeing recent garbage from the young generation. If an object survives a collection cycle of the young generation, it gets moved into the old generation (sometimes referred to as the "tenured generation"), which is processed less frequently.</p>
<p>So, off the top of my head, I'm going to say "no, the 'final' modifer doesn't help the GC reduce its workload".</p>
<p>In my opinion, the best strategy for optimizing your memory-management in Java is to eliminate spurious references as quickly as possible. You could do that by assigning "null" to an object reference as soon as you're done using it.</p>
<p>Or, better yet, minimize the size of each declaration scope. For example, if you declare an object at the beginning of a 1000-line method, and if the object stays alive until the close of that method's scope (the last closing curly brace), then the object might stay alive for much longer that actually necessary.</p>
<p>If you use small methods, with only a dozen or so lines of code, then the objects declared within that method will fall out of scope more quickly, and the GC will be able to do most of its work within the much-more-efficient young generation. You don't want objects being moved into the older generation unless absolutely necessary.</p>
|
<p>The only thing that I can think of is that the compiler might optimize away the final variables and inline them as constants into the code, thus you end up with no memory allocated.</p>
| 39,475
|
<p>I have some UserControls that I created in ProjectA. I have ProjectB that has a windows form that I want to put the controls on. Both of these projects are in a single solution. There's a reference to ProjectA from ProjectB so it can "see" the UserControls.</p>
<p>However, the UserControls do not show up in the toolbox for me to drag to the windows form.</p>
<p>I've tried rebuilding. I've also deleted the 'bin' directory to force a rebuild-all.</p>
<p>How do I get VS2008 to populate the toolbox with my UserControls?</p>
|
<p>Check this setting:</p>
<p>Tools > Options > Windows Forms Designer > General : AutoToolboxPopulate</p>
<p>It should be set to True for this to work.</p>
|
<p>hello its answer Ctrl+Alt+X take this and later u have TOOLBOX :) </p>
| 36,655
|
<p>I'm writing some data acquisition software and need a gui plotting library that is fast enough to do realtime updated graphs. I've been using Nplot which is pretty good for a free library, but I'm wondering if there are any better libraries (preferably free or cheap).</p>
|
<p>There's a good post about this <a href="http://weblogs.asp.net/gbarnett/archive/2008/06/03/visualising-data.aspx" rel="nofollow noreferrer">here</a> and <a href="http://weblogs.asp.net/gbarnett/archive/2008/03/23/free-graphing-libraries-for-net-my-thoughts.aspx" rel="nofollow noreferrer">here</a>. I have also used NPlot in our last project since it's easier to use.</p>
|
<p>You might want to take a look at <a href="http://teethgrinder.co.uk/open-flash-chart/" rel="nofollow noreferrer">Open Flash Chart</a>. It's an open source graphing tool built in flash and can be dynamically updated.</p>
<p>Check out the <a href="http://teethgrinder.co.uk/open-flash-chart/gallery-js-2.php" rel="nofollow noreferrer">Ajax example</a> for an idea of what it can do.</p>
| 2,760
|
<p>I don't understand how GCC works under Linux. In a source file, when I do a:</p>
<pre><code>#include <math.h>
</code></pre>
<p>Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)</p>
<p>I guess a generic version of this question is: Is there an equivalent concept to Windows DLLs under *nix?</p>
|
<p>Well. When you include <code>math.h</code> the compiler will read the file that contains declarations of the functions and macros that can be used. If you call a function declared in that file (<em>header</em>), then the compiler inserts a call instruction into that place in your object file that will be made from the file you compile (let's call it <code>test.c</code> and the object file created <code>test.o</code>). It also adds an entry into the relocation table of that object-file:</p>
<pre><code>Relocation section '.rel.text' at offset 0x308 contains 1 entries:
Offset Info Type Sym.Value Sym. Name
0000001c 00000902 R_386_PC32 00000000 bar
</code></pre>
<p>This would be a relocation entry for a function bar. An entry in the symbol table will be made noting the function is yet undefined:</p>
<pre><code>9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar
</code></pre>
<p>When you link the <code>test.o</code> object file into a program, you need to link against the math library called <code>libm.so</code> . The <code>so</code> extension is similar to the <code>.dll</code> extension for windows. It means it is a <strong>shared object file</strong>. The compiler, when linking, will fix-up all the places that appear in the relocation table of <code>test.o</code>, replacing its entries with the proper address of the bar function. Depending on whether you use the shared version of the library or the static one (it's called <code>libm.a</code> then), the compiler will do that fix-up after compiling, or later, at runtime when you actually start your program. When finished, it will inject an entry in the table of shared libraries needed for that program. (can be shown with <code>readelf -d ./test</code>):</p>
<pre><code>Dynamic section at offset 0x498 contains 22 entries:
Tag Type Name/Value
0x00000001 (NEEDED) Shared library: [libm.so.6]
0x00000001 (NEEDED) Shared library: [libc.so.6]
... ... ...
</code></pre>
<p>Now, if you start your program, the dynamic linker will lookup that library, and will link that library to your executable image. In Linux, the program doing this is called <code>ld.so</code>. Static libraries don't have a place in the dynamic section, as they are just linked to the other object files and then they are forgotten about; they are part of the executable from then on.</p>
<p>In reality it is actually much more complex and i also don't understand this in detail. That's the rough plan, though.</p>
|
<p>The compiler is allowed to do whatever it pleases, as long as, in effect, it acts as if you'd included the file. (All the compilers I know of, including GCC, simply include a file called math.h.)</p>
<p>And no, it doesn't usually contain the function definitions itself. That's libm.so, a "shared object", similar to windows .DLLs. It should be on every system, as it is a companion of libc.so, the C runtime.</p>
<p>Edit: And that's why you have to pass -lm to the linker if you use math functions - it instructs it to link against libm.so.</p>
| 43,083
|
<p>Hoping some of you TinyXML++ people can help me out. Really, since you recomended to me before I think you owe me ;)</p>
<p>I have the following code:</p>
<pre><code> //ticpp::Iterator< ticpp::Element > child( "SetPiece" );
ticpp::Iterator< ticpp::Node > child("SetPiece");
GLuint lc_SPieces = 0;
for(child = child.begin( this ); child != child.end(); child++ )
{
lc_SPieces++;
}
</code></pre>
<p>If I use the top declaration for child I get the error:</p>
<blockquote>
<p>Unhandled exception at 0x7c812aeb in
Drawing.exe: Microsoft C++ exception:
__non_rtti_object @ 0x0012f7b4.</p>
</blockquote>
<p>And I get it in dbgheap.c at this line:</p>
<pre><code>pvBlk = _heap_alloc_dbg(nSize, nBlockUse, szFileName, nLine);
</code></pre>
<p>What's weird is it works with Node, and I know that there are elements in there(I checked using the TinyXML iteration methods).</p>
<p>Has anyone run into this before?</p>
|
<p>just poking in the dark, i don't know tinyxml, but it seems that a dynamic_cast went wrong.
If you dynamic_cast<> a pointer, you get a NULL-pointer on failure. However, if you cast to a reference type, there is no concept of a NULL-reference, so the runtime throws this exception (or bad_type). <a href="http://msdn.microsoft.com/en-us/library/cby9kycs(VS.71).aspx" rel="nofollow noreferrer">MSDN on dynamic_cast, and why it can go wrong</a></p>
<p>The line you pasted for the exception to occur does not help to clear up the situation, since it identifies the symptom rather than the cause.</p>
<p>Try to identify the cast that went wrong, you should be able to find it if you walk up the stack and find the last method in tinyxml libs or headers. Then you can decide whether tinyxml is worng, or you just applied it the wrong way.</p>
<p>good luck!</p>
|
<p>Project -> Properties -> C/C++ -> Language -> Enable Run-Time Type Info</p>
| 31,854
|
<p>I will take the example of the SO site. To go to the list of questions, the url is www.stackoverflow.com/questions. Behind the scene, this goes to a controller (whose name is unknown) and to one of its actions. Let's say that this is <strong>controller=home</strong> and <strong>action=questions</strong>.</p>
<p>How to prevent the user to type www.stackoverflow.com/<strong>home</strong>/<strong>questions</strong> which would lead to the same page and would lower the rank of the page as far as SEO is concerned. Does it take a redirect to solve this? Does it take some special routing rules to handle this kind of situation? Something else?</p>
<p>Thanks</p>
|
<p>Different.</p>
<p>foreach iterates over a list and <strong>performs</strong> some operation with side effects to each list member (such as saving each one to the database for example)</p>
<p>map iterates over a list, <strong>transforms</strong> each member of that list, and returns another list of the same size with the transformed members (such as converting a list of strings to uppercase)</p>
|
<p>ForEach tries to apply a function such as writing to db etc on each element of the RDD without returning anything back.</p>
<p>But the <code>map()</code> applies some function over the elements of rdd and returns the rdd. So when you run the below method it won't fail at line3 but while collecting the rdd after applying foreach it will fail and throw an error which says</p>
<blockquote>
<p>File "<stdin>", line 5, in <module></p>
<p>AttributeError: 'NoneType' object has no attribute 'collect'</p>
</blockquote>
<pre><code>nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])
num2 = nums.map(lambda x: x+2)
print ("num2",num2.collect())
num3 = nums.foreach(lambda x : x*x)
print ("num3",num3.collect())
</code></pre>
| 46,249
|
<p>There are certain messages which i wish to display to the personal who is doing putty to a linux shell. How do i like configure some kind of welcome message when people login to the linux shell?</p>
|
<p><a href="http://computing.vt.edu/infrastructure_services/vtaix/learning.html#4" rel="noreferrer">Message of the day</a>, /etc/motd</p>
<p>i.e. edit the /etc/motd text file</p>
|
<p>Put some content in the file /etc/issue</p>
<p>Some more details in <a href="http://www.linuxfromscratch.org/blfs/view/svn/postlfs/logon.html" rel="nofollow noreferrer">http://www.linuxfromscratch.org/blfs/view/svn/postlfs/logon.html</a></p>
<hr>
<p>crap /etc/motd was the file i was trying to remember. Upvoting his answer :)</p>
| 30,529
|
<p>Is there a PHP version of JavaScript's confirm() function?<br>
If not, what are my other options or how do I make something similar to the confirm()?</p>
|
<p>Because PHP is a server-side language (all the PHP code is executed on the server, and the output of the code is sent to the client), you'd have to make an HTML form with OK/Cancel buttons that would submit to your PHP page. Something like this:</p>
<p>confirm.php:</p>
<pre><code><p>Are you sure you want to do this?</p>
<form action="page2.php" method="post">
<input type="submit" name="ok" value="OK" />
<input type="submit" name="cancel" value="Cancel" />
</form>
</code></pre>
<p>page2.php:</p>
<pre><code><?php
if (isset($_POST['ok'])) {
// They pressed OK
}
if (isset($_POST['cancel'])) {
// They pressed Cancel
}
?>
</code></pre>
|
<p>Using the same answer from the previous post adding some error treatment and safety:</p>
<pre><code><form action="page2.php" method="post">
Your choice: <input type="radio" name="choice" value="yes"> Yes <input type="radio" name="choice" value="no" /> No
<button type="submit">Send</button>
</form>
</code></pre>
<p>And in your page2.php:</p>
<pre><code>if (isset($_POST['choice']) /* Always check buddy */) {
switch($_POST['choice']) {
case 'yes':
/// Code here
break;
case 'no':
/// Code here
break;
default:
/// Error treatment
break;
}
}
else {
// error treatment
}
</code></pre>
| 37,465
|
<p>More and more mobile devices are consuming content on my eCommerce sites. IPhones, Blackberries, PSPs, Windows Mobile, etc and I need some ideas how to handle repurposing my data using CSS templates for these devices. Any ideas would be great. </p>
|
<p>I recommend you look at what Delta Airlines does with CSS at <a href="http://mobile.delta.com" rel="nofollow noreferrer">http://mobile.delta.com</a>. They get help from a company called MShift who does a bunch of mobile banking (which, obviously, has to work on many different devices).</p>
<p>You can get some inspiration from the stylesheet used by the Delta site with <a href="https://my.mshift.com/deltacss.css" rel="nofollow noreferrer">https://my.mshift.com/deltacss.css</a>.</p>
<p>Finally, there are a long list of demo mobile sites from MShift at <a href="http://www.mshift.com/demo.html" rel="nofollow noreferrer">http://www.mshift.com/demo.html</a>.</p>
<p>FWIW, I don't have any association with either Delta or MShift, I have just admired their mobile UI.</p>
|
<p>I would say keep it as simple as possible. Internet on phones can be 3g/wifi or as slow as you can possibly imagine. I would keep the test large so it's easier to read, and links easy to click if you are targeting a touch device. I would also say no to images unless they are 1kb or less.</p>
| 9,381
|
<p>The surfaces of my printed parts using PLA plastic look rough and uneven.</p>
<p>Would changing filament to a better one make any difference?</p>
<p>If not, what kind of methods can I use to achieve a smoother finish for my for 3D-printed objects?</p>
|
<p><a href="https://en.wikipedia.org/wiki/Polylactic_acid">PLA</a> parts can be finished with a coat of epoxy like <a href="http://www.smooth-on.com/Epoxy-Coatings-XTC/c1397_1429/index.html">XTC-3D from Smooth-On</a>. This will smooth out the part and give it a pretty nice shine.</p>
<p>I've also had a fair amount of success sanding prints, giving them a coat of automotive filler primer, and using glossy spray paint.</p>
<p>You can also get great results with an acetone <a href="https://en.wikipedia.org/wiki/Vapor_polishing">vapor finish</a> if you're willing to switch to <a href="https://en.wikipedia.org/wiki/Acrylonitrile_butadiene_styrene">ABS</a>. Though that will require a heated bed and can be a bit more finicky to work with than PLA.</p>
|
<p>It is called <strong>Acetone Finishing</strong></p>
<p>Basically the 3D printed part stays in acetone vapor and the outer shell turns to smooth surface. I have heard that it works better with ABS. </p>
<p>This article shows how <em>with videos</em>:</p>
<ul>
<li>(<a href="https://ultimaker.com/en/community/10412-acetone-finishing-on-pla" rel="nofollow noreferrer">Acetone Finishing on PLA</a> - dead link). </li>
<li>New link: <a href="https://community.ultimaker.com/topic/8530-acetone-finishing-on-pla/" rel="nofollow noreferrer">Acetone Finishing on PLA</a> </li>
</ul>
| 89
|
<p>I'm trying to convert a VARIANT from VT_DATE to an <strong>invariant</strong> VT_BSTR. The following code works on Windows XP:</p>
<pre><code>VARIANT va;
::VariantInit(&va);
// set the variant to VT_DATE
SYSTEMTIME st;
memset(&st, 0, sizeof(SYSTEMTIME));
st.wYear = 2008;
st.wMonth = 9;
st.wDay = 22;
st.wHour = 12;
st.wMinute = 30;
DATE date;
SystemTimeToVariantTime(&st, &date);
va.vt = VT_DATE;
va.date = date;
// change to a string
err = ::VariantChangeTypeEx(&va,
&va,
LOCALE_INVARIANT,
0,
VT_BSTR);
</code></pre>
<p>But on PPC 2003 and Windows Mobile 5, the above code returns E_FAIL. Can someone correct the above code or provide an alternative?</p>
<p><strong>EDIT</strong>: After converting the date to a string, I'm using the string to do a SQL update. I want the update to work regardless of the device's regional settings, so that's why I'm trying to convert it to an "invariant" format.</p>
<p>I'm now using the following to convert the date to a format that appears to work:</p>
<pre><code>err = ::VariantTimeToSystemTime(va.date, &time);
if (FAILED(err))
goto cleanup;
err = strDate.PrintF(_T("%04d-%02d-%02d %02d:%02d:%02d.%03d"),
time.wYear,
time.wMonth,
time.wDay,
time.wHour,
time.wMinute,
time.wSecond,
time.wMilliseconds);
</code></pre>
|
<p>This isn't really an answer, but changing a date to a string <em>isn't</em> a Locale-invariant task - it highly depends on the locale. In this case, I'd convert the Variant Time to System Time, then use a sprintf-style function to convert it to a string</p>
|
<p>Not certain in your context here, but it seems maybe you're on the wrong path. Why not use <a href="http://msdn.microsoft.com/en-us/library/ms891320.aspx" rel="nofollow noreferrer">VarBstrFromDate</a>? This aloows using a locale (or optionally ignoring one) and is probably far closer to what you want.</p>
| 14,129
|
<p>I know a question like this was already asked, but the situation is a little different, and all the answers on that problem didn't work for me.</p>
<p>I'm trying to compile some C code in VS2008 and it doesn't create an exe. Also, when I try to run it with f5, I get:</p>
<blockquote>
<p>This application has failed to start
because MSVCR90.DLL was not found.</p>
</blockquote>
<p>I did some googling and it said that this was because my c++ redistributable package wasnt installed. So I installed that, restarted everything and tried again. But alas, I still get the same error. Does anyone have any clue how to fix this?</p>
|
<p>It sounds like either a problem with your VS2008 installation, or something wrong with your DLL search path. MSVCR90.DLL is installed when you install VS2008, you shouldn't have to install any additional redistributable packages.</p>
<p>First I would check your PATH environment variable and make sure there is no gobbledydook in it that will break some of the entries, and if you don't find a problem there, then I would uninstall and reinstall Visual Studio. </p>
<p>You could also try searching for MSVCR90.DLL (and other DLLs like it), and move them to your Windows/System32 folder.</p>
<p>If you just want to get going now, another thing you could do is change your project to statically link to the runtime libraries, and then it wont even try to load that DLL. Go to your Project settings, Configuration Properties->C/C++->Code Generation and change Runtime Library from Multi-Threaded DLL to just Multi-Threaded (or any of the options that doesn't end with DLL).</p>
|
<p>If you give the finished exe to someone else they will need to install the latest visual c runtime to run it. This will only work for release build AFAIK. Visual studio should install the required runtime both release and debug into your path. The project probably has an additional dependency accidently set for an incorrect version of the runtime.</p>
<p>See if <a href="http://msdn.microsoft.com/en-us/library/abx4dbyh.aspx" rel="nofollow noreferrer">this page</a> helps.</p>
| 37,448
|
<p>I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window ...</p>
<p>I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor.</p>
<p>[]'s</p>
<p>André Casteliano</p>
<p>PS: I'm using Visio 2007 here.</p>
|
<p>This allows you to open two or more instances of Visio so that you can view different Visio docs at the same time without going through the process to stretch the Visio window across two screens. I found this to be a simpler method and a bit easier to manipulate. If it doesn't work on your first try recheck the registry setting. It changed back on me a couple of times before it took.</p>
<p>To implement the new behaviour, follow the following registry trick:</p>
<ol>
<li><p>Open Microsoft Visio.</p>
</li>
<li><p>Go to <code>Tools -> Options -> Advanced</code> or <code>File -> Options -> Advanced</code> in newer versions.</p>
</li>
<li><p>Check the Put all settings in Windows Registry option.</p>
</li>
<li><p>Close Microsoft Visio</p>
</li>
<li><p>Run Registry Editor (regedit).</p>
</li>
<li><p>Navigate to the following registry key:</p>
<p><code>HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Visio\Application\</code><br />
<strong>Note:</strong> The value <code>12.0</code> in the key can be different.
(i.e: for Visio 2010: <code>14.0</code>, Visio 2019: <code>16.0</code>)</p>
</li>
<li><p>In the right pane, right click on <code>SingleInstanceFileOpen</code>, and then select Modify. Update the value of <code>SingleInstanceFileOpen</code> from <code>1</code> to <code>0</code></p>
</li>
</ol>
<p><strong>If the value <code>SingleInstanceFileOpen</code> doesn't exist</strong>, it can be created as a type REG_SZ.</p>
|
<p>Seems like my installation of Visio is the problem. I've tried on another computer here and it allow me to open 2 instances of the software.</p>
| 5,052
|
<p>I've just started developing in Silverlight 2 and have not run into any "missing parts" of .Net that I was using in the full version. Have you found anything to be missing from Silverlight 2's version of .Net that (1) you missed, (2) really needed, or (3) had to abandon Silverlight 2 because it was missing?</p>
|
<p>Do your tables have primary keys? LINQ to SQL won't allow you to change the data if it doesn't have a key to use. I've run into that a lot with legacy systems. A lot of the time the table is using a defacto key, but it's not specifically set up in the database. In those cases, you can just mark the field as primary (in the database) and it should work. Otherwise you may have to add a primary key column just to give LINQ something to use to uniquely identify each row.</p>
|
<p>If you right-click on the table in the designer and choose properties, the Delete, Insert and Update are grayed out. I am not sure if you can supply alternate Delete, Insert and Update methods...</p>
<p>But if your question is about inserting, updating and deleting values in your tables, once you drag a table onto your dbml designer you are able to insert, update and delete using linq in your code. There is nothing else that needs to be done to the dbml.</p>
| 44,953
|
<p>Under Windows Server 2003, Enterprise Edition, SP2 (/3GB switch not enabled)</p>
<p>As I understand it, and I may be wrong, the maximum addressable memory for a process is 4GB. </p>
<p>Is that 2GB of private bytes and 2GB of virtual bytes? </p>
<p>Do you get "out of memory" errors when the private byte limit or virtual byte limit is reached?</p>
|
<p>It is correct that the maximum address space of a process is 4GB, in a sense. Half of the address space is, for each process, taken up by the operating system. This can be changed with the 3GB switch but it might cause system instability. So, we are left with 2GB of addressable memory for the process to use on its own. Well, not entirely. It turns out that a part of this space is taken up by other stuff such as DLLs an other common code. The actual memory available to you as a programmer is around 1.5GB - 1.7GB.</p>
<p>I'm not sure about how you can handle accidentally going above this limit but I know of games which crash in large multiplayer maps for this reason. Another thing to note is that a 32bit program cannot use more than the 2GB address space on a 64bit system unless they enable the /LARGEADDRESSAWARE:YES linker flag.</p>
|
<p>Mark Russinovich started a series of posts on this..
<a href="http://blogs.technet.com/markrussinovich/archive/2008/07/21/3092070.aspx" rel="nofollow noreferrer">Pushing the Limits of Windows: Physical Memory</a></p>
<p>While 4GB is the licensed limit for 32-bit client SKUs, the effective limit is actually lower and dependent on the system's chipset and connected devices. The reason is that the physical address map includes not only RAM, but device memory as well, and x86 and x64 systems map all device memory below the 4GB address boundary to remain compatible with 32-bit operating systems that don't know how to handle addresses larger than 4GB. If a system has 4GB RAM and devices, like video, audio and network adapters, that implement windows into their device memory that sum to 500MB, 500MB of the 4GB of RAM will reside above the 4GB address boundary.</p>
| 24,670
|
<p>I would like to execute <code>ls</code> in a Perl program as part of a CGI script. For this I used <code>exec(ls)</code>, but this does not return from the <code>exec</code> call.</p>
<p>Is there a better way to get a listing of a directory in Perl?</p>
|
<p>Exec doesn't return at all. If you wanted that, use system.</p>
<p>If you just want to read a directory, open/read/close-dir may be more appropriate.</p>
<pre><code>opendir my($dh), $dirname or die "Couldn't open dir '$dirname': $!";
my @files = readdir $dh;
closedir $dh;
#print files...
</code></pre>
|
<p>I would recommend you have a look at <a href="http://perldoc.perl.org/IPC/Open3.html" rel="nofollow noreferrer">IPC::Open3</a>. It allows for far more control over the spawned process than system or the backticks do.</p>
| 25,132
|
<p>I have a line color property in my custom grid control. I want it to default to <code>Drawing.SystemColors.InactiveBorder</code>. I tried:</p>
<pre><code>[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }
</code></pre>
<p>But it doesn't seem to work. How do I do that with the default value attribute?</p>
|
<p>You need to change first argument from <code>SystemColors</code> to <code>Color</code>.<br>
It seems that there is no type converter for the <code>SystemColors</code> type, only for the <code>Color</code> type.</p>
<pre><code>[DefaultValue(typeof(Color),"InactiveBorder")]
</code></pre>
|
<p>According to the link Matt posted, the DefaultValue attribute doesn't set the default value of the property, it just lets the form designer know that the property <em>has</em> a default value. If you change a property from the default value it is shown as bold in the properties window.</p>
<p>You can't set a default value using automatic properties - you'll have to do it the old-fashioned way:</p>
<pre><code>class MyClass
{
Color lineColor = SystemColors.InactiveBorder;
[DefaultValue(true)]
public Color LineColor {
get {
return lineColor;
}
set {
lineColor = value;
}
}
}
</code></pre>
| 6,529
|
<p>There is a UNIQUE database constraint on an index which doesn't allow more than one record having identical columns.</p>
<p>There is a piece of code, managed by Hibernate (v2.1.8), doing two DAO <BR>
<code>getHibernateTemplate().save( theObject )</code><BR>
calls which results two records entered into the table mentioned above.</p>
<p>If this code is executed without transactions, it results INSERT, UPDATE, then another INSERT and another UPDATE SQL statements and works fine. Apparently, the sequence is to insert the record containing DB NULL first, and then update it with the proper data.</p>
<p>If this code is executed under Spring (v2.0.5) wrapped in a single Spring transaction, it results two INSERTS, followed by immediate exception due to UNIQUE constraint mentioned above.</p>
<p>This problem only manifests itself on <a href="http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=299229" rel="nofollow noreferrer">MS SQL</a> due to its incompatibility with ANSI SQL. It works fine on MySQL and Oracle. Unfortunately, our solution is cross-platform and must support all databases.</p>
<p>Having this stack of technologies, what would be your preferred workaround for given problem?</p>
|
<p>You could try flushing the hibernate session in between the two saves. This may force Hibernate to perform the first update before the second insert.</p>
<p>Also, when you say that hibernate is inserting NULL with the insert, do you mean every column is NULL, or just the ID column?</p>
|
<p>I have no experience in Hibernate, so I don't know if you are free to change the DB at your will or if Hibernate requires a specific DB structure you cannot change.</p>
<p>If you can make changes then you can use this workaround in MSSQL tu emulate the ANSI behaviour :</p>
<p>drop the unique index/constraint</p>
<p>define a calc field like this:</p>
<pre><code>alter table MyTable Add MyCalcField as
case when MyUniqueField is NULL
then cast(Myprimarykey as MyUniqueFieldType)
else MyUniqueField end
</code></pre>
<p>add the unique constraint on this new field you created.</p>
<p>Naturally this applies if MyUniqueField is not the primary key! :) </p>
<p>You can find more details in <a href="http://www.databasejournal.com/features/mssql/article.php/3711501" rel="nofollow noreferrer">this article at databasejournal.com</a></p>
| 16,060
|
<p>I have the following regex expression to match html links:</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>it kind of works. Except not really. Because it grabs everything after the < a href...
and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that?</p>
<p><strong>EDIT:</strong> This would make it grab only up to the quotes instead of everything after the < a href btw</p>
|
<p>I don't think your regex is doing what you want.</p>
<pre><code><a\s*href=['|"](http:\/\/(.*?)\S['|"]>
</code></pre>
<p>This captures anything non-greedily from http:// up to the first non-space character before a quote, single quote, or pipe. For that matter, I'm not sure how it parses, as it doesn't seem to have enough close parens.</p>
<p>If you are trying to capture the href, you might try something like this:</p>
<pre><code><a .*?+href=['"](http:\/\/.*?)['"].*?>
</code></pre>
<p>This uses the .*? (non-greedy match anything) to allow for other attributes (target, title, etc.). It matches an href that begins and ends with either a single or double quote (it does not distinguish, and allows the href to open with one and close with the other).</p>
|
<p>Why are you trying to match HTML links with a regex?</p>
<p>Depending on what you're trying to do the appropriate thing to do would vary.</p>
<p>You could try using an HTML Parser. There are several available, there's even one in the Python Library: <a href="https://docs.python.org/library/htmlparser.html" rel="nofollow noreferrer">https://docs.python.org/library/htmlparser.html</a></p>
<p>Hope this helps!</p>
| 37,280
|
<p>I'm using lucene in my project.
Here is my question:
should I use lucene to replace the whole search module which has been implemented with sql using a large number of <code>like</code> statement and accurate search by id or sth,
or should I just use lucene in fuzzy search(i mean full text search)?</p>
|
<p>Probably you should use lucene, unless the SQL search is very performant.</p>
<p>We are right now moving to Solr (based on Lucene) because our search queries are inherently slow, and cannot be sped up with our database.... If you have reasonably large tables, your search queries will start to get really slow unless the DB has some kind of highly optimized free text search mechanisms.</p>
<p>Thus, let Lucene do what it does best....</p>
|
<p>I don't think using <strong>like</strong> statement abusively is a good idea.
And I believe the performance of lucene will be better than database.</p>
| 14,519
|
<p>I'm just getting into unit testing, and have written some short tests to check if function called isPrime() works correctly.</p>
<p>I've got a test that checks that the function works, and have some test data in the form of some numbers and the expected return value.</p>
<p>How many should I test? How do I decide on which to test? What's the best-practices here?</p>
<p>One approach would be to generate 1000 primes, then loop through them all, another would be to just select 4 or 5 and test them. What's the correct thing to do?</p>
|
<p>You'd want to check edge cases. How big a prime number is your method supposed to be able to handle? This will depend on what representation (type) you used. If you're only interested in small (<em>really</em> relative term when used in number theory) primes, you're probably using int or long. Test a handful of the biggest primes you can in the representation you've chosen. Make sure you check some non-prime numbers too. (These are much easier to verify independently.)</p>
<p>Naturally, you'll also want to test a few small numbers (primes and non-primes) and a few in the middle of the range. A handful of each should be plenty. Also make sure you throw an exception (or return an error code, whichever is your preference) for numbers that are out of range of your valid inputs.</p>
|
<p>A few questions, the answers may inform your decision:</p>
<ul>
<li>How important is the correct functioning of this code?</li>
<li>Is the implementation of this code likely to be changed in the future? (if so, test more to support the future change)</li>
<li>Is the public contract of this code likely to change in the future? (if so, test less - to reduce the amount of throw-away test code)</li>
<li>How is the code coverage, are all branches visited?</li>
<li>Even if the code doesn't branch, are boundary considerations tested?</li>
<li>Do the tests run quickly?</li>
</ul>
<p>Edit: Hmm, so to advise in your specific scenario. Since you started writing unit tests yesterday, you might not have the experience to decide among all these factors. Let me help you:</p>
<ul>
<li>This code is probably not too important (no one dies, no one goes to war, no one is sued), so a smattering of tests will be fine.</li>
<li>The implementation probably won't change (prime number techniques are well known), so we don't need tests to support this. If the implementation does change, it's probably due to an observed failing value. That can be added as a new test at the time of change.</li>
<li>The public contract of this won't change.</li>
<li>Get 100% code coverage on this. There's no reason to write code that a test doesn't visit in this circumstance. You should be able to do this with a small number of tests.</li>
<li>If you care what the code does when zero is called, test that.</li>
<li>The small number of tests should run quickly. This will allow them to be run frequently (both by developers and by automation).</li>
</ul>
<p>I would test 1, 2, 3, 21, 23, a "large" prime (5 digits), a "large" non-prime and 0 if you care what this does with 0.</p>
| 39,444
|
<p>I'm working on a setup which <em>wants to include the Microsoft.Web.Services3 (WSE 3.0) DLL</em>. However, I typically do not like including Microsoft DLL's in our installs except by way of Microsoft's redistributables. There is both a developer and a redist install package available from Microsoft.</p>
<p>So, as a best practice, should I include the single DLL in my install or refer them to one of the WSE 3.0 installs (assuming they do not already have it installed)?</p>
|
<p>Usually, redistributing any of Microsoft DLLs outside of the redistributable package is forbidden by their EULA, so you might first want to check the appropriate EULA for that DLL.</p>
<p>Generally, I would prefer the redist package since that makes sure that it's correctly "registered" into the system, i.e. if you install a newer version of the redist it gets updated (like DirectX) or not overwritten if it's an older version (also like DirectX).</p>
|
<p>If you don't include it you should at the very least link to it directly on your site or have your installer open the web browser to it (or even download it automatically). Or better yet, include the redistributable in your software package.</p>
<p>However, if the DLL is not very large and you suspect that few users will have it, in the interest of a better user I would prepackage it in the default installer. However, you can always have an installer that does not include it for those who want a smaller installer... a great deal of other vendors do this all the time.</p>
| 3,842
|
<p>in context of SQL Server 2005, I have a table for which the primary key is a uniqueidentifier (GUID), with a default value generated by the newid() function. I want to write a stored procedure that inserts a new record into the table. How do I get the record's PK value? for an identity-declared field, this is easy - I call scope_identity(). How should I proceed with guids?</p>
<p>Thanks,
Lucian</p>
|
<p>I would generate a new Guid prior to inserting the record, and explicitly use this new Guid as the PK for the record. You then use that guid after the insert, knowing that it refers to the row you have just inserted, e.g.</p>
<pre><code>DECLARE @newGuid uniqueidentifier
SET @newGuid = newid()
INSERT INTO myTable(id, stringval)
VALUES (@newGuid, "Hello")
SELECT * FROM myTable
WHERE id = @newGuid
</code></pre>
|
<p>You can return it as row by using <code>SELECT</code> statement or use <code>OUTPUT</code> parameter if it's one row at a time.</p>
| 44,147
|
<p>I have one website on my server, and my IIS Worker Process is using 4GB RAM consistently. What should I be checking?</p>
<pre><code>c:\windows\system32\inetsrv\w3wp.exe
</code></pre>
|
<p>I would check the CLR Tuning Section in the <a href="http://msdn.microsoft.com/en-us/library/ms998583.aspx#scalenetchapt17_topic9" rel="noreferrer">document</a> Gulzar mentioned.</p>
<p>As the other posters pointed out, any object that implements <code>IDispose</code> should have <code>Dispose()</code> called on it when it's finished with, preferably using the <code>using</code> construct.</p>
<p>Fire up <code>perfmon.exe</code> and add these counters:</p>
<blockquote>
<ul>
<li>Process\Private Bytes</li>
<li>.NET CLR Memory# Bytes in all Heaps</li>
<li>Process\Working Set</li>
<li>.NET CLR Memory\Large Object Heap size</li>
</ul>
<p>An increase in Private Bytes while the
number of Bytes in all Heaps counter remains the same indicates unmanaged
memory consumption.</p>
<p>An increase in
both counters indicates managed memory
consumption</p>
</blockquote>
|
<p>As other people noted common cause of this problem is resource leaking, also there is a known issue with win2k3 server and IIS6 <a href="http://support.microsoft.com/kb/916984" rel="nofollow noreferrer">KB916984</a></p>
| 30,481
|
<p>Further to my previous question about the <a href="https://stackoverflow.com/questions/165383/optimal-raid-setup-for-sql-server">Optimal RAID setup for SQL server</a>, could anyone suggest a quick and dirty way of benchmarking the database performance on the new and old servers to compare them? Obviously, the proper way would be to monitor our actual usage and set up all sorts of performance counters and capture the queries, etc., but we are just not at that level of sophistication yet and this isn't something we'll be able to do in a hurry. So in the meanwhile, I'm after something that would be a bit less accurate, but quick to do and still better than nothing. Just as long as it's not misleading, which would be worse than nothing. It should be SQL Server specific, not just a "synthetic" benchmark. It would be even better if we could use our actual database for this.</p>
|
<p>Measure the performance of your application itself with the new and old servers. It's not necessarily easy:</p>
<ul>
<li>Set up a performance test environment with your application on (depending on your architecture this may consist of several machines, some of which may be able to be VMs, but some of which may not be)</li>
<li>Create "driver" program(s) which give the application simulated work to do</li>
<li>Run batches of work under the same conditions - remember to reboot the database server between runs to nullify effects of caching (Otherwise your 2nd and subsequent runs will probably be amazingly fast)</li>
</ul>
<p>Ensure that the performance test environment has enough hardware machines in to be able to load the database heavily - this may mean swapping out some VMs for real hardware.</p>
<p>Remember to use production-grade hardware in your performance test environment - even if it is expensive.</p>
<p>Our database performance test cluster contains six hardware machines, several of which are production-grade, one of which contains an expensive storage array. We also have about a dozen VMs on a 7th simulating other parts of the service.</p>
|
<p>you can always insert, read, and delete a couple of million rows - it's not a realistic mix of operations but it should strain the disks nicely...</p>
| 21,886
|
<p>I am using UIImagePicker to take photo and save the photo. But appears the photo it takes was truncated on top and bottom, which was top and bottom menu when UIImagePicker taking the photo. I am wondering how to take the whole screen of the photo.</p>
<p>Thanks.</p>
|
<p>The UIImagePicker crops all images to 320x320 if you allow editing. If you want something sized differently, you'll have to look at the original image and the cropping rect, both in the editingInfo dictionary you get back from the picker. Once you have those, you can resize or re-crop as needed.</p>
|
<p>Look in the "editingInfo" dictionary that you get back in the didFinishPickingImage: method, if there's a value for the @"Original" key then it's the real, uncropped image (stored as a UIImage object).</p>
<p>From there you can look at the other editingInfo values to see if the user cropped that image, which you can then apply (or take the UIImage passed to you which is the cropped verson). If you are getting an image back from the photo library, the original is not in the dictionary and you only have the image passed in.</p>
| 30,186
|
<p>I have asp.net form that contains fields. When I access this window, my javascript functions can access the fields via the DOM with the getElementById() method and when I postpack to the server I am receiving the updates made by the client.</p>
<p>However, when I launch the form as a child window using Telerik's RadWindow control, the javascript can not access the hidden fields on the child form. Instead I get null. </p>
<p>My questions are:</p>
<ol>
<li>Are hidden fields on a child window
not accessible when the window is
launched from a parent asp.net form?</li>
<li>Has anyone attempted this with Telerik controls and run into issues?</li>
</ol>
<p><strong>EDIT</strong>
Craig pointed out that the id may be different. Two additional questions then:</p>
<ol>
<li>Can you ensure that the id you assign at the server is actually used?</li>
<li>Is using getElementByName() a better mechanism to access DOM elements?</li>
</ol>
|
<p>To get the ID of your asp.net control do something like this:</p>
<pre><code><%= theControl.ClientID %>
</code></pre>
<p>getElementByName is not as commonly used as getElementById. The ID attribute is supposed to be unique for each element on the page whereas the name attribute can be duplicated.</p>
|
<p>I use getElementsByName for checkboxes within the same group.</p>
<p>As for the control's ID, TonyB has the right idea, but make sure you refer to the ClientID property in the PreRender event handler, because if you do it too early in the page life cycle, it will not be available yet).</p>
| 24,272
|
<p>I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support <code>äöå</code> etc. for regular Finnish text and Cyrillic alphabets like <code>ЦжФ</code> for special cases.</p>
<p>My setup is the following:</p>
<ul>
<li>Development environment: Windows XP</li>
<li>Production environment: Debian</li>
</ul>
<p>Database used: MySQL 5.x</p>
<p>Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site.</p>
<p>How to achieve this?</p>
|
<p><em>Answering myself as the FAQ of this site encourages it. This works for me: </em></p>
<p>Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.</p>
<p>To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:</p>
<h2>Configuring Tomcat's server.xml</h2>
<p>It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:</p>
<pre><code><Connector port="8080" maxHttpHeaderSize="8192"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
compression="on"
compressionMinSize="128"
noCompressionUserAgents="gozilla, traviata"
compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
URIEncoding="UTF-8"
/>
</code></pre>
<p>The key part being <b>URIEncoding="UTF-8"</b> in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.
As a result, when the user writes the following to the address bar of the browser:</p>
<pre><code> https://localhost:8443/ID/Users?action=search&name=*ж*
</code></pre>
<p>the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as <b>%D0%B6</b>.</p>
<p><i>POST request are not affected by this.</i></p>
<h2> CharsetFilter </h2>
<p>Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:</p>
<pre><code>package fi.foo.filters;
import javax.servlet.*;
import java.io.IOException;
public class CharsetFilter implements Filter {
private String encoding;
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("requestEncoding");
if (encoding == null) encoding = "UTF-8";
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
throws IOException, ServletException {
// Respect the client-specified character encoding
// (see HTTP specification section 3.4.1)
if (null == request.getCharacterEncoding()) {
request.setCharacterEncoding(encoding);
}
// Set the default response content type and encoding
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy() {
}
}
</code></pre>
<p>This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. </p>
<p>The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application. </p>
<p>This filter has to be added to the <b>web.xml</b> or the deployment descriptor of the webapp:</p>
<pre><code> <!--CharsetFilter start-->
<filter>
<filter-name>CharsetFilter</filter-name>
<filter-class>fi.foo.filters.CharsetFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</code></pre>
<p>The instructions for making this filter are found at the <a href="http://wiki.apache.org/tomcat/Tomcat/UTF-8" rel="noreferrer">tomcat wiki (<a href="http://wiki.apache.org/tomcat/Tomcat/UTF-8" rel="noreferrer">http://wiki.apache.org/tomcat/Tomcat/UTF-8</a>)</a> </p>
<h2> JSP page encoding </h2>
<p>In your <strong>web.xml</strong>, add the following:</p>
<pre><code><jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</code></pre>
<p>Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:</p>
<pre><code> <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
</code></pre>
<p>If some kind of a layout with different JSP-fragments is used, then this is needed in <b>all</b> of them.</p>
<h2> HTML-meta tags </h2>
<p>JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.
Then it's time to tell the browser in which encoding the html page is:</p>
<p>This is done with the following at the top of each xhtml page produced by the webapp:</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
...
</code></pre>
<h2> JDBC-connection </h2>
<p>When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in <b>context.xml</b> or wherever the JDBC connection is defiend as follows: </p>
<pre><code> <Resource name="jdbc/AppDB"
auth="Container"
type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="10000"
username="foo"
password="bar"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&amp;characterEncoding=UTF-8"
/>
</code></pre>
<h2> MySQL database and tables</h2>
<p>The used database must use UTF-8 encoding. This is achieved by creating the database with the following:</p>
<pre><code> CREATE DATABASE `ID_development`
/*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;
</code></pre>
<p>Then, all of the tables need to be in UTF-8 also:</p>
<pre><code> CREATE TABLE `Users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(30) collate utf8_swedish_ci default NULL
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;
</code></pre>
<p>The key part being <b>CHARSET=utf8</b>.</p>
<h2> MySQL server configuration </h2>
<p>MySQL serveri has to be configured also. Typically this is done in Windows by modifying <b>my.ini</b> -file and in Linux by configuring <b>my.cnf</b> -file.
In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.</p>
<pre><code> [client]
port=3306
default-character-set=utf8
[mysql]
default-character-set=utf8
</code></pre>
<h2> Mysql procedures and functions </h2>
<p>These also need to have the character set defined. For example:</p>
<pre><code> DELIMITER $$
DROP FUNCTION IF EXISTS `pathToNode` $$
CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
READS SQL DATA
BEGIN
DECLARE path VARCHAR(255) CHARACTER SET utf8;
SET path = NULL;
...
RETURN path;
END $$
DELIMITER ;
</code></pre>
<h2> GET requests: latin1 and UTF-8 </h2>
<p>If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:</p>
<pre><code> https://localhost:8443/ID/Users?action=search&name=Petteri
https://localhost:8443/ID/Users?action=search&name=ж
</code></pre>
<p>Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.</p>
<p>The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as <b>%D0%B6</b>. </p>
<p>If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as <b>%D0%B6</b>. </p>
<p>The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found.</p>
<h3>But what about äåö?</h3>
<p>HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following</p>
<pre><code> https://localhost:8443/ID/Users?action=search&name=*Päivi*
</code></pre>
<p>in to the encoded version</p>
<pre><code> https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*
</code></pre>
<p>In latin1 the character <b>ä</b> is encoded as <b>%E4</b>. <em>Even though the page/request/everything is defined to use UTF-8</em>. The UTF-8 encoded version of ä is <b>%C3%A4</b></p>
<p>The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8.
<b>Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8</b></p>
<h2> Stuff to read </h2>
<p>A very big thank you for the writers of the following for giving the answers for my problem:</p>
<ul>
<li> http://tagunov.tripod.com/i18n/i18n.html </li>
<li> http://wiki.apache.org/tomcat/Tomcat/UTF-8 </li>
<li> http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ </li>
<li> http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html </li>
<li> http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html </li>
<li> http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html </li>
<li> http://jeppesn.dk/utf-8.html </li>
<li> http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html </li>
<li> http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html </li>
<li> http://www.utf8-chartable.de/ </li>
</ul>
<h2>Important Note</h2>
<p><a href="/questions/tagged/mysql" class="post-tag" title="show questions tagged 'mysql'" rel="tag">mysql</a> supports the <a href="http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane" rel="noreferrer">Basic Multilingual Plane</a> using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of <code>VARBINARY</code> column type or use the <a href="http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html" rel="noreferrer"><code>utf8mb4</code> character set</a> (which requires MySQL 5.5.3 or later). Just be aware that using the <code>utf8</code> character set in MySQL won't work 100% of the time.</p>
<h2>Tomcat with Apache</h2>
<p>One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:</p>
<ol>
<li>Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <code><Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/></code></li>
<li>Goto your apache folder i.e. <code>/etc/httpd/conf</code> and add <code>AddDefaultCharset utf-8</code> in <code>httpd.conf file</code>. <strong>Note:</strong> First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.</li>
</ol>
|
<p>In case you have specified in connection pool (mysql-ds.xml), in your Java code you can open the connection as follows:</p>
<pre><code>DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection conn = DriverManager.getConnection(
"jdbc:mysql://192.168.1.12:3308/mydb?characterEncoding=greek",
"Myuser", "mypass");
</code></pre>
| 16,816
|
<p>Some programs read the company name that you entered when Windows was installed and display it in the program. How is this done? Are they simply reading the name from the registry?</p>
|
<p>If you want the registered company name as entered in the registry, you can get it from:</p>
<pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\RegisteredOrganization
</code></pre>
<p>Using the Registry class you can do something along these lines:</p>
<pre><code>string org = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion", "RegisteredOrganization", "");
</code></pre>
|
<p>I don't like to have text-y registry calls in my business code, and I'm not a fan of utility classes, so I wrote an extension method that gets the company name from the registry.</p>
<pre><code>using Microsoft.Win32;
namespace Extensions
{
public static class MyExtensions
{
public static string CompanyName(this RegistryKey key)
{
// this string goes in my resources file usually
return (string)key.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion").GetValue("RegisteredOrganization");
}
}
}
</code></pre>
<p>Then I can easily get that value:</p>
<pre><code>RegistryKey key = Registry.LocalMachine;
return key.CompanyName();
</code></pre>
<p>It's nothing fancy, just a prettier way of dealing with oft-retrieved registry values.</p>
| 34,284
|
<p>I have a producer-consumer pattern working for one product. What is the best implementation when the producer produce many products? For example a DataBaseEvent, GuiEvent and ControlEvent that the consumer shall consume. The code below shows the pattern for one product (a DataBaseEvent). Should each event type be enqueued on an own queue or should the events inherit a base class that can be enqueued. Maybe there exist a better pattern when working with many event types?</p>
<pre><code>class DataBaseEventArgs : EventArgs
{
public string textToDB = "";
}
class Consumer
{
private Producer mProducer = new Producer();
private Queue<DataBaseEventArgs> mDataBaseEventQueue = new Queue<DataBaseEventArgs>();
private static EventWaitHandle mDataBaseEventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
private Thread mDataBaseEventDequeueThread = null;
public Consumer()
{
mDataBaseEventDequeueThread = new Thread(DataBaseDequeueEvent);
mDataBaseEventDequeueThread.Start();
mProducer.mDataBaseEventHandler += WhenDataBaseEvent;
}
protected void DataBaseDequeueEvent()
{
while (true)
{
DataBaseEventArgs e;
lock (((ICollection)mDataBaseEventQueue).SyncRoot)
{
if (mDataBaseEventQueue.Count > 0)
{
e = mDataBaseEventQueue.Dequeue();
}
}
// WriteToDatabase(e.textToDB);
if (mDataBaseEventQueue.Count == 0)
{
mDataBaseEventWaitHandle.WaitOne(1000);
mDataBaseEventWaitHandle.Reset();
}
}
}
internal void WhenDataBaseEvent(object sender, DataBaseEventArgs e)
{
lock (((ICollection)mDataBaseEventQueue).SyncRoot)
{
mDataBaseEventQueue.Enqueue(e);
mDataBaseEventWaitHandle.Set();
}
}
}
class Producer
{
public event EventHandler<DataBaseEventArgs> mDataBaseEventHandler = null;
public void SendDataBaseEvent()
{
if (mDataBaseEventHandler != null)
{
DataBaseEventArgs e = new DataBaseEventArgs();
e.textToDB = "This text will be written to DB";
mDataBaseEventHandler(this, e);
}
}
}
</code></pre>
|
<p>Multiple queues would be useful if you want to actively separate the work - i.e. have different threads/pools for different types of event. If you want to share the load, there is another option - use an interface (rather than a base-class). Base-class is fine, but I can't think of anything that would mandate a base-class over an interface. Or even just a delegate to the work to do!</p>
<p>Also - I'm not sure you need a reset event in this case; you can often handle producer/consumer with just lock and Monitor.Pulse / Wait (which has less overhead, as no OS-objects are involved - just managed objects). However, if the code is currently stable, perhaps leave "as is" - threading is hard enough to get right once, let alone twice...</p>
<p>But for reference, it would be something like:</p>
<pre><code>while(true) {
T item;
lock(lockObj) {
if(queue.Count == 0) { // empty
Monitor.Wait(lockObj);
continue; // ensure there is genuinely something to do
}
item = queue.Dequeue();
}
// TODO: process item
}
...
void Add(T item) {
lock(lockObj) {
queue.Enqueue(item);
if(queue.Count == 1) { // first
Monitor.PulseAll(lockObj);
}
}
}
</code></pre>
<p>(and remember to PulseAll when clearing down the queues)</p>
|
<p>I think that it would be better enqueue all of the request to one queue if they have the same priority and will be handled in similar way. </p>
<p>If one of the requests has higher probability, then either you need some fancy priority queue or you can use different queues.</p>
<p>Also, if you process the messages in a different way, then there is no point to overcomplicate the pattern.</p>
| 37,713
|
<p>What is the slowest (therefore best) hash algorithm for passwords in ASP Classic?</p>
<p>EDIT: For those unaware, when hashing passwords, slower hashes are preferred to faster to help slow rainbow table style attacks. </p>
<p>EDIT2: And yes, of course speed isn't the only valid concern for hash selection. My question assumes that <strong>All other things being equal</strong>, <a href="http://www.securityfocus.com/blogs/262" rel="nofollow noreferrer">the slowest hash method is preferred</a> when hashing a password. Though collision/reverse engineering is of course a concern too, I'm prioritizing speed in this question since it is arguably the most critical factor to consider when comparing popular hash algorithms for use on passwords.</p>
<p>Thanks!</p>
|
<p>A lot of people seem to be beating on the question-asker because he's looking for a slow hash function. Actually, all other aspects being equal, a slower hash function is more secure than a fast one. This is because a slower hash function results in <strong>slower generation of rainbow tables</strong> and <strong>slower brute forcing or dictionary attacks on the password</strong>.</p>
<p>From Thomas Ptacek at <a href="http://www.securityfocus.com/blogs/262" rel="noreferrer">http://www.securityfocus.com/blogs/262</a>, as referenced in this <a href="http://www.codinghorror.com/blog/archives/000953.html" rel="noreferrer">Coding Horror article</a>:</p>
<blockquote>
<p>The problem is that <strong>MD5 is fast. So
are its modern competitors, like SHA1
and SHA256</strong>. Speed is a design goal of
a modern secure hash, because hashes
are a building block of almost every
cryptosystem, and usually get
demand-executed on a per-packet or
per-message basis.</p>
<p><strong>Speed is exactly what you don’t want
in a password hash function.</strong></p>
<p>Modern password schemes are attacked
with incremental password crackers.</p>
<p>Incremental crackers don’t
precalculate all possible cracked
passwords. They consider each password
hash individually, and they feed their
dictionary through the password hash
function the same way your PHP login
page would. Rainbow table crackers
like Ophcrack use space to attack
passwords; incremental crackers like
John the Ripper, Crack, and LC5 work
with time: statistics and compute.</p>
<p>The password attack game is scored in
time taken to crack password X. With
rainbow tables, that time depends on
how big your table needs to be and how
fast you can search it. With
incremental crackers, the time depends
on how fast you can make the password
hash function run.</p>
<p>The better you can optimize your
password hash function, the faster
your password hash function gets, the
weaker your scheme is. MD5 and SHA1,
even conventional block ciphers like
DES, are designed to be fast. MD5,
SHA1, and DES are weak password
hashes. On modern CPUs, raw crypto
building blocks like DES and MD5 can
be bitsliced, vectorized, and
parallelized to make password searches
lightning fast. Game-over FPGA
implementations cost only hundreds of
dollars.</p>
</blockquote>
<p>Some <a href="http://php.oregonstate.edu/manual/en/function.hash.php" rel="noreferrer">comments on the PHP MD5 documentation</a> also discuss preference for slowness.</p>
<p>To answer your question, it looks like BCrypt is the way to go. However, I have not been able to find any implementations for ASP Classic. If that's true, I would stick with a regular hash function like SHA512.</p>
|
<p>psuedocode for the slowest method:</p>
<pre><code>function hashPassword(password)
sleep for 10 seconds
return password
end function
</code></pre>
<p>This certainly isn't the most secure (or at all) but it's slow...</p>
<p>(I'm just pointing out that making it slower is not the answer...)</p>
| 31,620
|
<p>Say we are creating Acme CMS. This CMS web application will allow you to create an unlimited number of categories with sub-categories (unlimited depth), and each category can have 0+ content pages associated with it.</p>
<p>So this project, at a high level will have: </p>
<p><em>Front End</em>
1. index page
2. category page with list of content pages
3. content page</p>
<p><em>Admin Control Panel</em>
1. categories (add/update/delete)
2. pages (add/update/delete/)</p>
<p>Schema design
1. tables
2. stored procedures
3. data access layer</p>
<p>Questions:
I am using a bug tracker and Wiki, so how should I break this project down?</p>
<p>I am thinking of breaking each section (front end/ admin panel) down into individual pages, then writing simple user stories for each page (or theme).</p>
<p>When I have the user stories completed, I will then create a list of cases in my bug tracker representing features that I have to develop, along with an estimate for each one.</p>
<p><b>Am I breaking down this project properly? Any major gaps in planning that will make this project fail (in theory anyway!)</b></p>
<p><b>Please provide a detailed answer, maybe a general idea of what I should do, with a detailed example explaining it and why etc.</b></p>
|
<p>"I am thinking of breaking each section (front end/ admin panel) down into individual pages, then writing simple user stories for each page (or theme)."</p>
<p>Pages don't have stories. Users have stories. Pages are a thing you build to implement the user story.</p>
<p>The Theme -- if there is one for something this small -- is "managing content". Perhaps there are two themes: the collection of stories about writing/editing and the story(s) around browsing/reading.</p>
<p>Some users ('editors'?) want to create, organize, update and remove content so they can <em>something</em> [the question doesn't say]. You force them to use web pages because it's better - cheaper - faster than 5x8 cards and markers.</p>
<p>Some users ('readers'?) want to examine content and navigate so they can -- who knows? -- be happier and more productive at something. You force them to use web pages because it's somehow better than 5x8 cards held to a whiteboard with magnets.</p>
<p>You have stories about the theme of creating and managing content. </p>
<p>"then create a list of cases in my bug tracker representing features that I have to develop, along with an estimate for each one"</p>
<p>Right. And the features have to begin with data model first, then presentation in some useful form. Perhaps on pages. Indeed, once you have a model that satisfies the use cases in a broad way, you can fine-tune the presentation to make the model more usable.</p>
<p>"business layer & presentation is what I need to detail"</p>
<p>Model == business layer. They're the same thing.</p>
<p>Pages == presentation. Note. This is last. Once you have use cases and a model that supports those use cases, you can present your stuff to people so they can interact with the model.</p>
|
<p>The "unlimited" part is broken... even GMail has an upper limit... </p>
<p>Edit: Although my answer got downvoted I think it is right. As soon as you talk with non-programmers the "unlimite" parts become very dangerous, and will likely stab you in the back. Also you can't really have a scalable data schema for unlimited nesting... but that should be obvious.</p>
| 39,078
|
<p>For example, I hate typing things like:</p>
<pre><code>$x = mysql_escape_string(stripslashes($_GET['x']));
</code></pre>
<p>Is there a way to alias those two functions in init.php or something without writing a separate function that takes one argument and returns that argument with those functions applied to it?</p>
<p>My C/C++ is not very good, but I think this is sort of like #typedef but for functions?</p>
|
<p>This should do the trick :</p>
<pre><code>// Macros
$mes = "mysql_escape_string";
$ss = "stripslashes";
// Using your macros
$x = $mes($ss($_GET['x']));
</code></pre>
<p>Though I don't recommend coding like this at all. </p>
<p>I'm just answering the question since you said you didn't want to create any new function and get a "#define"-like functionality.</p>
|
<p>"easily", sure? "elegantly", nope.</p>
| 41,318
|
<p>I would like to know if it is possible to copy/move files to a destination based on the origin name.</p>
<p>Basically, I have a /mail folder, which has several subfolders such as cur and new etc. I then have an extracted backup in /mail/home/username that is a duplicate. mv -f will not work, as I do not have permission to overwrite the directories, but only the files within.</p>
<p>I get errors such as mv: cannot overwrite directory `/home/username/mail/username.com'</p>
<p>What I want to do is for each file in the directory username.com, move it to the folder of the same name in /mail. There could be any number of folders in place of username.com, with seperate sub sirectories of their own.</p>
<p>What is the best way to do this?</p>
<p>I have to do it this way as due to circumstances I only have access to my host with ftp and bash via php.</p>
<p>edit: clarification</p>
<p>I think I need to clarify what happened. I am on a shared host, and apparently do not have write access to the directories themselves. At least the main ones such as mail and public_html. I made a backup of ~/mail with tar, but when trying to extract it extracted to ~/mail/home/mail etc, as I forgot about the full path. Now, I cannot simply untar because the path is wrong, and I cannot mv -f because I only have write access to files, not directories.</p>
|
<p>For copying, you should consider using <code>cpio</code> in 'pass' mode (<code>-p</code>):</p>
<pre><code>cd /mail; find . -type f | cpio -pvdmB /home/username/mail
</code></pre>
<p>The <code>-v</code> is for verbose; <code>-d</code> creates directories as necessary; <code>-m</code> preserves the modification times on the files; <code>-B</code> means use a larger block size, and may be irrelevant here (it used to make a difference when messing with tape devices). Omitted from this list is the <code>-u</code> flag that does unconditional copying, overwriting pre-existing files in target area. The <code>cd</code> command ensures that the path names are correct; if you just did:</p>
<pre><code>find /mail -type f | cpio -pvdmB /home/username
</code></pre>
<p>you would achieve the same result, but only by coincidence - because the sub-directory under <code>/home/username</code> was the same as the absolute pathname of the original. If you needed to do:</p>
<pre><code>find /var/spool/mail -type f | cpio -pvdmB /home/username/mail
</code></pre>
<p>then the copied files would be found under <code>/home/username/mail/var/spool/mail</code>, which is unlikely to be what you had in mind.</p>
<p>You can achieve a similar effect with (GNU) <code>tar</code>:</p>
<pre><code>(cd /mail; tar -cf - . ) | (cd /home/username/mail; tar -xf - )
</code></pre>
<p>This copies directories, not just files. To do that, you need GNU-only facilities:</p>
<pre><code>(cd /mail; find . -type f | tar -cf - -F - ) | (cd /home/username/mail; tar -xf - )
</code></pre>
<p>The first solo dash means 'write to stdout'; the second means 'read from stdin'; the '-F' option means 'read the file names to copy from the named file'.</p>
|
<p>I'm not entirely clear on what it is that you want to do, but you could try the following:</p>
<pre><code>for file in /mail/*; do
mv -f $file /home/username/mail/$(basename $file)
done
</code></pre>
<p>This will move every file and subdirectory in /mail from there into /home/username/mail.</p>
| 47,418
|
<p>I'm working on a module for a CMS. This module is distributed as a class library DLL.</p>
<p>I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)?</p>
<p>I would like to have only one DLL.</p>
|
<p>You can merge your many DLLs with ILMERGE:</p>
<p><a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="noreferrer">http://research.microsoft.com/~mbarnett/ILMerge.aspx</a></p>
<p>Haven't tried it myself. Hope it helps.</p>
<hr>
<p>Download here:<br />
<a href="http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en" rel="noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en</a></p>
<p><strong>Brief Description</strong> <em>(from download-page)</em><br />
ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details.</p>
|
<p>The short answer for this is no!
You can not link in a dll during compilation.
I don't know if there is some subtle way to do this, but you would probably have to distribute the dlls along with your cms.
The best way to do this is to make some kind of re-distributable.</p>
| 6,019
|
<p>I'm really interested in speech-to-text algorithms, but I'm not sure where to start studying up on them. A bunch of searching around led me to <a href="http://cslu.cse.ogi.edu/HLTsurvey/download.html" rel="noreferrer">this</a>, but it's from 1996 and I'm fairly certain that there have been improvements since then.</p>
<p>Does anyone who has any experience with this sort of stuff have any recommendations for reading / source code to examine? Or just general advice on what I should be trying to learn about if I want to get into the world of writing speech recognition programs (sometimes it's hard to know what to search for if you don't have much knowledge about the domain).</p>
<p>Edit: I'd like to do something cross-platform, but for the moment I'd be targeting linux. </p>
<p>Edit 2: Thanks csmba for the well-thought out reply. At this point in time, I'm mainly interested in being able to create applications that allow automation, or execution of different commands through voice. So, a limited amount of recognizable commands being able to be strung together. An example would be a music player that took commands like "Play the album Hello Everything by Squarepusher", or an application launcher that allowed the user to create voice-shortcuts to launch specific apps.</p>
<p>I realize that it's a pretty giant problem, and that I have nowhere near the level of knowledge required right now to tackle implementing an entire recognition engine, although the techniques involved with doing so fascinate me, and it is something I'd like to work myself up to doing. In all likelihood, I'll probably end up picking up a book or two on the subject and studying up / playing with "simple" implementations in my free time.</p>
|
<p>This is a HUGE questions, I wouldn't know how to begin... So let me just try giving you the right "terms" so you can refine your quest:</p>
<p>First, understand that Speech Recognition is a diverse and complicated subject, and it has many different applications. People tend to map this domain to the first thing that comes to their head (usually, that would be computers understanding what you are saying like in IVR systems). So first lets distinguise the concept into the main categories:</p>
<p><strong>Human-to-Machine:</strong> Applications that deal with understanding what a human is saying, but the human knows he is talking to a machine and the <em>grammar</em> is very limited. Examples are </p>
<ul>
<li>Computer automation</li>
<li>Specialized: Pilots automating some controls for example (noise a huge problem) </li>
<li>IVR (Interactive Voice Response) systems like Google-411 or when you call the bank and the computer on the other side says "say 'service' to get customer service"</li>
</ul>
<p><strong>human-to-human</strong> (Spontaneous speech): This is a bigger, more complex problem. Here we can also break it down into different applciations:</p>
<ul>
<li>Call Center: conversation between Agent-Customer, phone quality, compressed</li>
<li>Intelligence: radio/phone/live conversations between 2 or more individuals</li>
</ul>
<p>Now, Speech-To-Text is not what you should be saying that you care about. What you care about is solving a problem. Different technologies are used to solve different problems. See an overview <a href="http://knol.google.com/k/csmba/speech-analytics/2p76v0g9rhval/3#" rel="nofollow noreferrer">here</a> of some of them. to summarize, other approaches are Phonetic transcription, LVCSR and direct based.</p>
<p>Also, are you interested in being the PHd behind the technology? you would need a Masters equivalent involving <em>Signal processing</em> and probably a PHd to be cutting edge. In which case, you will work for a company that develops the actual <strong>speech engine</strong>. Companies like Nuance and IBM are the big ones, but also Phillips and other startups exist.</p>
<p>On the other hand, if you want to be the one implementing applications, you will not be working on the engine, but working on building application that USE the engine. A good analogy I think is form the gaming industry:
Are you developing the graphic engine (like the Cry engine), or working on one of several hundred games, all use the same graphic engine?</p>
<p>Don't get me wrong, there is plenty to work on the quality of the search also outside the IBM/Nuance of the world. The engine is usually very open, and there are a lot of algorithmic tweaking to be done that can dramatically affect performance. Each business application has different constraints and cost/benefit function, so you can make experiments for many years building better voice recognition based applications.</p>
<p>one more thing: in general, you would also want to have good statistics background the lower in the stack you want to be.</p>
<blockquote>
<p>At this point in time, I'm mainly interested in being able to create applications that allow automation</p>
</blockquote>
<p>Good, we are converging here... Then you have no interest in "Speech-to-Text". That buzzwords takes you to the world of full transcription, a place you do not need to go to. You should be focusing on some of the more Human-to-Machine technologies like Voice XML and the ones used in IVR systems (Nuance is the biggest player there)</p>
|
<p>What platform are you targeting ?. There is <a href="http://www.microsoft.com/speech/speech2007/default.mspx" rel="nofollow noreferrer">Microsoft Speech APIs</a> that you can use if its for windows. </p>
| 3,561
|
<p>I have searched the internet and found various 3D printers with different advantages and materials which they can print - some even multi color. </p>
<p>However, I cannot seem to find a printer that can print multiple material with different properties; for instance, simultaneously printing PLA and metal. Is there currently such a printer available or in development? </p>
|
<p>Yes and no.</p>
<blockquote>
<p>for instance simultanious printing of plas plastic and lets say metal. Is such a printer available or in development ?</p>
</blockquote>
<p>Practically speaking, no. Metal printing requires significantly higher temperatures than plastic, and the two processes are so incompatible that there is currently no good solutions that would allow one printer to print both in the same print. Whether extruding filament, laser sintering, or curing resins, the materials involved have to be fairly similar in processing environment to print adjacent to each other without issue.</p>
<p>There are many printers that are intended to print multiple materials by changing the print head. You might, for instance, use a ceramic paste extruder, then change the head for the next print using plastic.</p>
<p>There have been efforts in the past, and some efforts are ongoing, to resolve this. For instance wood's metal, a low temperature alloy, can be poured at temperatures compatible with plastics, so it's possible to create a printer that prints plastic, leaving troughs or voids in the plastic, then the same printer during this print would pour molten woods metal into these areas, which then solidifies into an internal metal structure. These are intended for circuitry and electrical use, however significant problems still exist because the thermal expansion differences in these materials lead to stress and result in poor reliability.</p>
<p>So while some of these processes are being developed, this is still just in the experimental stage and there are significant problems to overcome before printers can print widely different materials in a single printing session.</p>
<p>Of course you can find plastics with such a wide range of characteristics that they can be seen as printing different materials. Plastics imbued with wood fibers, printing next to conductive plastics with graphite, printing next to flexible plastics, etc, etc are now possible, and depending on your requirements they may meet your needs.</p>
|
<p>For the most part, you can achieve this with a dual extruding printer. However, dual extrusion is best for either multi-color printing or printing with support material. For example, printing the part with PLA and all support material with water soluble PVA.</p>
<p>In practice, printing two completely different materials is not sound engineering practice as they have the potential to not make a well enough bond to each other. So, the case of pure metal and pure plastic, the two materials will not bond well because they will not both be in the same physical state together at any point in time.</p>
<p>However, your best option would be a printer like the <a href="https://markforged.com/" rel="nofollow">MarkForged</a> which uses a composite approach by combining a common binder (ABS, PLA, Nylon, etc.) and a strong material such as Carbon Fiber, Fiberglass, or Kevlar.</p>
| 182
|
<p>Given a columns' index, how can you get an Excel column name?</p>
<p>The problem is trickier than it sounds because it's <strong>not just base-26</strong>. The columns don't wrap over like normal digits would. Even the <a href="http://support.microsoft.com/kb/833402" rel="nofollow noreferrer">Microsoft Support Example</a> doesn't scale beyond ZZZ.</p>
<p><sub><em>Disclaimer: This is some code I had done a while back, and it came across my desktop again today. I thought it was worthy of posting here as a pre-answered question.</em></sub></p>
|
<p>The answer I came up with is to get a little recursive. This code is in VB.Net:</p>
<pre class="lang-vb prettyprint-override"><code>Function ColumnName(ByVal index As Integer) As String
Static chars() As Char = {"A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}
index -= 1 ' adjust so it matches 0-indexed array rather than 1-indexed column
Dim quotient As Integer = index \ 26 ' normal / operator rounds. \ does integer division, which truncates
If quotient > 0 Then
ColumnName = ColumnName(quotient) & chars(index Mod 26)
Else
ColumnName = chars(index Mod 26)
End If
End Function
</code></pre>
<p>And in C#:</p>
<pre class="lang-cs prettyprint-override"><code>string ColumnName(int index)
{
index -= 1; //adjust so it matches 0-indexed array rather than 1-indexed column
int quotient = index / 26;
if (quotient > 0)
return ColumnName(quotient) + chars[index % 26].ToString();
else
return chars[index % 26].ToString();
}
private char[] chars = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
</code></pre>
<p>The only downside it that it uses 1-indexed columns rather than 0-indexed.</p>
|
<p>I enjoy writing recursive functions, but I don't think it's necessary here. This is my solution in VB. It works up to column ZZ. If someone can tell me if it works for AAA to ZZZ that would be nice to know.</p>
<pre><code>Public Function TranslateColumnIndexToName(index As Integer) As String
'
Dim remainder As Integer
Dim remainder2 As Integer
Dim quotient As Integer
Dim quotient2 As Integer
'
quotient2 = ((index) / (26 * 26)) - 2
remainder2 = (index Mod (26 * 26)) - 1
quotient = ((remainder2) / 26) - 2
remainder = (index Mod 26) - 1
'
If quotient2 > 0 Then
TranslateColumnIndexToName = ChrW(quotient2 + 65) & ChrW(quotient + 65) & ChrW(remainder + 65)
ElseIf quotient > 0 Then
TranslateColumnIndexToName = ChrW(quotient + 65) & ChrW(remainder + 65)
Else
TranslateColumnIndexToName = ChrW(remainder + 65)
End If
</code></pre>
<p>End Function</p>
| 38,018
|
<p>I would like to implement a sliding notification bar as the one in Firefox or IE for my java application. But I don't want to reinvent the wheel and I'm sure someone out there has already done it and is willing to share.
Do you know any open-source implementation of this in java/swing?</p>
|
<p>There's an example in <a href="https://rads.stackoverflow.com/amzn/click/com/0596009070" rel="nofollow noreferrer" rel="nofollow noreferrer">Swing Hacks</a> called "Slide Notes Out from the Taskbar" that seems pretty close to what you want (there's a <a href="http://books.google.com/books?id=oNbFfcyAtv4C&pg=PA240&dq=%22Swing+hacks%22+%22slide+notes+out+from+the+taskbar%22" rel="nofollow noreferrer">preview</a> on Google's Book Search at the moment). </p>
<p>The code is freely available from the <a href="http://oreilly.com/catalog/9780596009076/" rel="nofollow noreferrer">official O'Reilly Swing Hacks page</a>, under "examples." Not sure what the license is, but it's worth a look (Chapter 6, hack 46). At any rate, Swing Hacks is a worthy purchase at ~$20.</p>
|
<p>A standard way to do it is to use <a href="http://docs.oracle.com/javase/7/docs/api/java/awt/TrayIcon.html" rel="nofollow noreferrer">Swing TrayIcon API</a>. That would probably be the most convenient way too :)</p>
| 36,982
|
<p>Our web application renders fast in some IE browsers, slow in others... It seems to be an HTML rendering problem... The first 10% of the page displays immediately, the last 90% takes up to 10 seconds, and this is static content. I've run with firefox/yslow, renders very quickly. Seems to be isolated to some users/configurations of ie. Quirks mode does not seem to make a difference.</p>
<p>Is there a tool or application that I can use to help me discover a rendering bottleneck? Am I doing something egregious in my code? Could it be a javascript issue? Any help or suggestions will be much appreciated. thanks.</p>
|
<p>Use Fiddler to look at the times to load images, css, js files, etc. In other words, is caching a problem? Javascript can definitely cause issues in different browser versions. There's lots of optimizations you find in some versions that aren't in others. Also, make sure your html is well-formed xhtml if possible. How the page is arranged can also affect life. If your document tree is deep, it may need to wait to render large sections until it reads all the child nodes. Another thing to note, certain toolbars and plugins do look ahead loading and can slow down life. An HTTP Proxy can help you watch what's going on network-wise at least.</p>
<p>Not sure if anything of those ideas might help your exact problem, but they can help life overall.</p>
|
<p>Steve Souders gives an excellent presentation on 14 (simple) steps to improve the performance of your web pages:</p>
<p><a href="http://developer.yahoo.net/blogs/theater/archives/2007/08/steve_souders_high_performance.html" rel="nofollow noreferrer">http://developer.yahoo.net/blogs/theater/archives/2007/08/steve_souders_high_performance.html</a></p>
<p>If it's hanging in the middle of the page, the first thing I would personally look to do is ensure or move all my JavaScript is at the bottom of the page.</p>
<p>IE is great at being a bad performer, particularly with JavaScript, so if you move it to the bottom, IE can render the page, <em>then</em> get on with processing the JavaScript.</p>
| 26,089
|
<p>I have a problem with classic ASP. The encoding is wrong when I send data with <code>XMLHttp.send</code>. The response is a PDF file, but the “ÆØÅ” gets wrong, the “Ø” is read as “øy” for example. It’s like it’s a converting mistake from UTF-8 to ISO-8859-1, but it should be ISO-8859-1 now. I have <code><%@CODEPAGE="28591"%></code> at the top at the page and <code>ISO-8859-1</code> as encoding in the XML file, I have checked the file so it’s valid ISO-8859-1. I don’t have access to the server I am sending this data to, but I fixed it in a VB6 program which use the same logic with:</p>
<pre><code>aPostBody = StrConv(strBody, vbFromUnicode)
WinHttpReq.SetTimeouts 100000, 100000, 100000, 1000000
WinHttpReq.Send aPostBody
</code></pre>
<p>And in a C# program that also uses the same logic with</p>
<pre><code>// ISO-8859-1
byte[] bytes = Encoding.GetEncoding(28591).GetBytes(data);
</code></pre>
<p>But in ASP classic I need some help to find a way to change the encoding on a string to ISO-8859-1.</p>
|
<p>Try:</p>
<pre><code>Session.CodePage = 28591
</code></pre>
<p>There is some good information <a href="http://devlibrary.businessobjects.com/BusinessObjectsXIR2/en/en/RAS_SDK/rassdk_com_doc/doc/rassdk_com_doc/BestPractices11.html" rel="nofollow noreferrer">here</a>, and I got the CodePage number <a href="http://support.microsoft.com/kb/287946" rel="nofollow noreferrer">here</a>.</p>
|
<p>AFAIK this is a known problem with WinHttpReq / XMLHTTPRequest, hope someone proves me wrong.</p>
| 42,905
|
<p>Can someone explain the main benefits of different types of references in C#?</p>
<ul>
<li>Weak references</li>
<li>Soft references</li>
<li>Phantom references</li>
<li>Strong references.</li>
</ul>
<p>We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.</p>
|
<p>Soft and phantom references come from Java, I believe. A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference. If there is an analog to SoftReference in C#, I don't know what it is.</p>
<p>Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope. They can be useful for holding on to large objects that are expensive to initialize, but should be available for garbage collection if they are not actively in use. </p>
<p>Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application. For example, if you have a moderate number of cached objects hanging around that may or may not be reused in the future, weak references could help improve the memory consumption of the caches. However, if the app is working with a very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.</p>
|
<p>Brilliant real example with WeakReference is explained in <a href="http://developer.android.com/training/displaying-bitmaps/process-bitmap.html" rel="nofollow noreferrer">Android development tutorial</a>.</p>
<p>There is an image (Bitmap) and image container on the view (ImageView). If image will be loaded not from memory (but e.g. from disk, net) then it can lock UI thread and the screen. To avoid it an async task can be used.</p>
<p>The problem arises when async task finishes. Image container can be not useful at all at that time (screen is changed or Android unloads invisible view part after scrolling). WeakReference can help here and ImageView will be garbage collected.</p>
<pre><code>class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Method for getting bitmap is removed for code clearness
// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
</code></pre>
<p>P.S. the example is in Java, but can be understood by C# developers.<br />
Source: <a href="http://developersdev.blogspot.ru/2014/01/weakreference-example.html" rel="nofollow noreferrer">http://developersdev.blogspot.ru/2014/01/weakreference-example.html</a></p>
| 40,034
|
<p>We currently have developed an application using WCF. Our clients make connections to different WCF servicehosts located on the server, and the servicehosts return the data from the DB that the clients need. Standard model. However, this current design has all of our WCF data in app.config files both on the client side as well as the servicehost side. We want to make this more dynamic, and have moved all of the data, including the endpoints, the contracts, and the bindings, into the DB.</p>
<p>Now the question is how do we retrieve this data, and access it properly. We've got the design working where we have one defined endpoint in a config file, and using that endpoint, we can make a call to it to get the rest of the endpoint information that we need (i.e. all of the bindings, contracts and different endpoints that it used to have defined in its app.config). This is the case on both the client side as well as the servicehost side.</p>
<p>The issue that I'm now struggling with is how do I code against these dynamic endpoints? When the client makes a call to the servicehost, it not only is making simple calls to the servicehost, but retrieving and passing back objects for the servicehost to process as needed. For example, on form load we may retrieve the object with all of the currently defined settings from the DB, and then the user does whatever on the fornm, and we then pass back the updated object to the servicehost. We can do that now because in Visual Studio 2008 we've added all of the service references, which has auto-generated the methods and objects that can be called and retrieved from the servicehosts. If we go to a dynamic endpoint connection, how do we get this data during the development phase?</p>
<p>I've developed a similar application in the past in .NET 2.0 using .NET remoting, where we were passing the object back and forth, and the client and server both used the same object definition class to know about the object. I'm not sure how we would go about doing this with WCF.</p>
|
<p>Please look at using the <a href="http://search.cpan.org/dist/WWW-Mechanize/" rel="noreferrer">WWW::Mechanize</a> module for this. It will fetch your web pages for you, and then give you easy-to-work with lists of URLs.</p>
<pre><code>my $mech = WWW::Mechanize->new();
$mech->get( $some_url );
my @links = $mech->links();
for my $link ( @links ) {
printf "%s, %s\n", $link->text, $link->url;
}
</code></pre>
<p>Pretty simple, and if you're looking to navigate to other URLs on that page, it's even simpler.</p>
<p>Mech is basically a browser in an object.</p>
|
<p>We can use regular expression to extract the link with its link text. This is also the one way.</p>
<pre><code>local $/ = '';
my $a = <DATA>;
while( $a =~ m/<a[^>]*?href=\"([^>]*?)\"[^>]*?>\s*([\w\W]*?)\s*<\/a>/igs )
{
print "Link:$1 \t Text: $2\n";
}
__DATA__
<a href="http://www.google.com">Google</a>
<a href="http://www.apple.com">Apple</a>
</code></pre>
| 31,726
|
<p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
|
<p>What you're talking about is establishing a "session". That is, a way to remember the user and the state of their transaction.</p>
<p>There are several ways of tackling this, all of which rely on techniques for remembering that you're in a session in the first place.</p>
<p>HTTP provides you no help. You have to find some place to save session state on the server, and some place to record session identification on the client. The two big techniques are</p>
<ul>
<li><p>Use a cookie to identify the session. Seamless and silent.</p></li>
<li><p>Use a query string in the URL to identify the session. Obvious because you have a <code>?sessionid=SomeSessionGUID</code> in your URL's. This exposes a lot and makes bookmarking annoying. After the session is cleaned up, you still have this session id floating around in people's bookmarks.</p></li>
<li><p>In a limited way, you can also use hidden fields in a form. This only works if you have forms on every page. Not always true.</p></li>
</ul>
<p>Here's how it plays out in practice.</p>
<ol>
<li><p>GET response. Check for the cookie in the header.</p>
<p>a. No cookie. First time user. Create a session. Save it somewhere (memory, file, database). Put the unique ID into a cookie. Respond knowing this is their first time.</p>
<p>b. Cookie. Been here recently. Try to get the cookie. </p>
<ul>
<li><p>FInd the session object. Respond using information in the cookie.</p></li>
<li><p>Drat. No session. Old cookie. Create a new one and act like this is their first visit.</p></li>
</ul></li>
<li><p>POST response. Check for the cookie in the header.</p>
<p>a. No cookie. WTF? Stupid kids. Get off my lawn! Someone bookmarked a POST or is trying to mess with your head. Respond as if it was a first-time GET.</p>
<p>b. Cookie. Excellent. Get the cookie. </p>
<ul>
<li><p>Find the session object. Find the thing you need in the session object. Respond.</p></li>
<li><p>Drat. No session. Old cookie. Create a new one and respond as if was a first-time GET.</p></li>
</ul></li>
</ol>
<p>You can do the same thing with a query string instead of a cookie. Or a hidden field on a form. </p>
|
<p>I don't know specifically about the google app engine, but normally, here's what happens:</p>
<p>The server would have some kind of thread pool. Every time an http request is sent to the server, a thread is selected from the pool or created.</p>
<p>In that thread an instance of some kind of controller object will be created. This object will decide what to do with the request (like instantiating other classes and preprocessing the http request parameters). Usually, this object is the core of web frameworks. The request parameters are also resent by the browser every time (the server cannot guess what the browser wants).</p>
<p>Web servers usually have state stores for objects in a permanent or a session state. The session is represented by a unique user (usually by a cookie or a GUID in the url), which expires after a certain time.</p>
<p>Now in your case, you would need to take the values you got from your first function, store that in the session store and in the second function, get those values back from the session store.</p>
<p>Another solution would be to send the items back to the page as url parameters in your generated HTML from the first function and then you would get those back "as usual" from your second function.</p>
| 46,739
|
<p>I have done a bit of testing on this myself (During the server side processing of a DWR Framework Ajax request handler to be exact) and it seems you CAN successfully manipulate cookies, but this goes against much that I have read on Ajax best practices and how browsers interpret the response from an XmlHttpRequest. Note I have tested on:</p>
<ul>
<li>IE 6 and 7</li>
<li>Firefox 2 and 3</li>
<li>Safari</li>
</ul>
<p>and in all cases standard cookie operations on the HttpServletResponse object during Ajax request handling were correctly interpreted by the browser, but I would like to know if it best practice to push the cookie manipulation to the client side, or if this (much cleaner) server side cookie handling can be trusted.</p>
<p>I would welcome answers both specific to the DWR Framework and Ajax in general.</p>
|
<p>XMLHttpRequest always uses the Web Browser's connection framework. This is a requirement for AJAX programs to work correctly as the user would get logged out if the XHR object lacked access to the browser's cookie pool. </p>
<p>It's theoretically possible for a web browser to simply share session cookies without using the browser's connection framework, but this has never (to my knowledge) happened in practice. Even the Flash plugin uses the Web Browser's connections. </p>
<p>Thus the end result is that it IS safe to manipulate cookies via AJAX. Just <strong>keep in mind</strong> that the AJAX call might never happen. They are not guaranteed events, so don't count on them.</p>
|
<p>Manipulating cookies on the client side is rather the opposite of "best practice". And it shouldn't be necessary, either. HttpOnly cookies weren't introduced for nothing.</p>
| 11,507
|
<p>I have a directory full of files and I need to pull the headers and footers off of them. They are all variable length so using head or tail isn't going to work. Each file does have a line I can search for, but I don't want to include the line in the results.</p>
<p>It's usually </p>
<pre><code>*** Start (more text here)
</code></pre>
<p>And ends with </p>
<pre><code>*** Finish (more text here)
</code></pre>
<p>I want the file names to stay the same, so I need to overwrite the originals, or write to a different directory and I'll overwrite them myself.</p>
<p>Oh yeah, it's on a linux server of course, so I have Perl, sed, awk, grep, etc.</p>
|
<p>Try the <a href="http://perldoc.perl.org/perlop.html#Range-Operators" rel="nofollow noreferrer">flip flop!</a> ".." operator.</p>
<pre><code># flip-flop.pl
use strict;
use warnings;
my $start = qr/^\*\*\* Start/;
my $finish = qr/^\*\*\* Finish/;
while ( <> ) {
if ( /$start/ .. /$finish/ ) {
next if /$start/ or /$finish/;
print $_;
}
}
</code></pre>
<p>U can then use the -i perl switch to update your file(s) like so.....</p>
<pre><code> $ perl -i'copy_*' flip-flop.pl data.txt
</code></pre>
<p>...which changes data.txt but makes a copy beforehand as "copy_data.txt".</p>
|
<p>Maybe? Start to Finish with not-delete.</p>
<pre><code>$ sed -i '/^\*\*\* Start/,/^\*\*\* Finish/d!' *
</code></pre>
<p>or...less sure of it...but, if it works, should remove the Start and Finish lines as well:</p>
<pre><code>$ sed -i -e '/./,/^\*\*\* Start/d' -e '/^\*\*\* Finish/,/./d' *
</code></pre>
<p><code>d!</code> may depend on the build of <code>sed</code> you have -- not sure.<br>
And, I wrote that entirely on (probably poor) memory.</p>
| 37,897
|
<p>I'm using the DnsQueryConfig Win32 function to get the DNS servers used by Windows. This works fine for IPv4 addresses, but what if the DNS servers have IPv6 addresses?</p>
|
<p>I could not find an API in MSDN, but I did find this line command:</p>
<blockquote>
<p><a href="http://msdn.microsoft.com/en-us/library/aa916844.aspx" rel="nofollow noreferrer">IPv6 dp6dns</a></p>
</blockquote>
|
<p>Which version of Windows do you mean?</p>
<p>At least in Windows XP, there's no support for querying DNS servers over IPv6 transport, so the question is moot.</p>
<p>I don't know whether that's fixed in Vista.</p>
| 24,007
|
<p>I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.</p>
<p>Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.</p>
<p>An update table set replicated=0;</p>
<p>is not possible:</p>
<ul>
<li>It takes very much time</li>
<li>It duplicates the size of the tabel because of MVCC</li>
<li>It is done in one transaction: It either fails or goes through.</li>
</ul>
<p>I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.</p>
<p>Several other problems:
Doing an </p>
<pre><code>update set replicated=0 where id >10000 and id<20000
</code></pre>
<p>is also bad: It does a sequential scan all over the whole table which is too slow.
If it weren't doing that, it would still be slow because it would be too many seeks.</p>
<p>What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.</p>
<p>Strangely, an</p>
<pre><code>UPDATE table
SET replicated=0
WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000)
</code></pre>
<p>is also slow, although it should be a good thing: Go through the table in DISK-order...</p>
<p>(Note that in that case there was also an index that covered this)</p>
<p>(An update LIMIT like Mysql is unavailable for PostgresQL)</p>
<p>BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible
It's PostgresQL 7.4 unfortunately.</p>
<p>The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.</p>
<p>The database itself only contains 5 tables, one is a very large one.
But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!</p>
<p>Any ideas?</p>
|
<p>How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then you simply add a record for every replicated item, and delete records to remove the replicated flag. (Or maybe the other way around - a record for every non-replicated record, depending on which is the common case).</p>
<p>That would also simplify the case when you want to set them all back to 0, as you can just truncate the table (which zeroes the table size on disk, you don't even have to vacuum to free up the space)</p>
|
<p>I think it's better to change your postgres to version 8.X. probably the cause is the low version of Postgres. Also try this query below. I hope this can help. </p>
<pre><code>UPDATE table1 SET name = table2.value
FROM table2
WHERE table1.id = table2.id;
</code></pre>
| 13,741
|
<p>I'm having problems refreshing .Net 2.0 with IIS 6.</p>
<p>I have been able to successfully execute "aspnet_regiis.exe -i", but when I try to register the aspnet_isapi.dll:</p>
<pre><code>regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
</code></pre>
<p>I get the error</p>
<blockquote>
<p>C:\Windows..\aspnet_isapi.dll was loaded, but the DllRegisterServer entry point was not found.</p>
<p>The file cannot be registered.</p>
</blockquote>
<p>Does anyone know how to resolve this? Google hasn't been very helpful.</p>
<p><strong>Edit:</strong> My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.</p>
<p>I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.</p>
<p><strong>@aaronjensen</strong>: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.</p>
<p>Microsoft tells me this because "<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true" rel="nofollow noreferrer">Lockdown Policy Prevents This Request</a>".</p>
<blockquote>
<p>If a request is denied because the
associated ISAPI or CGI has not been
unlocked, a 404.2 error is returned.</p>
</blockquote>
<p>Which I assume is due to the isapi DLL in my original query being denied?</p>
|
<p>In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.</p>
<p>I managed to resolve this using the following steps:</p>
<ul>
<li><p>Refresh the install using <code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root</code></p></li>
<li><p>Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true" rel="nofollow noreferrer">Lockdown Policy Prevents This Request</a> errors that I was seeing. Instructions to <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596ff388-bc4c-472f-b029-aea2b0418bea.mspx?mfr=true" rel="nofollow noreferrer">enable the ASP.Net webservice extension</a> are on MSDN.</p></li>
</ul>
|
<p>When you get the error, it means either:</p>
<p>1 The DLL does not need to be registered</p>
<p>or</p>
<p>2 The DLL is corrupt</p>
| 12,419
|
<p>I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers.</p>
<p>I would like to modify this <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow noreferrer">script</a> to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following:</p>
<p>1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow noreferrer">Red Book</a> does not indicate this clearly or I must have not seen it.</p>
<p>2) I would like to run the <a href="http://linux.about.com/od/commands/l/blcmdl1_dos2uni.htm" rel="nofollow noreferrer">dos2unix</a> command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in.</p>
<p>I would like your comments/feedback on this approach.</p>
|
<p>I think you can avoid a commit hook script in this case by using the <code>svn:eol-style</code> property as described in the SVNBook:</p>
<ul>
<li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.advanced.props.file-portability.html#svn.advanced.props.special.eol-style" rel="nofollow noreferrer">End-of-Line Character Sequences</a></p></li>
<li><p><a href="http://svnbook.red-bean.com/en/1.7/svn.ref.properties.html" rel="nofollow noreferrer">Subversion Properties</a></p></li>
</ul>
<p>This way SVN can worry about your line endings for you.</p>
<p>Good luck!</p>
|
<p>What exactly are you trying to do?</p>
<p>Of course, there are numerous places to learn about svn pre-commit hooks (e.g. <a href="http://wordaligned.org/articles/a-subversion-pre-commit-hook" rel="nofollow noreferrer"> here </a>, <a href="http://www.windley.com/archives/2008/08/using_a_precommit_hook_to_check_puppet_syntax.shtml" rel="nofollow noreferrer"> here</a>, and in the <a href="http://svnbook.red-bean.com/nightly/en/svn.reposadmin.create.html" rel="nofollow noreferrer">Red Book</a>) but it depends what you're trying to do and what is available on your system. </p>
<p>Can you be more specific? </p>
| 7,103
|
<p><b><a href="http://www.javafx.com/" rel="noreferrer">JavaFX 1.0</a></b> was released on Thursday, Dec. 4. </p>
<p>As a developer, what do you think of JavaFX? In your workplace, do you have any plans to move forward with JavaFX-based apps or websites? Do you have near-term plans to learn JavaFX?</p>
|
<p>JavaFX is the only open RIA platform, so I believe it will catch up with competition sooner or later.</p>
<p>It looks pretty good for 1.0 version. Demos are well documented and offer everything I need. </p>
<p>There are some problems of course. Java applet seems improved a little, but it's still way behind. Loading took long time with high cpu load. It didn't show any progress, like usual flash application do, so user can't be sure if his internet is slow, applet is big or java is slow. I also had to accept certificate, even more than one in some demos.</p>
|
<p>As far as I can tell JavaFX is falling flat on it's face. I've looked at the demos and example source code and I'm not impressed. JavaFX has an uphill battle to compete with Adobe and Silverlight which have already been in the wild for some time. Note that I'm a long time Java developer. </p>
| 45,985
|
<p>I have been adding dependency injection to my code because it makes by code much easier to Unit test through mocking.</p>
<p>However I am requiring objects higher up my call chain to have knowledge of objects further down the call chain.</p>
<p>Does this break the Law of Demeter? If so does it matter?</p>
<p>for example: a class A has a dependency on an interface B, The implementation of this interface to use is injected into the constructor of class A. Anyone wanting to use class A must now also have a reference to an implementation of B. And can call its methods directly meaning and has knowledge of its sub components (interface B)</p>
<p>Wikipedia says about the law of Demeter: "The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents)."</p>
|
<p>Dependency Injection CAN break the Law of Demeter. If you force consumers to do the injection of the dependencies. This can be avoided through static factory methods, and DI frameworks.</p>
<p>You can have both by designing your objects in such a way that they require the dependencies be passed in, and at the same time having a mechanism for using them without explicit performing the injection (factory functions and DI frameworks).</p>
|
<p>Depends :-)</p>
<p>I think the top answer is not correct , even with a framework a lot of code uses Dependency injection and injects high level objects. You then get spaghetti code with lots of dependencies. </p>
<p>Dependency injection is best used for all the stuff that would pollute your object model eg an ILogger. If you do inject business object ensure its at the lowest level possible and try to pass it the traditional method if you can . Only use the dependecy injection if it gets to messy .</p>
| 19,355
|
<p>I'm using NHibernate on a project and I need to do data auditing. I found <a href="http://www.codeproject.com/KB/cs/NHibernate_IInterceptor.aspx" rel="nofollow noreferrer">this article</a> on codeproject which discusses the IInterceptor interface.</p>
<p>What is your preferred way of auditing data? Do you use database triggers? Do you use something similar to what's dicussed in the article?</p>
|
<p>For NHibernate 2.0, you should also look at <a href="http://knol.google.com/k/fabio-maulo/nhibernate-chapter-11/1nr4enxv3dpeq/14#view" rel="noreferrer">Event Listeners</a>. These are the evolution of the IInterceptor interface and we use them successfully for auditing.</p>
|
<p>I prefer the CodeProject approach you mentioned.</p>
<p>One problem with database triggers is that it leaves you no choice but to use Integrated Security coupled with ActiveDirectory as access to your SQL Server. The reason for that is that your connection should inherit the identity of the user who triggered the connection; if your application uses a named "sa" account or other user accounts, the "user" field will only reflect "sa".</p>
<p>This can be overriden by creating a named SQL Server account for each and every user of the application, but this will be impractical for non-intranet, public facing web applications, for example.</p>
| 3,671
|
<p>Programming PHP in Eclipse PDT is predominately a joy: code completion, templates, method jumping, etc.</p>
<p>However, one thing that drives me crazy is that I can't get my lines in PHP files to word wrap so on long lines I'm typing out indefinitely to the right.</p>
<p>I click on Windows|Preferences and type in "wrap" and get:</p>
<pre><code>- Java | Code Style | Formatter
- Java | Editor | Typing
- Web and XML | CSS Files | Source
</code></pre>
<p>I've tried changing the "wrap automatically" that I found there and the "Line width" to 72 but they had no effect.</p>
<p>How can I get word wrap to work in Eclipse PDT for PHP files?</p>
|
<p>This has really been one of the most desired features in Eclipse. It's not just missing in PHP files-- it's missing in the IDE. Fortunately, from Google Summer of Code, we get this plug-in <a href="http://ahtik.com/blog/projects/eclipse-word-wrap/" rel="noreferrer">Eclipse Word-Wrap</a></p>
<p>To install it, add the following update site in Eclipse:</p>
<p><a href="http://ahtik.com/eclipse-update/" rel="noreferrer">AhtiK Eclipse WordWrap 0.0.5 Update Site</a></p>
|
<p>It's a known enhancement request. <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=35779" rel="noreferrer">Bug 35779</a></p>
| 12,316
|
<p>What firefox plugins could you not live without, as relates to webdev?</p>
<p>My list would be:</p>
<ul>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/3227" rel="nofollow noreferrer">DBGBar</a></li>
<li><a href="https://addons.mozilla.org/nl/firefox/addon/6622" rel="nofollow noreferrer">Dom Inspector</a></li>
<li>Firebug</li>
<li><a href="https://addons.mozilla.org/en-US/firefox/addon/6683" rel="nofollow noreferrer">Firecookie</a></li>
<li>Google toolbar (useful for seo)</li>
<li>Live HTTP</li>
<li><a href="https://addons.mozilla.org/nl/firefox/addon/115" rel="nofollow noreferrer">ReloadEvery</a></li>
<li>TamperData</li>
<li>Web Developer</li>
</ul>
<p>I am always on the lookout for new ones though, so I wonder if anyone knows of any great ones that I may have missed?</p>
|
<p><a href="http://getfirebug.com/" rel="noreferrer">Firebug</a> is the main one I use.</p>
|
<ul>
<li>Web Developer</li>
<li>Firebug</li>
<li>Delicious</li>
</ul>
<p>Might also add Page Validator</p>
| 45,310
|
<p>I am fairly new to WPF. I want to develop a datagrid control which supports databinding.</p>
<p>There is a lot of information available about databinding to existing controls, but I cannot find any information how to develop a control from scratch which supports databinding. </p>
<p>I do not expect a simple answer to this question, a link to get me started would be nice.</p>
|
<p>Are you planning to build a DatGrid control?. There is one here <a href="http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14963" rel="nofollow noreferrer">http://www.codeplex.com/wpf/Release/ProjectReleases.aspx?ReleaseId=14963</a></p>
<p>Binding is one of the important features of WPF, Dependancyproperty actually gives a control the ability to bind and listen to data change events(Data Binding).
When you develop your control you dont need to do anything special to make the DataBinding work, just need to define appropriate Dependency properties to the control,</p>
<p>You can read more about DataBinding here <strong><a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms752347.aspx</a></strong></p>
|
<p>Thanks for the answer.</p>
<p>Yes, when I said 'grid' I meant a 'datagrid'. I edited the question to make this more clear.</p>
<p>The article on MSDN main describes how to use databinding, and does not say too much what you have to do if you want to develop a WPF-control which supports databinding.</p>
| 23,968
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.