input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
CodeIgniter: URIs and Forms <p>I'm implementing a search box using CodeIgniter, but I'm not sure about how I should pass the search parameters through. I have three parameters: the search string; product category; and the sort order. They're all optional. Currently, I'm sending the parameters through <code>$_POST</code> to a temporary method, which forwards the parameters to the regular URI form. This works fine. I'm using a weird URI format though:</p>
<pre><code>http://site.com/products/search=computer,sort=price,cat=laptop
</code></pre>
<p>Does anyone have a better/cleaner format of passing stuff through?
I was thinking of passing it into the products method as arguments, but since the parameters are optional things would get messy. Should I suck it up, and just turn <code>$_GET</code> methods on? Thanks in advance!</p>
| <h1>Query Strings</h1>
<p>You can <a href="http://codeigniter.com/user%5Fguide/general/urls.html" rel="nofollow">enable query strings in CodeIgniter</a> to allow a more standard search function. </p>
<p><strong>Config.php</strong></p>
<pre><code>$config['enable_query_strings'] = FALSE;
</code></pre>
<p>Once enabled, you can accept the following in your app:</p>
<pre><code>http://site.com/products/search?term=computer&sort=price&cat=laptop
</code></pre>
<p>The benefit here is that the user will find it easy to edit the URL to make a quick change to their search, and your search uses common search functionality.</p>
<p>The down side of this approach is that you are going against one of the design decisions of the CodeIgniter development team. However, my personal opinion is that this is OK provided that query strings are not used for the bulk of your content, only for special cases such as search queries.</p>
|
Is there any open source program that use the inpout.dll? <p>Is there any open source program that use the inpout.dll to hook up the parell port and turn LED's on and off ive been looking for almost a whole month and havent found jack. I want to do this without any microcontrollers.</p>
| <p>These sites, <a href="http://www.lvr.com/parport.htm" rel="nofollow">http://www.lvr.com/parport.htm</a> and <a href="http://lcdinterfacing.googlepages.com/" rel="nofollow">http://lcdinterfacing.googlepages.com/</a>, have some VB code for testing and using inpout.dll in real world scenarios, which you could probably tailor to C++.</p>
<p><a href="http://logix4u.net/Legacy%5FPorts/Parallel%5FPort/A%5Ftutorial%5Fon%5FParallel%5Fport%5FInterfacing.html" rel="nofollow">This site</a>, has a C++ tutorial on using it.</p>
<p>(* Strange, if you click on that link, you get a 404 but, if you then just hit ENTER in the address bar, it works - the address is:</p>
<pre><code>http://logix4u.net/Legacy_Ports/Parallel_Port/A_tutorial_on_Parallel_port_Interfacing.html
</code></pre>
<p>if you want to cut and paste - it appears to be something to do with underscore/%5F translation *).</p>
<p>Note the comments that, if you're developing for the more secure Windows platforms (anything after Win98, I guess), you should be using the inpout32 variant.</p>
<p>Those links are good if you're just looking for source to be able to write your own. If, by open source, you actually meant 'speech-free', I haven't been able to find any (SourceForge, which is my go-to place for FOSS, returns zero hits).</p>
|
Closing application and running an external application <p>I am writing the update system for my application and I need to shutdown the application to overwrite the exe but after it shuts down I need to run the update executable, how can I do this?</p>
| <p>Do it in reverse. Get the entire updated file down using the old application (storing it temporarily) and then start the updater application using process start. All the update has to do is copy the new file over the old file and restart the application.</p>
<p>The updater can catch the access denied exceptions and wait for the application to become available for being copyied over. Once the copy is done - it deletes the temporary new file and starts the application again before shutting down.</p>
<p>Then you can update the updater (using the normal application) if you need to.</p>
|
TSQL Passing MultiValued Reporting Services Parameter into Dynamic SQL <p><strong>Duplicate of</strong>: <a href="http://stackoverflow.com/questions/712443/tsql-varchar-string-manipulation-problem/712453#712453">http://stackoverflow.com/questions/712443/tsql-varchar-string-manipulation-problem/712453#712453</a></p>
<p>I'm building a dynamic SQL statement out of parameters from a reporting services report. Reporting services passes MutiValue Parameters in a basic CSV format. For example a list of states may be represented as follows: AL,CA,NY,TN,VA</p>
<p>In a SQL statement this is OK: </p>
<pre><code>WHERE customerState In (@StateList)
</code></pre>
<p>However, the dynamic variant isn't OK:</p>
<pre><code>SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (' + @StateList + ') '
</code></pre>
<p>This is because it translates to (invalid SQL):</p>
<pre><code>AND customerState IN (AL,CA,NY,TN,VA)
</code></pre>
<p>To process it needs something like this:</p>
<pre><code>AND customerState IN ('AL','CA','NY','TN','VA')
</code></pre>
<p>Is there some cool expression I can use to insert the single quotes into my dynamic SQL?</p>
| <p>For anyone attempting to use Dynamic SQL with a multi-valued parameter in the where clause AND use it to run an SSRS report, this is how I got around it...</p>
<pre><code>create table #temp
(id, FName varchar(100), LName varchar(100))
declare @sqlQuery (nvarchar(max))
set @sqlQuery =
'insert into #temp
select
id,
FName,
LName
from dbo.table'
exec (@sqlQuery)
select
FName, LName
from #temp
where #temp.id in (@id) -- @id being an SSRS parameter!
drop table #temp
</code></pre>
<p>Granted, the problem with this query is that the dynamic SQL will select everything from dbo.table, and then the select from #temp is where the filter kicks in, so if there's a large amount of data - it's probably not so great. But... I got frustrated trying to get REPLACE to work, or any other solutions others had posted. </p>
|
Interpreting Number Ranges in Python <p>In a Pylons webapp, I need to take a string such as "<3, 45, 46, 48-51, 77" and create a list of ints (which are actually IDs of objects) to search on. </p>
<p>Any suggestions on ways to do this? I'm new to Python, and I haven't found anything out there that helps with this kind of thing.</p>
<p>The list would be: [1, 2, 3, 45, 46, 48, 49, 50, 51, 77]</p>
| <p>Use parseIntSet from <a href="http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html">here</a></p>
<p>I also like the pyparsing implementation in the comments at the end.</p>
<p>The parseIntSet has been modified here to handle "<3"-type entries and to only spit out the invalid strings if there are any.</p>
<pre><code>#! /usr/local/bin/python
import sys
import os
# return a set of selected values when a string in the form:
# 1-4,6
# would return:
# 1,2,3,4,6
# as expected...
def parseIntSet(nputstr=""):
selection = set()
invalid = set()
# tokens are comma seperated values
tokens = [x.strip() for x in nputstr.split(',')]
for i in tokens:
if len(i) > 0:
if i[:1] == "<":
i = "1-%s"%(i[1:])
try:
# typically tokens are plain old integers
selection.add(int(i))
except:
# if not, then it might be a range
try:
token = [int(k.strip()) for k in i.split('-')]
if len(token) > 1:
token.sort()
# we have items seperated by a dash
# try to build a valid range
first = token[0]
last = token[len(token)-1]
for x in range(first, last+1):
selection.add(x)
except:
# not an int and not a range...
invalid.add(i)
# Report invalid tokens before returning valid selection
if len(invalid) > 0:
print "Invalid set: " + str(invalid)
return selection
# end parseIntSet
print 'Generate a list of selected items!'
nputstr = raw_input('Enter a list of items: ')
selection = parseIntSet(nputstr)
print 'Your selection is: '
print str(selection)
</code></pre>
<p>And here's the output from the sample run:</p>
<pre><code>$ python qq.py
Generate a list of selected items!
Enter a list of items: <3, 45, 46, 48-51, 77
Your selection is:
set([1, 2, 3, 45, 46, 77, 48, 49, 50, 51])
</code></pre>
|
VB6 silently deleting huge chunks of control data from forms <p>My project has maybe 130 controls (total of all labels, textboxes, etc.) in an SSTab (4 tabs). The project loads fine, it runs fine, I don't see a single error or warning at any point, but when I save the form with the SStab on it, the SStab data isn't saved (it is completely gone). Normally the relevant portion of the .frm file looks like this: </p>
<pre> Begin TabDlg.SSTab SSTab1
Height = 8895
[1550 more lines of code for all the controls]
Width = 540
End
Begin VB.Menu FileMenu</pre>
<p>But lately it's getting cropped to:</p>
<pre> Begin TabDlg.SSTab SSTab1
Begin VB.Menu FileMenu</pre>
<p>This is very frustrating! In my VB IDE, the frame, sstab, and all the controls are there, editable, running/compiling fine, no error messages at any point, but when you save the file, 1550 lines of precious sstab data just disappears - again, with no warning or error messages. So if you exit and restart the IDE, you get a form load error because 60% of the code is now missing. The log file points to the first error it finds (in this case a Begin TabDlg with no End) - there's no other info in it. (The log file was generated after the code was deleted and saved, so it makes sense that it wouldn't be helpful.)</p>
<p>When I first posted this question, I thought it had to do with the number of controls, because it appeared after I added a control, and in my first few tests, seemed to disappear when that control (or other controls) was deleted. Now I can't seem to get that form to save under any circumstances, even when I delete many controls (bringing the number of controls far below where it was when it was last stable).</p>
<p>I also tried deleting the SStab and moving all the controls to 4 different frames. I successfully did that in the IDE, but when I saved, a huge chunk of the data (starting with a slider control) was missing. So I have no fraking idea what is going on.</p>
<p>The problem is reproducible on two different PCs, so it doesn't appear to be a hardware/corrupt software VB install issue.</p>
<p>Has anyone else run into something like this?</p>
| <p>Create a UserControl for each tab. That makes editing MUCH easier. It also allows you to nicely modularize the code, so each tab lives in its own file, and it'll allow you to reuse tabs elsewhere if you want.</p>
|
Using CSV as a mutable database? <p>Yes, this is as stupid a situation as it sounds like. Due to some extremely annoying hosting restrictions and unresponsive tech support, I have to use a CSV file as a database. </p>
<p>While I can use MySQL with PHP, I can't use it with the Python backend of my program because of install issues with the host. I can't use SQLite with PHP because of more install issues, but can use it as it's a Python builtin.</p>
<p>Anyways, now, the question: is it possible to update values SQL-style in a CSV database? Or should I keep on calling the help desk?</p>
| <p><strong>Don't walk, run to get a new host immediately</strong>. If your host won't even get you the most basic of free databases, it's time for a change. There are many fish in the sea.</p>
<p>At the very least I'd recommend an xml data store rather than a csv. <a href="http://chrisballance.com" rel="nofollow">My blog</a> uses an xml data provider and I haven't had any issues with performance at all.</p>
|
Where can I find a nice .NET Tab Control for free? <p>I'm doing this application in C# using the free Krypton Toolkit but the Krypton Navigator is a paid product which is rather expensive for me and this application is being developed on my free time and it will be available to the public for free.</p>
<p><strong>So, I'm looking for a free control to integrate better into my Krypton application because the default one doesn't quite fit and it will be different depending on the OS version...</strong></p>
<p>Any suggestions?</p>
<p>P.S: I know I could owner-draw it but I'm trying not to have that kind of work... I prefer something already done if it exists for free.</p>
<p><strong>EDIT:</strong>
I just found exactly what I wanted:<br />
<a href="http://www.angelonline.net/CodeSamples/Lib%5F3.5.0.zip">http://www.angelonline.net/CodeSamples/Lib_3.5.0.zip</a></p>
| <p>My first suggestion would be to talk to Phil at ComponentFactory. I find him to be a very reasonable fellow. Maybe he can give you a special deal or make a design suggestion on how to customize the existing tab control.</p>
<p>But your's is more of a design/subjective question that, I think, would benefit from a screenshot to better communicate the design challenge you need to "integrate better". Saying "the default one doesn't quite fit" is pretty vague.</p>
<p>After that, people will have a better starting point for making suggestions. In the mean time, I would look at <a href="http://windowsclient.net/downloads/folders/controlgallery/default.aspx" rel="nofollow">the WindowsClient.NET control gallery</a>.</p>
|
List of special characters for SQL LIKE clause <p>What is the complete list of all special characters for a SQL (I'm interested in SQL Server but other's would be good too) LIKE clause?</p>
<p>E.g.</p>
<pre><code>SELECT Name FROM Person WHERE Name LIKE '%Jon%'
</code></pre>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/ms179859.aspx">SQL Server</a>:</strong></p>
<ol>
<li>%</li>
<li>_</li>
<li>[specifier] E.g. [a-z]</li>
<li>[^specifier]</li>
<li>ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true</li>
<li>' characters need to be escaped with ' E.g. they're becomes they''re</li>
</ol>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator%5Flike"><strong>MySQL:</strong></a></p>
<ol>
<li><code>%</code> - Any string of zero or more characters.</li>
<li><code>_</code> - Any single character</li>
<li>ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true</li>
</ol>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator%5Flike"><strong>Oracle:</strong></a></p>
<ol>
<li><code>%</code> - Any string of zero or more characters.</li>
<li><code>_</code> - Any single character</li>
<li>ESCAPE clause E.g. %30!%%' ESCAPE '!' will evaluate 30% as true</li>
</ol>
<p><strong>Sybase</strong></p>
<ol>
<li>%</li>
<li>_</li>
<li>[specifier] E.g. [a-z]</li>
<li>[^specifier]</li>
</ol>
<p><strong><a href="http://www.progress.com">Progress:</a></strong></p>
<ol>
<li><code>%</code> - Any string of zero or more characters.</li>
<li><p><code>_</code> - Any single character</p>
<p><a href="http://www.progress.com/progress/products/documentation/docs/sql92/e92/e92.pdf">Reference Guide here</a> [PDF]</p></li>
</ol>
<p><strong><a href="http://www.postgresql.org/docs/7.4/interactive/functions-matching.html">PostgreSQL:</a></strong></p>
<ol>
<li><code>%</code> - Any string of zero or more characters.</li>
<li><code>_</code> - Any single character</li>
</ol>
<p><strong><a href="http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt">ANSI SQL92:</a></strong></p>
<ol>
<li>%</li>
<li>_</li>
<li>An ESCAPE character <em>only if specified</em>.</li>
</ol>
<p>PostgreSQL also has the <code>SIMILAR TO</code> operator which adds the following:</p>
<ol>
<li><code>[specifier]</code></li>
<li><code>[^specifier]</code></li>
<li><code>|</code> - either of two alternatives</li>
<li><code>*</code> - repetition of the previous item zero or more times.</li>
<li><code>+</code> - repetition of the previous item one or more times.</li>
<li><code>()</code> - group items together</li>
</ol>
<p>The idea is to make this a community Wiki that can become a "One stop shop" for this.</p>
| <p>For SQL Server, from <a href="http://msdn.microsoft.com/en-us/library/ms179859.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms179859.aspx</a> : </p>
<ul>
<li><p>% Any string of zero or more characters.</p>
<p><code>WHERE title LIKE '%computer%'</code> finds all book titles with the word 'computer' anywhere in the book title.</p></li>
<li><p>_ Any single character.</p>
<p><code>WHERE au_fname LIKE '_ean'</code> finds all four-letter first names that end with ean (Dean, Sean, and so on).</p></li>
<li><p>[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).</p>
<p><code>WHERE au_lname LIKE '[C-P]arsen'</code> finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.</p></li>
<li><p>[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).</p>
<p><code>WHERE au_lname LIKE 'de[^l]%'</code> all author last names starting with de and where the following letter is not l.</p></li>
</ul>
|
Transactional theory <p>(I have a simple CRUD API in a DAO pattern implementation.)
All operations (save, load, update, delete) have a transaction id that must be supplied.
So eg. its possible to do:</p>
<p>...</p>
<pre><code>id = begintransaction();
dao.save(o, id);
sao.update(o2, id);
rollback(id);
</code></pre>
<p>All examples excluding load invocations seems intuitive. But as soon as you start to load objects from the database, things "feel" a little bit different. Are load-operations, per definition, tied to a transaction? Or should my load operations be counted as a single amount of work?</p>
| <p>Depends on the transaction isolation level (<a href="http://en.wikipedia.org/wiki/Isolation%5F%28database%5Fsystems%29" rel="nofollow">http://en.wikipedia.org/wiki/Isolation_(database_systems)</a>) you're using, but in general they should be part of the transaction. What if somebody else is just in the middle of updating the data you're trying to read? If the read operation is not transactional, you would get old data, and maybe you're interested in the latest data.</p>
|
PROBLEM encountered visual studio 2008 installation <p>I installed visual studio 2008 package FULL option. It worked with out any problem. I installed Vstudio 2008 and MSDN in separate folder in the D drive. 2 days later in order to remove my projects i uninstalled every thing and also i deleted visual studio 2008, visual studio 2005 folders from C:\Documents and Settings\IRCTC\My Documents. (i believe these 2 folders were automatically created when we install visual studio) also i cleared %path% and path (c/windows/path). Again i installed VISUAL STUDIO 2008 but now i can't able to create window application (other web, vb also), what is the solution for this ...
ERROR that shown is</p>
<p>c:/documents and settings/IRCTC/local settings/temp/g1zzsdl.bak/temp/windowsFormsApplication.csproj cannot be opened because project type (.csproj) is not supported by this version of visual studio.......please help....</p>
<p>whether any system file corrupted (windows temp or .net folber in windows).....
no other installation problem found in my system..... please help.....what are the files/folders required for the installation......</p>
| <p>When you get that error is usually because:</p>
<ol>
<li><strong>You are trying to open a project created with a previous version of Visual Studio</strong> (not your case)</li>
<li><strong>There was a bit of a screw-up during the installation</strong> (sounds like your case)</li>
</ol>
<p>I'd uninstall the thing and reinstall completely first thing.</p>
<p>If it still doesn't work, it could be related to VS templates and you might wanna try and run from Visual Studio 2008 command prompt:</p>
<pre><code>devenv /InstallVSTemplates
</code></pre>
<p>If it still doesn't work, open Visual Studio, in the menu, Open Tools->Options->Projects and Solutions->General. At this point you will notice the path of Project Templates is set to "C:\Documents and Settings[yourUserName]\My Documents\Visual Studio 9\Templates\ProjectTemplates" or something very similar to that. In order to fix it you gotta set that path to C:\Program Files\Microsoft Visual Studio 9\Common7\IDE\Project Templates or the same path according to wherever you installed Visual Studio</p>
<p>I don't hitnk is related to VS project Templates though - see <a href="http://www.discussweb.com/server-management/10317-csproj-not-supported-version-visual-studio-2008-a.html" rel="nofollow">this link</a> </p>
<p>try and see what happens!</p>
|
When to close NSOutputStream? <p>I want to send the data of a UIImage to the server through a socket, so I:</p>
<p>a) open NSOutputStream</p>
<pre><code>
- (IBAction)send:(id)sender {
NSURL *website = [NSURL URLWithString:str_IP];
NSHost *host = [NSHost hostWithName:[website host]];
[NSStream getStreamsToHost:host port:1100 inputStream:nil outputStream:&oStream];
[oStream retain];
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];
}
</code></pre>
<p>b) write data to oStream when space is available</p>
<pre><code>
- (void) stream: (NSStream *) stream handleEvent: (NSStreamEvent) eventCode
{
switch(eventCode)
{
case NSStreamEventHasSpaceAvailable:
{
if(stream == oStream)
{
NSData *data = UIImageJPEGRepresentation(drawImage.image, 90);
//Convert from host to network endianness
uint32_t length = (uint32_t)htonl([data length]);
[oStream write:(uint8_t *)&length maxLength:4];
[oStream write:[data bytes] maxLength:length];
}
}
break;
}
</code></pre>
<p>The problem is that the data keeps writing to the oSream again and again. How to stop it when all the data is sent?</p>
<p>I send the length of the data before the Image data in order to let the server know when it reaches the end. Do I have to change the code in the server side to close the socket when it reaches the end? And where can I add [oStream close] to close the oStream in the client side?</p>
| <blockquote>
<p>The problem is that the data keeps writing to the oSream again and again. How to stop it when all the data is sent?</p>
</blockquote>
<p>See, this is the danger of thinking in the passive voice. Reword the question in the active voice:</p>
<blockquote>
<p>The problem is that the data keeps writing to the oSream again and again. How to stop it when I have sent all the data?</p>
</blockquote>
<p>And you have almost answered your own question.</p>
<p>A large part of the problem is your <code>HasSpaceAvailable</code> handler. Here's what you're doing:</p>
<ol>
<li>Creating a complete JPEG representation of the image (every time)</li>
<li>Sending the length of the representation (every time)</li>
<li>Sending the first portion of the representation (every time)</li>
</ol>
<p>These are three problems and you need to solve all three.</p>
<ol>
<li>Create the JPEG representation once.</li>
<li>Send the length of the representation only once.</li>
<li>Keep track of what you have already sent and only send the first part of what you haven't.</li>
</ol>
<p>To do all three, put the length into an NSMutableData and append the JPEG representation to it. Then, retain this new data object, and have additional instance variables for the bytes pointer and the length remaining. You'll do all this <em>before</em> you get to the <code>HasSpaceAvailable</code> state.</p>
<p>Then, when you do get to <code>HasSpaceAvailable</code>, don't separately send the length, because you've put it into the data object. You need only send the bytes from your pointer instance variable with the length remaining as the max length. After you check that the number of bytes sent was not 0 or -1 (see <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSOutputStream%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSOutputStream/write:maxLength:">the documentation</a>), add it to the pointer and subtract it from the length remaining.</p>
<p>When the length remaining reaches zero, you have sent everything. Assuming you don't want to follow the JPEG data up with something, you can then close the stream.</p>
|
windows services <p>Is it possible to create a windows service which will be unstoppable until the machine gets shutdown. Because I want to run one of my applications along with the service, is it possible to do it?</p>
<p>Thanks, just tell me how to run my application along with the service.</p>
| <p>You cannot create a process that is un-killable in Windows. Otherwise Windows would do this to critical processes (kill csrss.exe for a quick BSOD). With careful setting of service and process ACLs you can make it harder, but this can always be beaten with Take Ownership and Debug privileges.</p>
|
Upgrading Enterprise Library (1.0) to LINQ or Entity framework <p>We are working on a C# windows project with <strong>enterprise library 1.0</strong> that needs to be updated to either LINQ or Entity framework. (.NET 3.5)</p>
<p>The application uses mainly SQL connections as <strong>stored procedures</strong> and <strong>XML</strong> files to store settings.</p>
<ol>
<li>What is the pros and cons with
<strong>LINQ</strong> and <strong>Entity framework</strong> in this case?</li>
<li><em>Are the rumors true that LINQ will be discontinued?</em> </li>
<li>Which one would be most efficient to change to considering our setup?</li>
<li>Any good starting points?</li>
<li>What to avoid?</li>
</ol>
| <p>Here's a brief overview..</p>
<ol>
<li><p>This has been asked somewhat frequently - Here's a <a href="http://stackoverflow.com/questions/8676/entity-framework-vs-linq-to-sql">previous Q & A</a> and I answered bascially this same question before <a href="http://stackoverflow.com/questions/349718/ado-net-entity-framework-decision-making-between-orm-solutions/349755#349755">here</a> - however to be more specific to your scenario.. I'd need to know a bit more beyond what you've already described (i.e. besides upgrading/migrating from an Enterprise Library architecture).</p></li>
<li><p>I think you meant "Are the rumors true that <strong>LINQ to SQL</strong> will be discontinued?".. That's also been previously discussed <a href="http://stackoverflow.com/questions/253263/has-microsoft-really-killed-linq-to-sql">here</a> but the short answer is not in the immediate future.</p></li>
<li><p>You need to discuss a little more about your broader plans. IMHO either will work fine in the architecture you've described (feel free to provide more detail). Ask some more questions such as.. will you ever need to support a database other than SQL Server? Would you ever use eSQL (Entity SQL) or just stick with LINQ based queries?</p></li>
<li><p>I'd suggest creating a proof of concept with your ORM of choice first and migrate a "vertical slice" of functionality, e.g. UI -> WS -> DAL and see what kind of issues you run into. What I'd suggest is that you consider how either L2S or EF will be used within your architecture.. Especially with regard to the entities themselves - i.e. change tracking.</p></li>
<li><p>Don't rule out other options, such as NHibernate or using Codesmith templates to generate data access classes, unless you've already decided on L2S or EF..</p></li>
</ol>
|
Intercepting action methods of an MVC controller <p>I use an O/R mapper, that can reload objects from the DB in a generic manner. I would like to be able to intercept the request <em>right after</em> the creation of the mapped objects, in order to reload them. </p>
<p>ActionFilters are of course there, yet the problem is that ActionFilters (or the examples I have seen) can handle the data as provided by the form and not after an object had been created.</p>
<p>I looked at the overridable methods of the Controller, but found nothing obvious that caught my eyes. Does any one know of a way to do this? </p>
<p>Thank you for your suggestions!</p>
<p>Nasser</p>
| <p>If I right understand you need something like this.</p>
<pre><code>public class Navigate : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
ViewResult view = filterContext.Result as ViewResult;
}
}
</code></pre>
<p>In view you will find view.ViewData.Model that belongs to current Controller and you can do all that you want with this mapped data.
Let me know if I was right :)</p>
|
Should a business object collection inherit from Collection<T> when it doesn't extend it? <p>I have a business object collection (representing data from the database) that inherits from Collection and has a static method that calls a stored proc and then populates its properties with the data returned.</p>
<p>My question is; is it wrong to inherit from Collection as it doesnt really extend the class? or would it be better to not inherit from anything but instead maintain a private variable that is of type Collection?</p>
| <p>If it's OK for your business object to provide usual collection methods to the world, then it's quite OK to inherit from <code>Collection<T></code>. And as I guess, in fact you add something to it - you specify <code>T</code>.</p>
<p><strong>Udate:</strong><br/>
According to author's comments, publishing of all collection methods would make object editable which is not acceptable. So instead of inheriting he would make private field and make the class enumerable. </p>
|
table sorting in groups <p>I have table with folders first and then documents.I want to sort such that sorting applies to both the folders and documents but want to keep sorted folders first and then sorted documents.Is it possible with jQuery table sorter. Any suggestions?</p>
| <p>Read the <a href="http://tablesorter.com/docs/" rel="nofollow">tablesorter documentation</a>. You can manually sort by clicking one column, holding shift, and clicking other columns. Or you can code in a default sort by setting configuration options - the example in documentation to sort by first and second columns in ascending order is:</p>
<pre><code>$(document).ready(function()
{
$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
}
);
</code></pre>
|
Extending c# code with separate assembly <p>I have some extra functionality i need to add which includes adding a new property to an object and extending methods in another class that handles this object. I'm dealing with source code of a product (in C# 2.0) we use which i really don't want to modify, i just want to extend on it.</p>
<p>I'd ideally like to have a separate assembly to do this so that it's clear it's our code. It seems like partial classes and delegates may be the way to go, but I'm not sure if this is possible to do. Has anyone done something similar? or know any good articles?</p>
| <p>Like hfcs101 said.</p>
<p>See if you can extend the class given some existing OO design patterns.</p>
<p>Take a look at:</p>
<ul>
<li><a href="http://www.fluffycat.com/Java-Design-Patterns/Adapter/" rel="nofollow">Adapter patten</a></li>
<li><a href="http://www.fluffycat.com/Java-Design-Patterns/Decorator/" rel="nofollow">Decorator pattern</a></li>
<li><a href="http://www.fluffycat.com/Java-Design-Patterns/Facade/" rel="nofollow">Facade pattern</a></li>
</ul>
<p>See if you can find a pattern that closely matches your problem. Decorator looks like the best candidate.</p>
|
Text Format Toolbar <p>I am looking for how to implement a toolbar similar to the one used here when you add a new question, this toolbar should format the text entered in my text box and allow me to make it Bold, Italic, choose size and fond and highlights, colors as well...
One important thing, I want one that is both supported on firefox and IE, discountasp.net offers one which is only supported by IE.</p>
<p>PS: I am coding my website in asp.net 3.5, vb.net, MS SQL 2005 Express, and all is done with MS VWD 2008 express.</p>
<p>And I may add that I am not a programming guru, I just make things work, so keep it simple folks ;)</p>
<p>thanks in advance.</p>
| <p>You can get the SO Editor <a href="http://github.com/cky/wmd/tree/master" rel="nofollow">here</a>.</p>
|
Am confused about parallel Haskell <p>How is this code:</p>
<pre><code>parfib :: Int -> Int
parfib 0 = 1
parfib 1 = 1
parfib n = nf2 `par` (nf1 `par` (nf1+nf2+1))
where nf1 = parfib (n-1)
nf2 = parfib (n-2)
</code></pre>
<p>Better than this:</p>
<pre><code>parfib :: Int -> Int
parfib 0 = 1
parfib 1 = 1
parfib n = nf2 `par` (nf1 `seq` (nf1+nf2+1))
where nf1 = parfib (n-1)
nf2 = parfib (n-2)
</code></pre>
<p>I don't get the explanations I've found online that say "In order to guarantee that the main expression is evaluated in the right order (i.e. without blocking the main task on the child task) the seq annotation is used".</p>
<p>Why is seq used? I know it forces the interpreter to evaluate parfib (n-1) first but why is it necessary? </p>
<p>When executing the second program, won't the interpeter spark a new process to evaluate nf2, while evaluating nf1 of the nf1+nf2+1 expression in parallel? What is the need to tell it to specify that it should start with nf1?</p>
| <p>It doesn't make much sense to evaluate <code>nf1</code> in parallel to <code>nf1+...</code> since the latter depends on nf1, so all it would do is block on the spark of <code>nf1</code>. Using <code>seq</code> it will only try to use <code>nf1</code> once you know it has been evaluated.</p>
|
Export Dataset to Excel <p>How can I export a dataset to file that can be opened by Excel 2003 ?</p>
<p>will you elaborate it ? because it is diffculties to understand the CSV/TSV</p>
<p>marc will u give us a sample for doing it .v now ony heard the terms csv/tsv</p>
| <p>I think This will help you. Use http handler</p>
<pre><code><%@ WebHandler Language="C#" Class="DownloadAllEvent" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
public class DownloadAllEvent : IHttpHandler
{
const int BUFFERSIZE = 1024;
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
response.BufferOutput = true;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=Events.csv");
response.Cache.SetCacheability(HttpCacheability.NoCache);
//string csvfile = request.QueryString["csvfile"];
string strNoofIds = request.QueryString["NoofIds"];
// declare variables or do something to pass parameter to writecalEntry function
writeCalEntry(response.Output, strguid, sectionid);
response.End();
}
public void writeCalEntry(TextWriter output, string[] strguid,string sectionid)
{
DataTable dt = createDataTable();
DataRow dr;
StringBuilder sbids = new StringBuilder();
// process table if neeed.. use following code to create CSV format string from table
string separator;
separator = ","; //default
string quote = "\"";
//create CSV file
//StreamWriter sw = new StreamWriter(AbsolutePathAndFileName);
//write header line
StringBuilder sb = new StringBuilder();
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
//sw.Write(TheDataTable.Columns[i]);
sb.Append(dt.Columns[i]);
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
//write rows
foreach (DataRow tempdr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(tempdr[i]))
{
string data = tempdr[i].ToString();
data = data.Replace("\"", "\\\"");
//sw.Write(quote + data + quote);
sb.Append(quote + data + quote);
}
if (i < iColCount - 1)
{
//sw.Write(separator);
sb.Append(separator);
}
}
//sw.Write(sw.NewLine);
sb.AppendLine();
}
//sw.Close();
UnicodeEncoding uc = new UnicodeEncoding();
output.WriteLine(sb);
}
public static DataTable createDataTable()
{
DataTable dt = new DataTable("EventsData");
// create tables as needed which will be converted to csv format.
return dt;
}
</code></pre>
<p>call this httphandler file where you want to export data in to excell format as </p>
<pre><code>Response.Redirect("downloadFile.ashx");
</code></pre>
<p>you can send parametres also in Response.Redirect which can be fetched in .ashx file.
I think this will hepl you.</p>
|
Subversion problem with case sensitivity <p>I discovered an issue today regarding Subversion support for file name's case sensitivity.</p>
<p>I committed a class named 'ClassOne.file'. Another person committed another file, 'Classone.file'. Both files are exactly the same except the file name.</p>
<p>When I do SVN update, it says error, "unable to add, the file already exists".
I noticed that in SVN respository, both files exist, but I cannot update my local copy. It halts there.</p>
<p>What I do is delete one of them and only then the SVN update resumes as usual.
The SVN server is running on Linux, but our PC are running windows.</p>
<p>My questions: </p>
<ul>
<li>Is this a standard configuration in SVN?</li>
<li>How to avoid this kind of error (other than enforcing everybody to use the same file naming convention)?</li>
</ul>
<p>Advanced thanks for your kind help!</p>
| <p><a href="http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py" rel="nofollow">http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py</a></p>
<p>Exactly what you need :)</p>
<p>Just dump that in your </p>
<pre><code>/svnroot/<repos>/hooks/pre-commit
</code></pre>
<p>file, and BAM, problem will never repeat.</p>
<p><strong>In response to comment</strong></p>
<p>You have to edit the hooks for your repository; Working Copies don't have hooks. Locate your repository on your filesystem, then under a folder called "hooks" you will see a file called "pre-commit.tmpl" just rename that to "pre-commit" and edit it by adding in the code found above :)</p>
|
How to config. Linq DataContext (in Class Lib Proj) to use connection string in web.config of web application? <p>I'm looking for a solution on how to configure Linq DataContext in Class Library Project in order to use Connection String in web.config of web application.
Your advice would be much appreciated.</p>
| <p>I am not sure if this is a solution to your problem, but you have to create app.config (or web.config I believe) in a startup project (the project which is executed for solution). Click on project, add new, general, application configuration file (in case of app.config).</p>
<p>Then you have to add some content. That's it.</p>
|
OLEDB connection to Access database using DSN <p>i want oledb connection using Dsn. I used the following code </p>
<pre><code>'Dsn Create
dbRegBase.RegisterDatabase("GEMINI", "Microsoft Access Driver (*.mdb)", True,DBQ=D:\Gemini\GEMINI\database\paints_01_2008-2009.mdb
Description=Greenchip Technologies ODBC Database File Path
OemToAnsi=No
UID=admin
PWD=XXXXXX
conection code
Provider=Microsoft.Jet.OLEDB.4.0;DBQ ='GEMINI';Persist Security Info=False;Jet OleDB:Database Password = XXXXXX
</code></pre>
<p>But Error come error name is "Could not find installable ISAM"
what i do . please tell me. </p>
| <p>My question is why would anyone want to use odbc? There are many sites out there that show the speed improvements of oledb vs odbc. Also, odbc has not been updated in a while and is very buggy. </p>
|
Clustered primary key on unique identifier ID column in SQL Server <p>If your ID column on a table is a unique identifier (Guid), is there any point creating a <strong>clustered</strong> primary key on the ID column? </p>
<p>Given that they are globally unique, how would the sorting work?</p>
| <p>I strongly advise against using clustered Guid key... We had big performance issues on SQL server because of such poor design a few years ago.</p>
<p>Also check out: <a href="http://stackoverflow.com/questions/583001/improving-performance-of-cluster-index-guid-primary-key">http://stackoverflow.com/questions/583001/improving-performance-of-cluster-index-guid-primary-key</a></p>
|
Creating objects without breaking encapsulation <p>I'm fairly new to all this, so this is probably OOP 101 but I can't get my head around it, assume the following C# code lives in an assembly:</p>
<pre><code>internal interface IDataStore
{
void Store(string name, object data);
object Retrieve(string name);
}
internal class DBStore : IDataStore
{
public DBStore(string connection) { }
public void Store(string name, object data) { }
public object Retrieve(string name) { }
}
public class GizmoManager
{
public GizmoManager(IDataStore dataStore) { }
// Other stuff
}
public class WidgetManager
{
public WidgetManager(IDataStore dataStore) { }
// Other stuff
}
</code></pre>
<p>If a second assembly tries to create a GizmoManager and a WidgetManager, it can't because it has no way to get hold of a DBStore (since it is internal not public).</p>
<p>The following don't work AFAICS: </p>
<ul>
<li>Make DBStore and IDataStore public. Bad because the client assembly can then bypass GizmoManager/WidgetManager and access the DB however it likes. </li>
<li>Don't pass in an IDataStore to the GizmoManager and WidgetManager constructors. Bad because it reduces testability (you can't easily pass in a MockDataStore). </li>
<li>Do something magic with factories. Doesn't seem to solve anything because you need to pass the same IDataStore to both GizmoManager and WidgetManager and thus the client assembly still needs to assign an IDataStore to a variable (which it can't because IDataStore is internal).</li>
</ul>
<p>This is probably stunningly obvious but I just can't see it. How would one overcome this contradiction?</p>
<p>TIA.</p>
| <p>Just make the interface <code>IDataStore</code> public. That way, clients can instantiate your <code>WidgetManager</code> and <code>GizmoManager</code> classes with mock objects they create themselves.</p>
<p>Implement on of the <em>Factory</em> class of design patterns to allow creation of <code>GiszmoManager</code> and <code>WidgetManager</code> objects by client code. That way, client code can never create a <code>DBStore</code> object, so they can never circumvent your managers.</p>
<p><strong>BTW:</strong> Why bother fussing with encapsulation? This might make sense if you are in the proprietary frameworks business, but otherwise, <a href="http://en.wikipedia.org/wiki/You%5FAin%27t%5FGonna%5FNeed%5FIt" rel="nofollow">YAGNI</a>.</p>
|
ClassLoader confusion <p>I have seen several places that "Class.getClassLoader() returns the ClassLoader used to load that particular class", and therefore, I am stumped by the results of the following example:</p>
<pre><code>
package test;
import java.lang.*;
public class ClassLoaders {
public static void main(String[] args) throws java.lang.ClassNotFoundException{
MyClassLoader mcl = new MyClassLoader();
Class clazz = mcl.loadClass("test.FooBar");
System.out.println(clazz.getClassLoader() == mcl); // prints false
System.out.println(clazz.getClassLoader()); // prints e.g. sun.misc.Launcher$AppClassLoader@553f5d07
}
}
class FooBar { }
class MyClassLoader extends ClassLoader { }
</code></pre>
<p>Shouldn't the statement clazz.getClassLoader() == mcl return true? Can someone explain what I am missing here?</p>
<p>Thanks.</p>
| <p>Whenever you create your own classloader it will be attached in a tree-like hierarchy of classloaders. To load a class a classloader first delegates the loading to its parent. Only once all the parents didn't find the class the loader that was first asked to load a class will try to load it. </p>
<p>In your specific case the loading is delegated to the parent classloader. Although you ask you MyClassLoader to load it, it is the parent that does the loading. In this case it is the AppClassLoader.</p>
|
Concurrent file write in Java on Windows <p>What happens when you concurrently open two (or more) FileOutputStreams on the same file?</p>
<p>The <a href="http://java.sun.com/javase/6/docs/api/">Java API</a> says this:</p>
<blockquote>
<p>Some platforms, in particular, allow a file to be opened for writing by only one FileOutputStream (or other file-writing object) at a time.</p>
</blockquote>
<p>I'm guessing Windows isn't such a platform, because I have two threads that read some big file (each one a different one) then write it to the same output file. No exception is thrown, the file is created and seems to contain chunks from both input files.</p>
<p>Side questions:</p>
<ul>
<li>Is this true for Unix, too?</li>
<li>And since I want the behaviour to be the same (actually I want one thread to write correctly and the other to be warned of the conflict), how can I determine that the file is already opened for writing?</li>
</ul>
| <p>There's not a reliable, cross-platform way to be passively notified when a file has another writer—i.e., raise an exception if a file is already open for writing. There are a couple of techniques that help you actively check for this, however.</p>
<p>If multiple processes (which can be a mix of Java and non-Java) might be using the file, use a <a href="http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileLock.html"><code>FileLock</code></a>. A key to using file locks successfully is to remember that they are only "advisory". The lock is guaranteed to be visible if you check for it, but it won't stop you from doing things to the file if you forget. All processes that access the file should be designed to use the locking protocol.</p>
<p>If a single Java process is working with the file, you can use the concurrency tools built into Java to do it safely. You need a map visible to all threads that associates each file name with its corresponding lock instance. The answers to <a href="http://stackoverflow.com/questions/659915/synchronizing-on-an-integer-value">a related question</a> can be adapted easily to do this with <code>File</code> objects or <a href="http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getCanonicalPath%28%29">canonical paths</a> to files. The lock object could be a <code>FileOutputStream</code>, some wrapper around the stream, or a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html"><code>ReentrantReadWriteLock</code>.</a></p>
|
AJAX and asp.net security question <p>I have a couple of questions regarding security mechanisms in asp.net (2.0).</p>
<p>I have always been using Forms authentication + Page.User for validating permissions.</p>
<p>Now I need to send some data from client side javaScript (jQuery) to a WCF service.
Will my IPrincipal be still accessible from HttpContext of WCF service (I'm hosting my services on same IIS, same domain). </p>
<p>I'm particulary interested if $.Ajax will grab client authentication cookie and assign it to HttpContext on the server (or does it happen automagically)?</p>
<p>What are possible gotchas / pitfalls here?</p>
<p>Thank you.</p>
| <p>You can, but need to set this property in web.config of your WCF service.</p>
<pre><code><system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</code></pre>
|
Pass JSON obj out from parse function? | noob javascript question <p>I'm trying to pass an object out of a function. Here's my code:</p>
<pre><code><script type="text/javascript">
// finds the head element; creates a script with passed url; appends it to the head
function loadJSON(url) {
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript'; // isn't this 'application/json' really?
newScript.src = url;
headID.appendChild(newScript);
}
function parseJSON(o) {
if (content == null) {
document.write("<p>parseJSON(): JSON failed.</p>");
return false;
}
isDST = "<strong>not</strong> ";
if ( o.rawOffset == o.dstOffset ) {
isDST = "";
}
document.getElementById("geonames").innerHTML = "<p>The time now is " + o.time + " in " + o.countryName +".</p>";
}
var lat = "47.01"; var long = "10.2"; // test data for austria
var jsonUrl = " {{URL}} ";
loadJSON(jsonUrl);
</script>
</code></pre>
<p>What I want to do is instead of using the object o inside the parseJSON function I want to pass the object out so that after the loadJSON() call I can do things with the object. I find it's not "neat" having the innerHTML calls inside the parse function.</p>
<p>I've tried lots of iterations of, eg declaring "var jsonOutput" at start of script and then making "jsonOutput = o" but that just leaves jsonOutput undefined. If I try to return jsonOutput then I don't know where it's being returned to, I can't use it anyway.</p>
<p>Do I need to make a global variable? I've tried a simple "global jsonOutput" declaration but it doesn't seem to be modified inside the function.</p>
<p>Am stuck, please help.</p>
| <p>Also, it seems that you are trying to load the JSON data using the <code><script></code> tag.</p>
<p>You could also load the JSON data via an <a href="http://developer.apple.com/internet/webcontent/xmlhttpreq.html" rel="nofollow">XMLHttpRequest</a> and then turn it into an object via:</p>
<pre><code>var dataObject = eval('(' + myJSONData + ')');
</code></pre>
<p>And if you can't verify how secure the data is, you can use the <a href="https://github.com/douglascrockford/JSON-js" rel="nofollow">official JSON JavaScript parser</a> (see <a href="http://json.org/js" rel="nofollow">here</a> for more information) to validate the data before executing it.</p>
<p>Steve</p>
|
Reading/writing from named pipes under mono/Linux <p>I would like to read/write from a named pipe/FIFo queue under Linux.
I have tried the standard classes StreamWriter and other classes from System.IO, but it fails because it is using seek.
Has anyone ever written/read from a named pipe using Mono?.
I am managing to read and write - but not the same time...</p>
| <p>You'll need to open separate readers and writers; for some reason, Mono treats FIFOs as if they are seekable (it's a bug), even though they aren't.</p>
|
Do you use pre-release software to develop commercial products? <p>So the question is.. have you used a pre-release product or technology (a Community Technology Preview, Beta or Release Candidate, etc) to develop your own product with?</p>
<p>For example, you might have developed a website using Microsoft's ASP.Net MVC (which just went RTM yesterday) or built software against SQL Server 2008 RC 1..etc</p>
<p>If so..<br/><br/>
1. What steps do you (or did you) take to minimise the risk of problems occuring when the pre-release product is properly released?<br/><br/>
2. Do you wait a specific timeframe (until a product is a Release Candidate, for example) before working with a product?
<br/><br/>
3. What would be the main advantages (vs. risk) of working with pre-release technologies?</p>
| <p>Practically all successful software projects I've ever been on have been released (erm, published - web sites) with a fair amount of betas in use.</p>
<p>We mainly evaluate the test-coverage of these (mostly open source projects) and the previous track record for not doing stupid things. </p>
<p>Any old beta will do as long as it does what we need ;) But usually we stay off the immediate snapshots after major rewrites.</p>
<p>These days we're test driven, so we know if <em>our</em> stuff works. If the libraries have bugs we stay with an older version or fix the bugs. We can also assess immediately if an update has serious bugs in it, because it will break our own tests. So using "unfinished" software is really not a big deal any more. Access to the latest features is always the reason, sometimes we do it to get important fixes.</p>
|
Looking for pointers on MIDI driver development <p>I am looking for resources, documentation and general advices on writing a virtual MIDI device (see my <a href="http://stackoverflow.com/questions/702842/virtual-midi-and-vsts">previous question</a> for reasons) and basics of generating MIDI events from a VST plugin.</p>
<p>The target platform is Windows, but Mac compatibility would be a plus.</p>
| <p>I hope you don't mind me editing the subject of your question -- but I think that you shouldn't be so worried about the VST part of your software here, and the nature of your question is more about driver development than VST development.</p>
<p>That said, you are essentially trying to write a normal MIDI driver, but you don't actually need to connect to any hardware. So writing a virtual driver is really not as hard as you anticipate... you just need to find the driver API's (see the edit to my answer on your previous question).</p>
<p>One more thing I should add here, is that the best way to accomplish what you are trying to use a separate application with <a href="http://www.propellerheads.se/developer/index.cfm?fuseaction=get%5Farticle&article=rewiretechinfo" rel="nofollow">Rewire</a>. So that is to say, you write an application which initializes a MIDI device when started, and connects to the sequencer via Rewire. Your users would start up the sequencer first, then your application, then send the audio on a bus track to your app, and configure their sequencer to receive MIDI from the device driver which you would write. The app, conversely, streams audio from rewire, does some type of FFT to get the pitches (or whatever you want to do to the audio stream), and then pushes those events out to the host through the MIDI driver API. IMO, that's probably the best way to solve this problem here, if I understand your project correctly.</p>
|
How to drop IDENTITY property of column in SQL Server 2005 <p>I want to be able to insert data from a table with an identity column into a temporary table in SQL Server 2005.</p>
<p>The TSQL looks something like:</p>
<pre><code>-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
...
END
</code></pre>
<p>The above code created #Tmp_Table with an identity column, and the insert subsequently fails with an error "An explicit value for the identity column in table '#Tmp_MyTable' can only be specified when a column list is used and IDENTITY_INSERT is ON."</p>
<p>Is there a way in TSQL to drop the identity property of the column in the temporary table <strong>without listing all the columns explicitly</strong>? I specifically want to use "SELECT *" so that the code will continue to work if new columns are added to MyTable.</p>
<p>I believe dropping and recreating the column will change its position, making it impossible to use SELECT *.</p>
<p><strong>Update:</strong></p>
<p>I've tried using IDENTITY_INSERT as suggested in one response. It's not working - see the repro below. What am I doing wrong?</p>
<pre><code>-- Create test table
CREATE TABLE [dbo].[TestTable](
[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)
GO
-- Insert some data
INSERT INTO TestTable
(Name)
SELECT 'One'
UNION ALL
SELECT 'Two'
UNION ALL
SELECT 'Three'
GO
-- Create empty temp table
SELECT *
INTO #Tmp
FROM TestTable
WHERE 1=0
SET IDENTITY_INSERT #Tmp ON -- I also tried OFF / ON
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
SET IDENTITY_INSERT #Tmp OFF
GO
-- Drop test table
DROP TABLE [dbo].[TestTable]
GO
</code></pre>
<p>Note that the error message *"An explicit value for the identity column in table '#TmpMyTable' can only be specified <strong>when a column list is used</strong> and IDENTITY_INSERT is ON."* - I specifically don't want to use a column list as explained above.</p>
<p><strong>Update 2</strong>
Tried <a href="http://stackoverflow.com/questions/713960/how-to-drop-identity-property-of-column-in-sql-server-2005/714247#714247">the suggestion from Mike</a> but this gave the same error:</p>
<pre><code>-- Create empty temp table
SELECT *
INTO #Tmp
FROM (SELECT
m1.*
FROM TestTable m1
LEFT OUTER JOIN TestTable m2 ON m1.ID=m2.ID
WHERE 1=0
) dt
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
</code></pre>
<p>As for why I want to do this: MyTable is a staging table which can contain a large number of rows to be merged into another table. I want to process the rows from the staging table, insert/update my main table, and delete them from the staging table in a loop that processes N rows per transaction. I realize there are other ways to achieve this.</p>
<p><strong>Update 3</strong></p>
<p>I couldn't get <a href="http://stackoverflow.com/questions/713960/how-to-drop-identity-property-of-column-in-sql-server-2005/714247#714247">Mike's solution</a> to work, however it suggested the following solution which does work: prefix with a non-identity column and drop the identity column:</p>
<pre><code>SELECT CAST(1 AS NUMERIC(18,0)) AS ID2, *
INTO #Tmp
FROM TestTable
WHERE 1=0
ALTER TABLE #Tmp DROP COLUMN ID
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
</code></pre>
<p>Mike's suggestion to store only the keys in the temporary table is also a good one, though in this specific case there are reasons I prefer to have all columns in the temporary table.</p>
| <p>You could try</p>
<pre><code>SET IDENTITY_INSERT #Tmp_MyTable ON
-- ... do stuff
SET IDENTITY_INSERT #Tmp_MyTable OFF
</code></pre>
<p>This will allow you to select into <code>#Tmp_MyTable</code> even though it has an identity column.</p>
<p>But this <strong>will not</strong> work:</p>
<pre><code>-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
SET IDENTITY_INSERT #Tmp_MyTable ON
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
SET IDENTITY_INSERT #Tmp_MyTable OFF
...
END
</code></pre>
<p>(results in the error "An explicit value for the identity column in table '#Tmp' can only be specified when a column list is used and IDENTITY_INSERT is ON.")</p>
<p>It seems there is no way without actually dropping the column - but that would change the order of columns as OP mentioned. Ugly hack: Create a new table based on #Tmp_MyTable ...</p>
<p>I suggest you write a stored procedure that creates a temporary table based on a table name (<code>MyTable</code>) with the same columns (in order), but with the identity property missing.</p>
<p>You could use following code:</p>
<pre><code>select t.name as tablename, typ.name as typename, c.*
from sys.columns c inner join
sys.tables t on c.object_id = t.[object_id] inner join
sys.types typ on c.system_type_id = typ.system_type_id
order by t.name, c.column_id
</code></pre>
<p>to get a glimpse on how reflection works in TSQL. I believe you will have to loop over the columns for the table in question and execute dynamic (hand-crafted, stored in strings and then evaluated) alter statements to the generated table.</p>
<p>Would you mind posting such a stored procedure for the rest of the world? This question seems to come up quite a lot in other forums as well...</p>
|
OS detecting makefile <p>I routinely work on several different computers and several different operating systems, which are Mac OS X, Linux, or Solaris. For the project I'm working on, I pull my code from a remote git repository.</p>
<p>I like to be able to work on my projects regardless of which terminal I'm at. So far, I've found ways to get around the OS changes by changing the makefile every time I switch computers. However, this is tedious and causes a bunch of headaches.</p>
<p>How can I modify my makefile so that it detects which OS I'm using and modifies syntax accordingly?</p>
<p>Here is the makefile:</p>
<pre><code>cc = gcc -g
CC = g++ -g
yacc=$(YACC)
lex=$(FLEX)
all: assembler
assembler: y.tab.o lex.yy.o
$(CC) -o assembler y.tab.o lex.yy.o -ll -l y
assembler.o: assembler.c
$(cc) -o assembler.o assembler.c
y.tab.o: assem.y
$(yacc) -d assem.y
$(CC) -c y.tab.c
lex.yy.o: assem.l
$(lex) assem.l
$(cc) -c lex.yy.c
clean:
rm -f lex.yy.c y.tab.c y.tab.h assembler *.o *.tmp *.debug *.acts
</code></pre>
| <p>There are many good answers here already, but I wanted to share a more complete example that both a) doesn't assume <code>uname</code> exists on Windows and b) also detects the processor. The CCFLAGS defined here aren't necessarily recommended or ideal; they're just what the project to which I was adding OS/CPU auto-detection happened to be using.</p>
<pre><code>ifeq ($(OS),Windows_NT)
CCFLAGS += -D WIN32
ifeq ($(PROCESSOR_ARCHITEW6432),AMD64)
CCFLAGS += -D AMD64
else
ifeq ($(PROCESSOR_ARCHITECTURE),AMD64)
CCFLAGS += -D AMD64
endif
ifeq ($(PROCESSOR_ARCHITECTURE),x86)
CCFLAGS += -D IA32
endif
endif
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
CCFLAGS += -D LINUX
endif
ifeq ($(UNAME_S),Darwin)
CCFLAGS += -D OSX
endif
UNAME_P := $(shell uname -p)
ifeq ($(UNAME_P),x86_64)
CCFLAGS += -D AMD64
endif
ifneq ($(filter %86,$(UNAME_P)),)
CCFLAGS += -D IA32
endif
ifneq ($(filter arm%,$(UNAME_P)),)
CCFLAGS += -D ARM
endif
endif
</code></pre>
|
Is a Slice 256 enough for Apache2 + Passenger hosting AT LEAST 4 Rails sites? <p>I've a <strong>Slice 256</strong> with 4 <strong>Rails 1.2.6</strong> sites running pretty decently on <strong>Lighttpd + FastCGI</strong> (Ubuntu Server 8.04 LTS upgraded from 6.06 LTS); although it's such and old configuration, it's proven reliable enough for my smallish websites.</p>
<p>Now I'd like to upgrade some to Rails 2.x and I'm wondering if the same Slice 256 can take an <strong>Apache2 + Passenger</strong> configuration, since it worked great on my local development Linux box.</p>
<p>So my question is: <strong>Is a Slice 256 enough for Apache2 + Passenger hosting AT LEAST 4 Rails sites?</strong></p>
<p>Any advice and experiencies on this will be greatly appreciated.</p>
| <p>In case anyone is confused, the asker is probably refering the 256 MB VPS at <a href="http://www.slicehost.com" rel="nofollow">Slicehost.com</a></p>
<p>And to answer your question: It depends.</p>
<p>Could you run four Twitters, of course not. Could you run 4 sites that will have 1 (or less) concurrent user between them then yes, you could.</p>
|
How can make column widths bindable in two Flex AdvancedDataGrids? <p>Bear with me here. I have a strange setup to accomplish what I need. I basically have an AdvancedDataGrid that displays data returned by a WebService. The data is in XML format:</p>
<pre><code><children label="parent 1" value="3100">
<children label="child 1" value="1100">
<children label="grandchild 1" value="200">
</children>
<children label="grandchild 2" value="300">
</children>
<children label="grandchild 3" value="600">
</children>
</children>
<children label="child 2" value="2000">
<children label="grandchild 4" value="1200">
</children>
<children label="grandchild 5" value="800">
</children>
</children>
</children>
<children label="parent 2" value="1000">
<children label="child 3" value="1000">
<children label="grandchild 6" value="300">
</children>
<children label="grandchild 7" value="700">
</children>
</children>
</children>
</code></pre>
<p>I convert the XML to a HierarchicalData Object in the WebService result handler. I also dynamically build the columns for the AdvancedDataGrid, since it used to display different columns depending on the user input. However, I also need to display a totals "row" at the bottom of the AdvancedDataGrid. I cannot figure out how to convert my XMLListCollection to a GroupingCollection, and thereby create a totals row this way, so, I actually calculate the totals in the WebService and return this as a node in the XML:</p>
<pre><code><totals value="4100" />
</code></pre>
<p>I use this "totals" data to populate a second AdvancedDataGrid with no headers that sits directly below the first ADG, so that it "appears" to be the "last row" of the first ADG. Both ADGs use the same Bindable columns Array:</p>
<pre><code><mx:AdvancedDataGrid id="reportADG" dataProvider="{__model.reportData}"
columns="{__model.adgDrillColumns}" width="100%" height="100%" />
<mx:AdvancedDataGrid id="reportTotalsADG"
dataProvider="{__model.reportTotalsData}"
folderOpenIcon="{null}" folderClosedIcon="{null}"
disclosureClosedIcon="{null}" disclosureOpenIcon="{null}"
defaultLeafIcon="{null}" showHeaders="false"
selectable="false" rowCount="1"
columns="{__model.adgColumns}" width="100%" />
</code></pre>
<p>However, if the columns are resized in the first ADG, I can't find a way to have the columns in the second ADG to resize as well. What can I do?</p>
| <p>You can use the summary row method, or you can create a custom component to display the totals separately. In my case, I had to create a custom component that gets all of the ADG columns, determines their widths, draws vertical lines/separators, and then sums all of the rows and shows a label. It's nice because it's used like this:</p>
<pre><code><components:DataGridSummaryFooter id="summaryView"
height="6%" width="100%"
totalsColumns="{[impressionsCol, estimatedSpendingCol]}"
dataSource="{dataViewSource}"
/>
</code></pre>
<p>...and the rest is magic!</p>
<p>FYI, the reason I had to create a separate component and not use the summary row was due to the design requirements of this application. In fact, I would hope that it's always done this way, because with the summary rows, you have to scroll all the way to the bottom of the grid to see the summaries, and that's not very good UX.</p>
<p>I hope this helps someone with something at some point! :)</p>
<p>Cheers</p>
|
Simple (Dumb) LINQ Provider <p>How easy would it be to write a dumb LINQ provider that can just use my class definitions (which don't have any object references as properties) and give me the translated SQL. It can assume the name of the properties and the columns to be same as well as the names of the classes and the underlying tables. Can you please give me some pointers.?</p>
| <p>It took me about 4 months of fulltime work (8 hours a day) to build a stable, working provider that implements the entire spec of linq. I would say I had a very simple, buggy and unstable version after about three weeks, so if you're just looking for something rough I would say you're probably looking at anything from a week up to two months depending on how good you are and what types of requiements you have. </p>
<p>I must point you to the Wayward blog for this, Matt has written a really good walkthrough on how to implement a linq provider, and even if you're probably not going to be able to copy and paste, it will help you to get to grips with how to think when working. You can find Matt´s walkthrough here: <a href="http://blogs.msdn.com/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx">http://blogs.msdn.com/mattwar/archive/2007/07/30/linq-building-an-iqueryable-provider-part-i.aspx</a> . I recommend you go about it the same way Matt does, and extend the expression tree visitor Matt includes in the second part of his tutorial. </p>
<p>Also, when I began working with this, I had so much help from the expression tree visualizer, it really made parsing a whole lot easier once you could see how linq parsed to queries. </p>
<p>Building a provider is really a lot of fun, even if a bit frustrating at times. I wish you all the best of luck!</p>
|
Referrals DB schema <p>I'm coding a new {monthly|yearly} paid site with the now typical "referral" system: when a new user signs up, they can specify the {username|referral code} of other user (this can be detected automatically if they came through a special URL), which will cause the referrer to earn a percentage of anything the new user pays.</p>
<p>Before reinventing the wheel, I'd like to know if any of you have experience with storing this kind of data in a relational DB. Currently I'm using MySQL, but I believe any good solution should be easily adapted to any RDBMS, right?</p>
<p>I'm looking to support the following features:</p>
<ul>
<li><p><strong>Online billing system</strong> - once each invoice is paid, earnings for referrals are calculated and they will be able to cash-out. This includes, of course, having the possibility of browsing invoices / payments online.</p></li>
<li><p><strong>Paid options vary</strong> - they are different in nature and in costs (which will vary sometime), so commissions should be calculated based on each final invoice.</p></li>
<li><p><strong>Keeping track of referrals</strong> (relationship between users, date in which it was referred, and any other useful information - any ideas?)</p></li>
<li><p>A simple way to <strong>access historical referring data</strong> (how much have been paid) or accrued commissions.</p></li>
<li><p>In the future, I might offer to <strong>exchange accrued cash for subscription renewal</strong> (covering the whole of the new subscription or just a part of it, having to pay the difference if needed)</p></li>
<li><p><strong>Multiple levels</strong> - I'm thinking of paying something around 10% of direct referred earnings + 2% the next level, but this may change in the future (add more levels, change percentages), so I should be able to store historical data.</p></li>
</ul>
<p>Note that I'm not planning to use this in any other project, so I'm not worried about it being "plug and play".</p>
<p>Have you done any work with similar requirements? If so, how did you handle all this stuff? Would you recommend any particular DB schema? Why?</p>
<p>Is there anything I'm missing that would help making this a more flexible implementation?</p>
| <p>Rather marvellously, there's a library of <a href="http://www.databaseanswers.org/data%5Fmodels/" rel="nofollow">database schemas</a>. Although I can't see something specific to referrals, there may be something related. At least (hopefully) you should be able to get some ideas.</p>
|
retrieve PK of mapped table with NHibernate <p>just started out with NHIbernate and have one question, probably a bit of a stupi one! ;-)
I have 2 tables, Email and Attachment, an email can have zero or more attachments. so I created a hbm file like this: </p>
<p>
</p>
<pre><code><set name="Attachments" table="Attachments">
<key column="EmailId" foreign-key="fk_Attachments_Emails"/>
<composite-element class="Foo.Emails.Attachment, Foo.Emails">
<!-- PROBLEM HERE!!! -->
<property name="Id" column="Id" type="long" />
<!-- END PROBLEM -->
<property name="Name" column="Name" type="String" length="50"/>
<property name="Mime" column="MimeType" type="String" length="50"/>
<property name="Size" column="Size" type="long" />
<property name="FilePath" column="FilePath" type="String" length="256"/>
<property name="Parsed" column="Parsed" type="Boolean" />
</composite-element>
</set>
</code></pre>
<p>
</p>
<p>As I want to be able to search for the attachments by PK (the Id column in the set) I included it, but now everytime I try to save an email with attachments I get an error from the db as Nhibernate tries to insert a value into the PK, which my db naturally wont allow. </p>
<p>So, my question is, can I extract the pk for the Attqachment table but stop Nhiberntate from writing it when inserting a an email/attachment? Should I swap to another container like ?? if so wold you be abler to provide an example as I struggling to find a one that I understand!</p>
<p>THanks for your help!</p>
| <p>Perhaps a more practical example? Where you have an object structure like this: </p>
<p>Email<br>
--EmailId<br>
--EmailProperty1<br>
--AttachmentCollection </p>
<p>Attachment<br>
--AttachmentId<br>
--ParentEmail<br>
--AttachmentProperty1 </p>
<p>mapped to a table structure like this (not how i'd name it, but it's for example): </p>
<p>email<br>
--emailId int PK, identity<br>
--emailProp1 varchar(50) </p>
<p>emailattachment<br>
--attachmentId int PK, identity<br>
--emailId int, FK to email table<br>
--attachmentProp1 varchar(50) </p>
<pre><code><hibernate-mapping>
<class name="Email" table="email">
<id name="EmailId">
<!-- this tells NHibernate to use DB to generate id -->
<generator class="native"/>
</id>
<property name="EmailProperty1" column="emailProp1"/>
<bag name="AttachmentCollection" lazy="true" inverse="true">
<key column="emailId"/>
<one-to-many class="Foo.Emails.Attachment, Foo.Emails"/>
</bag>
</class>
<class name="Attachment" table="emailattachment">
<id name="AttachmentId">
<generator class="native"/>
</id>
<property="AttachmentProperty1" column="attachmentProp1"/>
<many-to-one name="ParentEmail" class="Foo.Emails.Email, Foo.Emails" lazy="proxy" column="emailId">
</class>
</hibernate-mapping>
</code></pre>
<p>In this map, you'd get the bi-directional relationship, and that generator tag is telling nhibernate that objects with a null Id property (you can also specify another "unsaved-value"), then you're inserting the object, else updating. Should fix your current problem.</p>
<p>Couple other things: examine closely what kind of containers you need to use when mapping (bag vs. set vs. list). There's an excellent writeup in hibernatingrhino's <a href="https://web.archive.org/web/20110227204838/http://blogs.hibernatingrhinos.com/nhibernate/Default.aspx" rel="nofollow">NHibernateFAQ</a>.</p>
<p>Also, since you're new to NHibernate, I very, very greatly recommend the <a href="http://www.summerofnhibernate.com/" rel="nofollow">summer of nhibernate screencasts</a>. The best tool I've found so far for learning.</p>
|
How to execute an arbitrary shell script and pass multiple variables via Python? <p>I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby.</p>
<p>From what I've read, I can easily execute Ruby scripts (or other arbitrary shell scripts) using <code>subprocess</code> and capture their output with a pipe; that's not a problem, and there's lots of examples online. However, I need to provide the script with multiple variables (say a chunk of text along with some simple boolean information about the text the script is modifying) and I'm having trouble figuring out the best way to do this.</p>
<p>Does anyone have a suggestion for the best way to accomplish this? My goal is to provide scripts with the information they need with the least required code needed for accessing that information within the script.</p>
<p>Thanks in advance!</p>
| <p>See <a href="http://docs.python.org/library/subprocess.html#using-the-subprocess-module" rel="nofollow">http://docs.python.org/library/subprocess.html#using-the-subprocess-module</a></p>
<blockquote>
<p>args should be a string, or a sequence
of program arguments. The program to
execute is normally the first item in
the args sequence or the string if a
string is given, but can be explicitly
set by using the executable argument.</p>
</blockquote>
<p>So, your call can look like this</p>
<pre><code>p = subprocess.Popen( args=["script.sh", "-p", p_opt, "-v", v_opt, arg1, arg2] )
</code></pre>
<p>You've put arbitrary Python values into the args of <code>subprocess.Popen</code>.</p>
|
Flash and SharePoint <p>I have a flash control that I want to integrate with in SharePoint and would like to know what is the best way to read from a list so that I can display items in the flash control?</p>
<p>Code examples/ideas are welcome.</p>
| <p>I think the easiest way to retrieve items from a list in a Flash control will be through SharePoint's <a href="http://msdn.microsoft.com/en-us/library/lists.aspx" rel="nofollow">Lists Web Service</a>. Specifically the <a href="http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems.aspx" rel="nofollow">GetListItems method</a> can be used to retrieve a list item (or certain fields in a list item) based on a <a href="http://msdn.microsoft.com/en-us/library/ms467521.aspx" rel="nofollow">CAML query</a></p>
|
I need to persist data on the client side (about 1MB) <p>I need to persist my data on the client side, without it moving back and forth in each request (Kills the cookies option).
I can't use special plugins/extensions.</p>
<p>One thought I had was to generate a dynamic JS file with the needed data for the current session of the user and make sure it is cached. There is a small problem with that, as in the event this data needs to be changed during the session, it is a bit complex (dirty code).</p>
<p>One more thought: Is there a service (out there in the cloud) which allows me to store key/value pairs and is very fast to access/query with JS? (Someone said Google?)</p>
<p>Is there a better/another way?</p>
| <p>You may store data in <code>window.name</code>, which can hold up to 2MB of data (!).</p>
<pre><code>/* on page 1 */
window.name = "Bla bla bla";
/* on page 2 */
alert(window.name); // alerts "Bla bla bla"
</code></pre>
<p><strong>Edit:</strong> Also have a look at <a href="http://ajaxian.com/archives/whats-in-a-windowname">this Ajaxian article</a> regarding this.</p>
<p>Note that other sites in the same tab/window does also have access to <code>window.name</code>, so you shouldn't store anything confidential here.</p>
|
Inner joining UDF on SQL Server <p>I have a table valued function that does a complex query and returns a table (UDF1), and then I have another table that has a bunch of rows that can be used to reduce the output from this UDF.</p>
<p>Is it possible to join these two and pass columns from the table as arguments to the UDF ?</p>
<p>like, </p>
<pre><code>SELECT *
FROM UDF1 (TBL1.Column1, TBL1.Column2)
INNER JOIN TBL1
ON (TBL1.Column3 = UDF1.Col3)
</code></pre>
| <p>You need to use the <a href="http://msdn.microsoft.com/en-us/library/ms175156.aspx" rel="nofollow">CROSS APPLY</a> syntax here.</p>
<p>For reasonable performance, the UDF should be an inline one rather than a multistatement one if at all possible.</p>
|
Most Efficient (Fast) T-SQL DELETE For Many Rows? <p>Our server application receives information about rows to add to the database at a rate of 1000-2000 rows per second, all day long. There are two mutually-exclusive columns in the table that uniquely identify a row: one is a numeric identifier called 'tag' and the other is a 50character string called 'longTag'. A row can have either a tag or a longTag; not both.</p>
<p>Each row that comes in off the socket may or may not already exist in the table. If it exists, that row must be updated with the new information. If it doesn't exist, it must be added. We are using SQL 2005 and in a few cases even SQL 2000, so we cannot use the new MERGE keyword.</p>
<p>The way I am doing this now is to build a giant DELETE statement that looks like this:</p>
<pre><code>DELETE from MyRecords
WHERE tag = 1
OR tag = 2
OR longTag = 'LongTag1'
OR tag = 555
</code></pre>
<p>...where each incoming row has its own 'OR tag = n' or 'OR longTag = 'x'' clause.</p>
<p>Then I perform an XML Bulk Load using ISQLXMLBulkLoad to load all the new records at once.</p>
<p>The giant DELETE statement sometimes times out, taking 30 seconds or longer. I'm not sure why.</p>
<p>As records come in off the socket they must either be inserted or they must replace existing rows. Is the way I'm doing it the best way to do it?</p>
<p><strong>EDIT</strong>: The ratio of new rows to replacement rows is going to be very heavily slanted toward new rows. In data I have seen coming from production, there will typically be 100-1000 new rows for each correction.</p>
<p><strong>EDIT 2</strong>: Both the inserts and the deletes must be handled as a single transaction. If either the insert or the delete fails, they must both be rolled back, leaving the table in the same state it was in before the inserts & deletes began.</p>
<p><strong>EDIT 3</strong>: Regarding NULL tags. I need to first briefly describe the system a little more. This is a database for a trading system. MyTable is a trades table containing two kind of trades: so-called "day trades" and so-called "opening positions." Day trades are simply trades -- if you were an options trader and you did a trade, that trade would be a day trade in this system. Opening positions are basically a summary of your portfolio up until today. Both opening positions and day trades are stored in the same table. Day trades have tags (either longTags or numeric tags), and opening positions do not. There can be duplicate rows for opening positions -- that is fine & normal. But there cannot be duplicate rows for day trades. If a day trade comes in with the same tag as some record already in the database, then the data in the table is replaced with the new data.</p>
<p>So there are 4 possibilities for the values in tag & longTag:</p>
<p>1) tag is non-zero & longTag is empty: this is a day trade with a numeric identifier.
2) tag is zero and longTag has a non-empty character value. This is a day trade with an alphanumeric identifier.
3) tag is zero and longTag is empty: this is an opening position.
4) tag is non-zero and longTag has a non-empty character value. This is prevented from every happening by our server software, but if it were to happen the longTag would be ignored and it would be treated the same as case #1. Again, this does not happen.</p>
| <p>I think splitting the giant DELETE statement into 2 DELETE may help.</p>
<p>1 DELETE to deal with tag and a separate DELETE to deal with longTag.
This would help SQL server to choose to use indexes efficiently.</p>
<p>Of course you can still fire the 2 DELETE statements in 1 DB round-trip.</p>
<p>Hope this helps</p>
|
What is the best practice for role security for an Intratnet ASP.NET/SQL2K5 environment? <p>Our current Intranet environment is a little outdated. The current stack has ASP.NET 1.1/2.0 applications that are querying against a SQL 2000 database. </p>
<p>For role security, there are user groups on the servers that users are added into (so you need to be added into the group on the test and production machine). These user groups are synchronized into user roles on SQL 2000 itself. Roles are granted execute permissions to stored procedures as needed to prevent any access violations.</p>
<p>At the web application level, we use basic authentication (which authenticates against our Active Directory) and have identity impersonation turned on. The connection string to the database uses Integrated Security. This creates an environment where the web application connects to the database as the user logged in, which will enforce database security on stored procedures being called. It also allows us to use the typical User.IsInRole() method to perform authorization within the application itself.</p>
<p>There are several problems with this. The first is that only our server administrators have access to the user groups on the machine, so updating role security, or adding additional users is out of the hands of the application administrators. In addition, the only way to get the role was to call a SQL procedure called "xp_logininfo" which is locked down in SQL 2005. While I don't know the full details, our DBA tells us that this general model doesn't play nice with SQL 2005 given the nature of schemas in the newer version.</p>
<p>We're at the point now that we're ready to update our environment. We're writing .NET 3.5 apps to leverage more AJAX and SQL Server 2005 is the primary environment for our database. We're looking to update the security model as well to be a bit more flexible for the application administrators, and potentially leverage Active Directory more.</p>
<p>One concern we have as well is that a given user will most likely have access to multiple applications, so having some kind of centralized solution is optimal so we can easily remove users when needed.</p>
<p>What is considered the best practice for maintaining role security in this kind of environment?</p>
| <p><a href="http://www.4guysfromrolla.com/articles/120705-1.aspx" rel="nofollow">ASP.NET 2.0's Membership, Roles, and Profile</a></p>
|
Silverlight MVVM Isolated Storage <p>I've tried to use IsolatedStorageSettings in my ViewModel, but these are not getting retained across browser refreshes (F5).</p>
<p>for example;</p>
<pre><code>//look in the IsoStore for remembered details
IsRememberMe = IsolatedStorageSettings.ApplicationSettings.Contains(Constants.LOGIN_REMEMBERED_USERNAME);
if (IsRememberMe)
{
UserName = IsolatedStorageSettings.ApplicationSettings[Constants.LOGIN_REMEMBERED_USERNAME] as string;
}
</code></pre>
<p>Do I need to do something differently in my MVVM ViewModel's??</p>
<p><strong>EDIT</strong>
It's worth noting that this code is sitting in a referenced project - so ultimately a seperate XAP file to the parent XAP that is loaded in the browser - might this cause the settings to be lost on each refresh?</p>
<p>THanks,
Mark</p>
| <p>Well...</p>
<p>In my case I have issues using Application Isolated Storage, each time I deployed a new version of my app (just for instance changing the color of a button I lost my Iso Storage :-().</p>
<p>I move to use SiteStorage instead of Application level, and it worked:</p>
<p><a href="http://www.tipsdotnet.com/TechBlog.aspx?PageIndex=0&BLID=13" rel="nofollow">http://www.tipsdotnet.com/TechBlog.aspx?PageIndex=0&BLID=13</a></p>
<p>On the other hand what I had done with Iso Storage is perform CRUD on folders and files, not sure abou that other kind of settings.</p>
<p>HTH
Braulio</p>
|
Keeping Mobile Data Synchronized <p>I'd like a simple method to keep a SQL CE database (on Windows Mobile or CE) synchronized to SQL Server Express. My understanding is that SQL Express does not have replication which is what would normally be used. Are there any other ways to accomplish this?</p>
<p>I'm working in C# with .Net 2.0.</p>
<p>Thanks!</p>
| <p><a href="http://msdn.microsoft.com/en-us/sync/default.aspx" rel="nofollow">Microsoft Sync Framework</a></p>
|
PHP @exec is failing silently <p>This is driving me crazy. I'm trying to execute a command line statement on a windows box for my PHP web app. It's running on windows XP, IIS5.1. The web app is running fine, but I cannot get @exec() to work with a specific contactenated variable. My command construction looks like this:</p>
<pre><code>$cmd = ($config->svn." cat ".$this->repConfig->svnParams().quote($path).' -r '.$rev.' > '.quote($filename));
</code></pre>
<p>This command does not work as is above, when it generates the following string:</p>
<pre><code>svn --non-interactive --config-dir /tmp cat "file:///c:/temp/test/acccount/dbo_sproctest.sql" -r 1 > "C:\Inetpub\sites\websvn\temp\wsv5B45.tmp"
</code></pre>
<p>If I copy/paste this to my own command line, it works fine.</p>
<p>If I hard code that very same path instead of adding it with the variable, it works! I've tried with and without quotes around the file name. I've tried with and without quotes around the entire command. I've tried other directories. I've tried passing an output paramter to exec(), and it comes back empty (Array () ). I've tried redirecting the output of the error stream of the command to a file, and that error output file never gets created. </p>
<p>The only thing I can possibly concieve of is that exec() is failing silently. What on earth am I doing wrong here? If I hard code the file path, using the same dir structure and filename, it works fine. If I don't, it doesn't.</p>
<p>Maybe the slashes () in the file path aren't being escaped properly, but when I do it manually with single quotes they are not considered escape sequences??</p>
<p><em>UPDATE:</em></p>
<p>I took the @ off of exec, and still not seeing any errors.</p>
<p>I gave the full path to SVN, still no luck. It should be noted that the command worked fine before with the non-full path SVN so long as I manually specify the file destination for cat.</p>
<p><em>Update 2: RE: Kieth</em></p>
<p>I'm calling exec by trying both:</p>
<pre><code>exec($cmd);
</code></pre>
<p>or</p>
<pre><code>exec($cmd, $out);
</code></pre>
<p>My php.ini already had safe_mode = 0.</p>
<p>I added error_reporting(E_ALL); and didn't see anything new</p>
<p>If I echo (or print_r) my exec call, I am not actually seing <em>anything</em></p>
<p>If I echo (or print_r) my exec call when included an output var, I get an empty arr</p>
<p><em>Update 3</em></p>
<p>I tried both escapeshellcmd and escapeshellarg to no avail (good idea though).</p>
<p>I should add that the file is being created through invoking</p>
<pre><code>tempnam("temp", "wbsn");
</code></pre>
<p>The fact that it works just fine if I manually specify the string instead of letting it be generated by tempname seems to suggests that the source of the problem, but I can't figure out how. I did a comparison of the manual string with the one generated, and it came back as a match.</p>
| <p><code>@exec</code> will always fail silently, because @ is PHP's error suppression operator.</p>
|
How to use Unit files in Delphi <p>I'm just trying to get the hang of separate units to make my code more encapsulated.
I'm trying to get the public/private declarations of my methods sorted out, so I can call them from other units that use <code>testunit</code>. In this example I want to make <code>hellofromotherunit</code> public, but <code>stickletters</code> private.</p>
<pre><code>unit testunit;
interface
uses
Windows, Messages, Dialogs;
implementation
function stickletters(a,b:string):string;
begin
result:=a+b;
end;
procedure hellofromotherunit();
begin
showmessage(stickletters('h','i'));
end;
end.
</code></pre>
<p>I could not seem to copy the private/public structure from other units as in:</p>
<pre><code>Type
private
function stickletters(a,b:inter):integer;
public
procedure hellofromotherunit();
end
</code></pre>
| <p>The Unit structure looks a bit like the public/private sections from objects, you could say it is their forerunner. But the syntax is different.</p>
<p>You only have to declare the method header in the interface section, as in:</p>
<pre><code>interface
procedure hellofromotherunit();
implementation
procedure hellofromotherunit(); begin .. end;
</code></pre>
<p>Only one of each section allowed.</p>
|
searching social networking <p>How can I organize a search in a social network web application? Searching is done by full name. I want to use stored procedures. Is it the best sollution? What algorithm can be used?</p>
<p>While registering, the user specifies his/her full name for ex: Alice Johnson Martin.
I want to search for a user using his/her fullname. In case someone is searching for Johnson Martin Alice, the user with the name Alice Johnson Martin should be found. I am using postgre sql and asp.net mvc.</p>
| <blockquote>
<p>What algorithm can be used?</p>
</blockquote>
<p>Graph algorithms, machine learning, heuristics etc come to my mind. Depends on what you want to achieve.</p>
|
selectionStart-End with textareas <p>I'm having this annoying problem, I can't seem to get the starting and ending index of the selected text in a textarea, all I get is undefined like this:</p>
<pre><code>$('#myarea').selectionStart; // return undefined
</code></pre>
<p>Did I do something wrong?</p>
| <p>Try:</p>
<pre><code>$('#myarea')[0].selectionStart;
</code></pre>
<p>Why? A jQuery selector does not return the actual DOM elements but the wrapped jQuery collection. jQuery makes the actual DOM elements accessible as an array, so if you wanted to use the 1st matched element (and in this case, the only one, since it's by ID), you would do the above.</p>
|
Find the App_Data path from a WCF service <p>I'm trying to write a WCF function that gives me back the URI of an image in the App_Data folder so I can display it in a silverlight application.</p>
<p>How do I get the location of the App_Data folder so that I can search inside it to find the Image I want to display?</p>
| <p><a href="http://stackoverflow.com/questions/480504/access-appdata-in-wcf-service">http://stackoverflow.com/questions/480504/access-appdata-in-wcf-service</a></p>
|
MySQL performance optimization: order by datetime field <p>I have a table with roughly 100.000 blog postings, linked to a table with 50 feeds via an 1:n relationship. When I query both tables with a select statement, ordered by a datetime field of the postings table, MySQL always uses filesort, resulting in very slow query times (>1 second). Here's the schema of the <code>postings</code> table (simplified):</p>
<pre><code>+---------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| feed_id | int(11) | NO | MUL | NULL | |
| crawl_date | datetime | NO | | NULL | |
| is_active | tinyint(1) | NO | MUL | 0 | |
| link | varchar(255) | NO | MUL | NULL | |
| author | varchar(255) | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| excerpt | text | NO | | NULL | |
| long_excerpt | text | NO | | NULL | |
| user_offtopic_count | int(11) | NO | MUL | 0 | |
+---------------------+--------------+------+-----+---------+----------------+
</code></pre>
<p>And here's the <code>feed</code> table:</p>
<pre><code>+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| type | int(11) | NO | MUL | 0 | |
| title | varchar(255) | NO | | NULL | |
| website | varchar(255) | NO | | NULL | |
| url | varchar(255) | NO | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
</code></pre>
<p>And here's the query that takes >1 second to execute. Please note that the <code>post_date</code> field has an index, but MySQL isn't using it to sort the postings table:</p>
<pre><code>SELECT
`postings`.`id`,
UNIX_TIMESTAMP(postings.post_date) as post_date,
`postings`.`link`,
`postings`.`title`,
`postings`.`author`,
`postings`.`excerpt`,
`postings`.`long_excerpt`,
`feeds`.`title` AS feed_title,
`feeds`.`website` AS feed_website
FROM
(`postings`)
JOIN
`feeds`
ON
`feeds`.`id` = `postings`.`feed_id`
WHERE
`feeds`.`type` = 1 AND
`postings`.`user_offtopic_count` < 10 AND
`postings`.`is_active` = 1
ORDER BY
`postings`.`post_date` desc
LIMIT
15
</code></pre>
<p>The result of the <code>explain extended</code> command on this query shows that MySQL is using filesort:</p>
<pre><code>+----+-------------+----------+--------+---------------------------------------+-----------+---------+--------------------------+-------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+--------+---------------------------------------+-----------+---------+--------------------------+-------+-----------------------------+
| 1 | SIMPLE | postings | ref | feed_id,is_active,user_offtopic_count | is_active | 1 | const | 30996 | Using where; Using filesort |
| 1 | SIMPLE | feeds | eq_ref | PRIMARY,type | PRIMARY | 4 | feedian.postings.feed_id | 1 | Using where |
+----+-------------+----------+--------+---------------------------------------+-----------+---------+--------------------------+-------+-----------------------------+
</code></pre>
<p>When I remove the <code>order by</code> part, MySQL stops using filesort. Please let me know if you have any ideas on how to optimize this query to get MySQL to sort and select the data by using indexes. I have already tried a few things such as creating a combined index on all where/order by fields, as suggested by a few blog postings, but this didn't work either.</p>
| <p>Create a composite index either on <code>postings (is_active, post_date)</code> (in that order).</p>
<p>It will be used both for filtering on <code>is_active</code> and ordering by <code>post_date</code>.</p>
<p><code>MySQL</code> should show <code>REF</code> access method over this index in <code>EXPLAIN EXTENDED</code>.</p>
<p>Note that you have a <code>RANGE</code> filtering condition over <code>user_offtopic_count</code>, that's why you cannot use an index over this field both in filtering and in sorting by other field.</p>
<p>Depending on how selective is your <code>user_offtopic_count</code> (i. e. how many rows satisfy <code>user_offtopic_count < 10</code>), it may be more useful to create an index on <code>user_offtopic_count</code> and let the post_dates be sorted.</p>
<p>To do this, create a composite index on <code>postings (is_active, user_offtopic_count)</code> and make sure the <code>RANGE</code> access method over this index is used.</p>
<p>Which index will be faster depends on your data distribuion. Create both indexes, <code>FORCE</code> them and see which is faster:</p>
<pre><code>CREATE INDEX ix_active_offtopic ON postings (is_active, user_offtopic_count);
CREATE INDEX ix_active_date ON postings (is_active, post_date);
SELECT
`postings`.`id`,
UNIX_TIMESTAMP(postings.post_date) as post_date,
`postings`.`link`,
`postings`.`title`,
`postings`.`author`,
`postings`.`excerpt`,
`postings`.`long_excerpt`,
`feeds`.`title` AS feed_title,
`feeds`.`website` AS feed_website
FROM
`postings` FORCE INDEX (ix_active_offtopic)
JOIN
`feeds`
ON
`feeds`.`id` = `postings`.`feed_id`
WHERE
`feeds`.`type` = 1 AND
`postings`.`user_offtopic_count` < 10 AND
`postings`.`is_active` = 1
ORDER BY
`postings`.`post_date` desc
LIMIT
15
/* This should show RANGE access with few rows and keep the FILESORT */
SELECT
`postings`.`id`,
UNIX_TIMESTAMP(postings.post_date) as post_date,
`postings`.`link`,
`postings`.`title`,
`postings`.`author`,
`postings`.`excerpt`,
`postings`.`long_excerpt`,
`feeds`.`title` AS feed_title,
`feeds`.`website` AS feed_website
FROM
`postings` FORCE INDEX (ix_active_date)
JOIN
`feeds`
ON
`feeds`.`id` = `postings`.`feed_id`
WHERE
`feeds`.`type` = 1 AND
`postings`.`user_offtopic_count` < 10 AND
`postings`.`is_active` = 1
ORDER BY
`postings`.`post_date` desc
LIMIT
15
/* This should show REF access with lots of rows and no FILESORT */
</code></pre>
|
Compromised interoperability in .NET? <p>Recently I asked a question here about using F# extensions in C#. Brian quoted:</p>
<blockquote>
<p>Per the language spec, section 10.7 "Type extensions":</p>
<p>Optional extension members are syntactic sugar for static members. Uses of optional extension members elaborate to calls to static members with encoded names where the object is passed as the first argument. The encoding of names is not specified in this release of F# and is not compatible with C# encodings of C# extension members.</p>
</blockquote>
<p>I am wondering if there are any other interoperability issues in .NET that restricts the usage of some functionality to some languages but not others?</p>
| <p>I expect there are lots of things, but mostly in corner cases if you're talking about the major managed languages (C#, VB, and soon F#). Other cases where F# currently interacts poorly with C# is when there method overloads that take both Action and Func (the C# overload resolution works differently than F#, so F# calls to such an API may be more verbose); 'params' argument arrays (especially when trying to tak advantage of 'array covariance', which is a feature of C# but not F#); there are some issues regarding subclassing or implementing interfaces, combined with accessibility (e.g. public versus internal), where sometimes you cannot derive an F# class from a C# one...</p>
<p>Many of these issues are simply either 'bugs' in the F# CTP compiler or 'design issues' with the F# language spec that may be changed before the final release of F#.</p>
<p>I don't know the dusty corners of the CLR well enough, but I bet that there are places where C# and VB fails to mesh. And there are features of the CLR that none of the major languages use, so I expect there's ways to create valid IL that may cause problems with some interop.</p>
<p>Overall I think all this stuff is minor, and in the case of F#, a bit of it will be 'fixed' before the final release. But I will be curious to see what other things people call out, as it could be useful feedback for the managed language teams at MS.</p>
|
How do you search for a & (ampersand) in the tsql contains function? <p>I have a table T which has a column C which contains text that have the character & within it, but if I do the following query, it returns nothing, although I may have 10 rows.</p>
<pre><code>SELECT * FROM T WHERE Contains(C, 'a&b')
</code></pre>
| <p>Use like instead:</p>
<pre><code>SELECT * FROM T WHERE C like '%&%'
</code></pre>
<p>if you're looking just for & </p>
<p>or</p>
<pre><code>SELECT * FROM T WHERE C like '%a&b%'
</code></pre>
<p>if you need to search for a&b </p>
|
Ruby eval behaves differently in irb versus in a file <p>This code works in irb:</p>
<pre><code>irb(main):037:0> eval <<-EOS
irb(main):038:0" #{attribute} = "host"
irb(main):039:0" puts machine
irb(main):040:0" EOS
host
=> nil
irb(main):041:0> puts machine
host
=> nil
irb(main):042:0> puts attribute
machine
=> nil
irb(main):043:0>
</code></pre>
<p>however when I try to execute the same code as a ruby script I get the following error:</p>
<pre><code>../autosys/convert_jil_to_zapp.rb:40: undefined local variable or method `machine' for main:Object (NameError)
from ../autosys/convert_jil_to_zapp.rb:29:in `each_line'
from ../autosys/convert_jil_to_zapp.rb:29
from ../autosys/convert_jil_to_zapp.rb:27:in `each'
from ../autosys/convert_jil_to_zapp.rb:27
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 77$ gvim try.rb
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 78$ chmod +x try.rb
pi929c1n10 /ms/user/h/hirscst/ruby/autosys 79$ ./try.rb
host
./try.rb:8: undefined local variable or method `machine' for main:Object (NameError)
</code></pre>
<p>can anyone explain why?</p>
| <p>It's because the <code>machine</code> variable was not already defined when <code>eval</code> was run. A more concise example:</p>
<h3>Works in IRB but not as a script</h3>
<pre><code>eval 'x = 3'
puts x # throws an exception when run as a script
=> 3
</code></pre>
<h3>Works in IRB and as a script</h3>
<pre><code>x = 1
eval 'x = 3'
puts x
=> 3
</code></pre>
<p>To <a href="http://groups.google.com/group/comp.lang.ruby/browse%5Fthread/thread/a954f8aaf698a0b9/e1c761b71b63b82e?#422ad5daee216181">quote Matz</a>:</p>
<blockquote>
<p>local variables should be determined at compile time, thus local
variables defined first in the eval'ed string, can only be accessed from
other eval'ed strings. In addition, they will be more ephemeral in
Ruby2, so that these variables will not be accessed from outside. </p>
</blockquote>
<p>The difference is that in IRB <em>everything</em> is being eval'd, so it's all in the same scope. That is, you're essentially doing this in IRB:</p>
<pre><code>eval 'x = 3'
eval 'puts x'
</code></pre>
<p>Which works both in IRB and as a script.</p>
|
MYSQL: Complex Query Question <p>I am working with polls: Each poll has many options and users can vote in polls once. Thus I have a 'votes' table with the following fields:</p>
<ul>
<li>id (id of the vote) </li>
<li>option_id (id of the poll option chosen)</li>
<li>user_id (id of the user)</li>
<li>poll_id (id of the poll)</li>
</ul>
<p><strong>So here is what I'm trying to do</strong>: Given an array of poll_ids, I want to have a query return the most voted on option for each poll. Thus if I give poll_id's of 1 & 2, I want to get back the most voted on options for polls 1 & 2. I have tried the following:</p>
<pre><code>SELECT
t1.poll_id,
t1.option_id,
count(t1.option_id) AS num_votes,
t2.option_id AS user_vote
FROM
votes AS t1
JOIN
votes AS t2
ON
t1.id = t2.id
WHERE
t1.poll_id IN (30,40)
GROUP BY
t1.option_id;
</code></pre>
<p>That almost does the trick...but gives me <em>all</em> poll options with corresponding votes for each poll provided, not just the most voted option. If anyone has any ideas, I'd really appreciate it. Thanks.</p>
| <pre><code>SELECT (
SELECT option_id
FROM votes v
WHERE v.poll_id = p.id
GROUP BY
option_id
ORDER BY
COUNT(*) DESC
LIMIT 1
) cnt
FROM polls p
WHERE p.id IN (1, 2)
</code></pre>
|
Looking for a better alternative to PIL for basic image file I/O and processing in Python? <p>Are there better alternatives to PIL (<a href="http://www.pythonware.com/products/pil/">Python Imaging Library</a>) for basic image file I/O and processing in Python?</p>
| <p>Try Pillow: <a href="http://pypi.python.org/pypi/Pillow">http://pypi.python.org/pypi/Pillow</a></p>
<p>It's a fork of PIL but maintained by Plone community. Which is great as it is being maintained (in comparison to it's predecessor) and it is backward compatible with PIL. Existing code will work out of the box with Pillow. </p>
<p>They mostly focus on packaging issues and AFAIK this was the biggest pain with PIL.</p>
<p>Good luck!</p>
|
SQL Reporting: Null Parameter <p>I have discovered that in SQL Reporting there might be a problem. I have a ReportViewer on my page and I am sending in parameters using the following method:</p>
<pre><code>List<ReportParameter> myParams = new List<ReportParameter>();
myParams.Add(new ReportParameter("Start_Date", StartDate));
myParams.Add(new ReportParameter("End_Date", EndDate));
ReportViewer1.ServerReport.SetParameters(myParams);
</code></pre>
<p>This works great! But, when I try to set a parameter to null, after running that query, it maintains the previous value rather than setting it to null.</p>
<p>I run this code on another event that executes after the above code:</p>
<pre><code>List<ReportParameter> myParams = new List<ReportParameter>();
myParams.Add(new ReportParameter("Start_Date"));
// I even tried omiting this line.
//(This is the null parameter I wish to pass)
myParams.Add(new ReportParameter("End_Date", EndDate));
ReportViewer1.ServerReport.SetParameters(myParams);
</code></pre>
<p>Has anyone come across a work around or a different technique to get this working?</p>
<p>Also if I initially do not define the parameter, then assign the parameter, then do not define the paramter, it maintains the value that was assigned. (These are all postbacks, each event)</p>
| <p>Do something like this..I've tested it in my own little test project and it seems to work.</p>
<pre><code>List<ReportParameter> myParams = new List<ReportParameter>();
ReportParameter p = new ReportParameter("Start_Date");
p.Values.Add(null);
myParams.Add(p);
//myParams.Add(new ReportParameter("Start_Date"));
// I even tried omiting this line.
//(This is the null parameter I wish to pass)
myParams.Add(new ReportParameter("End_Date", EndDate));
ReportViewer1.ServerReport.SetParameters(myParams);
</code></pre>
|
jQuery mouseover invoking a click <p>New to jQuery but quite fascinated with it and really loving it. Starting to turn me off, though, with this problem. Would really appreciate any help. Spent the last week trying to make heads or tails out of it. I apologize if this problem has been posted before.</p>
<p>I have a list of products. Each product is enclosed in a <code><div></code>. Inside each div has a floated <code><span></code> for product information and an <code><a></code> to go the appropriate URL of the product. This list is generated programmatically using ASP.NET. </p>
<pre><code><div id="prod1">
<span id="infoProd1" class="prodInfo" />
<a class="prodURL" href="url1">Name of product #1</a>
</div>
:
:
</code></pre>
<p>Unfortunately, I don't have a URL as this is only in a development platform behind a firewall. The site pretty much looks like the one below. I hope this helps.</p>
<pre><code>+----------+------------------------------+
| #prod1 | |
+----------+ | Each #prodNum div looks like:
| #prod2 | overlay and frame divs |
+----------+ appear over here | +-- #prod1 -----------------+
| #prod3 | with product details | | | |
+----------+ only if .prodInfo | | .prodURL | .prodInfo |
| | is clicked. | | | |
| : | | +---------------------------+
| | |
+----------+------------------------------+
</code></pre>
<p>The information for each product (including photo) is stored in a database.<br />
Depending on the action of the user on the span (<em>i.e. prodInfo</em>), the desired process is:</p>
<ul>
<li><strong>hover</strong> will display a small popup with some product info and some details (e.g. price).</li>
<li><strong>click</strong> will show (animate) a semi-transparent overlay and a <div id="frame"> containing all information regarding the product, including the photo.</li>
</ul>
<p>I have an image inside the frame that when clicked, would hide the overlay/frame.<br />
Information (including photo) is pulled using jQuery Ajax <code>$.get()</code>.<br />
Using jQuery, I was able to achieve this on the first pass (the first <strong>click</strong>). However, after I close "frame" and hide the overlay, and then <strong>hover</strong> over any "prodInfo," it'll display the small popup as it should be but at the same time ALSO DISPLAYS the overlay and the "frame" as if I invoked a <strong>click</strong>. </p>
<p>Here is the simplified jQuery code for the two events:</p>
<pre><code>$(".prodInfo").mouseover(
function(e) { // function fired when 'moused over'
var popupItem = $("#div_infoPopupItem"); // absolute positioned popup
var prod = $(this).attr('id');
var prd;
popupInit(popupItem, e); // changes the top/left coords
$.ajax({
type : 'GET',
url : 'prodInfo.aspx',
data : 'id=' + prod,
success :
function(prodInfo, status) {
var prodStr = '<b>No product name.</b>';
prd = prodInfo.split('::'); // product info delimited by '::'
prodStr = '<div class="popupInfo_head">' + prd[0] + '</div>' +
'<div style="margin:2px;">' + prd[1] + '</div>';
// and so on...
popupItem.html(prodStr);
return false;
},
error :
function() {
popupItem.html('Error in collecting information.');
}
});
popupItem.animate({ opacity : .94 }, { queue:false, duration: 120 });
return false;
}
);
$(".prodInfo").click(
function(e) {
var prod = $(this).attr('id');
var frame = $("#div_frame");
var overlay = $("#div_overlay");
var info;
var img = new Image();
document.getElementById('div_frame').scrollTop = 0;
$.get('prodInfo.aspx', { id: prod },
function (result) {
info = result.split(';;'); // name ;; status ;; description ;; price, etc.
$(this).ajaxSuccess(
function (e, request, settings) {
img.src = 'prodImage.aspx?id=' + prod;
img.id = 'prodImg';
//populate the frame with prod info
$(img).load(function () {
$("#prodInfoImage")
.css('background', 'transparent url("prodImage.aspx?id=' + prod + '") no-repeat 50% 50%');
switch (info[1]) {
case '0':
$("#prodStatus")
.removeAttr("class")
.addClass("status_notavail")
.text('Not available');
break;
case '1':
$("#prodStatus")
.removeAttr("class")
.addClass("status_avail")
.text('Available');
break;
} // switch
$("#prodInfoDesc")
.empty()
.append(info[2]);
$("#prodInfoExtra")
.empty()
.append(info[3]);
$("#prodName").text(info[0]);
}
)
.error(
function() {
return false;
}
); // image load
// animate overlay, frame and display product info
overlay .animate({ top : '0' }, { queue: false, duration: 280 })
.animate({ height: '100%' }, 280, '',
function() {
frame.animate({ opacity : .92 }, 320);
return false;
}
);
return false;
}
); // ajax success
}
); // get
}
);
</code></pre>
<p>Below is the event definition of the "close" image located inside the frame.</p>
<pre><code>$("#img_close").click(
function (e) {
$("#div_frame")
.animate({ opacity: 0}, 100, '',
function() {
$("#div_overlay")
.animate({ top : "50%" }, { queue: false, duration: 120 })
.animate({ height: "0px" }, 120);
}
);
return false;
}
);
</code></pre>
<p>As mentioned, this will work as planned only before the first click. After I click on a <em>prodInfo</em> <code>span</code> and close the frame/overlay, the next mouseover on a <em>prodInfo</em> actually invokes BOTH mouseover and ALSO a click (which shows back the overlay/frame).</p>
<p>EDIT:
Thanks to all who responded. I will try to debug it using each of your suggestions.</p>
<p>EDIT(2):
<em>Mahalo</em> for everyone who commented and responded.</p>
| <p>I can't quite picture the entire setup you have, but this was the first thing that popped to mind. It might be a case of event bubbling, carrying the click event to both the close button and the span. Perhaps when you click the close event, the span click might also fire, but the frame is being hidden by the close event. Check out the bind function for more info on stopping default action and event bubbling: <a href="http://jquery.bassistance.de/api-browser/#bindStringObjectFunction" rel="nofollow">http://jquery.bassistance.de/api-browser/#bindStringObjectFunction</a></p>
<p>As Don mentioned, a sample URL would definitely help a lot!</p>
<p>Edit:</p>
<p>Upon further examination, I think that it's the way you're attaching the ajaxSuccess event within the click() event. It might still be active and firing whenever ANY ajax request is made.</p>
<p>Edit, again:</p>
<p>I've just confirmed this with my own test of the code and it definitely seems to be the issue. In fact, it's attaching the ajaxSuccess function each time you click, so if you've clicked five times, it executes that function five times. Since an AJAX request is made in the mouseover event, it's also firing the previously attached ajaxSuccess functions and showing your overlay and frame.</p>
<p>To get around this try the following:</p>
<p>Instead of:</p>
<pre><code> $.get('prodInfo.aspx', { id: prod },
function (result) {
info = result.split(';;'); // name ;; status ;; description ;; price, etc.
$(this).ajaxSuccess(
</code></pre>
<p>Try:</p>
<pre><code> $.get('prodInfo.aspx', { id: prod },
function (result, statusText) {
info = result.split(';;'); // name ;; status ;; description ;; price, etc.
if ( statusText == 'success' ) {
</code></pre>
|
XSL and Flash XML breaks escaping <p>I have an XSL file I am loading in flash that includes the following snippet: </p>
<pre><code><xsl:text>&#x2022;</xsl:text>
</code></pre>
<p>I load it this way:</p>
<pre><code>_root.brochure_xsl = new XML();
_root.brochure_xsl.onLoad = function() {
_root.SendPdfXml();
}
_root.brochure_xsl.ignoreWhite = true;
_root.brochure_xsl.load(_root.appSettings.XmlDataLocation +"xml/brochure.xsl");
</code></pre>
<p>On the event, I trace the results like such:</p>
<pre><code>send_lv.XslContent = _root.brochure_xsl.toString();
trace(send_lv.XslContent);
</code></pre>
<p>In the result trace, it converts the snippet to a bullet.</p>
<pre><code><xsl:text>
</code></pre>
<p>* </p>
<pre><code></xsl:text>
</code></pre>
<p>I want it to stay the encoded, is this possible?</p>
| <p>This is certainly an encoding issue. The <code>toString()</code> method is suspect, but you have to check. Can you dump the contents of the XML character-by-character.</p>
|
First item in excel omitted in results (DataSet, OleDB) <p>[Sample.xlsx]</p>
<pre><code>Column 0, Row 0 = "ItemA"
Column 0, Row 1 = "ItemB"
Column 0, Row 2 = "ItemC"
Column 0, Row 3 = "ItemD"
</code></pre>
<p>[Application]</p>
<pre><code>DataSet dsData = new DataSet();
string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties='Excel 12.0;'";
OleDbDataAdapter daGetExcel = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
daGetExcel.Fill(dsData);
foreach (DataRow row in dsData.Tables[0].Rows)
{
lbExcelData.Items.Add(row[0].ToString());
}
</code></pre>
<p><code>lbExcelData</code> is a ListBox control on the form.</p>
<p>[RESULTS]</p>
<blockquote>
<p>"ItemB", "ItemC", "ItemD"</p>
</blockquote>
<p>[PROBLEM]</p>
<p>Why is the first item, "ItemA", being ignored?</p>
| <p>For Excel, set HDR=NO in the Extended Properties setting of the connection string.</p>
<p>"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Sample.xlsx;Extended Properties='Excel 12.0;HDR=NO'"</p>
<p><a href="http://connectionstrings.com/excel-2007" rel="nofollow">http://connectionstrings.com/excel-2007</a></p>
|
Image processing/enhancement algorithms for document OCR / readability? <p>I'm looking for algorithms, papers, or software to enhance faxes, images from cell phone cameras, and other similar source for readability and OCR. </p>
<p>I'm mainly interested in simple enhancements (eg. things you could do using ImageMagick), but I'm also interested in more sophisticated techniques. I'm already talking to vendors, so for this question I'm mostly looking for algorithms or open source software.</p>
<p>To further clarify: I'm not looking for OCR software or algorithms; I'm looking for algorithms to clean up the image so it looks more readable to the human eye, and can possibly be used for OCR.</p>
| <p>I had a similar problem when I was writing some software to do book scanning; floating around on the internet is a program called <a href="http://sourceforge.net/projects/pagetools/files" rel="nofollow">pagetools</a> that does straightening of scanned-in pages using a fairly clever mathematical trick called the Radon transform.</p>
<p>I also wrote a small routine that would white out the blank space on the page; OCR algorithms tend to do a lot better when they don't have to contend with background noise. What I did, was look for light-colored pixels that were more than a small radius away from dark-colored ones, and then boost those up to being pure white.</p>
<p>It's been a few years, though, so I don't have the exact implementation details handy.</p>
|
How do I translate a ® into Silverlight Text Represenation <p>I make calls to a webservice to get information that bind to the Text property of a TextBlock. Sometimes the information will contain encoded special characters for HTML - most notably the ® which I believe to the (r) symbol. The silverlight TextBlock just displays the raw text and not the (r). Of course, I can strip out the text, but it seems that someone on here will know how to translate HTMl codes like this into something that the TextBlock can understand. My first though is an iValueConverter with a Regex relace???</p>
<p>has anyone done one of these?</p>
| <p>You just need to use HtmlDecode:</p>
<pre><code>System.Windows.Browser.HttpUtility.HtmlDecode(yourStringHere)
</code></pre>
|
reverse string php <p>What would be the best way to reverse the order of a string so for instance,</p>
<pre><code>'Hello everybody in stackoverflow'
</code></pre>
<p>becomes</p>
<pre><code>'stackoverflow in everybody Hello'
</code></pre>
<p>any ideas</p>
| <p>Try this:</p>
<pre><code>$s = 'Hello everybody in stackoverflow';
echo implode(' ', array_reverse(explode(' ', $s)));
</code></pre>
|
Show a one to many relationship as 2 columns - 1 unique row (ID & comma separated list) <p>I need something similar to these 2 SO questions, but using Informix SQL syntax. </p>
<ul>
<li><p><a href="http://stackoverflow.com/questions/37696/concatenate-several-fields-into-one-with-sql">http://stackoverflow.com/questions/37696/concatenate-several-fields-into-one-with-sql</a></p></li>
<li><p><a href="http://stackoverflow.com/questions/368459/sql-help-select-statement-concatenate-a-one-to-many-relationship">http://stackoverflow.com/questions/368459/sql-help-select-statement-concatenate-a-one-to-many-relationship</a></p></li>
</ul>
<p>My data coming in looks like this:</p>
<pre><code>id codes
63592 PELL
58640 SUBL
58640 USBL
73571 PELL
73571 USBL
73571 SUBL
</code></pre>
<p>I want to see it come back like this:</p>
<pre><code>id codes
63592 PELL
58640 SUBL, USBL
73571 PELL, USBL, SUBL
</code></pre>
<p>See also <a href="http://stackoverflow.com/questions/489081/groupconcat-in-informix/">group_concat() in Informix</a>.</p>
| <p>I believe that the answer you need is a user-defined aggregate, similar to this one:</p>
<pre><code>CREATE FUNCTION gc_init(dummy VARCHAR(255)) RETURNING LVARCHAR;
RETURN '';
END FUNCTION;
CREATE FUNCTION gc_iter(result LVARCHAR, value VARCHAR(255))
RETURNING LVARCHAR;
IF result = '' THEN
RETURN TRIM(value);
ELSE
RETURN result || ',' || TRIM(value);
END IF;
END FUNCTION;
CREATE FUNCTION gc_comb(partial1 LVARCHAR, partial2 LVARCHAR)
RETURNING LVARCHAR;
IF partial1 IS NULL OR partial1 = '' THEN
RETURN partial2;
ELIF partial2 IS NULL OR partial2 = '' THEN
RETURN partial1;
ELSE
RETURN partial1 || ',' || partial2;
END IF;
END FUNCTION;
CREATE FUNCTION gc_fini(final LVARCHAR) RETURNING LVARCHAR;
RETURN final;
END FUNCTION;
CREATE AGGREGATE group_concat
WITH (INIT = gc_init, ITER = gc_iter,
COMBINE = gc_comb, FINAL = gc_fini);
</code></pre>
<p>Given a table of elements (called elements) with a column called name containing (funnily enough) the element name, and another column called atomic_number, this query produces this result:</p>
<pre><code>SELECT group_concat(name) FROM elements WHERE atomic_number < 10;
Hydrogen,Helium,Lithium,Beryllium,Boron,Carbon,Nitrogen,Oxygen,Fluorine
</code></pre>
<p>Applied to the question, you should obtain the answer you need from:</p>
<pre><code>SELECT id, group_concat(codes)
FROM anonymous_table
GROUP BY id;
</code></pre>
<hr>
<pre><code>CREATE TEMP TABLE anonymous_table
(
id INTEGER NOT NULL,
codes CHAR(4) NOT NULL,
PRIMARY KEY (id, codes)
);
INSERT INTO anonymous_table VALUES(63592, 'PELL');
INSERT INTO anonymous_table VALUES(58640, 'SUBL');
INSERT INTO anonymous_table VALUES(58640, 'USBL');
INSERT INTO anonymous_table VALUES(73571, 'PELL');
INSERT INTO anonymous_table VALUES(73571, 'USBL');
INSERT INTO anonymous_table VALUES(73571, 'SUBL');
INSERT INTO anonymous_table VALUES(73572, 'USBL');
INSERT INTO anonymous_table VALUES(73572, 'PELL');
INSERT INTO anonymous_table VALUES(73572, 'SUBL');
SELECT id, group_concat(codes)
FROM anonymous_table
GROUP BY id
ORDER BY id;
</code></pre>
<p>The output from that is:</p>
<pre><code>58640 SUBL,USBL
63592 PELL
73571 PELL,SUBL,USBL
73572 PELL,SUBL,USBL
</code></pre>
<p>The extra set of data was added to test whether insert sequence affected the result; it appears not to do so (the codes are in sorted order; I'm not sure whether there's a way to alter - reverse - that order).</p>
<hr>
<p>Notes:</p>
<ol>
<li>This aggregate should be usable for any type that can be converted to VARCHAR(255), which means any numeric or temporal type. Long CHAR columns and blob types (BYTE, TEXT, BLOB, CLOB) are not handled.</li>
<li>The plain LVARCHAR limits the aggregate size to 2048 bytes. If you think you need longer lengths, specify <code>LVARCHAR(10240)</code> (for 10 KiB), for example.</li>
<li>As of Informix 12.10.FC5, the maximum length that works seems to be 16380; anything longer seems to trigger <code>SQL -528: Maximum output rowsize (32767) exceeded</code>, which surprises me.</li>
<li><p>If you need to remove the aggregate, you can use:</p>
<pre><code>DROP AGGREGATE IF EXISTS group_concat;
DROP FUNCTION IF EXISTS gc_fini;
DROP FUNCTION IF EXISTS gc_init;
DROP FUNCTION IF EXISTS gc_iter;
DROP FUNCTION IF EXISTS gc_comb;
</code></pre></li>
</ol>
|
method_missing in "Programming Ruby" over my head <p><strong>method_missing</strong> </p>
<p>*obj.method_missing( symbol h , *args i ) â other_obj*</p>
<blockquote>
<p>Invoked by Ruby when obj is sent a
message it cannot handle. symbol is
the symbol for the method called, and
args are any arguments that were
passed to it. The example below
creates a class Roman, which responds
to methods with names consisting of
roman numerals, returning the
corresponding integer values. A more
typical use of method_missing is to
implement proxies, delegators, and
forwarders.</p>
</blockquote>
<pre><code>class Roman
def roman_to_int(str)
# ...
end
def method_missing(method_id)
str = method_id.id2name
roman_to_int(str)
end
end
r = Roman.new
r.iv ! 4
r.xxiii ! 23
r.mm ! 2000
</code></pre>
<p>I just heard about method-missing and went to find out more in <em><a href="http://www.ruby-doc.org/docs/ProgrammingRuby/" rel="nofollow">Programming Ruby</a></em> but the above explanation quoted from the book is over my head. Does anyone have an easier explanation? More specifically, is method-missing only used by the interpreter or is there ever a need to call it directly in a program (assuming I'm just writing web apps, as opposed to writing code for NASA)?</p>
| <p>It's probably best to not think of ruby as having methods. When you call a ruby "method" you are actually sending a message to that instance (or class) and if you have defined a handler for the message, it is used to process and return a value.</p>
<p>So <code>method_missing</code> is a special definition that gets called whenever ruby cannot find an apropriate handler. You could also think of it like a <code>*</code> method.</p>
|
array_flip certain keys <p>What would be a good way of fliping key 1 with key 2?</p>
<pre><code>// original
Array
(
[0] => Text1
[1] => World
[2] => Hello
)
// after
Array
(
[0] => Text1
[1] => Hello
[2] => World
)
</code></pre>
<p>Any clues. Thanks</p>
| <p>If it's a simple as that, </p>
<pre><code>$tmp = $array[1];
$array[1] = $array[2];
$array[2] = $tmp;
</code></pre>
|
Unit testing and mocking small, value-like classes in C++ <p>I am trying to set up some unit tests for an existing c++ project. </p>
<p>Here's the setup:
I have chosen Google Mock, which includes Google Test. I have added another project (called Tests) to the Visual Studio Solution. The units to test are in another project called Main. The plan is to add each cpp file that I want to test to the Tests project. The Tests project has access to all header files from Main.</p>
<p>I have added one cpp file to the Tests project, and it compiles, but comes up with linker errors. Most are because of a class derived from COleDateTime, called CTimeValue. The unit under test has methods with pass-by-value CTimeValue parameters and also declares some CTimeValue attributes.</p>
<p>I want to test the UUT in isolation, and use mocks and fakes for all dependencies. I don't see how to do it with CTimeValue. It is used as a value, contains no virtual methods, but is still quite complex and would deserve a seperate unit test. </p>
<p>CTimeValue is only one of many classes that is like this in the project. How can I isolate the testing of classes that use these user-defined types?</p>
<p>Cheers, Felix</p>
| <p>Sometimes one can not simply mock things. In that case what you can do is have a comprehensive test for the class in question (CTimeValue) and make sure you run the tests for that class as a subsuite in your other test.</p>
|
Best way to encode tuples with json <p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p>
| <p>You might consider saying</p>
<pre><code>{"[1,2]": [(2,3),(1,7)]}
</code></pre>
<p>and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in <code>JSON.parse</code> method (I'm using <code>jQuery.each</code> to iterate here but you could use anything):</p>
<pre><code>var myjson = JSON.parse('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
var key = JSON.parse(keystr);
// do something with key and val
});
</code></pre>
<p>On the other hand, you might want to just structure your object differently, e.g.</p>
<pre><code>{1: {2: [(2,3),(1,7)]}}
</code></pre>
<p>so that instead of saying</p>
<pre><code>myjson[1,2] // doesn't work
</code></pre>
<p>which is invalid Javascript syntax, you could say</p>
<pre><code>myjson[1][2] // returns [[2,3],[1,7]]
</code></pre>
|
XML Deserialization Permissions Error <p>I'm trying to use VS 2008 t publish a website to a virtual on my computer. The website runs just fine in VS2008 while debugging, but when I publish it, I'm getting the following error.</p>
<blockquote>
<p>Access to the path 'C:\dummy.xml' is
denied. Description: An unhandled
exception occurred during the
execution of the current web request.
Please review the stack trace for more
information about the error and where
it originated in the code. </p>
<p>Exception Details:
System.UnauthorizedAccessException:
Access to the path 'C:\dummy.xml' is
denied. </p>
<p>ASP.NET is not authorized to access
the requested resource. Consider
granting access rights to the resource
to the ASP.NET request identity.
ASP.NET has a base process identity
(typically {MACHINE}\ASPNET on IIS 5
or Network Service on IIS 6) that is
used if the application is not
impersonating. If the application is
impersonating via , the identity
will be the anonymous user (typically
IUSR_MACHINENAME) or the authenticated
request user. </p>
<p>To grant ASP.NET access to a file,
right-click the file in Explorer,
choose "Properties" and select the
Security tab. Click "Add" to add the
appropriate user or group. Highlight
the ASP.NET account, and check the
boxes for the desired access.</p>
</blockquote>
<p>I'm deserializing an XML file into a class built up by xsd.exe. The file and directory have the same permissions, and I can get to the xml file from a web browser. The service account being used to run / access the website (directory security settings in IIS) has full control permissions on the folder and the xml file.</p>
<p>I'm running Server 2003 R2 with IIS 6. </p>
<p>Any thoughts on how to correct this error?</p>
| <p>Set a filemon (<a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow">http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx</a>) to monitor 'C:\dummy.xml'. When you'll get the error check which Windows user is trying to access the file.</p>
|
How to clone ArrayList and also clone its contents? <p>How can I clone an <code>ArrayList</code> and also clone its items in Java?</p>
<p>For example I have:</p>
<pre><code>ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....
</code></pre>
<p>And I would expect that objects in <code>clonedList</code> are not the same as in dogs list.</p>
| <p>I, personally, would add a constructor to Dog:</p>
<pre><code>class Dog
{
public Dog()
{ ... } // Regular constructor
public Dog(Dog dog) {
// Copy all the fields of Dog.
}
}
</code></pre>
<p>Then just iterate (as shown in Varkhan's answer):</p>
<pre><code>public static List<Dog> cloneList(List<Dog> dogList) {
List<Dog> clonedList = new ArrayList<Dog>(dogList.size());
for (Dog dog : dogList) {
clonedList.add(new Dog(dog));
}
return clonedList;
}
</code></pre>
<p>I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.</p>
<p>Another option could be to write your own ICloneable interface and use that. That way you could write a generic method for cloning.</p>
|
Integrating FogBugz, what kind of API/integration points does it have? <p>Other than logging into FogBugz and using it etc, what kind of integration points does it have?</p>
| <p>It has a pretty complete API: <a href="http://www.fogcreek.com/FogBugz/docs/60/topics/advanced/API.html" rel="nofollow">http://www.fogcreek.com/FogBugz/docs/60/topics/advanced/API.html</a></p>
<p>Their are solutions for a lot of IDEs and you can integrate it with source control:
<a href="http://www.fogcreek.com/FogBugz/Ecology.html" rel="nofollow">http://www.fogcreek.com/FogBugz/Ecology.html</a></p>
|
Ugly looking text when drawing NSAttributedString in CGContext <p>I want to display strings inside CoreAnimation layers, but unfortunately CATextLayer is not enough, mostly because it's difficult to use when using constraints <em>and</em> you want to wrap the text.</p>
<p>I am using NSLayoutManager, using the following code (PyObjC):</p>
<pre><code>NSGraphicsContext.saveGraphicsState()
# THIS SOLVES THIS ISSUE
CGContextSetShouldSmoothFonts(ctx, False)
graphics = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(ctx, True)
NSGraphicsContext.setCurrentContext_(graphics)
height = size.height
xform = NSAffineTransform.transform();
xform.translateXBy_yBy_(0.0, height)
xform.scaleXBy_yBy_(1.0, -1.0)
xform.concat()
self.textContainer.setContainerSize_(size)
glyphRange = self.layoutManager.glyphRangeForTextContainer_(self.textContainer)
self.layoutManager.drawBackgroundForGlyphRange_atPoint_(glyphRange, topLeft)
self.layoutManager.drawGlyphsForGlyphRange_atPoint_(glyphRange, topLeft)
NSGraphicsContext.restoreGraphicsState()
</code></pre>
<p>This is all fine and working, but the only issue is that it produces bad-looking text (although it <em>is</em> antialised).</p>
<p>Here's the CATextLayer version: <img src="http://i39.tinypic.com/23h0h1d.png"></p>
<p>And here's the NSLayoutManager version: <img src="http://i40.tinypic.com/2vv9rw5.png"></p>
<p>Anything I'm missing?</p>
| <p>I'm answering this because the coretext-dev archives are not searchable, and Aki Inoue from Apple just answered my question:</p>
<blockquote>
<p>Since CALayer cannot represent subpixel color (aka font smoothing), you need to disable it.
I believe CATextLayer does it by default.</p>
<p>Do CGContextSetShouldSmoothFonts(context, false).</p>
</blockquote>
<p>Thanks, Aki!</p>
<p>Another comment by Milen Dzhumerov:</p>
<blockquote>
<p>I don't believe this is accurate. We're drawing text into CALayers with subpixel anti-aliasing. You just have to make sure that you've drawn behind the text before drawing the text itself. See <a href="http://www.cocoabuilder.com/archive/message/cocoa/2008/3/28/202581">http://www.cocoabuilder.com/archive/message/cocoa/2008/3/28/202581</a> for references.</p>
</blockquote>
<p>Milen is correct, in case you know the background colour beforehand, you can do:</p>
<pre><code>CGContextSetRGBFillColor(ctx, r, g, b, a)
CGContextFillRect(ctx, (topLeft, size))
CGContextSetShouldSmoothFonts(ctx, True)
</code></pre>
<p>And you get pretty <strong>sub-pixel</strong> anti-aliased text. However, if you <em>don't</em> know the background colour, you <em>need</em> to turn off font smoothing or you'll get garbled results.</p>
|
What is the best way to translate text inside a database <p>We have a problem here. </p>
<p>We need to translate a website into multiple language.
We already use gettext to translate the static content. But we have to translate some text content in multiple language.</p>
<p>The ui isn't a problem.</p>
<p>We found 2 ways to translate the text.
1. use JSON inside our text input
Why this solution is bad. Every text input will need to be bigger because we can't guess the real size of the attribute.</p>
<ol>
<li><p>Use the a translating table that keep reference to the original model and translate every field. It will still need big field because we cant define the field size by record.</p></li>
<li><p>Finally, the best solution I came with is creating a translating table. The table will keep foreign key of other tables. For each translation, we copy the record that need to be translated. Inside the translation table, there is 4 field, model_name(primary), reference_id(primary), translated_id(primary), locale(primary). This solution make it impossible to have multiple translation for the same model in the same language.</p></li>
<li><p>Last but not least, we could use something like someone proposed...a database gettext. We have a table that contain strings and only string (key, text, locale) so we can search for a model, a string that is the same as the one used in the model and then use the we found instead.</p></li>
</ol>
<p>My opinion is that all of these solutions are hack, the 4 solution is probably the one that looks better.</p>
<p>As I didn't found any good documentation, I would really like to make this question shine.</p>
| <p>Here is how we dealt with the multiple languages (we had some experts look at this solutions as well!).</p>
<ul>
<li>We have text a table in the database (textid, key, nl, uk, de, fr)</li>
<li>We have foreignkeys to the text table (from for instance the productnameid)</li>
<li>Static text that needs to be translated in html pages is surrounded with hashes: ##name##</li>
<li>right before the html content is send from the server to the client the htmlstream is parsed to translate the content between hashes.</li>
<li>the translated texts are stored in the cache which makes this solution flexible and still fast</li>
</ul>
<p>It works for us, and we build websites that have over 100k pageviews per hour.</p>
|
Does bitrot have any accepted dimensions? <p>Every modern source control system can slice and dice the history of a program. There are many tools to statically and dynamically analyze code. What sort of mathematical formula would allow me to integrate the amount of activity in a file along with the number of deployments of that software? We are finding that even if a program completes all of its unit tests, it requires more work than we would expect at upgrade time. A measure of this type should be possible, but sitting down and thinking about even its units has me stumped.</p>
<p><strong>Update:</strong> If something gets sent to a test machine I could see marking it less rotten. If something gets sent to all test boxes I could see it getting a fresh marker. If something goes to production I could give it a nod and reduce its <a href="http://en.wikipedia.org/wiki/Bit%5Frot" rel="nofollow">bitrot</a> score. If there is a lot of activity within its files and it never gets sent anywhere I would ding the crap out of it. Don't focus on the code assume that any data I need is at hand. </p>
<p>What kind of commit analysis (commit comments (mentioned below) or time between commits) is fair data to apply? </p>
<p><strong>Update:</strong> I think dimensional analysis could probably just be based on age. Relative to that is a little more difficult. Old code is rotten. The average age of each line of code still is simply a measure of time. Does a larger source module rot faster than a smaller, more complex one? </p>
<p><strong>Update</strong> Code coverage is measured in lines. Code executed often must by definition be less rotten than code never executed. To accurately measure bitrot you would need coverage analysis to act as a damper.</p>
| <p>Very interesting train of thought!</p>
<p>First, what <strong>is</strong> bitrot? The <a href="http://en.wikipedia.org/wiki/Software%5Frot" rel="nofollow">Software Rot</a> article on wikipedia collects a few points:</p>
<ul>
<li>Environment change: changes in the runtime</li>
<li>Unused code: changes in the usage patterns</li>
<li>Rarely updated code: changes through maintenance</li>
<li>Refactoring: a way to stem bitrot</li>
</ul>
<p>By <a href="http://en.wikipedia.org/wiki/Moore%27s%5Flaw" rel="nofollow">Moore's Law</a>, <code>delta(CPU)/delta(t)</code> is a constant factor two every 18 to 24 months. Since the environment contains more than the CPU, I would assume that this forms only a very weak lower bound on actual change in the environment. <em>Unit: OPS/$/s, change in Operations Per Second per dollar over time</em></p>
<p><code>delta(users)/delta(t)</code> is harder to quantify, but evidence in the frequency of occurrences of the words "Age of Knowledge" in the news, I'd say that users' expectations grow exponentially too. By looking at the development of <code>$/flops</code> basic economy tells us that supply is growing faster than demand, giving Moore's Law as upper bound of user change. I'll use <a href="http://en.wikipedia.org/wiki/Function%5Fpoints" rel="nofollow">function points</a> ("amount of business functionality an information system provides to a user") as a measure of requirements. <em>Unit: FP/s, change in required Function Points over time</em></p>
<p><code>delta(maintenance)/delta(t)</code> depends totally on the organisation and is usually quite high immediately before a release, when quick fixes are pushed through and when integrating big changes. Changes to various measures like <a href="http://en.wikipedia.org/wiki/Source%5Flines%5Fof%5Fcode" rel="nofollow">SLOC</a>, <a href="http://en.wikipedia.org/wiki/Cyclomatic%5Fcomplexity" rel="nofollow">Cyclomatic Complexity</a> or implemented function points over time can be used as a stand-in here. Another possibility would be bug-churn in the ticketing system, if available. I'll stay with implemented function points over time. <em>Unit = FP/s, change in implemented Function Points over time</em> </p>
<p><code>delta(refactoring)/delta(t)</code> can be measured as time spent <strong>not</strong> implementing new features. <em>Unit = 1, time spent refactoring over time</em></p>
<p>So bitrot would be</p>
<pre><code> d(env) d(users) d(maint) d(t)
bitrot(t) = -------- * ---------- * ---------- * ----------------
d(t) d(t) d(t) d(refactoring)
d(env) * d(users) * d(maint)
= ------------------------------
d(t)² * d(refactoring)
</code></pre>
<p>with a combined unit of <code>OPS/$/s * FP/s * FP/s = (OPS*FP²) / ($*s³)</code>.</p>
<p>This is of course only a very forced pseudo-mathematical notation of what the Wikipedia article already said: bitrot arises from changes in the environment, changes in the users' requirements and changes to the code, while it is mitigated by spending time on refactoring. Every organisation will have to decide for itself how to measure those changes, I only give very general bounds.</p>
|
Is E-texteditor's "open company" and open source model really open? <p>E-Texteditor recently <a href="http://e-texteditor.com/blog/2009/opencompany" rel="nofollow">announced</a> going open-source with their open company model. However after reading through I am not sure if this model is really open.</p>
<p>The way I understand is that they open up the source and contributors, depending on how much the contribute get badges (like at stackoverflow) and are compensated accordingly from the company's revenue stream. Here are the steps:</p>
<blockquote>
<p>1st step: Releasing the source</p>
<p>The source will be made a available,
so that users can study and modify the
application for their own needs. If
they want to contribute their changes
back, they can submit them for review.
To discourage piracy, a tiny but
essential core (also containing the
licensing code), will be kept private
(at least until users reach a certain
rating). This will gradually be
followed by a similar opening of the
rest of the company (web site,
documentation, bug tracking, etc..)</p>
<p>2nd step: Building the Trust Metric</p>
<p>The basic infrastructure will be set
up so that participants can start
rating each other. The algorithms and
code will be released as open source,
so that they can be studied and
discussed (and used by others). It
will probably need quite some time and
tweaking before we reach a fair
balance.</p>
<p>3rd step: Compensating Participants</p>
<p>All income in the company (minus
operating expenses), will be passed
through the trust metric and
distributed to participants.</p>
</blockquote>
<p>The company still keeps some bits private to retain control and that doesn't make it truly open. How is that any different from hiring developers and compensating them with stock options and merit-based bonuses?</p>
<p>EDIT: David Brown points out the <a href="http://e-texteditor.com/blog/2009/releasing-the-source" rel="nofollow">developer response</a></p>
<blockquote>
<p>While the addition of the extra clause
means that the license can no longer be
termed an Open Source License, it is
ideal for the open company. It is
essentially an issue of mutual respect.
If I fully respect your ownership, you
will in return respect my right to make
a living.</p>
</blockquote>
| <p>If the "essential core" prevent us from forking the project or creating a mac port, it's not really open source.</p>
|
How do I use .NET 3.0 in VS2005? <p>I am trying to use Auto-implemented properties in VS2005. I have .NET 3.0 framework loaded on my machine, but Visual Studio is still compiling with .NET 2.0. How do I tell it to use .NET 3.0?</p>
| <p>Unfortunately, I don't think it is possible to do this, since that is a feature of the C# compiler. Visual Studio 2005 is hard-coded to use the C# 2.0 compiler. You need to upgrade to Visual Studio 2008 to use the new C# 3.0 features.</p>
|
Unicode First, Previous, Next, and Last <p>Unicode has snowmen and chess pieces. Does it have the first (<< or |<), previous (<), next (>) and last (>> or >|) symbols? Those would be quite useful for site navigation between articles and the like.</p>
| <p>it has <strong>«</strong> (0x00AB) and <strong>»</strong> (0x00BB)</p>
<p>or maybe these:</p>
<ul>
<li>⤠(first 0x21E4)</li>
<li>â (prev 0x2190)</li>
<li>â (next 0x2192)</li>
<li>⥠(last 0x21E5)</li>
</ul>
|
Qt: QGraphicsScene not updating when I would expect it to <p>Ok so I've got a <code>QGraphicsScene</code> in a class called eye. I call a function:</p>
<pre><code>void eye::playSequence(int sequenceNum) {
for (int i=0; i<sequences[sequenceNum].numberOfSlides(); i++) {
presentSlide(sequenceNum, i);
time_t start;
time(&start);
bool cont=false;
while (!cont) {
time_t now;
time(&now);
double dif;
dif=difftime(now, start);
if (dif>5.0)
cont=true;
}
}
}
</code></pre>
<p>which for each slide calls:</p>
<pre><code>void eye::presentSlide(int sequenceNum, int slideNum) {
Slide * slide=sequences[sequenceNum].getSlide(slideNum);
QGraphicsPixmapItem * pic0=scene.addPixmap(slide->getStimulus(0)->getImage());
pic0->setPos(0,0);
QGraphicsPixmapItem * pic1=scene.addPixmap(slide->getStimulus(1)->getImage());
pic1->setPos(horizontalResolution-350,0);
QGraphicsPixmapItem * pic2=scene.addPixmap(slide->getStimulus(2)->getImage());
pic2->setPos(horizontalResolution-350,verticalResolution-450);
QGraphicsPixmapItem * pic3=scene.addPixmap(slide->getStimulus(3)->getImage());
pic3->setPos(0,verticalResolution-450);
}
</code></pre>
<p>Now, I would expect this to display one set of images, wait for 5 seconds, then display the next, and so on. Instead, it displays nothing until all the slides have been processed and then the last four images are displayed. I've tried calling <code>scene.update()</code> in every place I could image and it didn't do anything. It seems like the scene only updates when the <code>playSequence</code> function returns. Any ideas what might be going on here?</p>
| <p>This is the kind of behaviour that is often seen in event driven GUI frameworks when one wants to do continuous animation. I'm going to guess that eye::playSequence is called from a button click or maybe from some point during the application startup code? In any case, here is what's going on.</p>
<p>Qt uses the main application thread to drive an event loop. The event loop is something like this:</p>
<pre><code>while(app_running)
{
if(EventPending)
ProcessNextEvent();
}
</code></pre>
<p>The problem you are seeing is that updates to the screen are done during a paint event. If you are running some code during a mouse click event or any other event, then all the drawing you are doing is queued up and will be drawn to the screen on the next paint event. Sometimes it takes awhile for this to sink in.</p>
<p>The best way to address this is to change your approach a bit. One way is to throw away your while loop and setup a QTimer set to fire every 5 seconds. In the timer slot you can draw one slide. When the timer fires again, draw the next slide, etc.</p>
<p>If you want a more direct and less elegant quick fix, try calling qapp->processEvents() right after your call to presentSlide(sequenceNum, i). This (most of the time) will force the application to clear out any queued up events which should include paint events.</p>
<p>I should also mention that eye::presentSlide() is merely adding new scene objects to the scene on each iteration covering the ones that were added during the last call. Think of the scene as a fridge door and when you call scene().addXXX you are throwing more fridge magnets on the door :)</p>
|
A wxPython timeline widget <p>I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:</p>
<p>Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, with a ruler. It is possible to zoom in and out, and to scroll, and the ruler updates to reflect where / how deep you are on the timeline.
Only a finite segment of the timeline is "occupied", i.e., actually contains data. The rest is empty.
It is possible to select with the mouse any time point on the timeline, and, of course, it is possible to let it "play": to traverse the timeline from left to right in a specified speed.</p>
<p>If you know something that's at least close to what I describe, I'd be interested.</p>
<p><hr /></p>
<p>If you want to know what the job of this widget is: It's for a program for running simulations. The program calculates the simulation in the background, extending the "occupied" part of the timeline. It is possible to select different points in the timeline to observe the state of the system in a certain timepoint, and of course it is possible to play the simulation.</p>
<p>Thanks!</p>
| <p>A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a <a href="http://zetcode.com/wxpython/widgets/#slider" rel="nofollow">wxSlider</a>. This is far from ideal, but it'll get you up and running. You can also look at creating a <a href="http://www.zetcode.com/wxpython/customwidgets/" rel="nofollow">custom widget</a> -- that'd definitely do what you want, but it will be a lot of work. Sorry I don't have anything better, but I figured some answer is better than nothing. </p>
|
Using dependency injection in a library <p>I'm writing a java library that will be used by an existing application. I'm using dependency injection so testing is easier, and I'm familiar with Spring so I was planning to use it to manage the dependency injection while testing. The applications that will eventually use the library are not Spring-based, however, nor does it use any IoC/DI container of any sort currently. My question is, what's the best approach for injecting dependencies if Spring or Guice are not used? Should I consider something like a factory method to instantiate and wire the objects? The dependencies are all inside the library, so it doesn't seem appropriate to have the application instantiate each dependency to create the main object. </p>
| <blockquote>
<p>what's the best approach for injecting dependencies if Spring or Guice are not used?</p>
</blockquote>
<p>If your library was written in a DI-friendly idiom. It should be fairly easy to use as a straitforward java API. Think of your past experience with spring. There are several libraries out there that fit perfectly with the spring model but were written before spring time. I don't see nothing bad with a <code>new</code> followed by a couple of <code>setXX</code> followed by a call to the <em>real work</em> method. Just be extra careful, since, among other things, your client can forget to call thouse <code>init</code> methods that spring reliably calls.</p>
<blockquote>
<p>Should I consider something like a factory method to instantiate and wire the objects? The dependencies are all inside the library, so it doesn't seem appropriate to have the application instantiate each dependency to create the main object.</p>
</blockquote>
<p>Let the client application decide that. You are providing a library. Let the API client wire its own objects. Provide an example. Later, that same example can be used to make the factory method on the client's domain. Maybe the client application has it's own way to configure itself, and it would be desirable if the API your library provides to be flexible enough to take advantage of that.</p>
<p>Or maybe you can include guice. The licence is Apache. Just like a whole piece of Java itself.</p>
|
Why is my array throwing Out of Range Exception Error? <p>Why does the following code throw an exception? </p>
<pre><code>for (int i = 0; i <= Items.Length-1; i++)
{
Console.WriteLine(Items[i,1]);
}
</code></pre>
<p>Exception:</p>
<pre><code>System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="Es"
StackTrace:
at Es.Program.Main(String[] args) in C:\Users\Fero\Documents\Visual Studio 2005\Projects\Es\Es\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</code></pre>
<p>Declaration of Items:</p>
<p>Function which gets the array of strings:</p>
<pre><code>static string[,] ReadFromFile(string filename, int rowsF)
{
StreamReader SR;
string S;
string[] S_split;
SR = File.OpenText(filename);
S = SR.ReadLine();
string[,] myItems = new String[rowsF, 2];
int row_number = 0;
while (S != null)
{
S_split = S.Split('"');
//temp_items[row_number,0] =
myItems[row_number,0] = S_split[1];
myItems[row_number,1] = S_split[2];
row_number++;
S = SR.ReadLine();
}
SR.Close();
return myItems;
}
string[,] Items = ReadFromFile(myFile, rowsF);
</code></pre>
| <p>You have a straight two-dimensional array. Length gives you the <a href="http://msdn.microsoft.com/en-us/library/system.array.length.aspx" rel="nofollow">total number of elements</a> in the array, but you're using it to calculate the index for a single dimension. What you want is: </p>
<pre><code>for (int i = 0; i < Items.GetLength(0); i++)
{
Console.WriteLine(Items[i,1]);
}
</code></pre>
|
Convert Dictionary<String,Int> to Dictionary<String,SomeEnum> using LINQ? <p>I'm trying to find a LINQ oneliner that takes a Dictionary<String,Int> and returns a Dictionary<String,SomeEnum>....it might not be possible, but would be nice.</p>
<p>Any suggestions?</p>
<p>EDIT: ToDictionary() is the obvious choice, but have any of you actually tried it? On a Dictionary it doesn't work the same as on a Enumerable... You can't pass it the key and value.</p>
<p>EDIT #2: Doh, I had a typo above this line screwing up the compiler. All is well.</p>
| <p>It works straight forward with a simple cast.</p>
<pre><code>Dictonary<String, Int32> input = new Dictionary<String, Int32>();
// Fill input dictionary
Dictionary<String, SomeEnum> output =
input.ToDictionary(item => item.Key, item => (SomeEnum)item.Value);
</code></pre>
<p><hr /></p>
<p>I used this test and it does not fail.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace DictonaryEnumConverter
{
enum SomeEnum { x, y, z = 4 };
class Program
{
static void Main(string[] args)
{
Dictionary<String, Int32> input =
new Dictionary<String, Int32>();
input.Add("a", 0);
input.Add("b", 1);
input.Add("c", 4);
Dictionary<String, SomeEnum> output = input.ToDictionary(
pair => pair.Key, pair => (SomeEnum)pair.Value);
Debug.Assert(output["a"] == SomeEnum.x);
Debug.Assert(output["b"] == SomeEnum.y);
Debug.Assert(output["c"] == SomeEnum.z);
}
}
}
</code></pre>
|
How can I test C# SmtpClient code in Vista <p>I have to test some C# code which sends simple HTML content with Attachment through SMTP server. How can I make sure my code works. My machine is Vista and have IIS-7, I don't want to connect to any external SMTP</p>
| <p>Please see:</p>
<p><a href="http://stackoverflow.com/questions/567765/how-can-i-save-an-email-instead-of-sending-when-using-smtpclient">How can I save an email instead of sending when using SmtpClient?</a></p>
<p><a href="http://stackoverflow.com/questions/372742/can-i-test-smtpclient-before-calling-client-send/372794">Can I test SmtpClient before calling client.Send()?</a></p>
<p><a href="http://stackoverflow.com/questions/510748/c-smtpclient-sends-email-to-junk">SmtpClient sends email to junk</a></p>
|
How do I skip lines that aren't whitespace or a number in Perl? <p>I am reading data from a file like this</p>
<pre><code>while (<$fh>)
{
@tmp = split; # <-- ?
push @AoA, [@tmp];
}
</code></pre>
<p>I have a couple of questions regarding this. What does the marked line do? Does it split the file by lines and store elements of each line into an array?? If so, is it possible to convert @tmp into a string or do a regex on @tmp?</p>
<p>Basically I want to stop pushing data onto the AoA if I find anything other than a space or an integer in the file. I have the regex for it already: \^[\s\d]*$\ </p>
| <p>[<code>@tmp = split;</code>] is shorthand for:</p>
<pre><code>@tmp = split " ", $_, 0;
</code></pre>
<p>which is similar to</p>
<pre><code>@tmp = split /\s+/, $_, 0;
</code></pre>
<p>but ignores any leading whitespace, so <code>" foo bar baz"</code> becomes <code>("foo", "bar", "baz")</code> instead of <code>("", "foo", "bar", "baz")</code>.</p>
<p>It takes each line in the filehandler <code>$fh</code> and splits it, using spaces as a delimiter.</p>
<p>Regarding what you want to do, why don't you just run the regex on <code>$_</code> to begin with? That's a string.</p>
<p>You could do:</p>
<pre><code>while (<$fh>) {
last unless /^[\s\d]*$/; # break if a line containing something
# other than whitespace or a number is found
@tmp = split;
push @AoA, [@tmp];
}
</code></pre>
|
Actionscript3: how can I access elements on the stage from external classes? <p>I have an external class in a .as file, my problem is that I can't access elements on the stage. Code like stage.txtfield.text or this.parent.txtfield.text does not work. The txtfield is the instace name of a Dynamic Text field.</p>
| <p>It depends a bit on the external class.</p>
<p>If it extends DisplayObject (or any grandchild of DisplayObject), you will be able access with the stage property as soon as it is added to the display list (which is when it's added to the stage or any other DisplayObjectContainer on the display list).</p>
<p>To listen for that use the following code in the external class:</p>
<pre><code>addEventListener(Event.ADDED_TO_STAGE, AddedToStage);
//...
private function AddedToStage(e:Event):void
{
trace("TextField text" + TextField(stage["textfield"]).text);
}
</code></pre>
<p>If it not a displayObject or if it's not gonna be on the display list, the best thing would proberly be to give it the objects that it needs to access (like the TextField), in either the contructor or a seperate method call.
You could give it a reference to the stage it self, but that wouldn't be very generic if for example you need the class to manipulate a TextField inside MovieClip.</p>
<p>You could give at reference to the TextField with this code:</p>
<pre><code>//In any DisplayObject on the display list (could be inside a MovieClip or on the Stage itself)
var manipulator:MyClass = new MyClass(TextField(stage["textfield"]));
//In the external class
public class MyClass
{
publich function MyClass(txt:TextField)
{
trace("TextField text" + txt.text);
}
}
</code></pre>
<p>Mind you that this code doesn't check if the textfield is actually there. You should check that first and throw a proper error to make debugging easier.</p>
|
How to transition from embedded software development to web development? <p>I am an embedded software developer with about 5+ years of experience working on mobile devices. I recently lost my job and most of the jobs in the embedded field (that I came across) require security clearance and I am not eligible for that. So, for this reason and also just to learn something new, I am planning to move to web development (Web services or any meaningful application that uses databases etc.). </p>
<p>Please guide me as to what factors should I consider to decide which technology (MSFT / Java related / LAMP) should I pick. If possible, also provide suggestions for projects that could have some application in real life, and how much time should I allocate for the same (as I have lots of unscheduled time these days :) ).</p>
<p>Thanks.</p>
| <p>Have you considered linux kernel development? There are many companies in the consumer electronics space that need software engineers with knowledge of linux driver development. This is quite an easy transition for someone with good embedded experience and is great fun too! </p>
<p>Even better, the <a href="http://lwn.net/Kernel/LDD3/" rel="nofollow">Linux Driver Development</a> book is available free online.</p>
|
Write XML in Silverlight with VB <p>is it possible to write xml in silverlight with vb</p>
| <p>Yes you can write XML in silverlight. Silverlight's System.Xml dll supports XmlWriter which allows you to write XML to a Stream, TextWriter or a StringBuilder.</p>
<p>If you are looking for standard XML DOM implementation you won't find it, Silverlight does not have that nor does it have XPath. Instead if you are looking to build an XML document in memory you can use System.Xml.Linq. Use the XDocument, XElement and XAttribute to create your document.</p>
|
how to work with z coordinates in a texture? <p>how to work with z coordinates in a texture in iphone openGl.</p>
| <p>z coordinates are only useful for 3d textures (which are rather unusual) or for cubemaps, which are far more popular (to create environment mapping, reflections, etc.).</p>
<p>for the latter case, the three coordinates represent an unit vector addressing a point on the unit sphere; the correct texel is automatically retreived.</p>
|
UDP, NAT and setting up "connections" <p>I know the word "connection" isn't really appropriate when talking about UDP, but...</p>
<p>How does a server (the one with the known IP) get its UDP packets through the Internet to a client that is behind NAT?</p>
<p>For example: say a client connects and authenticates to the server using some messaging over TCP. At this point the server is ready to start streaming data to the client over UDP, but how does the server know where to address the UDP packets so that they would find their way through any NAT routers to the client?</p>
<p>If the client fist sends an "I'm ready for the streaming please" message over UDP, would the NAT routers keep the port open so that the server can respond with its stream of UDP data?</p>
<p>Or am I waay off track here?</p>
| <p>Ignoring the provision of known port translation (i.e. data on <em>this</em> port goes to <em>this</em> address) in your router (providing the NAT), you can use <a href="http://en.wikipedia.org/wiki/UDP_hole_punching" rel="nofollow">UDP Hole Punching</a>.</p>
<p>I assume you're not talking about <a href="http://en.wikipedia.org/wiki/Multicast" rel="nofollow">multicasting</a>, in which each peer joins a group and announces that to interested parties (in this case the router), which can then perform the appropriate routing. Although that's normally used for routing traffic efficiently to multiple hosts, the routing-by-group mechanism would work for you're describing above.</p>
|
Difference between Content-Range and Range headers? <p>What is the difference between HTTP headers Content-Range and Range? When should each be used?</p>
<p>I am trying to stream an audio file from a particular byte offset. Should I use Content-Range or Range header?</p>
<p>Thanks</p>
| <p>Actually, the accepted answer is not complete. Content-Range is not only used in responses. It is also legal in requests that provide an entity body.</p>
<p>For example, an HTTP PUT provides an entity body, it might provide only a portion of an entity. Thus the PUT request can include a Content-Range header indicating to the server where the partial entity body should be merged into the entity.</p>
<p>For example, let's first create and then append to a file using HTTP:</p>
<p>Request 1:</p>
<pre><code>PUT /file HTTP/1.1
Host: server
Content-Length: 1
a
</code></pre>
<p>Request 2:</p>
<pre><code>PUT /file HTTP/1.1
Host: server
Content-Range: 1-2/*
Content-Length: 1
a
</code></pre>
<p>How, let's see the file's contents...</p>
<p>Request 3:</p>
<pre><code>GET /file HTTP/1.1
Host: server
HTTP/1.1 200 OK
Content-Length: 2
aa
</code></pre>
<p>This allows random file access, both READING and WRITING over HTTP. I just wanted to clarify, as I was researching the use of Content-Range in a WebDAV client I am developing, so perhaps this expanded information will prove useful to somebody else.</p>
|
Return plain objects in entity framework for serialization <p>I have been trying out both Linq to Sql and EF in my ASP.NET MVC application. After switching to EF I realized my XML/JSON serialization output has extra cruft.</p>
<p>XML:</p>
<pre><code><Test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityKey>
<EntitySetName>Persons</EntitySetName>
<EntityContainerName>PersonEntities</EntityContainerName>
<EntityKeyValues>
<EntityKeyMember>
<Key>Id</Key>
<Value xsi:type="xsd:int">1</Value>
</EntityKeyMember>
</EntityKeyValues>
</EntityKey>
<Id>1</Id>
<Name>John</Name>
</Test>
</code></pre>
<p>JSON:</p>
<pre><code>{"Id":1,"Name":"John","EntityState":2,"EntityKey"{"EntitySetName":"Persons","EntityContainerName":"PersonEntities","EntityKeyValues":[{"Key":"Id","Value":1}],"IsTemporary":false}}
</code></pre>
<p>Instead I would just like my output to be:</p>
<pre><code>{"Id":1, "Name":"John"}
</code></pre>
<p>My EF query to retrieve the object is:</p>
<pre><code>Tests.First(t => t.Id == testId);
</code></pre>
| <p>You can shape the JSON result in your controller like this:</p>
<pre><code>public JsonResult Person(int id)
{
var person = PersonRepository.FindByID(id);
var result = new { Id = person.Id, Name = person.Name };
return Json(result);
}
</code></pre>
<p>This will limit the DTO which is serialized to contain only the values you want.</p>
<p>Edit:
As a paritial answer to your comment question; you can create a simpler PersonViewModel class (DTO) that you can map the properties to. As John Saunders mentioned in his answer Automapper is a nice way to simplify the copying of the property values out of the EF Person instance:</p>
<p>The modified Action method may look like this:</p>
<pre><code>public JsonResult Person(int id)
{
var person = PersonRepository.FindByID(id);
var dto = Mapper.Map<Person, PersonViewModel>(person);
return Json(dto);
}
</code></pre>
<p>The only other option I can think of is to use reflection to modify the DataMemberAttributes on the Person entity to suppress the EntityKey property.</p>
|
BOOST_FOREACH: What is the error on using this of a STL container? <p>Does anyone know why the following generates an error on VC9?</p>
<pre><code>class Elem;
class ElemVec : public vector<Elem>
{
public:
void foo();
};
void ElemVec::foo()
{
BOOST_FOREACH(Elem& elem, *this)
{
// Do something with elem
}
return;
}
</code></pre>
<p>The error I get is:</p>
<pre><code>error C2355: 'this' : can only be referenced inside non-static member functions
</code></pre>
<p>The only (hack) solution I have right now which compiles without error is:</p>
<pre><code>void ElemVec::foo()
{
ElemVec* This = this;
BOOST_FOREACH(Elem& elem, *This)
{
// Do something with elem
}
return;
}
</code></pre>
| <p>You shouldn't inherit from STL containers. These are not polymorphic classes and it's the reason <code>BOOST_FORACH</code> can't handle your derived class.</p>
<p>Try to use aggregation instead.</p>
|
Pass multiple arrays to javascript via ajax <p>To pass an array from PHP to javascript via ajax, I am going to use json_encode, and recieve it on the javascript end.
However, I will be returning multiple rows from my MySQL database, and need to return multiple JSON-formatted arrays. One way I thought of doing this was to string the JSON arrays together in php with some obscure character, such as a pipe character, and then separate them on the javascript end. But is there a more elegant way to do this?</p>
<p>Edit: <a href="http://stackoverflow.com/questions/515684/how-to-use-json-with-jquery">this post</a> explains what I am trying to do.</p>
| <p>Just send them as an JSON-encoded array of arrays.</p>
<pre><code><?php
$row=array('foo'=>'bar','baz'=>'quux');
echo json_encode(array($row,$row,$row,$row));
?>
</code></pre>
<p>Results in </p>
<pre><code>[
{"foo":"bar","baz":"quux"},
{"foo":"bar","baz":"quux"},
{"foo":"bar","baz":"quux"},
{"foo":"bar","baz":"quux"}
]
</code></pre>
<p>This can then be processed exactly like an array on the client side.</p>
|
how to update dataGrid in database <p>In my C# project, i populated the values in DataGrid from DataTable. Now if i make changes in the values in the DataGrid i need to update them in the DataBase. I'm using MS access.
Here is the code snippet of how i populate values in the DataGrid.</p>
<pre><code> while (myReader.Read())
{
frmBind.dr = frmBind.dtResults.NewRow();
frmBind.dr["ClassName"] = myReader.GetString(0);
frmBind.dr["MethodSignature"] = myReader.GetString(1);
frmBind.dr["ParameterValues"] = myReader.GetString(2);
frmBind.dr["ExpectedResults"] = myReader.GetString(3);
frmBind.dtResults.Rows.Add(frmBind.dr);
}
frmBind.dataGrid2.DataSource = frmBind.dtResults;
</code></pre>
<p>where,
dtResults is DataTable,
frmBind is a Class Object,
dataGrid2 is the DataGrid,
myReader.Read() is used to get the values from the DataBase.</p>
| <p>The easy way would be to use a xxxADapter (depending on which ADO Provider you are using).</p>
<p>Please check if you have a good reason not to use Drag and Drop (for starters at least).
Here are some <a href="http://windowsclient.net/learn/videos.aspx" rel="nofollow">useful videos</a>, check the ones about Datasets first.</p>
<p>If you want to do it using xxxCommands, you will need an InsertCommand, UpdateCommand and DeleteCommand. You iterate over the Rows and check the RowState. If <code>RowState == DataRowState.Added</code> then use the InsertCommand etc.</p>
<p>It might be convenient tu use <code>dtchanged = dtResults.GetChanges()</code> first, and loop through the records that gives you. </p>
|
Why can I not get the selected value in a dropdownlist? <p>NET MVC 1.0.</p>
<p>I use</p>
<pre><code>ViewData["DeptID"] = new SelectList(DeptID, "ID", "Name", course.DeptID);
</code></pre>
<p>where I am passing the selected value <code>DeptID</code> as forth parameter, but it doesn't work. When I debug, then the above selection list is correct with the selected value.</p>
<p>I use </p>
<pre><code><%= Html.DropDownList("DeptID", (SelectList)ViewData["DeptID"]) %>
</code></pre>
<p>in the view.</p>
| <p>Try just using: </p>
<pre><code><%= Html.DropDownList("DeptID") %>
</code></pre>
<p>Here is an <a href="http://blog.wekeroad.com/blog/asp-net-mvc-dropdownlist-and-html-attributes/" rel="nofollow">article</a> about it.</p>
|
How to set height for a textfield in size inspector <p>i created a UITextField of type rounded textfield, using Interface Builder,so in order to set the Height of a textfield its window was disabled(not to set any height manually) in SizeInspector.so if we want to set height manually,what procedure should we follow.</p>
<p>One thing i would like to mention is ,we can do that in coding part,but what i would like to know is ,how can we acheive that in interfacebuilder.</p>
<p>Answers from you were always appreciated.</p>
| <p>Change the border style, like this:</p>
<p><img src="http://i.stack.imgur.com/cMrc8.png" alt="screen shot"></p>
|
Rotating table header text with CSS transforms <p>This looks like it should be possible with the following:</p>
<pre><code>.verticalText
{
/* IE-only DX filter */
writing-mode: tb-rl;
filter: flipv fliph;
/* Safari/Chrome function */
-webkit-transform: rotate(270deg);
/* works in latest FX builds */
-moz-transform: rotate(270deg);
}
</code></pre>
<p>This works in IE.</p>
<p>It goes wrong in a bizarre way in Safari, Chrome and FX - the cell's size is calculated <em>before</em> the text is rotated!</p>
<p><img src="http://i.stack.imgur.com/QT50z.png" alt="screenshot of bug"></p>
<p>Here is a demo: <a href="http://jsfiddle.net/HSKws/">http://jsfiddle.net/HSKws/</a></p>
<p>I'm using dynamic images as a workaround, although that <a href="http://stackoverflow.com/questions/388677">also has its problems</a>. I'm happy with that as a fall-back, but it seems like there should be a way to make this CSS work - it's almost there.</p>
<p>Anyone know a way to make the cells fit the content after the transform has been applied?</p>
| <p>âtransformâ alters the orientation of the entire element you declare it on, not the text content inside it. It's more like IE's âmatrixâ property than âwriting-modeâ. </p>
<p>Crucially, transforming an element doesn't change how its content size is calculated (or how its parent's layout is affected by that size). CSS's algorithms for vertical and horizontal sizing are different and difficult enough to get right to being with; there's no real consistent way they could accomodate content with arbitrary rotation. So âtransformâ is like using âposition: relativeâ: it changes where the content is rendered, but not anything to do with layout size.</p>
<p>So if you want to include one in a table you'll need to set the cell's âheightâ explicitly to accomodate the expected rotated âwidthâ. If you don't know that in advance you could potentially hack it up with JavaScript, perhaps.</p>
<p>FWIW: for me on Fx3.1b3 the span is also rotated like the others. However on Windows with its horizontal-only anti-aliasing (ClearType) the rendering doesn't look great... a well-rendered image could come out considerably better.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.