input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Image loop only returns one image but should return them all <pre><code>function all_images(&$post){
$content = $post->post_content;
if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)){
$i = 0;
$count = count($results);
$count = $count - 1;
while($i < $count)
{
foreach($results as $result){
echo $result[$i];
}
$i++;
}
}
}
</code></pre>
<p>The above loop manages to get all of the images out of the original text. However, it only returns one image. I have tried several different combinations of while() and foreach() but it only ever returns one image. Does anyone know what i am doing wrong? Thanks</p>
| <p>$results[1] should be an array of all the matches on the first parenthesized subpattern, so something as simple as this should work:</p>
<pre><code>if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/i', $content, $results)){
foreach($results[1] as $src)
{
echo "src is $src<br>";
}
}
</code></pre>
<p>Note I've used the /i modifier to make the match case insensitive, which might help you.</p>
<p>You might also want to supply some sample content you are trying to match against.</p>
|
How do I correct the error for this program to execute? <p>I have tried everything, this is my first C++ program and it not coming out right. I am receiving two error message. <code>error7:1 warning: character constan too long for its type.</code> and <code>7:error: expe</code></p>
<pre><code>//My first C++ program
#include <iostream>
int main():
{
"-std::cout << "I will get it" << -std::cout::end1";
"-std::cout << "I hope so" << -std::end1;
return(0);
}
</code></pre>
| <p>Your code should be fixed like so:</p>
<pre><code>#include <iostream>
int main()
{
std::cout << "I will get it" << std::endl;
std::cout << "I hope so" << std::endl;
return 0;
}
</code></pre>
|
set a default page in dynamic data <p>i am trying to set up a default page for my dynamic data website.. the problem is that its a template </p>
<p>so it would be something like this: Orders/List.aspx</p>
<p>can anyone please help me out with this..</p>
<p>Thanx</p>
<p>Owais F</p>
| <p>You can create a Default.aspx page outside of your DynamicData folder as the default and just have that page redirect to the Orders/List.aspx page.</p>
<pre><code>protected void Page_Init(object sender, EventArgs e) {
Response.Redirect("Orders/List.aspx");
}
</code></pre>
|
What is the opposite of Type.MakeByRefType <p>The <a href="http://msdn.microsoft.com/en-us/library/system.type.makebyreftype.aspx" rel="nofollow"><code>Type.MakeByRefType</code></a> method in .NET returns a by-ref version of a type, e.g. passing the type of <code>System.Int32</code> returns a type representing <code>System.Int32&</code>.</p>
<p>However, if you already have a <code>System.Int32&</code>, what is the mechanism for obtaining a plain old <code>System.Int32</code>? There doesn't seem to be an opposite method to remove the by-ref modifier.</p>
<p>At the moment I've put a hack in place which re-builds the assembly-qualified name without an <code>&</code> at the end of the type name and then loads that type, but this is horribly dirty...</p>
| <p>According to the docs for <code>IsByRef</code>, you can use <a href="http://msdn.microsoft.com/en-us/library/system.type.getelementtype.aspx">Type.GetElementType</a>. I don't have time to try this at the minute though...</p>
|
Databinding a Custom Control <p>I have a Custom Control (Windows Form) that is a lookup text box. A property on the Control is Current Selection which is a Custom Object containing "Identifier", "Code" and "Description". This property is Databound using a BindingSource.</p>
<p>Displaying the information works great. On the other hand regardless of whether I set the Update to OnValidate or OnValueChange it never updates the BindingSource. Is there something I'm missing to get this to auto update?</p>
<pre><code>private System.Windows.Forms.BindingSource buildPlanComponentDataBindingSource;
public void LoadBuildPlan(string itemNumber)
{
var buildPlanComponents = BuildPlan.LoadBuildPlanComponents(itemNumber, AutomaticPrice);
buildPlanComponentDataBindingSource.DataSource = buildPlanComponents;
AssemblyNumber = itemNumber;
}
[Bindable(true)]
[DefaultValue(null)]
public ILookupSelection CurrentSelection
{
get
{
if (currentSelection == null)
currentSelection = new LookupSelection {Code = txtLookup.Text};
return currentSelection;
}
set
{
if (value == null) return;
currentSelection = value;
SetText(currentSelection, DisplayText);
SetDescription(currentSelection, DisplayDescription);
}
}
</code></pre>
| <p>Implementing INotifyPropertyChanged seems to be the solution!</p>
<pre><code> #region IPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
</code></pre>
|
SQL Base32 Conversion <p>I am writing a SQL Function that will take in a decimal and return the base32 representation of that decimal.</p>
<p>My problem is with the decimal to ascii conversion. </p>
<p>I am allowed to run the following query and return an ascii character</p>
<p>"SELECT CHAR( 65 )" which returns "A"</p>
<p>However in my function when I am trying to build my output string of letters, I am having trouble casting a bigint into a char, then concatenate that char to the end of a another char(which would be my output).</p>
<p>Sample line of code: "SET @OutputChar = @OutputChar + CAST( ( @Output + 55 ) AS CHAR(255) )" </p>
<p>What is the proper way to cast a bigint to char and then concatenate that char to another?</p>
<p>Thanks</p>
| <p>How are you declaring @OutputChar?</p>
<p>If you have:</p>
<pre><code>DECLARE @OutputChar CHAR(255)
</code></pre>
<p>then every time you concantenate, it will truncate it to 255. CHAR includes the whitespace at the end, maybe you mean to use varchar instead of CHAR?</p>
|
Resources for designing .dll structure <p>I just came out of a design meeting and had a question posed to me about where I got one of my ideas about how to structure some .dlls of a project we are building. To be honest I have no idea where this "idea" came from it just seemed like natural knowledge to me. However it would useful if I could back up these opinions with some documented analysis.</p>
<p>Does anyone know of any resources that explicity discuss different mechanisms for structuring assemblies/modules/source?</p>
<p>UPDATE:</p>
<p>Well the idea was nothing special. We were discussing an abstraction layer for some hardware so the "app" that consumes these services could be (sort of) platform independant. Previously we've had an interfaces .dll that declares the interfaces the app requires and an implementation .dll that implements them for the one platform we've had thus far. Now we have two platforms but they are very similar. To prevent the interfaces .dll from being polluted or some hideous scenario where the implementations reference one another I merely suggested we create another .dll that sits between the interfaces and specificplatform.dlls where common abstract implementations can live. </p>
| <p>If you have a chance, have a look at the book by Robert C. Martin:</p>
<p><a href="http://search.barnesandnoble.com/Agile-Principles-Patterns-and-Practices-in-C/Martin-Robert-Martin-Micah-Martin-Robert-Martin-Micah/e/9780131857254" rel="nofollow">Agile Principles, Patterns, and Practices in C#</a> (This is the new version specifically targeted to .Net)</p>
<p>There is a chapter dedicated to component design that (probably) answers your question.</p>
<p>In summary, and after reading that book, I always recommend separating components by these criteria:</p>
<ul>
<li><p><strong>Assemblies are units or reuse</strong>: If there are classes that have to be used together, they go in the same assembly.</p></li>
<li><p><strong>Assemblies are units of change</strong>: If there are classes that do not have to change for the same reason, they probably should not be in the same assembly.</p></li>
<li><p><strong>Assemblies are units of deployment</strong>: If there are classes that have to be physically deployed in the same place, they probably should go in the same assembly.</p></li>
</ul>
<p>Of course these are just <em>heuristics</em> and not recipes. You eventually need to decide how much of each one of those three design heuristics you need based on the architectural goals of your application (specifically the architectural goals for deployment and evolution/modification).</p>
|
How do I get the type object of a genericized Enum? eg: EnumSet.noneOf(<huh?>) <p>I have a generic type that is parameterized on some Enum, declared like this:</p>
<pre><code>public class FlagsField<T extends Enum<T>> {
private EnumSet<T> _flagSet;
public FlagsField() {
_flagSet = EnumSet.<T>noneOf( /* what goes here? */ );
}
...
}
</code></pre>
<p>I want to initialize _flagsField in the constructor as above, but can't figure out for the life of me what the right parameter to the noneOf method is. It needs to be of type <code>Class<T></code>. If this weren't a generic, you'd use <code>MyFooEnumType.class</code> here, but <code>T.class</code> is not valid.</p>
<p>Thanks!</p>
| <p>You've run into <a href="http://java.sun.com/docs/books/tutorial/java/generics/erasure.html" rel="nofollow">type erasure</a>. Your constructor is going to need to look like:</p>
<pre><code>public FlagsField(Class<T> enumClass) {
_flagSet = EnumSet.<T>noneOf(enumClass);
}
</code></pre>
|
Nhibernate: Make Many-To-Many Relationship to Map as One-To-One <p>I have two items A and B, which have a uni directional one-to-one relationship. (A has one B)</p>
<p>In the database these are represented by ATable and BTable, and they are linked together by ABTable. (From the database setup it appears there is a many-to-many relationship but there is not, it was done this way for normalization reasons).</p>
<p>The problem is due to this setup, I have only been able to get NHibernate to map this as a many-to-many relationship between the entities. Is there anyway of making the entities have a one-to-one relationship?</p>
<p><em>The best I could think of is to leave its has a many to many relationship, and then have two properties on the A entity one that returns a List of B, which would satisfy the mapping and a second non-mapped property that would get the first B from the list, to satisfy my application.</em> - but this seems un-eligant.</p>
| <p>Are you sure you mean a one-to-one? I've had so many people ask for one-to-one's when they <a href="http://blog.jagregory.com/2009/01/27/i-think-you-mean-a-many-to-one-sir/" rel="nofollow">really mean many-to-one's</a>.</p>
<p>Anyway, short of changing your schema, the easiest thing is what you suggested; however, to make it a little cleaner, you can make the collections private so you're only exposing the two properties that fetch the first item. You can see the <a href="http://wiki.fluentnhibernate.org/show/StandardMappingPrivateProperties" rel="nofollow">various methods</a> in Fluent NHibernate for mapping private properties on the <a href="http://wiki.fluentnhibernate.org" rel="nofollow">wiki</a>.</p>
|
Problem installing OpenID on ASP.NET MVC Site <p>I am trying to install openID into my web site project that is using ASP.NET MVC, specifically with Yahoo</p>
<p>Yahoo keeps giving me this :
<strong>"Warning: This website has not confirmed its identity with Yahoo! and might be fraudulent. Do not share any personal information with this website unless you are certain it is legitimate."</strong></p>
<p>However I have followed the setup procedures I have a Yardis document setup and the following in the header of my realm URI</p>
<pre><code><meta http-equiv="X-XRDS-Location" content="http://www.daimokuchart.com/yadis" />
</code></pre>
<p>My Yardis document is as follows</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xrds:XRDS
xmlns:xrds="xri://$xrds"
xmlns:openid="http://openid.net/xmlns/1.0"
xmlns="xri://$xrd*($v*2.0)">
<XRD>
<Service priority="1">
<Type>http://specs.openid.net/auth/2.0/return_to</Type>
<URI>http://www.daimokuchart.com/Users/Authenticate</URI>
</Service>
</XRD>
</xrds:XRDS>
</code></pre>
<p>This is getting rather frustrating as I am not sure what else I can be missing.</p>
<p><strong>Note:</strong> The domain given in this example isn't actually live at this time... I am however testing it on a live site I just can not give out the URL at this time as we are not done developing the site yet.</p>
<p><strong>Update 3/4</strong> I did find a Yadis testing site, and it passed so the problem is Yahoo is not discovering it for some reason.</p>
<p><strong>Update 3/5</strong> Still no luck I talked with someone and they said this
</p>
<p>needed to be in my root url so I did that now yahoo reports something is wrong with the site... but not sure what the problem is...</p>
| <p>Check that your openid.return_to parameter is found in your YADIS/XRDS document, including matching capitalization.</p>
|
WPF: How do I set the Owner Window of a Dialog shown by a UserControl? <p>I've got a WPF application with these three types of things...</p>
<ul>
<li>WindowMain</li>
<li>UserControlZack</li>
<li>WindowModal</li>
</ul>
<p>UserControlZack1 sits on my WindowMain...</p>
<pre><code><Window x:Class="WindowMain"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ProjectName"
...
Name="WindowMain">
<Grid>
...
<local:UserControlZack x:Name="UserControlZack1" ... />
...
</Grid>
</Window>
</code></pre>
<p>UserControlZack1 displays a WindowModal dailog box...</p>
<pre>
Partial Public Class UserControlZack
...
Private Sub SomeButton_Click(...)
'instantiate the dialog box and open modally...
Dim box As WindowModal = New WindowModal()
box.Owner = ?????
box.ShowDialog()
'process data entered by user if dialog box is accepted...
If (box.DialogResult.GetValueOrDefault = True) Then
_SomeVar = box.SomeVar
...
End If
End Sub
End Class
</pre>
<p>How do I set box.Owner to the correct Window, my running instance of WindowMain?</p>
<p>I cannot use <code>box.Owner = Me.Owner</code>, because "'Owner' is not a member of 'ProjectName.UserControlZack'."</p>
<p>I cannot use <code>box.Owner = Me.Parent</code>, because that returns a Grid, not the Window.</p>
<p>I cannot use <code>box.Owner = WindowMain</code>, because "'WindowMain' is a type and cannot be used as an expression."</p>
| <p>Try to use </p>
<pre><code>.Owner = Window.GetWindow(this)
</code></pre>
|
Group by like row filtering <p>Lets say I have a table describing cars with make, model, year and some other columns.</p>
<p>From that, I would like to get one full row of each make and model for latest year.</p>
<p>Or to put it in another way. Each row would have unique combination of make and model with other data from corresponding row with largest value of year.</p>
<p>Standard SQL solution would be great.</p>
| <p>MySQL solution:</p>
<pre><code>SELECT * FROM cars GROUP NY CONCAT(make, "-", model) ORDER BY year DESC;
</code></pre>
|
How Do You Pass a Message From One Program To Another? <p>I have a .Net 3.0 application that needs to pass an integer to another program on the same machine. I was using a WCF service to do this, but ran into user rights issues when trying HOSTING the service on the local box. Any thoughts on how to accomplish this woudld be greatly appreciated.</p>
<p>Thanks,</p>
<p>Dave</p>
| <p>WCF is still the way to go here.</p>
<p>Generally, for inter-process communication on the same machine, you would use the named pipe channel. If you are not using this, I suggest you do and then determine what the error in hosting is.</p>
<p>If both programs have message loops that are being processed, and you are sending an integer, you could use a call to SendMessage through the P/Invoke layer as well, but that's only because you are sending data that is equal to or smaller than what SendMessage will allow. Larger messages will require something like WCF.</p>
|
Please Critique my PHP authentication efforts <p>After posting <a href="http://stackoverflow.com/questions/443988/simple-authorisation-login-capability-in-php">this</a> a while back, I decided to create my own Registration / Authentication capability in PHP. I'd love anyone to point out the flaws / opportunities for improvement, particularly around what's stored in the session...</p>
<p>The logical flow is:</p>
<p>1 - User Registers using email as username, a "site name" which then forms part of any url which they will have access to and a password of at least 6 characters which must contain letters and numbers (I know this could be stronger)</p>
<p>2 - Provided the user and site are unique, I then store both of those, along with a randomly generated string (salt) in a row in the auth table in my database. I then take the users password, concatenate the salt to it, and store an md5 hash of this salted password in the same database row</p>
<p>3 - When a user then logs in, I take the password she's entered and concatenate the salt to it, create an md5 hash of that, and compare it to what I have stored in the database - if they match, the user has entered the right password, and their username is written to the session</p>
<p>4 - On every request, I use the username stored in the session to query the database and read the site name associated with this user. I then compare this to the site name in the url itself, and if they match I set a variable which is accessible to the rest or of the script (not a global variable, it's just readable by my controller which decides if a user can see a particular page) if the two site names don't match, the user is redirected back to login</p>
<p>My concern is could someone write to the session, and thus be able to access peoples pages if they know the username they signed up with? How would you go about preventing this?</p>
<p>Before anyone accuses me of negligence by the way this is a personal project for learning - I'm not exposing any clients data!</p>
| <ol>
<li><p>Why 6 characters? Make it bigger and require a minimum of 6 (or more) characters. There is no excuse for limiting the number of characters in the password to 6.</p></li>
<li><p>Put more than the user name in the session. But to do this safely, you must change the salt every login:</p></li>
</ol>
<p>A- From the login page: Take name and password verify with existing salt. If valid update the user table salt and password with a new salt (you have the password from the user so you can md5 it and the salt again). Write the md5 of the password to the session.
B- From any other page: compare the user and hashed password against the database. If they don't match, redirect to the login page.</p>
<p>The flaw with this idea is the user cannot maintain logins on multiple machines/browsers.</p>
<p>Your registration system needs work to. How do you know the email address is valid? How do you know the user registering owns the email address? You must send email to the address containing a link back to your site which must be clicked before you allow the account access to anything. Otherwise someone can sign up under someone else's email address make fraudulent claims as that person or just cause your site to spam that person getting your site shut down.</p>
<p>You also might want to investigate CAPTCHA to limit scripted registrations.</p>
|
How to change the star images of the RatingBar? <p>With <code>Android SDK 1.1 r1</code>, is there any way to change the <code>RatingBar</code> widget class's star image with my own? Is this possible at all? If so, then how? </p>
<p>Thanks.</p>
| <p>Not sure about 1.1, but with 1.6 and later you can just extend <code>Widget.RatingBar</code> style and override the properties that are responsible for star drawables (in <code>values/styles.xml</code>):</p>
<pre><code> <style name="myRatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:progressDrawable">@drawable/my_ratingbar_full</item>
<item name="android:indeterminateDrawable">@drawable/my_ratingbar_full</item>
</style>
</code></pre>
<p>There's no need to subclass RatingBar, just pass this style to it with the 'style' attribute:</p>
<pre><code><RatingBar style="@style/myRatingBar" ... />
</code></pre>
<p>Download android sources and look at the ratingbar_full.xml in the core drawable folder to see what to put into <code>my_ratingbar_full</code>. </p>
<p>You can find a fuller version of this here:
<a href="http://stackoverflow.com/questions/5800657/how-to-create-custom-ratings-bar-in-android">How to create Custom Ratings bar in Android</a></p>
|
Is it bad practice to run tests on a DB instead of on fake repositories? <p>I know what the advantages are and i use fake data when i am working with more complex systems.</p>
<p>What if I am developing something simple and I can easily set up my environment in a real DB and the data being accessed is so small that the access time is not a factor and I am only running a few tests. </p>
<p>Is it still important to create fake data or can I forget the extra coding and skip right to the real thing? </p>
<p>EDIT: when I said real DB I do not mean a production DB, I mean a test db but using a real live DBMS and the same schema as the real DB.</p>
| <p>The reasons to use fake data instead of a real DB are:</p>
<ol>
<li>Speed. If your tests are slow you aren't going to run them. Mocking the DB can make your tests run much faster than they otherwise might.</li>
<li>Control. Your tests need to be the sole source of your test data. When you use fake data, your tests choose which fakes you will be using. So there is no chance that your tests are spoiled because someone left the DB in an unfamiliar state.</li>
<li>Order Independence. We want our tests to be runnable in any order at all. The input of one test should not depend on the output of another. When your tests control the test data, the tests can be independent of each other.</li>
<li>Environment Independence. Your tests should be runnable in any environment. You should be able to run them while on the train, or in a plane, or at home, or at work. They should not depend on external services. When you use fake data, you don't need an external DB. </li>
</ol>
<p>Now, if you are building a small little app, and by using a real DB (like MySql) you can achieve the above goals, then by all means use the DB. I do. But make no mistake, as your application grows you will eventually be faced with the need to mock out the DB. That's ok, do it when you need to. YAGNI. Just make sure you DO do it WHEN you need to. If you let it go, you'll pay.</p>
|
How to read an INI file in ruby <p>How do I read/write an ini file in ruby. I have an ini file that I need to</p>
<ol>
<li>read</li>
<li>change an entry</li>
<li>write out to a different location</li>
</ol>
<p>How would I do that in ruby? The documentation on this is bleak.</p>
| <p>I recently used <a href="http://rubygems.org/gems/inifile" rel="nofollow">ruby-inifile</a>. Maybe it's overkill compared to the simple snippets here...</p>
|
Windows shell command to get the full path to current directory? <p>Is there a Windows command line command that I can use to get the full path to current working directory? Also, how can I store this path inside a variable used in a batch file?</p>
| <p>Use <code>cd</code> with no arguments if you're using the shell directly, or <code>%cd%</code> if you want to use it in batch file (behaves like environment var).</p>
|
Python parsing <p>I'm trying to parse the title tag in an RSS 2.0 feed into three different variables for each entry in that feed. Using ElementTree I've already parsed the RSS so that I can print each title [minus the trailing <code>)</code>] with the code below:</p>
<blockquote>
<pre><code>feed = getfeed("http://www.tourfilter.com/dallas/rss/by_concert_date")
for item in feed:
print repr(item.title[0:-1])
</code></pre>
</blockquote>
<p>I include that because, as you can see, the item.title is a repr() data type, which I don't know much about.</p>
<p>A particular <code>repr(item.title[0:-1])</code> <code>print</code>ed in the interactive window looks like this:</p>
<blockquote>
<pre><code>'randy travis (Billy Bobs 3/21'
'Michael Schenker Group (House of Blues Dallas 3/26'
</code></pre>
</blockquote>
<p>The user selects a band and I hope to, after parsing each <code>item.title</code> into 3 variables (one each for band, venue, and date... or possibly an array or I don't know...) select only those related to the band selected. Then they are sent to Google for geocoding, but that's another story.</p>
<p>I've seen some examples of <code>regex</code> and I'm reading about them, but it seems very complicated. Is it? I thought maybe someone here would have some insight as to exactly how to do this in an intelligent way. Should I use the <code>re</code> module? Does it matter that the output is currently is <code>repr()</code>s? Is there a better way? I was thinking I'd use a loop like (and this is my pseudoPython, just kind of notes I'm writing):</p>
<pre>
list = bandRaw,venue,date,latLong
for item in feed:
parse item.title for bandRaw, venue, date
if bandRaw == str(band)
send venue name + ", Dallas, TX" to google for geocoding
return lat,long
list = list + return character + bandRaw + "," + venue + "," + date + "," + lat + "," + long
else
</pre>
<p>In the end, I need to have the chosen entries in a .csv (comma-delimited) file looking like this:</p>
<blockquote>
<pre><code>band,venue,date,lat,long
randy travis,Billy Bobs,3/21,1234.5678,1234.5678
Michael Schenker Group,House of Blues Dallas,3/26,4321.8765,4321.8765
</code></pre>
</blockquote>
<p>I hope this isn't too much to ask. I'll be looking into it on my own, just thought I should post here to make sure it got answered. </p>
<p>So, the question is, how do I best parse each <code>repr(item.title[0:-1])</code> in the <code>feed</code> into the 3 separate values that I can then concatenate into a .csv file?</p>
| <p>Don't let regex scare you off... it's well worth learning.</p>
<p>Given the examples above, you might try putting the trailing parenthesis back in, and then using this pattern:</p>
<pre><code>import re
pat = re.compile('([\w\s]+)\(([\w\s]+)(\d+/\d+)\)')
info = pat.match(s)
print info.groups()
('Michael Schenker Group ', 'House of Blues Dallas ', '3/26')
</code></pre>
<p>To get at each group individual, just call them on the <code>info</code> object:</p>
<pre><code>print info.group(1) # or info.groups()[0]
print '"%s","%s","%s"' % (info.group(1), info.group(2), info.group(3))
"Michael Schenker Group","House of Blues Dallas","3/26"
</code></pre>
<p>The hard thing about regex in this case is making sure you know all the known possible characters in the title. If there are non-alpha chars in the 'Michael Schenker Group' part, you'll have to adjust the regex for that part to allow them.</p>
<p>The pattern above breaks down as follows, which is parsed left to right:</p>
<p><code>([\w\s]+)</code> : Match any word or space characters (the plus symbol indicates that there should be one or more such characters). The parentheses mean that the match will be captured as a group. This is the "Michael Schenker Group " part. If there can be numbers and dashes here, you'll want to modify the pieces between the square brackets, which are the possible characters for the set.</p>
<p><code>\(</code> : A literal parenthesis. The backslash escapes the parenthesis, since otherwise it counts as a regex command. This is the "(" part of the string.</p>
<p><code>([\w\s]+)</code> : Same as the one above, but this time matches the "House of Blues Dallas " part. In parentheses so they will be captured as the second group.</p>
<p><code>(\d+/\d+)</code> : Matches the digits 3 and 26 with a slash in the middle. In parentheses so they will be captured as the third group.</p>
<p><code>\)</code> : Closing parenthesis for the above.</p>
<p>The python intro to regex is quite good, and you might want to spend an evening going over it <a href="http://docs.python.org/library/re.html#module-re" rel="nofollow">http://docs.python.org/library/re.html#module-re</a>. Also, check Dive Into Python, which has a friendly introduction: <a href="http://diveintopython3.ep.io/regular-expressions.html" rel="nofollow">http://diveintopython3.ep.io/regular-expressions.html</a>.</p>
<p>EDIT: See zacherates below, who has some nice edits. Two heads are better than one!</p>
|
Nameless enums in templates <p>Alot templated code looks like this:</p>
<pre><code>template <typename T>
class foo
{
enum { value = <some expr with T> };
};
</code></pre>
<p>An example can be seen <a href="http://zwabel.wordpress.com/2008/12/18/c-template-support-in-kdevelop4-another-milestone/" rel="nofollow">here</a> in the prime check program and I've seen it in a Factorial implementation once too.</p>
<p>My question is why use a nameless enum? Is there a particular reason to this?
A static const int could work as well for example?</p>
<p>edit:</p>
<p>@Benoît: Thanks for the link, it provided the insight I was looking for!</p>
| <p>A static const variable would take up memory (like Sean said), whereas enums do not take any memory. They only exist in the compiler's world. At runtime they are just regular integers.</p>
<p>Other than that it would work, except for bad implementation of the standard by the compiler.</p>
<p>There is a thorough <a href="http://lists.boost.org/Archives/boost/2003/01/41847.php">thread</a> on the subject in boost mailing-list :</p>
|
IHierarchicalDataSource, Hierarchy structure, ASP.NET <p>I am building a hierarchy structure from scratch and I am trying to determine the best route to take. I found the following link below from another StackOverflow question:</p>
<p><a href="http://www.intelligententerprise.com/001020/celko.jhtml" rel="nofollow">Nested Set Model</a></p>
<p>I like the idea of nested sets and have begun to build my database, based on this pattern. I am now unsure how to query the data out in such a way that I will easily be able to bind to a control, such as the TreeView. I will need to be able to reorder and commit the data back as well. Any suggestions?</p>
| <p>SQL 2005 added support for recursive queries. I'm using a recursive query to return a tree of data that populates a TreeView. For each record, I find the matching parent node from the TreeView and add its new child.</p>
<p>For updates you could serialize the tree to XML, then use the XML features in sql 2005 to run an "update" statement.</p>
|
Use windows authentication with ASP.Net AJAX <p>I'm working on my first application using ASP.Net with web services and I'm having an authentication issue. At least I think that's the issue.</p>
<p>When I run the application locally in debug mode it works fine. It even works when I run it out of debug mode (through IIS) in IE 7. But when I have a coworker run it (from my IIS) on their box, it doesn't work. When querying active directory to look up users it gives this error:</p>
<p>Sys.Net.WebServiceFailedException: The server method 'GetCurrentUser' failed with the following error: System.Runtime.InteropServices.COMException - An operations error has occurred.</p>
<p>What do I need to do to get this working remotely?</p>
| <p>Ensure IE is correctly identifying the zone as the Intranet so it will automatically send the username for it. If its not, you'll need to manually add the URL to the Intranet Zone in the IE settings. </p>
<p>That should resolve it, and depending on your config you may need to add to your web.config </p>
<p>What is your web.config for the webservice</p>
|
How do I enumerate JvMemoryData...Or, how do I create a hash with a single key and multiple values? <p>I am using <a href="http://sourceforge.net/projects/jvcl" rel="nofollow">JvMemoryData</a> to populate a JvDBUltimGrid. I'm primarily using this JvMemoryData as a data structure, because I am not aware of anything else that meets my needs.</p>
<p>I'm not working with a lot of data, but I do need a way to enumerate the records I am adding to JvMemoryData. Has anyone done this before? Would it be possible to somehow "query" this data using TSQLQuery?</p>
<p>Or, is there a better way to do this? I'm a bit naive when it comes to data structures, so maybe someone can point me in the right direction. What I really need is like a Dictionary/Hash, that allows for 1 key, and many values. Like so:</p>
<pre><code>KEY1: val1;val2;val3;val4;val5;etc...
KEY2: val1;val2;val3;val4;val5;etc...
</code></pre>
<p>I considered using <a href="http://www.functionx.com/bcb/classes/thashtable.htm" rel="nofollow">THashedStringList</a> in the IniFiles unit, but it still suffers from the same problem in that it allows only 1 key to be associated with a value.</p>
| <p>One way would be to create a TStringList, and have each item's object point to another TList (or TStringList) which would contain all of your values. If the topmost string list is sorted, then retrieval is just a binary search away.</p>
<p>To add items to your topmost list, use something like the following (SList = TStringList):</p>
<pre><code>Id := SList.AddObject( Key1, tStringList.Create );
InnerList := tStringList(SList.Objects[id]);
// for each child in list
InnerList.add( value );
</code></pre>
<p>When its time to dispose the list, make sure you free each of the inner lists also.</p>
<pre><code>for i := 0 to SList.count-1 do
begin
if Assigned(SList.Objects[i]) then
SList.Objects[i].free;
SList.Objects[i] := nil;
end;
FreeAndNil(SList);
</code></pre>
|
Use of Haskell state monad a code smell? <p>God I hate the term "code smell", but I can't think of anything more accurate.</p>
<p>I'm designing a high-level language & compiler to <a href="http://compsoc.dur.ac.uk/whitespace/">Whitespace</a> in my spare time to learn about compiler construction, language design, and functional programming (compiler is being written in Haskell).</p>
<p>During the code generation phase of the compiler, I have to maintain "state"-ish data as I traverse the syntax tree. For example, when compiling flow-control statements I need to generate unique names for the labels to jump to (labels generated from a counter that's passed in, updated, & returned, and the old value of the counter must never be used again). Another example is when I come across in-line string literals in the syntax tree, they need to be permanently converted into heap variables (in Whitespace, strings are best stored on the heap). I'm currently wrapping the entire code generation module in the state monad to handle this.</p>
<p>I've been told that writing a compiler is a problem well suited to the functional paradigm, but I find that I'm designing this in much the same way I would design it in C (you really can write C in any language - even Haskell w/ state monads). </p>
<p>I want to learn how to think in Haskell (rather, in the functional paradigm) - not in C with Haskell syntax. Should I really try to eliminate/minimize use of the state monad, or is it a legitimate functional "design pattern"?</p>
| <p>I've written multiple compilers in Haskell, and a state monad is a reasonable solution to many compiler problems. But you want to keep it abstract---don't make it obvious you're using a monad.</p>
<p>Here's an example from the Glasgow Haskell Compiler (which I did <em>not</em> write; I just work around a few edges), where we build control-flow graphs. Here are the basic ways to make graphs:</p>
<pre><code>empyGraph :: Graph
mkLabel :: Label -> Graph
mkAssignment :: Assignment -> Graph -- modify a register or memory
mkTransfer :: ControlTransfer -> Graph -- any control transfer
(<*>) :: Graph -> Graph -> Graph
</code></pre>
<p>But as you've discovered, maintaining a supply of unique labels is tedious at best, so we provide these functions as well:</p>
<pre><code>withFreshLabel :: (Label -> Graph) -> Graph
mkIfThenElse :: (Label -> Label -> Graph) -- branch condition
-> Graph -- code in the 'then' branch
-> Graph -- code in the 'else' branch
-> Graph -- resulting if-then-else construct
</code></pre>
<p>The whole <code>Graph</code> thing is an abstract type, and the translator just merrily constructs graphs in purely functional fashion, without being aware that anything monadic is going on. Then, when the graph is finally constructed, in order to turn it into an algebraic datatype we can generate code from, we give it a supply of unique labels, run the state monad, and pull out the data structure.</p>
<p>The state monad is hidden underneath; although it's not exposed to the client, the definition of <code>Graph</code> is something like this:</p>
<pre><code>type Graph = RealGraph -> [Label] -> (RealGraph, [Label])
</code></pre>
<p>or a bit more accurately</p>
<pre><code>type Graph = RealGraph -> State [Label] RealGraph
-- a Graph is a monadic function from a successor RealGraph to a new RealGraph
</code></pre>
<p>With the state monad hidden behind a layer of abstraction, it's not smelly at all!</p>
|
PHP&MySQL: Is it possible after running mysql_query with an insert to get the ID of the new row? <p>Is there a straightforward way to run mysql_query with an insert and get the ID of the new row, for example in the return? Or will I have to do another query with select to check it?</p>
| <p>mysql_insert_id()</p>
<p>or</p>
<p>select last_insert_id()</p>
|
Best way of Multithreading <p>I have a college assignment due quite soon, and I need to be able to call a C++ dll that takes a long time (possibly infinte, it relies on user input)to execute. Im calling this through VB. My VB GUI freezes up when this happens, and I would like to keep the GUI responsive, so that the user can stop this possibly infinte loop. </p>
<p>Can anyone suggest the best/fastest way of doing this? </p>
<p>A bit of background, the C++ is trying to keep score on a snooker table using a webcam, and while the VB scoreboard updates easily, I would like to script it so that the analysis is almost continuous, while still allowing the user to interact. Currently the project requires the user to press a button to start the shot analysis, but it would be preferable if the program scripted itself. I have only realised this problem now and the deadline is very soon.</p>
<p>Update: Our lecturer suggested an option to solve the problem, but it would appear that most options here and the one he suggested will not work for us as the processing time required for the webcam image capture is too great to handle due to hardware constraints. Thanks for taking the time to help, it was much appreciated!</p>
| <p>The best way to handle threading in VB.NET is via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.aspx" rel="nofollow">System.Threading</a> namespace.</p>
<p>You might also look into <strong>Application.DoEvents()</strong></p>
|
How do I create tables with sections and headers in ASP.NET? <p>I have some data that must be presented in tabular form with multiple sections. In particular, Each section of data is broken up (with it's own headers) by day. This is basically a one-off single page deal, and won't really be maintained, so I don't want to put a lot of effort into architecture.</p>
<p>I have two tables. HEADERS and ITEMS. </p>
<p>HEADERS have a format of:</p>
<pre><code>date(datetime), type(tinyint), firstline(varchar), secondline(varchar)
</code></pre>
<p>ITEMS has a format of</p>
<pre><code>id(int), date(datetime), type(tinyint), name(varchar), value1(int),
value2(int), value3(int)
</code></pre>
<p>I need the data to look similar to this (first and secondline are data populated, third line is static text, item lines are data populated):</p>
<pre><code>1/1/2009
--------------------------------------------------------------------------
| [First line] |
--------------------------------------------------------------------------
| [Second line] |
--------------------------------------------------------------------------
| Date | Name | Value 1 | Value 2 | Value 3 |
==========================================================================
| [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] |
--------------------------------------------------------------------------
| [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] |
--------------------------------------------------------------------------
1/2/2009
--------------------------------------------------------------------------
| [First line] |
--------------------------------------------------------------------------
| [Second line] |
--------------------------------------------------------------------------
| Date | Name | Value 1 | Value 2 | Value 3 |
==========================================================================
| [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] |
--------------------------------------------------------------------------
| [Date]| [Name] | [Value 1] | [Value 2] | [Value 3] |
--------------------------------------------------------------------------
</code></pre>
<p>This will repeat for all days currently in the database, each day having it's own table with it's own headers. They will also be filtered by type. the page will only show headers and items of the type specified. Type is an tinyint.</p>
<p><strong>So the question is, What is the best ASP.NET elements to use? DataList? GridView? And how do I include the data from two tables in a header/item format?</strong> </p>
<p>EDIT:
Sorry, forgot to mention that this has to work on Windows 2000/IIS5, so i'm stuck with ASP.NET 2.0 and can't use 3.0 or 3.5 features.</p>
| <p>Have a look at asp:table. You can programmaticaly add the rows and columns in some nested conditional iterations in code.</p>
|
Is it possible to deserialize XML into List<T>? <p>Given the following XML:</p>
<pre><code><?xml version="1.0"?>
<user_list>
<user>
<id>1</id>
<name>Joe</name>
</user>
<user>
<id>2</id>
<name>John</name>
</user>
</user_list>
</code></pre>
<p>And the following class:</p>
<pre><code>public class User {
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
</code></pre>
<p>Is it possible to use <code>XmlSerializer</code> to deserialize the xml into a <code>List<User></code> ? If so, what type of additional attributes will I need to use, or what additional parameters do I need to use to construct the <code>XmlSerializer</code> instance?</p>
<p>An array ( <code>User[]</code> ) would be acceptable, if a bit less preferable.</p>
| <p>You can <em>encapsulate</em> the list trivially:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("user_list")]
public class UserList
{
public UserList() {Items = new List<User>();}
[XmlElement("user")]
public List<User> Items {get;set;}
}
public class User
{
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializer ser= new XmlSerializer(typeof(UserList));
UserList list = new UserList();
list.Items.Add(new User { Id = 1, Name = "abc"});
list.Items.Add(new User { Id = 2, Name = "def"});
list.Items.Add(new User { Id = 3, Name = "ghi"});
ser.Serialize(Console.Out, list);
}
}
</code></pre>
|
Forms Authentication across Sub-Domains <p>Is it possible to authenticate users across sub-domains when the authentication takes place at a sub-domain instead of the parent domain? </p>
<p>For example:</p>
<p>User logs into site1.parent.com, and then we need to send them to reporting.parent.com.</p>
<p>Can I authenticate them to the reporting site even though the log-in occured at a sub-domain?</p>
<p>So far all of the research I have done has users logging into the parent domain first and then each sub-domain has access to the authentication cookie. </p>
| <p>When you authenticate the user, set the authentication cookie's domain to the second-level domain, i.e. parent.com. Each sub-domain will receive the parent domain's cookies on request, so authentication over each is possible since you will have a shared authentication cookie to work with.</p>
<p>Authentication code:</p>
<pre><code>System.Web.HttpCookie authcookie = System.Web.Security.FormsAuthentication.GetAuthCookie(UserName, False);
authcookie.Domain = "parent.com";
HttpResponse.AppendCookie(authcookie);
HttpResponse.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(UserName,
False));
</code></pre>
|
Pros/Cons of Binary Reference VS WCF <p>I am in the process of implementing an enhancement to an existing web application(A). The new solution will provide features(charts/images/data) to the application A. The new enhancement will be a new project and will generate new assemblies. I am trying to identify what would be most elegant way to read this information.
1) Do a binary reference and read the data directly. The new assemblies live with your application and are married together
2) Write a WCF call and get the data. This will help to decouple the application.</p>
<p>The new application will involve me to buy some expensive licences. So if i go with the 2nd option i can limit the license fee to a single server or atmost 2-3. My current applicaiton runs under a webfarm of 8 servers.</p>
<p>Please share out the pros/cons of both approach.</p>
<p>Thanks.</p>
| <p>If you decouple the two pieces sufficiently, you will also permit the use of clients running something other than .NET. Using the first option, you could only support .NET clients. This may turn out to be important, even if today you are absolutely certain that only .NET will ever be used - tomorrow, your company may be purchased by another which is a Java or PHP shop.</p>
<p>Even if you never need to support a non .NET client, coupling to the assemblies will require you to maintain version compatibility between the client and server. If this is not necessary, then use option #2.</p>
|
replace urls <p>I have a huge txt file and Editpad Pro list of urls with images on the root folder. </p>
<pre><code>http://www.othersite.com/image01.jpg
http://www.mysite.com/image01.jpg
http://www.mysite.com/category/image01.jpg
</code></pre>
<p>How can I change only that ones that has images on the root using regexp?</p>
<pre><code>http://www.othersite.com/image01.jpg
http://www.NEW_WEBSITE.com/image01.jpg
http://www.mysite.com/category/image01.jpg
</code></pre>
<p>I'm using <a href="http://gskinner.com/RegExr/" rel="nofollow">the RegExr online app</a>.</p>
| <p><strong>Search and replace</strong> (case insensitive, regular expression):</p>
<pre><code>http://www\.mysite\.com/([^/]*\.(?:jpg|gif|png))
</code></pre>
<p>with:</p>
<pre><code>http://www\.NEW_WEBSITE\.com/\1
</code></pre>
<hr>
<p><strong>EDIT</strong></p>
<p>And yes, this will also re-base files such as <code>http://www.mysite.com/.jpg</code>, if any such files or directories exist. If anyone doesn't like this then just replace <code>*</code> with <code>+</code> -- or with <code>{X,}</code> if your assumption happens to be that <em>an image file needs at least a X character name s</em> etc. etc. -- but <strong>really</strong>, this is probably quite outside the scope of what <code>lab72</code> is trying to achieve (i.e. <strong>not</strong> image file name validation.)</p>
|
C++ string memory management <p>Last week I wrote a few lines of code in C# to fire up a large text file (300,000 lines) into a Dictionary. It took ten minutes to write and it executed in less than a second. </p>
<p>Now I'm converting that piece of code into C++ (because I need it in an old C++ COM object). I've spent two days on it this far. :-( Although the productivity difference is shocking on its own, it's the performance that I would need some advice on.</p>
<p>It takes seven seconds to load, and even worse: it takes just exactly that much time to free all the CStringWs afterwards. This is not acceptable, and I must find a way to increase the performance.</p>
<p>Are there any chance that I can allocate this many strings without seeing this horrible performace degradation?</p>
<p>My guess right now is that I'll have to stuff all the text into a large array and then let my hash table point to the beginning of each string within this array and drop the CStringW stuff.</p>
<p>But before that, any advice from you C++ experts out there?</p>
<p><strong>EDIT</strong>: My answer to myself is given below. I realized that that is the fastest route for me, and also step in what <em>I</em> consider <em>the right direction</em> - towards more managed code.</p>
| <p>This sounds very much like the Raymond Chen vs Rico Mariani's C++ vs C# Chinese/English dictionary performance bake off. It took Raymond several iterations to beat C#.</p>
<p>Perhaps there are ideas there that would help.</p>
<p><a href="http://blogs.msdn.com/ricom/archive/2005/05/10/performance-quiz-6-chinese-english-dictionary-reader.aspx" rel="nofollow">http://blogs.msdn.com/ricom/archive/2005/05/10/performance-quiz-6-chinese-english-dictionary-reader.aspx</a></p>
|
finding the type of an element using jQuery <p>In jQuery, if I have a reference to an element, how can I determine what kind of element it is, for example, an input or an dropdown? Is there any way to find out?</p>
<p>Duplicate:</p>
<p><a href="http://stackoverflow.com/questions/341900/how-can-i-determine-the-element-type-of-a-matched-element-in-jquery">How can I determine the element type of a matched element in jQuery?</a></p>
| <p>The following will return true if the element is an input:</p>
<pre><code>$("#elementId").is("input")
</code></pre>
<p>or you can use the following to get the name of the tag:</p>
<pre><code>$("#elementId").get(0).tagName
</code></pre>
|
Calling another controller action after the current controller action has finished executing <p>What I am trying to achieve:</p>
<ol>
<li><p>After <strong>each</strong> view has finished executing I would like to make a separate http call to an external partner.</p></li>
<li><p>I need to pass one of the view's content as body of that http call.</p></li>
</ol>
<p>What I have so far:</p>
<p>I have a base controller from which all of my controllers inherit from. </p>
<p>I have found that i can override the onActionExecuted() method of the base controller and write my partner http call code there so that it will be executed after each action.</p>
<p>I have written a custom result after reading the article at <a href="http://stackoverflow.com/questions/520863/send-asp-net-mvc-action-result-inside-email">http://stackoverflow.com/questions/520863/send-asp-net-mvc-action-result-inside-email</a>. which enables me to grab the content of the view. (which is part of another controller that also inherits from base controller).</p>
<p>What I can't figure out:</p>
<ol>
<li>How do I make a call to the controller action (the one that will render the content for the http calls body) to get the content in my base controller onActionExecuted() method?</li>
</ol>
<p>anil</p>
| <p>This will call a second controller action from the first controller action within the same controller:</p>
<pre><code> public ActionResult FirstAction()
{
// Do FirstAction stuff here.
return this.SecondAction(ArgumentsIfAny);
}
public ActionResult SecondAction()
{
// Do SecondAction stuff here.
return View();
}
</code></pre>
<p>Doesn't need to be too complicated. :-)</p>
|
Using scandir() to find folders in a directory (PHP) <p>I am using this peice of code:</p>
<pre><code>$target = 'extracted/' . $name[0];
$scan = scandir($target);
</code></pre>
<p>To scan the directory of a folder which is used for zip uploads. I want to be able to find all the folders inside my <code>$target</code> folder so I can delete them and their contents, leaving only the files in the <code>$target</code> directory. </p>
<p>Once I have returned the contents of the folder, I don't know how to differentiate between the folders and the files to be able to delete the folders. </p>
<p>Also, I have been told that the <code>rmdir()</code> function can't delete folders which have content inside them, is there any way around this?</p>
<p>Thanks, Ben.</p>
| <p>To determine whether or not you have a folder or file use the functions <code>is_dir()</code> and <code>is_file()</code></p>
<p>For example:</p>
<pre>
$path = 'extracted/' . $name[0];
$results = scandir($path);
foreach ($results as $result) {
if ($result === '.' or $result === '..') continue;
if (is_dir($path . '/' . $result)) {
//code to use if directory
}
}
</pre>
|
Best way to stream files in ASP.NET <p>What's the best way to stream files using ASP.NET?</p>
<p>There appear to be various methods for this, and I'm currently using the <a href="http://msdn.microsoft.com/en-us/library/12s31dhy(v=vs.110).aspx" rel="nofollow">Response.TransmitFile()</a> method inside an http handler, which sends the file to the browser directly. This is used for various things, including sending FLV's from outside the webroot to an embedded Flash video player.</p>
<p>However, this doesn't seem like a reliable method. In particular, there's a strange problem with <em>Internet Explorer (7)</em>, where the browser just hangs after a video or two are viewed. Clicking on any links, etc have no effect, and the only way to get things working again on the site is to close down the browser and re-open it.</p>
<p>This also occurs in other browsers, but much less frequently. Based on some basic testing, I suspect this is something to do with the way files are being streamed... perhaps the connection isn't being closed properly, or something along those lines.</p>
<p>After trying a few different things, I've found that the following method works for me:</p>
<pre><code>Response.WriteFile(path);
Response.Flush();
Response.Close();
Response.End();
</code></pre>
<p>This gets around the problem mentioned above, and viewing videos no longer causes Internet Explorer to hang.</p>
<p>However, my understanding is that <a href="http://msdn.microsoft.com/en-us/library/system.web.httpresponse.writefile(v=vs.110).aspx" rel="nofollow">Response.WriteFile()</a> loads the file into memory first, and given that some files being streamed could potentially be quite large, this doesn't seem like an ideal solution.</p>
<p>I'm interested in hearing how other developers are streaming large files in ASP.NET, and in particular, streaming FLV video files.</p>
| <p>I would take things outside of the "aspx" pipeline. In particular, I would write a ran handler (ashx, or mapped via config), that does the <em>minimum</em> work, and simply writes to the response in chunks. The handler would accept input from the query-string/form as normal, locate the object to stream, and stream the data (using a moderately sized local buffer in a loop). A simple (incomplete) example shown below:</p>
<pre><code>public void ProcessRequest(HttpContext context) {
// read input etx
context.Response.Buffer = false;
context.Response.ContentType = "text/plain";
string path = @"c:\somefile.txt";
FileInfo file = new FileInfo(path);
int len = (int)file.Length, bytes;
context.Response.AppendHeader("content-length", len.ToString());
byte[] buffer = new byte[1024];
Stream outStream = context.Response.OutputStream;
using(Stream stream = File.OpenRead(path)) {
while (len > 0 && (bytes =
stream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytes);
len -= bytes;
}
}
}
</code></pre>
|
Coding guides: How do you split up your large source files? <p>The project I'm working on has just hit 4200 lines in the main C# file, which is causing Intellisense to take a few seconds (sometimes up to 6 or so) to respond, during which Visual Studio locks up. I'm wondering how everyone else splits their files and whether there's a consensus.</p>
<p>I tried to look for some guides and found <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="nofollow">Google's C++ guide</a> but I couldn't see anything about semantics such as function sizes and file sizes, maybe it's there - I haven't looked at it for a while. </p>
<p>So how do you split your files? Do you group your methods by the functions they serve? By types (event handlers, private/public)? And at what size limit do you split functions? </p>
<p><strong>Edit</strong>: To clarify, the application in question handles data - so it's interface is a big-ass grid, and everything revolves around the grid. It has a few dialogs forms for management but it's all about the data. The reason why it's so big as there is a lot of error checking, event handling, and also the grid set up as master-detail with 3 more grid for each row (but these load on master row expanded). I hope this helps to clarify what I'm on about. </p>
| <p>I think your problem is summed up with the term you use: "Main C# file".</p>
<p>Unless you mean main (as in the method main()) there is no place for that concept. </p>
<p>If you have a catch-all utility class or other common methods you should break them into similar functional parts.</p>
<p>Typically my files are just one-to-one mappings of classes.</p>
<p>Sometimes classes that are very related are in the same file.</p>
<p>If your file is too large it is an indication your class is too big and too general.</p>
<p>I try to keep my methods to half a screen or less. (When it is code I write from scratch it is usually 12 lines or fewer, but lately I have been working in existing code from other developers and having to refactor 100 line functions...)</p>
<p>Sometimes it is a screen, but that is getting very large.</p>
<p>EDIT:</p>
<p>To address your size limit question about functions - for me it is less about size (though that is a good indicator of a problem) and more about doing only one thing and keeping each one SIMPLE. </p>
|
Very simple web page won't display on IE but will on everything else <p>I have just started making web pages and I'm having lots of trouble with this very simple web page. I can't make anything appear on IE but it works fine on everyother browser. I'll take the liberty of putting all the code in my question because it is really short. If anyone could help me it would be great!</p>
<p>The html is:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Rhaya<title>
<link rel='stylesheet' media="screen" type="text/css"
href='rhaya.css'/>
</head>
<body>
<div id="masthead"> Rhaya </div>
<div id="content"> Aca va todo el
contenido </div>
<div id="footer"> ©2009 Rhaya | Teresa
Siu | PÃa Fabry </div>
</body>
</html>
</code></pre>
<p>and the css is:</p>
<pre><code>ul,ol,li {list-style:none}
body { margin:0 auto; padding:0;font-family: Tahoma;font-size:13px; background: #fff; line-height:15px; color:#000;}
a {color: #000;text-decoration:none}
a:hover {text-decoration:none;color:#000;cursos:default;}
/* Masthead */
#masthead {
margin:10px 0 10px 0;
height: 50px;
font-weight: bold;
padding:10px;
border:1px solid #a2ebf4;
background-color:#e1f2f9;
background-image: url(img/header.png);
}
/* Content */
#content {
margin-left:0px;
margin-bottom:10px;
padding:10px;
border:1px solid #000;
min-width: 300px;
min-height: 300px;
font-family: Tahoma;
font-size:13px;
}
/* Footer */
#footer {
clear:both;
padding:10px;
border:1px solid #a2ebf4;
background-color:#e1f2f9;
text-align:center;
}
#wrapper{
width:1002px;
clear:both;
height:auto;
margin:0px auto;
background:#fff;
}
</code></pre>
<p>I'm really sorry for asking so blatantly but I really am stumped.</p>
<p>Thanks!</p>
| <p>For future reference: <a href="http://validator.w3.org/#validate_by_input" rel="nofollow">http://validator.w3.org/#validate_by_input</a>
Use it for resolving html issues.</p>
|
Displaying MySQL tables as ASCII in blog posts <p>I would like to quickly display MySQL recordsets in blog posts, using a similar ASCII layout to that used by mysql.com in their help pages. I'm using wordpress v2.7. Any ideas? I should also add that I'm using wp-syntax for syntax highlighting, so it's really just generating the ASCII that I'm interesting in.</p>
| <p>If you mean things like</p>
<pre>
+----+------+
| id | name |
+----+------+
| 1 | Bob |
| 2 | Mary |
| 3 | Jane |
| 4 | Lisa |
+----+------+
</pre>
<p>then just running the query from the MySQL commandline should suffice, as the results are formatted when running queries in interactive mode on the commandline. You can then copy and paste them into your blog post, surrounding them with <code><pre></code> or similar if necessary.</p>
|
Planning for parallelism <p>If you plan to write a very computationally intensive parallel application, what guidelines would you use to design your objects (whether classes or structs, or anything else) to maximize your potential of getting the most out of the parallelism.</p>
<p>I am thinking of an application that say interprets/compiles a tree-like graph of objects that require creating stuff, passing it to another object to be processed, and so on, with tree like structure.</p>
<p>What should one consider from the early design process?</p>
| <p>If you can get away with using a lot of immutable data structures, that will save you a lot of time, typing, and headache.</p>
|
Monitoring user idle time <p>Developing a mac app, how can I tell whether the user is currently at their computer or not? Or how long ago they last pressed a key or moved the mouse?</p>
| <p>it turns out the answer was here</p>
<p><a href="http://osdir.com/ml/python.pyobjc.devel/2006-09/msg00013.html" rel="nofollow">http://osdir.com/ml/python.pyobjc.devel/2006-09/msg00013.html</a></p>
|
How do I use jQuery's form.serialize but exclude empty fields <p>I have a search form with a number of text inputs & drop downs that submits via a GET. I'd like to have a cleaner search url by removing the empty fields from the querystring when a search is performed.</p>
<pre><code>var form = $("form");
var serializedFormStr = form.serialize();
// I'd like to remove inputs where value is '' or '.' here
window.location.href = '/search?' + serializedFormStr
</code></pre>
<p>Any idea how I can do this using jQuery? </p>
| <p>I've been looking over the <a href="http://docs.jquery.com/">jQuery docs</a> and I think we can do this in one line using <a href="http://docs.jquery.com/Selectors">selectors</a>:</p>
<pre><code>$("#myForm :input[value!='']").serialize() // does the job!
</code></pre>
<p>Obviously #myForm gets the element with id "myForm" but what was less obvious to me at first was that the <strong>space character</strong> is needed between #myForm and :input as it is the <a href="http://docs.jquery.com/Selectors/descendant">descendant</a> operator.</p>
<p><a href="http://docs.jquery.com/Selectors/input"><strong>:input</strong></a> matches all input, textarea, select and button elements.</p>
<p><a href="http://docs.jquery.com/Selectors/attributeNotEqual"><strong>[value!='']</strong></a> is an attribute not equal filter. The weird (and helpful) thing is that <strong>all :input</strong> element types have value attributes even selects and checkboxes etc.</p>
<p>Finally to also remove inputs where the value was '.' (as mentioned in the question):</p>
<pre><code>$("#myForm :input[value!=''][value!='.']").serialize()
</code></pre>
<p>In this case juxtaposition, ie <a href="http://docs.jquery.com/Selectors/attributeMultiple">placing two attribute selectors next to each other</a>, implies an AND. <a href="http://docs.jquery.com/Selectors/multiple">Using a comma</a> implies an OR. Sorry if that's obvious to CSS people!</p>
|
Is there a way to exclude large files or certain file types from an SVN update? <p>Just wondering if its possible to exclude large files or certian file types from an SVN update?</p>
<p>I ask because I am doing a checkout from home, but we have got several large .flv files in trunk which I do not need at this time and I would like to save the bandwidth.</p>
<p>I am using Tortoise SVN.</p>
<p>Any ideas?</p>
| <p>Use Subversion 1.5 on your client and make use of <a href="http://subversion.tigris.org/svn%5F1.5%5Freleasenotes.html#sparse-checkouts" rel="nofollow">Sparse Checkouts</a>. This will only work if you can ensure all of the large files are in the same place.</p>
|
Building a large form, need advice <p>I have to build a large form for users to fill out in order to apply for graduate study at the college I work for. There will be a large amount of information to collect (multiple addresses, personal information, business information, past school information, experience, etc...) and I want to know the best way to handle all this. I'm going to be using PHP and Javascript. </p>
<p>Are there any helpers or pieces of frameworks that I can use to help with the building/validation of the form, something I can just pop into my existing project?</p>
<p>Also would like any advice as far as keeping track of a large form and the resulting data.</p>
| <p>You need to use multiple pages, and you need to include a mechanism whereby users can leave, and come back and fill out the rest of the form later (or if they're accidentally disconnected). Otherwise you're going to have all sorts of user issues, not due to your service, but because they're using computers and internet connections that are flaky, etc.</p>
<p>Survey software is probably a reasonable approximation of what you're doing, and there are survey packages for most PHP CMS's. Are you building this from scratch, or do you have an existing CMS underneath?</p>
|
gsoap - WS-Addressing elements in the SOAP Header <p>I need to add WS Addressing in my Soap header (I am using the gsoap framework).
Is there a way to add that automatically? I looked up gsoap documentation but didnt find any info on that.
So right now I have manually added the WS-Addressing to my SOAP_ENV_Header as shown below</p>
<pre><code>struct SOAP_ENV__Header
{
mustUnderstand _wsa__MessageID wsa__MessageID 0;
mustUnderstand _wsa__RelatesTo *wsa__RelatesTo 0;
mustUnderstand _wsa__From *wsa__From 0;
mustUnderstand _wsa__ReplyTo *wsa__ReplyTo 0;
mustUnderstand _wsa__FaultTo *wsa__FaultTo 0;
mustUnderstand _wsa__To wsa__To 0;
mustUnderstand _wsa__Action wsa__Action 0;
};
</code></pre>
<p>But I would like to generate it automatically since I have to add some other structs to the Soap Header which are autogenerated from my wsdl/xsd files.</p>
<p>Thanks</p>
| <p>You can define the SOAP_ENV_Header in your typemap.dat like so:</p>
<pre><code>wsa = <http://schemas.xmlsoap.org/ws/2004/08/addressing>
SOAP_ENV__Header =\
#import "wsa.h"\n\
struct SOAP_ENV__Header\n\
{\n\
mustUnderstand _wsa__MessageID wsa__MessageID 0;\n\
mustUnderstand _wsa__RelatesTo * wsa__RelatesTo 0;\n\
mustUnderstand _wsa__From * wsa__From 0;\n\
mustUnderstand _wsa__ReplyTo * wsa__ReplyTo 0;\n\
mustUnderstand _wsa__FaultTo * wsa__FaultTo 0;\n\
mustUnderstand _wsa__To wsa__To 0;\n\
mustUnderstand _wsa__Action wsa__Action 0;\n\
};
</code></pre>
<p>Then use wsdl2h with option "-t " to specify an external typemap.dat.</p>
|
How does unit testing work when the program doesn't lend itself to a functional style? <p>I'm thinking of the case where the program doesn't really compute anything, it just DOES a lot. Unit testing makes sense to me when you're writing functions which calculate something and you need to check the result, but what if you aren't calculating anything? For example, a program I maintain at work relies on having the user fill out a form, then opening an external program, and automating the external program to do something based on the user input. The process is fairly involved. There's like 3000 lines of code (spread out across multiple functions*), but I can't think of a single thing which it makes sense to unit test.</p>
<p>That's just an example though. Should you even try to unit test "procedural" programs?</p>
<p>*EDIT</p>
| <p>I'm not an expert on this but have been confused for a while for the same reason. Somehow the applications I'm doing just don't fit to the examples given for UNIT testing (very asynchronous and random depending on heavy user interaction)
I realized recently (and please let me know if I'm wrong) that it doesn't make sense to make a sort of global test but rather a myriad of small tests for each component. The easiest is to build the test in the same time or even before creating the actual procedures.</p>
|
How to use global caching in php? <p>ello all
im new to php and server scripting ( coming from the java/cpp background )
my question is , if i like to be able to build some kind of single tone cache that will hold me data in memory in all the web application
life , something that when i start the web server it will start main cache
that will server the web application not inside sessions static cache
like singletone map in c++/java that that leaves all the time
what are my options ? </p>
| <p>For this in PHP you need <a href="http://au2.php.net/apc" rel="nofollow">APC</a>, which comes pretty much as standard with PHP these days (and will be standard as of PHP 6)--all you have to do is enable it in the config--or <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>, particularly if you've got some sort of clustered solution.</p>
|
How can I stop IDLE from printing giant lists? <p>Sometimes I'll be working with, say, a list of thousands of items in IDLE, and accidently print it out to the shell. When this happens, it crashes or at least very significaly slows down IDLE. As you can imagine, this is extremely inconvenient.
Is there a way to make it, rather than printing the entire thing, just give me a summarised [1, 2, ...] output?
Any help would be much appreciated.</p>
| <p>As above, try a custom print function like:</p>
<pre><code>def my_print(obj):
if hasattr(obj, '__len__') and len(obj) > 100:
print '... omitted object of %s with length %d ...' % (type(obj), len(obj))
else: print obj
</code></pre>
|
Displaying Hebrew text in ASP <p>I am working on ASP application that reads data from sql server and displays it in a table. All my Hebrew text is replaced with "?????". </p>
<p>I installed and Configured Hebrew Font in Regional options. I have set the appropriate Charset in Head,Meta tag
I am able to see proper Hebrew text in sqlServer2005ManagementSudioExpress.
I have proper collation set for my Column (SQL_Latin1_General_CP1255_CI_AS) which is Hebrew.
I still see "?????" isntead of Hebrew text. </p>
<p>Did I miss something ?</p>
| <p>Make sure the column is set to store Unicode. For example, <code>nvarchar</code> instead of <code>varchar</code>, or <code>ntext</code> instead of <code>text</code>.</p>
|
Access Violation <p>Greetings everyone, going to need some help in clearing this exception.</p>
<p>I get the following when debugging my compiled program in Microsoft Visual C++ 6.0:</p>
<pre><code>Loaded 'ntdll.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\kernel32.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\tsappcmp.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\msvcrt.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\advapi32.dll', no matching symbolic information found.
Loaded 'C:\WINDOWS\system32\rpcrt4.dll', no matching symbolic information found.
First-chance exception in SA.exe: 0xC0000005: Access Violation.
</code></pre>
<p>Here are the relevant screenshots from the debugger.</p>
<p>Showing ostream.h:</p>
<p>http://img237.imageshack.us/my.php?image=accessviolation.png'>http://img237.imageshack.us/img237/1116/accessviolation.th.png' border='0'/></p>
<p>Showing main.ccp:</p>
<p>http://img509.imageshack.us/my.php?image=accessviolation2.png'>http://img509.imageshack.us/img509/3619/accessviolation2.th.png' border='0'/></p>
<p>I've tried to scour my code for null pointers and have also tried to ignore the exception with no luck. Here are the three main components of my script:</p>
<p>main.ccp</p>
<pre><code>#include <iostream>
#include "SA.h"
using namespace std; // For the use of text generation in application
int main()
{
SimAnneal Go;
cout << "Quadratic Function" << endl
<< "Solving method: Simulated Annealing" << endl;
cout << "\nSelect desired Initial Temperature:" << endl
<< "> ";
cin >> Go.T_initial;
cout << "\nSelect desired number of Temperature Iterations:" << endl
<< "> ";
cin >> Go.N_max;
cout << "\nSelect desired number of step Iterations:" << endl
<< "> ";
cin >> Go.N_step;
cout << "\nSelect desired Absolute Temperature:" << endl
<< "> ";
cin >> Go.T_abs;
Go.LoadCities();
Go.Initialize();
Go.SA();
system ("PAUSE");
return 0;
}
</code></pre>
<p>SA.h</p>
<pre><code> #ifndef SA_H
#define SA_H
class SimAnneal {
double S_order [15];
double S_trial [15];
int SwapNum1;
int SwapNum2;
double CityArray [15][15];
double E_initial;
double E_current;
double T;
void Metropolis (double, int, int);
void Next_State (double, int);
double Schedule (double, int);
double ObjFunction (double CityOrder []);
void EquateArray ();
void OrderInt ();
void OrderTrial ();
void OrderList (double array[]);
void WriteResults (double, double, double, double, double);
public:
int N_step;
int N_max;
double T_initial;
double T_abs;
void SA ();
void Initialize ();
void LoadCities ();
};
double Random_Number_Generator(double nHigh, double nLow);
#endif
</code></pre>
<p>SA.cpp</p>
<pre><code>#include <math.h>
#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>
#include <time.h>
#include <cstdlib>
#include "SA.h"
using namespace std;
void SimAnneal::SA()
{
T = T_initial;
E_current = E_initial;
for ( int N_temperatures = 1 ; N_temperatures <= N_max ; N_temperatures++ )
{
Metropolis(T, N_step, N_temperatures);
T = Schedule(T, N_temperatures);
if (T <= T_abs)
break;
}
cout << "\nResults:" << endl
<< "Distance> " << E_current << endl
<< "Temperature> " << T << endl;
OrderList(S_order);
}
void SimAnneal::Metropolis(double T_current, int N_Steps, int N_temperatures)
{
for ( int i=1; i <= N_step; i++ )
Next_State(T_current, N_temperatures);
}
void SimAnneal::Next_State (double T_current, int i)
{
OrderTrial();
double EXP = 2.718281828;
double E_t = ObjFunction(S_trial);
double E_c = ObjFunction(S_order);
double deltaE = E_t - E_c;
if ( deltaE <= 0 )
{
EquateArray();
E_current = E_t;
}
else
{
double R = Random_Number_Generator(1,0);
double Ratio = 1-(float)i/(float)N_max;
double ctrl_pram = pow(EXP, (-deltaE / T_current));
if (R < ctrl_pram*Ratio)
{
EquateArray();
E_current = E_t;
}
else
E_current = E_c;
}
}
double SimAnneal::Schedule (double Temp, int i)
{
double CoolingRate = 0.9999;
return Temp *= CoolingRate;
}
double SimAnneal::ObjFunction (double CityOrder [])
{
int a, b;
double distance = 0;
for (int i = 0; i < 15 - 1; i++)
{
a = CityOrder [i];
b = CityOrder [i + 1];
distance += CityArray [a][b];
}
return distance;
}
void SimAnneal::Initialize ()
{
int a, b;
double distance = 0;
OrderInt();
for (int i = 0; i < 15 -1; i++)
{
a = S_order [i];
b = S_order [i + 1];
distance += CityArray [a][b];
}
E_initial = distance;
}
void SimAnneal::EquateArray ()
{
for (int i = 0; i < 15; i++)
{
S_order [i] = S_trial [i];
}
}
void SimAnneal::OrderInt ()
{
for (int i = 0; i <15; i++)
{
S_order [i] = i;
}
}
void SimAnneal::OrderTrial ()
{
for (int i = 0; i < 15; i++)
{
S_trial [i] = S_order [i];
}
SwapNum1 = (int)Random_Number_Generator(15, 0);
SwapNum2 = (int)Random_Number_Generator(15, 0);
for (int n = 0; n <= 100000; n++)
{
SwapNum2 = (int)Random_Number_Generator(15, 0);
if ( SwapNum1 != SwapNum2 )
break;
}
S_trial [SwapNum1] = S_order [SwapNum2];
S_trial [SwapNum2] = S_order [SwapNum1];
}
void SimAnneal::OrderList (double array[])
{
cout << "Array List : " << endl;
for (int i = 0; i < 15; i++)
{
cout << " > " << array[i] << endl;
}
cout << "End of array" << endl;
}
void SimAnneal::LoadCities ()
{
int x, y;
for (y = 0; y < 15; y++)
{
for (x = 0; x < 15; x++)
{
if (x == y)
{ CityArray[x][y] = 0.0;
}
else if (x != y)
{ CityArray[x][y] = Random_Number_Generator(7, 1);
}
}
}
for (y = 0; y < 15; y++)
{
for (x = 0; x < 15; x++)
{
if (y > x)
CityArray[y][x] = CityArray[x][y];
}
}
}
double Random_Number_Generator(double nHigh, double nLow)
{
double fr = ((rand() % ((int)nHigh*1000 - (int)nLow*1000 + 1)) + nLow) / 1000;
return fr;
}
</code></pre>
<p>Any Assistance would be much appriciated. I'm all out of ideas myself.</p>
| <p>a = S_order [i];<br />
b = S_order [i + 1];<br />
distance += CityArray [a][b]; <--- This looks suspicious. When i = 14, b = 15...clearly outside the range...
my 2 cents</p>
|
How to ensure buttons reversed by CSS are spaced evenly? <p>I have a wizard-style HTML form with a row of submit buttons for the Back/Next/Cancel actions (in that order). The form can also contain a varying number of input fields, such as text fields, radio buttons, checkboxes, dropdowns (select tags), and textareas. The customer requires the "Next" button to be the default action, so that if the user types into a text field and presses Enter, it should submit the form as if they had clicked the "Next" button.</p>
<p>The problem is that in this scenario, the browser (at least IE, which is what 99% of our customers use) submits the form using the first button declared in the form, which as you can see from the above list is "Back", not "Next" as desired.</p>
<p>One fix I read about is to declare the Back and Next buttons in reverse order (i.e. Next first) then use CSS to display them around the right way, like so:</p>
<pre><code><html>
<head>
<style type="text/css">
.formSubmitButtons {
direction: rtl;
float: left;
}
.formSubmitButtons input {
direction: ltr;
float: none;
}
</style>
</head>
<body>
<form action="blah" method="POST" enctype="application/x-www-form-urlencoded">
<div class="formSubmitButtons">
<input type="submit" name="btnNext" value="Next">
<input type="submit" name="btnBack" value="Back">
</div>
<input type="submit" name="btnCancel" value="Cancel">
<br/>Some text fields go here...
</form>
</body>
</html>
</code></pre>
<p>This provides the desired behaviour and button order in both Firefox and IE, however the spacing of the Cancel button relative to the others is inconsistent. In IE6 it looks nice enough, but in Firefox 3.0.5, the Cancel button is jammed up against the Next button.</p>
<p>Does anyone know what CSS magic I need to weave in order to get these three buttons to space evenly in both browsers?</p>
<p>(avoiding the issue by sorting the buttons Next/Back/Cancel is not an option)</p>
<p>(also thanks to everyone who suggested JavaScript-based solutions, but not all our customers allow JS, so it has to be a straight HTML and/or CSS solution)</p>
<p>Here's what I ended up doing that worked nicely (based on Cletus's suggestion):</p>
<pre><code><!--
<input type="submit" name="btnNext" style="position: absolute; left: -9999px" tabindex="-1">
<input type="submit" name="btnBack" value="Back">
<input type="submit" name="btnNext" value="Next">
<input type="submit" name="btnCancel" value="Cancel">
-->
</code></pre>
<p>(ignore the wrapping comment tags, they're just so you can see the HTML)</p>
| <p>Have you considered using <a href="http://tapestryjava.blogspot.com/2005/06/html-form-trick.html" rel="nofollow">this trick</a>? Basically you just have a hidden button appear first which does the desired action.</p>
|
Search and replace text contents of a tag <p>I am trying to specifically to pad out the /'s in an a tag's text.</p>
<pre><code>1234/1234/ABCDE => 1234 / 1234 / ABCDE
</code></pre>
<p>In context; if I have an a tag:</p>
<pre><code><a href="http://www.domain.com/path/to/page.html">12 34/1234A/BC DEFG</a>
</code></pre>
<p>I would like to get:</p>
<pre><code><a href="http://www.domain.com/path/to/page.html">12 34 / 1234A / BC DEFG</a>
</code></pre>
| <p>This isn't really the kind of thing regular expressions are good at doing. You'll probably be better off using an HTML or XML parser - it creates a tree of nodes out of the document, and then you can just step through all the text nodes that are inside of tags and add spaces as needed.</p>
|
Download textarea contents as a file using only Javascript (no server-side) <p>I am being asked to make a "download" button that downloads the contents of a textarea on the same page as a file, with the browser's "Save As..." dialog showing up. Copy/paste would do the job just fine, but it is a "requirement".</p>
<p>Right now, I am just posting the contents of the textarea to the server, which echos them back with <code>Content-disposition: attachment</code> slapped on. Is there a way to do this with just client-side Javascript? </p>
| <p>This may be what you are looking for:
<a href="http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/">http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/</a></p>
<p>It uses the browser's download dialogue, but supports only FF and Chrome, and maybe more browsers now?</p>
<hr>
<p><strong>Edit:</strong></p>
<p>As commented I will embed the code from the article:</p>
<pre><code>function saveTextAsFile()
{
var textToWrite = //Your text input;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = //Your filename;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
</code></pre>
|
Object Oriented Analysis and Design <p>Why I can't able to specify static type of methods in interface.</p>
<p>Is there any alternative to do this??</p>
<p>but I should use only inerface insted of abstract class.</p>
<p>/</p>
<p>Is there any problem in specifing acess specifier in interface? </p>
<p>I want to specify the events in Interface and that should be acessed only by implemented class so i want protected acess specifier to that event.</p>
<p>and I have certain function that can be make use of interface in another class in that case i can use public acess specifier. </p>
| <p>I don't know what language you're taking about but I'll answer as if in C#.</p>
<p>Why I can't able to specify static type of methods in interface.
Is there any alternative to do this??</p>
<p>It is because you can't override static methods.
What are you trying to achieve?</p>
<p>Members in interfaces are always public in C#. If you need to have other protection levels, use an abstract class. What would the purpose of protected events be if you can't access them from the interface? It has nothing to do with the interface then (remember, the interface can't have any code). If you are referring to that only implementing classes can raise the events, rest assured that they are the only ones that can raise them. Events are built that way - only the class itself can raise events. You can't raise an event external from the class (except if you have a method on the class, raising the event).</p>
|
getting System.ServiceModel.AddressAccessDeniedException on Vista for WCF service <p>We have an application that starts a WCF server and the app reads from it.</p>
<p>It starts and can be read fine on all Windows XP machines.</p>
<p>On our Vista machine, however, we get:</p>
<pre><code>System.ServiceModel.AddressAccessDeniedException
"The process has no rights to this namespace."
System.Net.HttpListenerException
</code></pre>
<p>The URL is at localhost:</p>
<p><a href="http://localhost:8731/ABC.Testing.Business.Core/SecurityService/?wsdl">http://localhost:8731/ABC.Testing.Business.Core/SecurityService/?wsdl</a></p>
<p>The error message sent us here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms733768.aspx">http://msdn.microsoft.com/en-us/library/ms733768.aspx</a></p>
<p>And we did what it said:</p>
<pre><code>netsh http add urlacl url=... user=...
</code></pre>
<p>which changed the rights but the WCF service still cannot start on Vista.</p>
<p>Does anyone have any experience with this that could move us forward? Thanks.</p>
| <p>I had a similar issue with Windows 7 running Visual Studio 2010. My solution was a simple WCF service library with a simple console project serving as the WCF service host.</p>
<p>My base address in app.config was "http://localhost:8080/BookService" and I forgot that I had to start Visual Studio as an administrator in order to get Windows to map that port to my app.</p>
<p>As soon as I started Visual Studio as an Administrator (right click, Run as administrator) it ran like a champ.</p>
|
How can I create a Installer package for iPhone? <p>How can I create a Installer package for iPhone ?</p>
| <p>You should expose your question in a detailed and better way. Are you using xcode? It has everything you need to build your app for the iPhone.</p>
<p>You just code the app, and hit the button "build" or "build and run" and the .app file is automatically generated.</p>
|
Eclipse C++ debugging breaks in STL <p>I'm new to debugging with Eclipse.</p>
<p>I try to debug my app to know where it segfaults.</p>
<p>The problem is that Eclipse breaks within the STL, which is very annoying.</p>
<p>For example: I created a breakpoint in my source file on line 134, which works fine
but if I hit F6 for "Step Over", Eclipse/gdb breaks in basic_string constructor used in the next line with std::cout.</p>
<p>Any hints on this? Is there a configuration option for Eclipse or such?</p>
| <p>Perhaps that's where it segfaults?</p>
|
Problems title-casing a string in Python <p>I have a name as a string, in this example "markus johansson".</p>
<p>I'm trying to code a program that makes 'm' and 'j' uppercase:</p>
<pre><code>name = "markus johansson"
for i in range(1, len(name)):
if name[0] == 'm':
name[0] = "M"
if name[i] == " ":
count = name[i] + 1
if count == 'j':
name[count] = 'J'
</code></pre>
<p>I'm pretty sure this should work, but it gives me this error:</p>
<pre><code>File "main.py", line 5 in <module>
name[0] = "M"
TypeError: 'str' object does support item assignment
</code></pre>
<p>I know there is a library function called .title(), but I want to do "real programming".</p>
<p>How do I fix this?</p>
| <pre><code>>>> "markus johansson".title()
'Markus Johansson'
</code></pre>
<p>Built in string methods are the way to go.</p>
<p>EDIT:
I see you want to re-invent the wheel. Any particular reason ?
You can choose from any number of convoluted methods like:</p>
<pre><code>' '.join(j[0].upper()+j[1:] for j in "markus johansson".split())
</code></pre>
<p>Standard Libraries are still the way to go.</p>
|
Circular file logging <p>I would like to know if there are any logger libraries for C , that can do circular file logging?</p>
<p>I am currently looking at log4C, But cant find enough docs on it that can say it will do circular logging.</p>
<p>if anyone has done this. kindly let me know.</p>
<p>Thanks</p>
| <p><em>here is an example</em></p>
<p>This is a cut down version. In ours we use vargs and format them before calling log_it.</p>
<p><hr /></p>
<pre><code>typedef const char* c_str;
FILE* log_fp = 0;
const int max_log_size = 4 * 1024 * 1024;
const int max_no = 5;
c_str prefix = "logs_";
c_str postfix = ".txt";
void log_it( c_str str )
{
char file1[100], file2[100];
if( ! log_fp )
{
sprintf( file1 "%s%d%s", prefix, 0, postfix );
log_fp = fopen( file1, "a" );
}
if( log_fp )
{
if( ftell( log_fp ) > max_log_size )
{
fclose( log_fp );
log_fp = 0;
for( int i = (max_no - 1); i >= 0; i-- )
{
sprintf( file1 "%s%d%s", prefix, i, postfix );
sprintf( file1 "%s%d%s", prefix, i+1, postfix );
rename( file1, file2 );
}
sprintf( file1 "%s%d%s", prefix, 0, postfix );
log_fp = fopen( file1, "a" );
}
fputs( str, log_fp );
fflush( log_fp );
}
}
</code></pre>
<p><hr /></p>
<p>I hope that helps.</p>
<p>dave</p>
|
Convert from enum ordinal to enum type <p>I've the enum type <code>ReportTypeEnum</code> that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an <code>ReportTypeEnum</code> so that I can continue passing it. </p>
<p>How can I convert ordinal to the <code>ReportTypeEnum</code>?</p>
<p>Using Java 6 SE.</p>
| <pre><code>ReportTypeEnum value = ReportTypeEnum.values()[ordinal]
</code></pre>
|
How to create a photo gallery with slideshow effect of the images placed in server folder using jsp/servlet/javascript <p>I need to create slideshow of the images which are in server.These images would be changing as the user uploads. I need this using jsp/javascript/servlet/ajax</p>
| <p>Generally when the page loads, the slideshow code already has a list of the available files. It would need to use AJAX to poll the server periodically to determine if this list has changed (a user had uploaded a file). Typically you'd just replace the array or string holding the list of files in the AJAX call.</p>
<p>The server-side code just needs to supply the list of files in a folder in a format the slideshow expects.</p>
<p>Here's a <a href="http://www.smashingmagazine.com/2007/05/18/30-best-solutions-for-image-galleries-slideshows-lightboxes/" rel="nofollow">collection of different slideshows</a> you can grab and modify for this purpose.</p>
|
How to import a function from a DLL made in Delphi? <p>Can you tell me how do i use the following functions in my C program.</p>
<p>Delphi DLL - Exported functions :</p>
<pre><code>function GetCPUID (CpuCore: byte): ShortString; stdcall;
function GetPartitionID(Partition : PChar): ShortString; stdcall;
</code></pre>
<p>I don't have the source code for that DLL so I must adapt my C program to that DLL and not the other way around.</p>
<p>I do the following and get error</p>
<pre><code>typedef char* (_stdcall *GETCPUID)(BYTE);
typedef char* (_stdcall *GETPID)(PCHAR);
GETCPUID pGetSerial;
GETPID pGetPID
HMODULE hWtsLib = LoadLibrary("HardwareIDExtractor.dll");
if (hWtsLib){
pGetSerial = (GETCPUID)GetProcAddress(hWtsLib, "GetCPUID");
char *str = (char*) malloc(1024);
str = pGetSerial((BYTE)"1");
pGetPID= (GETPID )GetProcAddress(hWtsLib, "GetPartitionID");
char *str1 = (char*) malloc(1024);
str1 = pGetPID("C:");
}
</code></pre>
<p>Thanks</p>
| <p>Since you don't have the source to the DLL, you'll need to get a little creative on the C side of things. Even though the ShortString is listed as the function result, it is actually the responsibility of the <strong>caller</strong> to provide a location in which to place the result. Because this is a stdcall function, parameters are passed in from right to left, so that means that the address of the ShortString result is passed in last. To get this to line up, it will need to the first parameter listed. I'll do the first API, GetCPUID. In C, it might look something like this:</p>
<pre><code>typedef struct ShortString {
char len;
char data[255];
};
typedef void (_stdcall *GETCPUID)(struct ShortString *result, BYTE cpuCore);
GETCPUID pGetSerial;
HMODULE hWtsLib = LoadLibrary("HardwareIDExtractor.dll");
if (hWtsLib) {
ShortString serial;
pGetSerial = (GETCPUID)GetProcAddress(hWtsLib, "GetCPUID");
pGetSerial(&serial, '1');
char *str = malloc(serial.len + 1); // include space for the trailing \0
strlcpy(str, serial.data, serial.len);
str[serial.len] = '\0'; // drop in the trailing null
}
</code></pre>
<p>I'll leave the GetPartitionID as an exercise for the reader :-).</p>
|
Best practices for building and packaging on AIX <p>Does anyone know where i can find some best practices guide for building and packaging C applications on AIX.</p>
<p>I m using the xlc compiler and make.</p>
<p>Thanks</p>
| <p>Maybe <a href="http://publibn.boulder.ibm.com/doc%5Flink/en%5FUS/a%5Fdoc%5Flib/aixprggd/genprogc/pkging%5Fsw4%5Finstall.htm" rel="nofollow">here</a> ?</p>
|
How can I keep XML comments for method descriptions in a separate file? <p>This question stems from this question
<a href="http://stackoverflow.com/questions/288298/code-documentation-how-much-is-too-much">Code documentation how much is too much?</a></p>
<p>One the answers was to keep your xml documentation in a separate file. I really liked that answer as when I am looking through the code the verbosity of the documentation is annoying, on the other hand that verbosity is usefull when searching for the right method via intellisense or publishing the documentation.</p>
<p>The answer was to use the include tag </p>
<pre><code>/// <include file="Documentation/XML/YourClass.xml" path="//documentation/members[@name='YourClass']/*"/>
</code></pre>
<p>There is also a MSDN article about the include tag <a href="http://msdn.microsoft.com/en-us/library/9h8dy30z%28VS.71%29.aspx" rel="nofollow">here.</a></p>
<p>I figured out how to keep the summary information out, but I do not know and I couldn't find it how to put the method documentation there as well. (which is more important than the class summary itself.</p>
| <p>The answer is simple. Read the produced xml files. They give an idea how the separated xml files should look like.</p>
<p>Reading the produced xml files and how method is described (with parameters and such):</p>
<pre><code><member name="M:BitFactory.Logging.Logger.DoLog(BitFactory.Logging.LogEntry)">
<summary>
Really log aLogEntry. (We are past filtering at this point.)
Subclasses might want to do something more interesting and override this method.
</summary>
<param name="aLogEntry">The LogEntry to log</param>
<returns>true upon success, false upon failure.</returns>
</member>
</code></pre>
<p>T, M, F prefixes Type, Method, Field. </p>
|
Using GetHashCode to "secure" users passwords <p>The company I work for has taken on a support contract for a large order processing system. As part of the initial system audit I noticed that the passwords stored in the database were actually the hashcode of the password.</p>
<p>Essentially:</p>
<pre><code>string pwd = "some pasword";
string securePwd = pwd.GetHashCode();
</code></pre>
<p>My question is, how secure or otherwise is this? </p>
<p>I'm not comfortable with it, but I don't know enough about how GetHashCode works. I would prefer to use something like an MD5 hash, but if I'm wasting my time then I won't bother.</p>
| <p>You should use a salted, cryptographically strong hash, such as <code>SHA256Managed</code>.</p>
<p>Jeff Attwood has a few good posts on this topic:</p>
<p><a href="http://www.codinghorror.com/blog/archives/000949.html" rel="nofollow">Rainbow Hash Cracking</a></p>
<p><a href="http://www.codinghorror.com/blog/archives/000953.html" rel="nofollow">You're Probably Storing Passwords Incorrectly</a></p>
|
Do you use the original (German) apple keyboard/keyboard layout when programming on mac? <p>I'm a programmer, working with different languages/Formats (Java, Python, XML, HTML, Objective-C etc.). From time to I've to work on a Mac and I'm not very comfortable with the German keyboard layout for programming.</p>
<p>Is there somebody with the same problem and, if so, how did you solve it?</p>
| <p>I recently did an internship in England and used this opportunity to switch to the English keyboard layout. The switch was nearly completely straightforward and I can heartily recommend it, especially since you can still type the German umlauts very well on the English keyboard layout (Alt+u, then a/o/u types the corresponding umlaut; Alt+s types âÃâ).</p>
<p>The keys used for programming are much easier reachable, especially â<code>[]</code>â and â<code>{}</code>â (which are both on â<code>ü</code>â and â<code>+</code>â). Also, â<code>/</code>â and â<code>\</code>â better placed. The only think I absolutely <strong>hate</strong> is the placement of the â<code>+</code>â key because it requires the shift key!</p>
|
Comparing struts ognl value to scriptlet value in JSP <p>I have to compare this to a value like below:</p>
<pre><code>${page_id } ---- <% out.print(a); %>
<c:if test="${page_id != a}">
</code></pre>
<p>How can I do this?</p>
| <p>Presuming that "a" is a scriptlet variable.
El expressions map to page/request/session/application attributes in scope.</p>
<p>${page_id} is approximately equivalent to pageContext.findAttribute("page_id");</p>
<p>To be able to compare them, you need to get them into the same space.
One way of doing this is with scriptlet code:</p>
<pre><code><% pageContext.setAttribute("a", a); %>
</code></pre>
<p>You should now be able to access ${a} as an EL expression.
Not a preferred solution, as it uses scriptlet code (something to avoid in JSPs)
There might be a better way of course. It all depends on where the value of "a" come from in the first place.</p>
|
Multiple Java projects and refactoring <p>I have recently joined a project that is using multiple different projects. A lot of these projects are depending on each other, using JAR files of the other project included in a library, so anytime you change one project, you have to then know which other projest use it and update them too. I would like to make this much easier, and was thinking about merging all this java code into one project in seperate packages. Is it possible to do this and then deploy only some of the packages in a jar. I would like to not deploy only part of it but have been sassked if this is possible.</p>
<p>Is there a better way to handle this?</p>
| <h3>Approach 1: Using Hudson</h3>
<p>If you use a continuous integration server like <a href="http://hudson-ci.org/" rel="nofollow">Hudson</a>, then you can configure upstream/downstream projects (see <a href="http://wiki.hudson-ci.org/display/HUDSON/Terminology" rel="nofollow">Terminology</a>).</p>
<blockquote>
<p>A project can have one or several downstream projcets. The downstream projects are added to the build queue if the current project is built successfully. It is possible to setup that it should add the downstream project to the call queue even if the current project is unstable (default is off).</p>
</blockquote>
<p>What this means is, if someone checks in some code into one project, at least you would get early warning if it broke other builds.</p>
<h3>Approach 2: Using Maven</h3>
<p>If the projects are not too complex, then perhaps you could create a main project, and make these sub-projects child modules of this project. However, mangling a project into a form that Maven likes can be quite tricky.</p>
|
Appropriate placement for my testcases belonging to a non-app in Django <p>I have built my website in Django. And like any other django project I have got apps inside the project root directory and some special folders like(extensions a.k.a custom django command extensions). With an app, we dont have any problem with having testcases. "tests.py" inside the app directory will be the solution. But for a special folder(which is not an app or which doesn't have a models.py) where do I place the testcases. I tried placing the tests.py inside the extensions directory and it said the directory is not a model and unable to run the tests. HOw do I solve this? How can I have a proper placement of testcases related to non-apps?</p>
| <p>I think it will work to put them in a <code>tests/</code> directory at the project level.</p>
<p>If, for some reason, it doesn't then try creating an empty <code>models.py</code> in your extensions directory.</p>
|
Arrays as objects <p>I there a method to allow me to use an array as an object?</p>
<p>I have the following code in my main class</p>
<pre><code>function __construct()
{
require 'config.php';
$this->config = new PHPSO_Config();
}
</code></pre>
<p>where the PHPSO_Config class looks something like this</p>
<pre><code>class PHPSO_Config
{
/**
* The administrators email address
*/
var $adminEmail = 'user@domain.tld'; //I'm using this email to test
}
</code></pre>
<p>so can I accomplish the same thing and be able to access the config vars as an object without creating a second class?</p>
| <p>You can cast an array to an object using </p>
<pre><code>$myObject = (object) $myarray;
</code></pre>
<p>thus the following should work (untested):</p>
<pre><code>function __construct()
{
require 'config.php';
$this->config = (object) array("username" => "root");
}
</code></pre>
<p>then $class->config->username should work.</p>
|
What image type should I use when? GIF, JPG or PNG? <p>I am trying to create a personal home page for myself to learn more about web design (JavaScript, using Photo Shop, etc). I plan on having a graphical menu on the left, a banner across the top and also a "Photos" section where I can display photos of various pictures I have taken.</p>
<p>However, when I look at other sites that do anything similar, I see some using GIFs, and some use JPGs and some even use PNGs. Is there any difference between these? Should I use a GIF for graphical images used on the site and JPGs for my photos? Should I make everything PNGs?</p>
<hr>
<p><strong>Exact Duplicate:</strong></p>
<ul>
<li><a href="http://stackoverflow.com/q/2336522/199700">PNG vs. GIF vs. JPEG - When best to use?</a></li>
<li><a href="http://stackoverflow.com/questions/392635/website-image-formats-choosing-the-right-format-for-the-right-task">Website Image Formats: Choosing the right format for the right task.</a></li>
<li><a href="http://stackoverflow.com/questions/115818/which-format-for-small-website-images-gif-or-png/115838">Which format for small website images? GIF or PNG?</a></li>
</ul>
| <p>XKCD style comic strip that explains it:</p>
<p><img src="http://i.stack.imgur.com/XeIwO.png" alt="alt text"></p>
<p><a href="http://lbrandy.com/blog/2008/10/my-first-and-last-webcomic/" rel="nofollow">http://lbrandy.com/blog/2008/10/my-first-and-last-webcomic/</a></p>
|
Is there a java implementation of the ActiveRecord pattern that is built on top of Hibernate, similar to Castle Windsor? <p>I am looking for a Java implementationation of the ActiveRecord pattern which is built on top of Hibernate.</p>
<p>In .Net there is a open source project <a href="http://www.castleproject.org/activerecord/">Castle Windsor ActiveRecord</a> which implements the ActiveRecord pattern on top of NHibernate.</p>
<p>I'm looking for something like this, except sitting on top of the NHiberate persistence frameowork for Java.</p>
| <p>I released a project called ActiveJDBC: <a href="http://javalite.io/" rel="nofollow">http://javalite.io/</a>. This is what you are looking for
thanks
igor</p>
|
Web-based groupware for small company? <p>I'm looking for an open-source, web-based solution to provide a small company with the following groupware features:
- calendar/planner
- contacts
- emails
- document management (let people work on MS/OpenOffice docs on a shared drive, and have the server update the list of available docs periodically)
- log incoming phone calls (find a way to pop a list of past calls from this customer on their Windows PC when they call in)</p>
<p>I prefer a web-based solution, because more and more users need to access data from a smartphone.</p>
<p>Can you recommend solutions I should look at?</p>
<p>Thank you for any hint.</p>
| <p>To expand on TheTXI's answer (which was posted while I was typing this) -- <a href="http://technet.microsoft.com/en-us/windowsserver/sharepoint/default.aspx" rel="nofollow">Windows SharePoint Services</a> is free. Don't confuse it with SharePoint Server which has a richer publishing & user profile model (among other things). Its not a true CRM package but it should meet the rest of your req's.</p>
|
Linearly recursive list-difference function in Common Lisp <p>I was going through <a href="http://www.cs.sfu.ca/CC/310/pwfong/Lisp/1/tutorial1.html" rel="nofollow">this</a> tutorial for fun, and got stuck on the very last thing he says, "Exercise: Give a linearly recursive implementation of union and difference." (for a list)</p>
<p>Union, no sweat. </p>
<p>Difference, sweat. </p>
<p>An attempt looks like this. . .</p>
<pre><code>(defun list-diff (L1 L2)
(cond
((null L1) L2)
((null (member (first L1) L2)) (cons (first L1) (list-diff (rest L1) L2)))
(t (list-diff (rest L1) L2))
)
)
</code></pre>
<p>Now, that returns all the elements that are in L1 that aren't in L2, but it just returns all of L2 (obviously). Similarly, if I change the L2 in line 3 to "nil", then it just returns all of L1 that aren't in L2, but none of L2. </p>
<p>My attempts at work-arounds don't look recursive, and when they are, I end up getting stack-overflows (like if I try calling (list-diff L2 L1) somewhere). </p>
<p>Any of his other exercises, such as list-intersection, only require running through the elements of L1. Here, I want to strike the crucial elements from L2, or run (list-diff L2 L1) and then union the results from both, but that's not really linearly-recursive anymore. </p>
<p>Thoughts? </p>
<p>(not homework, really. I just thought I'd try to look at some LISP for fun.)</p>
<p>EDIT: a function that does this properly, based on the responses is:</p>
<pre><code>(defun list-diff (L1 L2)
(cond
((null L1) nil)
((null (member (first L1) L2)) (cons (first L1) (list-diff (rest L1) L2)))
(t (list-diff (rest L1) L2))
)
)
</code></pre>
| <p>The <a href="http://mathworld.wolfram.com/SetDifference.html">set difference</a> operation L1 \ L2 is defined as all elements e such that e is in L1 but e not in L2. So it looks to me like your second attempt is actually correct:</p>
<blockquote>
<p>Similarly, if I change the L2 in line
3 to "nil", then it just returns all
of L1 that aren't in L2, but none of
L2.</p>
</blockquote>
<p>It looks like you're trying to compute the <a href="http://mathworld.wolfram.com/SymmetricDifference.html">symmetric difference</a>, although it isn't clear to me that this is what the exercise requests.</p>
<p>If you want to be clever about it, you can probably pass a third list into the function to serve as an accumulator. When L1 has elements, push the first element into the accumulator (and call recursively) when <code>(null (member (first L1) L2))</code>. When L1 is null, check the elements of L2 against the accumulator list, doing the same thing. When L1 and L2 are null, return the accumulator list.</p>
|
Validate on text change in TextBox <p>I have implemented validation rules on a textBox in my WinForm and it works well. However it checks the validation only when I tab out of the field. I would like it to check as soon as anything is entered in the box and everytime the content changes. Also I'd like it to check validation as soon as the WinForm opens. </p>
<p>I remember doing this fairly recently by setting some events and whatnot, but I can't seem to remember how.</p>
| <p>TextChanged event</p>
<p>in the future you can find all of the events on the MSDN library, here's the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox%28VS.80%29.aspx" rel="nofollow">TextBox class reference</a>:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox</a>(VS.80).aspx</p>
|
Use of Global.asax in distributed approach ie Web garden <p>I understand the limitations of using application state and session state accross multiple application pools, that they cannot be shared. What about the Global.asax file is a single instace created per application pool or does it reside in a higher level somewhere common to all application pools in IIS? </p>
| <p>Global.asax (which is just a class file for HttpApplication) is contained by whatever application pool the site resides in. Just the same as any other class in your site. If you are using web gardening, then the same rules that apply to application/session state applies to code in global.asax. In other words, if you are running on 4 processors, when processors 1, 2, and 3 and busy, and #4 takes it's first request, any code that is in global.asax (event handlers, etc) is going to be executed.</p>
|
Sharepoint Workflow Fails When First Run But Succeeds When Run Manually <p>We are using an infopath form that when submitted is supposed to fire off a custom .NET workflow. Basically, the information within the form is used to create a new sharepoint site. What I am seeing happen is that the first time the workflow runs (which is automatic after the form is submitted), the workflow errors out. When I run the workflow manually immediately after it fails, the workflow runs fine.</p>
<pre><code>this.workflowProperties.Item["Client Name"]
</code></pre>
<p>I've debugged the issue down to the above line where workflowProperties is of type Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties. The first time the workflow runs, the property listed above (and all others) are null. The second time it is run the client name property is as it should be (populated from the infopath form).</p>
<p>Another important piece of information is that this workflow was working fine for over a year and suddenly started not working correctly a few weeks ago for no particular reason. We were having some permissions issues the past month but I cannot see how that could be related to the workflow issue. The user I am logged in as is a site collection administrator. I use the same user to kick the workflow off manually (which succeeds). I do not think that the workflow runs as the user that is logged in though (when it is run automatically on form submission).</p>
<p>Another interesting wrinkle to the whole situation: there are a total of 3 custom workflows that the application uses. 2 were made in visual studio - one of these works fine and other is displaying the behavior described above. The last was made in sharepoint designer and is failing.</p>
<p>I'm willing to try just about anything at this point. I am on a dev server (which displays the exact symptoms as production) so I can try just about anything.</p>
| <p>I'm guessing this has to do with the workflow being fired asynchronously from the commit operation that sets the fields values. Can you try and fetch the item explictly from the list instead of using the Item from the workflow properties. something like the following:</p>
<pre><code>SPListItem l_item =
workflowProperties.Item.List.Items.GetItemById(
workflowProperties.Item.Id
);
</code></pre>
<p>i'm not certain, but it may be worth a try. </p>
<p>The other thing to keep in mind is the <code>SPContext.Current</code> object will be null if being called from an EventReceiver, but will be valid if called manually. It doesn't sound like this is the issue, but its something to be aware of nonetheless.</p>
|
When do Extension Methods break? <p>We are currently discussing whether Extension methods in .NET are bad or not. Or under what circumstances Extension methods can introduce hard to find bugs or in any other way behave unexpectedly.</p>
<p>We came up with:</p>
<ul>
<li>Writing an extension method for types that are not under your control (e.g. extending DirectoryInfo with GetTotalSize(), etc...) is bad, because the owner of the API could introduce a method that hides our extension - and might have different edge cases. For example testing for null in an extension method will automatically translate into a NullReferenceException if the extension method is no longer used due to hiding.</li>
</ul>
<p>Question:</p>
<ul>
<li>Are there any other dangerous situations than "hiding" that we are not thinking of?</li>
</ul>
<p>Edit:</p>
<p>Another very dangerous situation.
Suppose you have an extension method:</p>
<pre><code>namespace Example.ExtensionMethods
{
public static class Extension
{
public static int Conflict(this TestMe obj)
{
return -1;
}
}
}
</code></pre>
<p>And use it:</p>
<pre><code>namespace Example.ExtensionMethods.Conflict.Test
{
[TestFixture]
public class ConflictExtensionTest
{
[Test]
public void ConflictTest()
{
TestMe me = new TestMe();
int result = me.Conflict();
Assert.That(result, Is.EqualTo(-1));
}
}
}
</code></pre>
<p>Notice that the namespace where you use it is longer.</p>
<p>Now you reference a dll with this:</p>
<pre><code>namespace Example.ExtensionMethods.Conflict
{
public static class ConflictExtension
{
public static int Conflict(this TestMe obj)
{
return 1;
}
}
}
</code></pre>
<p>And your Test will fail! It will compile without a compiler error. It will <strong>simply fail</strong>. Without you even having to specify "using Example.ExtensionMethods.Conflict". The compiler will walk the namespace name and find Example.ExtensionMethods.Conflict.ConflictExtension before Example.ExtensionMethods.Extension and will use that <strong>without ever complaining about ambiguous extension methods</strong>. Oh the horror!</p>
| <p>Some curiosities:</p>
<ul>
<li>extension methods might be called on <code>null</code> instances; this might be confusing (but sometimes useful)</li>
<li>the "hiding" issue is a biggie if they have different intent</li>
<li>equally, you might get a different extension method with the same name from 2 different namespaces; if you only have <em>one</em> of the two namespaces, this could lead to inconsistent behaviour (depending on which)...</li>
<li>...but if somebody adds a <em>similar</em> (same signature) extension method in a second namespace that your code uses, it will break at compile time (ambiguous)</li>
</ul>
<p>(<strong>edit</strong>) And of course, there is the "<code>Nullable<T></code>/<code>new()</code>" bomb (<a href="http://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/194671#194671">see here</a>)...</p>
|
Extending WebFormView in MVC <p>I want to extend the WebFormViewEngine so that I can perform some post-processing - I want it to do it's stuff, then hand me the Html back, so I can do put some final touches to it. It needs to be done as a View/ViewEngine because I need access to the ViewData.</p>
<p>Unfortunately there seems to be no way to get the Html back from the WebFormView, and no way to hand a custom HtmlTextWriter to the WebFormView or ViewPage.</p>
<p>Surely there's a way to do this? No?</p>
<p>Littlecharva</p>
| <p>You can use Action Filters to do this. Check out <a href="http://www.asp.net/LEARN/mvc/tutorial-14-cs.aspx" rel="nofollow">this tutorial</a> at asp.net/mvc. You want to use a ResultsFilter.</p>
<p>As an alternate, you can override the virtual OnResultExecuted method of the Controller.</p>
|
Maximum number of workable tables in SQL Server And MySQL <p>I know that in SQL Server, the maximum number of "objects" in a database is a little over 2 billion. Objects contains tables, views, stored procedures, indexes, among other things . I'm not at all worried about going beyond 2 billion objects. However, what I would like to know, is, does SQL Server suffer a performance hit from having a large number of tables. Does each table you add have a performance hit, or is there basically no difference (assuming constant amount of data). Does anybody have any experience working with databases with thousands of tables? I'm also wondering the same about MySQL.</p>
| <p>No difference, assuming constant amount of data.</p>
<p>Probably a gain in practical terms because of things like reduced maintenance windows (smaller index rebuilds), ability to have read-only file groups etc.</p>
<p>Performance is determined by queries and indexes (at the most basic level): not number of objects</p>
|
Install PHP 5 without libxml2 <p>I am trying to install a copy of PHP 5 to my home directory on the school computer. The problem is that whenever I try, it complains that my copy of libxml2 is too outdated to work.</p>
<p>Is there any way I can install this <strong>without</strong> upgrading libxml2, since I don't have permission to upgrade.</p>
<p>Any suggestions?</p>
| <p>Alternatively, you can make an install of libxml in your home directory and pass configure the location where you've installed it, i.e.</p>
<pre><code>--with-libxml-dir=<your local install>
</code></pre>
<p>When installing libxml, you just have to use the <code>--prefix=</code> option with configure to indicate that you don't want to do a system install.</p>
<p>Assuming that you compiled the cli client (and that the lib search path for the current user and the apache user are the same), you check that the correct lib is linked with:</p>
<pre><code># ldd /usr/bin/php
linux-vdso.so.1 => (0x00007ffff71ff000)
libcrypt.so.1 => /lib64/libcrypt.so.1 (0x00000030f3c00000)
libedit.so.0 => /usr/lib64/libedit.so.0 (0x00000030e8000000)
libncurses.so.5 => /lib64/libncurses.so.5 (0x00000030f7400000)
libgmp.so.3 => /usr/lib64/libgmp.so.3 (0x00000030e7800000)
libbz2.so.1 => /lib64/libbz2.so.1 (0x00000030f7800000)
libz.so.1 => /lib64/libz.so.1 (0x00000030e6c00000)
libpcre.so.0 => /lib64/libpcre.so.0 (0x00000030f9400000)
librt.so.1 => /lib64/librt.so.1 (0x00000030e7000000)
libm.so.6 => /lib64/libm.so.6 (0x00000030e5c00000)
libdl.so.2 => /lib64/libdl.so.2 (0x00000030e6400000)
libnsl.so.1 => /lib64/libnsl.so.1 (0x00000030f6800000)
libxml2.so.2 => /usr/lib64/libxml2.so.2 (0x00000030f2400000))
libssl.so.10 => /usr/lib64/libssl.so.10 (0x00000030f3000000)
libcrypto.so.10 => /usr/lib64/libcrypto.so.10 (0x00000030eb400000)
libc.so.6 => /lib64/libc.so.6 (0x00000030e6000000)
libresolv.so.2 => /lib64/libresolv.so.2 (0x00000030e7c00000)
libfreebl3.so => /lib64/libfreebl3.so (0x00000030f3800000)
libtinfo.so.5 => /lib64/libtinfo.so.5 (0x00000030f7c00000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00000030e6800000)
/lib64/ld-linux-x86-64.so.2 (0x00000030e5800000)
</code></pre>
<p>libxml is listed half-way down the library list.</p>
|
View all link within <h1></h1>, need to set style on it, to make link small <p>I am trying to make the "view all" link to the right of each h1 header to be smaller.</p>
<pre><code>.view-all a:link,
.view-all a:visited {
text-size:.5em;
}
<h1>Student Activities <span class="view-all">
<a href="/student_activities/calendar/" title="view all">
view all</a></span></h1>
</code></pre>
<p>Any help is appreciated as to what I am doing wrong.</p>
<p>All of this is within <code><div class="content-body"></div></code></p>
<p>If there is a better way of doing this, let me know.</p>
<p>Thanks.</p>
| <p>Try font-size instead. </p>
|
Counting with an Integer Divide-based routine - Is there a formulaic approach? <p>Consider a routine that counts by successive divide w/ remainder operations. </p>
<p>Starting with a 64-bit dividend, the routine divides by a constant divisor.<br />
If the remainder is 0, the routine returns.<br />
Otherwise, a new dividend is constructed by multiplying the remainder by 2^32 and adding the integer quotient. </p>
<p>In code: </p>
<pre><code>/// ULong - 64 bit, unsigned
/// UInt - 32 bit, unsigned
const UInt Divisor;
int TrickyCounter( ULong Dividend)
{
int count = 0;
Ulong Quotient;
UInt Remainder;
do {
Quotient = Dividend/Divisor;
Remainder = Dividend%Divisor;
assert((Quotient >> 32) == 0);
count = count + 1;
Dividend = ((ULong)Remainder << 32) + Quotient;
} while (Remainder != 0);
return count;
}
</code></pre>
<p>With an arbitrary Divisor, is there a preferably non-iterating method to calculate the necessary Dividend to get the desired count?<br />
For many initial dividends, this seems to quickly hit the "Assert" condition. Would some dividends cause this to loop forever? </p>
<p><hr />
If, instead of a count, the routine returns the quotient, can I calculate the Dividend to produce the number I want returned? </p>
<pre><code>Uint TrickyNumber( ULong Dividend, int count)
{
Ulong Quotient = 0;
UInt Remainder;
while (count > 0)
Quotient = Dividend/Divisor;
Remainder = Dividend%Divisor;
assert((Quotient >> 32) == 0);
count = count - 1;
Dividend = ((ULong)Remainder << 32) + Quotient;
}
return (UInt)Quotient;
}
</code></pre>
| <blockquote>
<p>Would some dividends cause this to loop forever? </p>
</blockquote>
<p>Dividend = 0x1ffffffffL, Divisor = 2 is a fairly obvious example, and the whole family (Divisor<<32)-1, Divisor are fixed points.</p>
<p>Working from these, many cyclic combinations of initial dividend and divisor can be found, and I'm sure there are more:</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
size_t tricky_counter( uint64_t dividend, const uint32_t divisor )
{
const size_t cycle_buffer_size = 1024;
size_t count = 0;
uint64_t quotient;
uint32_t remainder;
uint64_t pre[cycle_buffer_size];
do {
pre[ count % cycle_buffer_size ] = dividend;
quotient = dividend/divisor;
remainder = dividend%divisor;
if ( (quotient >> 32) != 0) {
printf("quotient: 0x%" PRIx64 "\n", quotient);
}
count = count + 1;
dividend = ((uint64_t)remainder << 32) + quotient;
for (size_t i = 0; i < count && i<cycle_buffer_size;++i) {
if (pre[i] == dividend) {
size_t cycle = 0;
printf("dividend repeats: \n");
while (i != count % cycle_buffer_size) {
//~ printf(" 0x%" PRIx64 " / %" PRId32 " \n", pre[i], divisor);
i = (i + 1) % cycle_buffer_size;
++cycle;
}
printf(" 0x%" PRIx64 " / %" PRId32 " cycle size %zd \n", dividend, divisor, cycle);
return 0;
}
}
} while (remainder != 0);
return count;
}
int main ( void )
{
for (uint64_t k = 1; k < 256; ++k)
for (uint64_t x = 2; x < 1024; ++x)
tricky_counter( (x-1 << 32) + 0x01010101L * k, x);
}
</code></pre>
|
Why are these Div tags not nesting properly? <p>If anyone can give any insight here it would be very much appreciated. I want to create output that shows reservations in fitness classes on various dates. The idea is to have three across and however many rows are needed to cover all of the dates. To do this, I'd like to use CSS rather than resorting to tables.</p>
<p>Ok, so I have the following CSS definitions:</p>
<pre><code>.ListSetContainer
{
background-color:Red;
border:1px solid #999999;
text-align:center;
}
.ListSet
{
margin: 2px 2px 2px 16px;
float: left;
clear:none;
}
.ListSet ul
{
background-color: #EEEEEE;
border: 1px solid #999;
margin: 2px 2px 16px 2px;
padding: 6px 6px 0px 6px;
}
</code></pre>
<p>And the following HTML:</p>
<pre><code> <div style="clear:both;">
<h4>Class Dates, Counts and Participants</h4>
<div class='ListSetContainer'>
<div class='ListSet'>
<ul>...{Class information here...}
</ul>
</div>
<div class='ListSet'>
<ul>...{Class information here...}
</ul>
</div>
<div class='ListSet'>
<ul>...{Class information here...}
</ul>
</div>
</div> -- End of First ListSetContainer
<div class='ListSetContainer'>
<div class='ListSet'>
<ul>...{Class information here...}
</ul>
</div>
<div class='ListSet'>
<ul>...{Class information here...}
</ul>
</div>
</div> -- End of Second ListSetContainer
</div> -- End of surrounding Div
</code></pre>
<p>But rather than getting three divs arranged horizontally, followed by a second row with two divs, I'm getting this:</p>
<p><a href="http://www.bsdi.cc/images/divproblem.png" rel="nofollow">Linked Image</a></p>
<p>A few notes. First, notice that the hierarchy in the HTML (ListSetContainer divs contain the ListSet divs) is not reflected in the output. Second, the ListSetContainer div is only one pixel high - there is no background shown! (I'm using a Red background just to be sure I don't miss it). The whole enclosing div is just squashed down and the inner divs are floating out on their own. Setting the height manually doesn't work because the inner div with the list is variable height (and it looks odd, to boot). If I remove the float:left; from the inner divs, they expand to be the full width of the screen and thus I cannot get three in a row. So...I'm at a loss.</p>
<p>Again, thanks for any help you can offer!</p>
| <p>Your ListSetContainer needs to contain some non-floated content for it to hava a height/width. Floating an element takes it out of the normal layout hierarchy and thus the container, containing only the ListSets, doesn't contain anything that gets rendered normally. Add a non-breaking space to the container, then you should be able to set its width/height as there will be something in it to render.</p>
<p>I would also have your ListSetContainer use <code>clear: both</code>. This should make it start a new "row" of ListSets.</p>
|
How can I set autoincrement format to 0001 in MySQL? <p>How can I make MySQL auto increment in 4 digit format?</p>
<p>So instead of '1' make '0001'?</p>
| <p>Try adding ZEROFILL attribute to the field.</p>
|
Anyway to error check PHP in Dreamweaver? <p>I do all my PHP coding in Dreamweaver (currently version CS3) I am used to it and like it. There is one thing I would like though, is to be able to check for errors. Currently I don't see them until I upload the page to a server. Is there anyway to setup PHP error checking in Dreamweaver?</p>
<p>Thanks.</p>
| <p>Do you mean as you type? Since PHP isn't compiled, it's not as easy to do as with a language like Java or C#. The closest you can come to that is with <a href="http://www.icosaedro.it/phplint/" rel="nofollow">PHPLint</a>. Unfortunately, you have to do some hackery with Cygwin to get it to work under Windows.</p>
<p>I know that this isn't what you asked for, but Dreamweaver is not a very good editor for PHP. It lacks many features and isn't really meant to be used mainly for PHP. Try these editors, which have on-the-go error checking:</p>
<ul>
<li><a href="http://www.eclipse.org/pdt/" rel="nofollow">Eclipse
PDT</a></li>
<li><a href="http://www.zend.com/en/products/studio/" rel="nofollow">Zend
Studio</a> </li>
<li><a href="http://www.activestate.com/komodo%5Fedit/" rel="nofollow">Komodo
Edit</a></li>
</ul>
<p>If you mean how can you setup your system so you can test PHP locally on your computer without the need to upload it to the web, you need a web server on your computer. I highly recommend <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow">Xampp</a>. It's an all-in-one package to install Apache, MySQL, PHP, and more on your computer and has a spiffy control panel.</p>
|
Continuous Integration stack on Windows with Mercurial + Mercurial Queues? <p>We've been using Mercurial with Mercurial Queues (+guards for patches) for source control of a number of Windows ASP.Net projects. </p>
<p>I'm interested in setting up a Continuous Integration environment for this but am getting lost in conflicting reports of success with CC/Trac etc. </p>
<p>I'm wondering who else out there is doing this and what your working stack of apps/utils is? Also, if you've got hints on workflow, I'm all ears :) </p>
<p>Appreciation in advance!</p>
| <p>We use hudson and mercurial together and have been quite successful. They are both flexible enough to about anything you want.</p>
|
Preventing directory traversal with web-facing application - are regular expressions bullet-proof? <p>I am in a situation where I need to allow a user to download a file dynamically determined from the URL. Before the download begins, I need to do some authentication, so the download has to run through a script first. All files would be stored outside of the web root to prevent manual downloading.</p>
<p>For example, any of the following could be download links:</p>
<ul>
<li><a href="http://example.com/downloads/companyxyz/overview.pdf" rel="nofollow">http://example.com/downloads/companyxyz/overview.pdf</a></li>
<li><a href="http://example.com/downloads/companyxyz/images/logo.png" rel="nofollow">http://example.com/downloads/companyxyz/images/logo.png</a></li>
<li><a href="http://example.com/downloads/companyxyz/present/ppt/presentation.ppt" rel="nofollow">http://example.com/downloads/companyxyz/present/ppt/presentation.ppt</a></li>
</ul>
<p>Basically, the folder depth can vary.</p>
<p>To prevent a directory traversal, like say:
<a href="http://example.com/downloads/../../../../etc/passwd" rel="nofollow">http://example.com/downloads/../../../../etc/passwd</a>
I need to obviously do some checking on the URI. (Note: I do not have the option of storing this info in a database, the URI must be used)</p>
<p>Would the following regexp be bullet-proof in making sure that a user doesnt enter something fishy:</p>
<pre><code>preg_match('/^\/([-_\w]+\/)*[-_\w]+\.(zip|gif|jpg|png|pdf|ppt|png)$/iD', $path)
</code></pre>
<p>What other options of making sure the URI is sane do I have? Possibly using realpath in PHP?</p>
| <p>I would recommend using <a href="http://www.php.net/manual/en/function.realpath.php"><code>realpath()</code></a> to convert the path into an absolute. Then you can compare the result with the path(s) to the allowed directories.</p>
|
MVC Ajax UpdatePanel <p>I know (at least i'm pretty sure) there isn't a control for MVC like the asp:UpdatePanel. Can anyone give me some idea on how to do this.</p>
<p>I have a collection that i add entries to from my repository & services layers. in my masterpage i would like to show an alert depending on if there is anything in this collection.</p>
<p>Normally i would have an UpdatePanel whose UpdateMode="Always" and it would check the collection and display my messages.</p>
<p>Do you know how i can achieve something similiar in MVC?</p>
| <p>Stay away from the UpdatePanel concept all together.</p>
<p>ASP.NET MVC includes jQuery, which is fully supported by Microsoft now. You will want to create partial views (RenderPartial) that make calls back to a method on a controller, that returns JSON.</p>
<p>Then, use jQuery to wire up the control and partial views.</p>
<p>jQuery is an extremely powerful javascript library. I highly recommend the <a href="http://rads.stackoverflow.com/amzn/click/1933988355" rel="nofollow">book jQuery in Action</a> as a reference when diving into the ASP.NET MVC /Scripts/jquery-x.x.x.js files. :)</p>
|
How to extract leaf nodes from Oracle XMLTYPE <p>I want to extract only the leaf nodes from an XMLTYPE object in Oracle 10g</p>
<pre><code>SELECT
t.getStringVal() AS text
FROM
TABLE( XMLSequence(
XMLTYPE(
'<xml>
<node>
<one>text</one>
</node>
<node>
<two>text</two>
</node>
<node>
<three>text</three>
</node>
</xml>'
).extract( '//*' )
) ) t
</code></pre>
<p>What should I use as the WHERE clause so this returns only these:</p>
<pre><code> <one>text</one>
<two>text</two>
<three>text</three>
</code></pre>
<p>I've tried the following but they don't work:</p>
<pre><code>WHERE t.existsNode( '//*' ) = 0
WHERE t.existsNode( '/.//*' ) = 0
WHERE t.existsNode( './/*' ) = 0
</code></pre>
<p>What am I missing?</p>
| <p>Nevermind, I found it:</p>
<pre><code>WHERE
t.existsNode( '/*//*' ) = 0
</code></pre>
|
SqlTransaction has completed <p>I have an application which potentially does thousands of inserts to a SQL Server 2005 database. If an insert fails for any reason (foreign key constraint, field length, etc.) the application is designed to log the insert error and continue.</p>
<p>Each insert is independent of the others so transactions aren't needed for database integrity. However, we do wish to use them for the performance gain. When I use the transactions we'll get the following error on about 1 out of every 100 commits.</p>
<pre><code>This SqlTransaction has completed; it is no longer usable.
at System.Data.SqlClient.SqlTransaction.ZombieCheck()
at System.Data.SqlClient.SqlTransaction.Commit()
</code></pre>
<p>To try to track down the cause I put trace statements at every transaction operation so I could ensure the transaction wasn't being closed before calling commit. I've confirmed that my app wan't closing the transaction.
I then ran the app again using the exact same input data and it succeeds.</p>
<p>If I turn the logging off it fails again. Turn it back on and it succeeds. This on/off toggle is done via the app.config without the need to recompile.</p>
<p>Obviously the act of logging changes the timing and causes it to work. This would indicate a threading issue. However, my app isn't multi-threaded.</p>
<p>I've seen one MS KB entry indicating a bug with .Net 2.0 framework could cause similar issues (<a href="http://support.microsoft.com/kb/912732" rel="nofollow">http://support.microsoft.com/kb/912732</a>). However, the fix they provided doesn't solve this issue.</p>
| <p>Difficult to help without seeing code. I assume from your description you are using a transaction to commit after every N inserts, which will improve performance vs committing each insert provided N is not too big.</p>
<p>But the downside is: if an insert fails, any other inserts within the current batch of N will be rolled back when you rollback the transaction. </p>
<p>In general you should dispose a transaction before closing the connection (which will rollback the transaction if it hasn't been committed). The usual pattern looks something like the following:</p>
<pre><code>using(SqlConnection connection = ...)
{
connection.Open();
using(SqlTransaction transaction = connection.BeginTransaction())
{
... do stuff ...
transaction.Commit(); // commit if all is successful
} // transaction.Dispose will be called here and will rollback if not committed
} // connection.Dispose called here
</code></pre>
<p>Please post code if you need more help.</p>
|
Java InputStream blocking read <p>According to the java api, the <code>InputStream.read()</code> is described as:</p>
<blockquote>
<p>If no byte is available because the
end of the stream has been reached,
the value -1 is returned. This method
blocks until input data is available,
the end of the stream is detected, or
an exception is thrown.</p>
</blockquote>
<p>I have a <code>while(true)</code> loop doing a read and I always get -1 when nothing's sent over the stream. That's expected.</p>
<p>My question is when would read() ever block? Since if it doesn't get any data it returns -1. I would expect a blocking read to wait until data is received. If you've reached the end of the input stream, shouldn't read() simply wait for data instead of returning -1?</p>
<p>Or does read() only block if there's another thread accessing the stream and your read() cannot access the stream? </p>
<p><hr /></p>
<p>Which leads me to my next question. I used to have event listener (provided by my library) that would notify me when data is available. When I was notified I would call <code>while((aByte = read()) > -1)</code> store the byte. I was puzzled when I'd get TWO events in very close time proximity and not all my data was being displayed. It seemed like only the tail end of the second event's data would be displayed and the the rest was missing.</p>
<p>I eventually changed my code so that when I get an event I'd called <code>if(inputStream.available() > 0) while((aByte = read()) > -1)</code> store the byte. Now it worked properly and all my data was displayed.</p>
<p>Can someone explain this behavior? The <code>InputStream.available()</code> is said to return the number of bytes you can read before blocking the next caller (of the stream?). Even if I don't use .available() I would expect the read of the first event to just block the read of the second event, but not erase or consume too much stream data. Why would doing this cause not all of my data to be displayed?</p>
| <p>The underlying data source for some implementations of <code>InputStream</code> can signal that the end of the stream has been reached, and no more data will be sent. Until this signal is received, read operations on such a stream can block. </p>
<p>For example, an <code>InputStream</code> from a <code>Socket</code> socket will block, rather than returning EOF, until a TCP packet with the FIN flag set is received. When EOF is received from such a stream, you can be assured that all data sent on that socket has been reliably received, and you won't be able to read any more data. (If a blocking read results in an exception, on the other hand, some data may have been lost.)</p>
<p>Other streams, like those from a raw file or serial port, may lack a similar format or protocol to indicate that no more data will be available. Such streams can immediately return EOF (-1) rather than blocking when no data are currently available. In the absence of such a format or protocol, however, you can't be sure when the other side is done sending data.</p>
<hr>
<p>With regard to your second question, it sounds like you may have had a race condition. Without seeing the code in question, I'm guessing that the problem actually lay in your method of "display". Perhaps the attempt to display by the second notification was somehow clobbering the work done during the first notification.</p>
|
Generating a WiX XML file at build and components questions <p>I am trying to write an installer for a website I created. In the WiX tutorial it says "Again, a component should only contain items that belong together so strongly that they always need to be installed or removed together.". I believe an entire website fits this description. I have 2 issues regarding components. The first is that obviously my website has many directories and I cannot figure out how to get all the directories/files into 1 component (is this even possible?) and that if I generate my components from a program my GUID would almost certainly have to be different on each build forcing a Major version change with each release? Is there something I am missing?</p>
| <p>A Component's Files cannot span directories. Limitiation of the Windows Installer. Getting stable Component Ids is a tricky problem, but there are a few new tricks in WiX v3 that can handle this for you. The Component/@Guid="*" is the trick. The new (like last week) heat.exe will generate Fragments for you that seem to meet your needs.</p>
|
Which Java oriented lexer parser for simple project (ANTLR, DIY, etc) <p>I am working on a small text editor project and want to add basic syntax highlighting for a couple of languages (Java, XML..just to name a few). As a learning experience I wanted to add one of the popular or non popular Java lexer parser.</p>
<p>What project do you recommend. Antlr is probably the most well known, but it seems pretty complex and heavy.</p>
<p>Here are the option that I know of.</p>
<ol>
<li>Antlr</li>
<li>Ragel (yes, it can generate Java source for processing input)</li>
<li>Do it yourself (I guess I could write a simple token parser and highlight the source code).</li>
</ol>
| <p>ANTLR or JavaCC would be the two I know. I'd recommend ANTLR first.</p>
|
MS SQL Server 2008 - Confusion in migrating from MySQL re: "select XYZ from TABLE" <p>So I'm just confused here.</p>
<p>I've got to migrate my database from MySQL to MS SQL Server 2008. I've transferred the data via the "MS SQL Data Wizard" app from SQL Maestros. It took the data+structure from my MySQL database "gk" and copied it into a database "gk" on my MS SQL Express instance.</p>
<p>But when I connect to the MS SQL instance and try to run an SQL query, I only get results when I execute "<code>select * from gk.TABLENAME</code>" or "<code>select * from gk.gk.TABLENAME</code>"... If I execute "<code>select * from TABLENAME</code>" after executing "<code>use gk</code>", I get:</p>
<blockquote>
<p>Error: Invalid object name 'TABLENAME'<br>
SQLState: S0002<br>
Error code: 208</p>
</blockquote>
<p>How do I make this behave "normally"? I.e., I connect to a specific database such that I don't have to explicitly tell it in which database/schema to find the table?</p>
<p><strong>UPDATE:</strong>
I should specify the structure that was created by the SQL Data Wizard app. Looking at the object browser tree on the SQL Server Management Studio, there's this:</p>
<pre><code>[HOSTNAME]\SQLEXPRESS (SQL Server ...)
|-- Databases
|-- System Databases
|-- gk
|...
|-- Tables
|-- TABLE1
|-- TABLE2
|-- TABLE3
</code></pre>
<p>... and so on.</p>
<p>Thanks.
-dan</p>
| <p>Try this, if you haven't already:</p>
<pre><code>USE gk
GO
SELECT * FROM tablename
</code></pre>
|
Start Directory in Windows Explorer running Vista not set properly? <p>When I right click on Windows Explorer, select Properties, it opens a panel, I set the value of "Start In" to "C:\", which means I want it to point to my C: drive when I open explorer, but it's not working, it always points to "Documents". On XP I did the same thing and it worked, but now I got this new PC with Vista, it doesn't work? How to fix this?</p>
| <p>Use the explorer start params, e.g.,:</p>
<pre><code>%SystemRoot%\explorer.exe /e,D:\Downloads
</code></pre>
|
Which generic collection to use? <p>I have 2 separate classes:</p>
<ul>
<li>AreaProperties </li>
<li>FieldProperties</li>
</ul>
<p>1 AreaProperties can map to 1 FieldProperties. Without changing the design, I want a method to return a <code>List<></code> of these objects</p>
<p>What generic collection in C# would be suitable?</p>
<p>I understand I can send 2 Lists and the function would look like:</p>
<pre><code>public List<AreaProperties> Save(ref List<FieldProperties>)
{
..code
}
</code></pre>
<p><strong>EDIT:
Dror Helper's solution sounds good. However, I recently found out that there is no 1:1 between FieldProperties and AreaProperties.
How would I now handle this. I still want to go with a custom class that has an object of FieldProperties and AreaProperties but how would I handle the 1 to many scenario?</strong></p>
| <p>You can create a class/struct that has two members - AreaProperties & FieldProperties and return a list of that class</p>
<pre><code>class Pair<T1, T2>
{
T1 t1;
T2 t2;
}
List<Pair<AreaProperties, FieldProperties>> Save(){ ...}
</code></pre>
<p>Or use System.Collections.Generic.KeyValuePair instead (per Patrick suggestion below)</p>
<pre><code>List<KeyValuePair<AreaProperties, FieldProperties>> Save(){ ... }
</code></pre>
<p>This way you keep the 1..1 relation as well.</p>
<p><strong>Edit:</strong>
In case you need 1..n relation I think you want to return
List>> instead this way you have a list of Field Properties for each AreaProperties you get back and you still keep the relation between them. </p>
|
Fail to install my NetBeans plugin <p>Playing around with creating a NetBeans plugin but I am making very little progress since the process of installing the module fails. What I am doing is right-clicking on the and choosing the 'Install/Reload in Development IDE' option and it fails with the following exception:</p>
<pre><code>Enabling StandardModule:org.willcodejavaforfood.com jarFile: /Users/Erik/NetBeansProjects/module2/build/cluster/modules/org-willcodejavaforfood-com.jar...
java.io.IOException: Cannot enable StandardModule:org.willcodejavaforfood jarFile: /Users/Erik/NetBeansProjects/module2/build/cluster/modules/org-willcodejavaforfood.jar; problems: [Java > 1.6]
at org.netbeans.core.startup.ModuleSystem.deployTestModule(ModuleSystem.java:358)
at org.netbeans.core.startup.TestModuleDeployer.deployTestModule(TestModuleDeployer.java:68)
at org.netbeans.modules.apisupport.ant.InstallModuleTask.execute(InstallModuleTask.java:77)
at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
at sun.reflect.GeneratedMethodAccessor176.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
at org.apache.tools.ant.Task.perform(Task.java:348)
at org.apache.tools.ant.Target.execute(Target.java:357)
at org.apache.tools.ant.Target.performTasks(Target.java:385)
at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1337)
at org.apache.tools.ant.Project.executeTarget(Project.java:1306)
at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
at org.apache.tools.ant.Project.executeTargets(Project.java:1189)
at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:273)
at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:499)
at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
</code></pre>
<p>Using NetBeans 6.5 and running Java 1.6 on Mac OS X 10.5.6</p>
| <p>Apperently this is a NetBeans issue for Mac OS X...</p>
<p><a href="http://forums.netbeans.org/viewtopic.php?p=26822#26822" rel="nofollow">Answer from netbeans forums</a></p>
|
Any way to make XmlSerializer output xml in a defined order? <p>Currently I'm using XmlSerializer to serialize and deserialize an object. The xml is generated in an undefined order which is understandable but makes it annoying when comparing versions of the object, since the order of properties is different each time. So for instance I can't use a normal diff tool to see any differences.</p>
<p>Is there an easy way to generate my xml in the same order every time, without writing the ReadXml and WriteXml methods myself? I have a lot of properties on the class, and add new ones every now and again, so would prefer to not have to write and then maintain that code.</p>
<p>(C# .net 2.0)</p>
| <p>The XmlElement attribute has an <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.order.aspx">order property</a>. You can use that as a start.</p>
<p>If you need to find the diff in Xml files, you might want to take a look at <a href="http://msdn.microsoft.com/en-us/library/aa302294.aspx">this</a>.</p>
|
WCF Server without config file <p>I'm tired of dealing with config files so I'm trying to setup a WCF service in code only.</p>
<p>So far I have this:</p>
<pre><code> m_ServiceHost = New ServiceHost(Me)
m_ServiceHost.AddServiceEndpoint(
GetType(Aam.AamServiceFramework.IServiceMonitor),
New NetTcpBinding, "net.tcp://localhost:6000)
m_ServiceHost.AddServiceEndpoint(
GetType(IMetadataExchange),
New NetTcpBinding, "net.tcp://localhost:6500)
m_ServiceHost.Open()
</code></pre>
<p>This works if I comment out the IMetadataExchange. How do I handle that piece?</p>
| <pre><code> m_ServiceHost.Description.Behaviors.Add(New ServiceMetadataBehavior())
m_ServiceHost.AddServiceEndpoint(
GetType(IMetadataExchange),
MetadataExchangeBindings.CreateMexTcpBinding(),
"net.tcp://localhost:6595")
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.