instruction stringlengths 0 30k ⌀ |
|---|
Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :).
Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation. |
I suppose you could do something like this:
#!/bin/bash
result=$( osascript << END
tell app "System Events"
set a to display dialog "What shall be the result?" default answer ""
end tell
return text returned of a
END
)
# do stuff with $result |
I don't think so. *a.concat(b)* is implemented in String and I think the implementation didn't change much since early java machines. The + operation implementation depends on java version and compiler. Currently + is implemented using StringBuffer to make the operation as fast as possible. Maybe in future this will change. In earlier versions of java + operation on Strings was much slower as it produced intermediate results. I guess that += is implemented using + and similarly optimized. |
Niyaz is correct, but it's also worth noting that the special + operator can be converted into something more efficient by the Java compiler. Java has a StringBuilder class which represents a non-thread-safe, mutable String. When performing a bunch of String concatenations, the Java compiler silently converts
String a = b + c + d;
into
String a = new StringBuilder(b).append(c).append(d).toString();
which for large strings is significantly more efficient. As far as I know, this does not happen when you use the concat method.
However, the concat method is more efficient when concatenating an empty String onto an existing String. In this case, the JVM does not need to create a new String object and can simply return the existing one. See the concat documentation to confirm this: http://java.sun.com/javase/6/docs/api/java/lang/String.html#concat(java.lang.String)
So if you're super-concerned about efficiency then you should use the concat method when concatenating possibly-empty Strings, and use + otherwise. However, the performance difference should be negligible and you probably shouldn't ever worry about this. |
[RowTest]
[Row("GoodName")]
[Row("GoodName2")]
public void Should_validate_username()
{
}
[RowTest]
[Row("BadUserName")]
[Row("Bad%!Name")]
public void Should_invalidate_username()
{
}
This might make more sense for more complex types of validation really. |
All the VS 2008 wizard does is upgrade the project & solution files to be used with VS 2008 - it still targets the framework you started with. If you want to move your projects to a newer version of the framework, you'll have to edit the project settings on each. Too much of a chance of breaking changes for MSFT to do this automatically. |
A compressed folder doesn't mean that it will be a .ZIP file, only the contents of the folder are compressed and to you it will look like a normal folder |
Apart from the target framework feature, you'll need to manually add a reference to System.Core.dll to utilise some of the latest features like Linq. |
If you're willing to put a vtable in the class you're exporting, you can export a function that returns an interface and implement the class in the .dll, then put that in the .def file. You might have to do some declaration trickery, but it shouldn't be too hard.
Just like COM. :)
MSN |
How to set encoding in .getJSON JQuery |
|jquery| |
In my web app, i submit some form fields with JQuery $.getJSON() Method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1 but i think this fields are submitted with UTF-8.
Does anyone know, how can i set encoding in $.getJSON calls? |
|jquery|ajax|json|character-encoding| |
I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly without knowing the kinds of errors you're seeing. A rough guess would be that usec can never be > 999999.
Anyway. Why not store the utime and stime components as float seconds rather than trying to build your own rusage on output? I'm pretty sure the following will give you proper seconds.
static int timeval_diff_ms(timeval const& end, timeval const& start) {
int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000
+ end.tv_usec - start.tv_usec;
return micro_seconds;
}
static float timeval_diff(timeval const& end, timeval const& start) {
return (timeval_diff_ms(start, end)/1000000.0f);
}
If you want to decompose this back into an rusage, you can always int-div and modulo.
|
I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly without knowing the kinds of errors you're seeing. A rough guess would be that usec can never be > 999999.
Anyway. Why not store the utime and stime components as float seconds rather than trying to build your own rusage on output? I'm pretty sure the following will give you proper seconds.
static int timeval_diff_ms(timeval const& end, timeval const& start) {
int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000
+ end.tv_usec - start.tv_usec;
return micro_seconds;
}
static float timeval_diff(timeval const& end, timeval const& start) {
return (timeval_diff_ms(end, start)/1000000.0f);
}
If you want to decompose this back into an rusage, you can always int-div and modulo.
|
My advice is this. Try to keep the installer as simple as possible. Windows Installer is a very complicated piece of software and when things don't work right it can be hard to figure out what's going on. I'm sure we have all experienced the endless loop of Windows Installer trying to repair a file that you no longer have the source .msi file for.
Most of the time using Windows Installer is like using a sledge hammer to crack a nut.
I use InnoSetup for my own stuff and InstallShield at work (against my will). Start with a simple script based installer and only use Windows Installer if you have a good reason to.
Note that support for installing assemblies to the GAC may be missing for some non Windows Installer setup tools (such as InnoSetup). |
I think you're right to worry that the wiki thing wouldn't be hands-on enough.
How about using it as an opportunity to refresh your process too, and do a mini project "Bootcamp" where you test drive the new language and IDE features along with some new development practices. Actually create a piece of software over the course of a week or so.
|
MS has [Visual Studio training kit][1]. I think the best way is to teach the basics and then start using it in projects. Let them learn the features they need as they are using it on a project.
[1]: http://www.microsoft.com/downloads/details.aspx?FamilyID=8BDAA836-0BBA-4393-94DB-6C3C4A0C98A1&displaylang=en |
I agree with John. But there was another question that was not answered.<br />
I have done this but instead of using a database we used a flat file, it did eventually cripple the server, but it wasn't until we has ~450 active users, and if we had done it with a database it probably would have fared better.<br />This was done on a basic hosting account from Godaddy.
Edit: BTW Godaddy sounded less then amused when I got the phone call. |
I'm not at all familiar with the inner workings of the UNIX file systems, as in how the bits and bytes are stored, but really that part is interchangeable ([ext3][1], [reiserfs][2], etc).
When people say that UNIX file systems are better, they might mean to be saying, "Oh ext3 stores bits in such as way that corruption happens way less than NTFS", but they might also be talking about design choices made at the common layer above. They might be referring to how the path of the file does not necessarily correspond to any particular device. For example, if you move your program files to a second disk, you probably have to refer to them as "D:\Program Files", while in UNIX /usr/bin could be a hard drive, a network drive, a CD ROM, or RAM.
Another possibility is that people are using "file system" to mean the organization of paths. Like, for instance, how Windows generally likes programs in "C:\Program Files\CompanyName\AppName" while a particular UNIX distribution might put most of them in /usr/local/bin. In the later case, you can access much more of your system readily from the command line with a much smaller PATH variable.
Also, since you mentioned grep, if all the source code for system libraries such as the kernel and libc is stored in /usr/local/src, doing a recursive grep for a particular error message coming from the guts of some system library is much simpler than if things were laid out as /usr/local/library-name/[bin|src|doc|etc]. If you already have an inkling of where you're searching, though, cygwin grep performs quite well under Windows. In fact, I find for full-text searching I get better results from grep than the search facilities built into Windows!
[1]: http://en.wikipedia.org/wiki/Ext3
[2]: http://en.wikipedia.org/wiki/ReiserFS |
No, not quite.
Firstly, there's a slight difference in semantics. If a is null, then the latter NPEs but the former will treat the original value of a as if it were "null".
To look under the hood, write a simple class with a += b;
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:
java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn
So, a += b is the equivalent of
a = new StringBuilder()
.append(a)
.append(b)
.toString();
The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.
The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.
|
T-SQL implementation, adapted from [dbo.UrlEncode](http://www.sqljunkies.com/WebLog/peter_debetta/archive/2007/03/09/28987.aspx):
CREATE FUNCTION dbo.Slug(@string varchar(1024))
RETURNS varchar(3072)
AS
BEGIN
DECLARE @count int, @c char(1), @i int, @slug varchar(3072)
SET @string = replace(lower(ltrim(rtrim(@string))),' ','-')
SET @count = Len(@string)
SET @i = 1
SET @slug = ''
WHILE (@i <= @count)
BEGIN
SET @c = substring(@string, @i, 1)
IF @c LIKE '[a-z0-9--]'
SET @slug = @slug + @c
SET @i = @i +1
END
RETURN @slug
END |
@Tony: No, schemas can be useful, and indeed, we use them to partition data in our database. But I'm talking about trying to scrub sensitive data before letting a consultant have a copy of the db. I want that data gone. |
If you're using the `mysqli` library, then either the `mysqli_errno()` function or `mysqli->errno()` method will return an error number (or zero if there wasn't an error) of the most recently executed statement. (The older `mysql` library has a `mysql_errno()` function that does the exact same thing.)
Figuring out the exact nature of the error may not always be necessary. If you get an error after an `UPDATE` statement, then probably a constraint was violated (unique, in your example). That may be enough for your error handling.
One thing in MySQL to be wary of for `UPDATE` statements: `mysqli_affected_rows()` will return zero even if the `WHERE` clause matched rows, but the `SET` clause didn't actually change the data values. I only mention this because that behaviour caused a bug in a system I once looked at--the programmer used that return value to check for errors after an update, assuming a zero meant that some error had occurred. It just meant that the user didn't change any existing values before clicking the update button. |
There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
public interface Foo {
public static int bar();
end
and
public interface Foo {
public static int bar() {
...
}
}
Java doesn't allow either, but it *could* allow the second. The first is impossible for the reasons that [Espo][1] mentions: you don't know which implementing class is the correct definition.
Java *could* allow the latter, as long as it treated `Interface`s as first-class `Object`s. Ruby's `Module`s, which are approximately equivalent to Java's `Interface`s, allow exactly that:
module Foo
def self.bar
...
end
end
[1]: http://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface#21826 |
What are the major differences between ANSI C and K&R C? |
|c|ansi-c|kr-c| |
The [Wikipedia article on ANSI C][1] says:
> One of the aims of the ANSI C standardization process was to produce a superset of K&R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style.
That makes me think that there are differences. However, I didn't see a comparison between K&R C and ANSI C. Is there such a document? If not, what are the major differences?
EDIT: I believe the K&R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore?
[1]: http://en.wikipedia.org/wiki/ANSI_C |
Formview problem |
|asp.net|formview| |
I have a form view, in the edit template I have two drop downs.
Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback.
Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2)
On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error
> Databinding methods such as Eval(),
> XPath(), and Bind() can only be used
> in the context of a databound control.
Here is the drop down list #2:
<asp:DropDownList ID="ProjectList" runat="server" SelectedValue='<%# Bind("ConnectToProject_ID","{0:D}") %>' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="{No Master Project}" Selected="True" />
</asp:DropDownList>
And here is the MasterProjectDataSource2:
<asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server"
SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" >
<SelectParameters>
<asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Any help on how to get this to work would be greatly appriciated. |
Updated to remove the stuff about errno functions which I now realize don't apply in your situation...
One thing in MySQL to be wary of for `UPDATE` statements: `mysqli_affected_rows()` will return zero even if the `WHERE` clause matched rows, but the `SET` clause didn't actually change the data values. I only mention this because that behaviour caused a bug in a system I once looked at--the programmer used that return value to check for errors after an update, assuming a zero meant that some error had occurred. It just meant that the user didn't change any existing values before clicking the update button.
So I guess using `mysqli_affected_rows()` can't be relied upon to find such warnings either, unless you have something like an `update_time` column in your table that will always be assigned a new timestamp value when updated. That sort of workaround seems kinda kludgey though. |
@Quarrelsome
> If will get called when the object is moved out of scope and is tidied by the garbage collector.
This statement is misleading and how I read it incorrect: There is absolutely no guarantee when the finalizer will be called. You are absolutely correct that billpg should implement a finalizer; however it will not be called automaticly when the object goes out of scope like he wants. [Evidence](http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx), the first bullet point under _Finalize operations have the following limitations_.
In fact Microsoft gave a grant to Chris Sells to create an implementation of .NET that used reference counting instead of garbage collection [Link](http://www.sellsbrothers.com/spout/default.aspx?content=archive.htm#refCountRotor). As it turned out there was a _considerable_ performance hit. |
This is no different from a programmer forgetting to use _delete_ in C++, except that at least here the garbage collect will still eventually catch up with it.
And you never need to use IDisposable if the only resource you're worried about is memory. The framework will handle that on it's own. IDisposable is only for unmanaged resources like database connections, filestreams, sockets, and the like. |
This is no different from a programmer forgetting to use _delete_ in C++, except that at least here the garbage collector will still eventually catch up with it.
And you never need to use IDisposable if the only resource you're worried about is memory. The framework will handle that on it's own. IDisposable is only for unmanaged resources like database connections, filestreams, sockets, and the like. |
How to do C++ style destructors in C#? |
|c#|using|dispose|idisposable| |
I've got a C# class with a Dispose function via IDisposable. Its intended to be used inside a using block so the expensive resource it handles can be released right away.
Problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.
<rant><br/>
In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.
<br/></rant>
Is there anyway to for a using block to be automatically used in C#?
Many thanks.
|
Build a time machine and go back to 1987? Ho ho.
Ok, no more snarky comments.
> How do I figure out what the configuration settings (e.g. baud rate) should be...
Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure.
Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out.
> one of the major Unix shells
In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there.
On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one.
See: <http://www.easysw.com/~mike/serial/serial.html#3_1>
> but I also have some interest in serial programming using Windows/Hyperterminal.
Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days. |
You mention your Dad was using a website publishing tool.
If the publishing tool publishes from his computer to the server, it may be the case that his local files are clean, and that he just needs to republish to the server.
He should see if there's a different login method to his server than plain FTP, though... that's not very secure because it sends his password as clear-text over the internet. |
To recurse on a solved problem: do nothing, you're done.
To recurse on an open problem: do the next step, then recurse on the rest. |
What is Inversion of Control? |
|inversion-of-control|design-patterns| |
Inversion of Control (or IoC) can be quite confusing when it is first encountered.
1. What is it?
2. What problems does it solve?
3. When is it appropriate and when not? |
From the other side, if you want to do it using C#, which will run on both Windows and Linux--with some [limitations][1] (EDIT: which may be out of date. I have no way to test it.). Just create a [SerialPort][2] object, set its baudrate, port and any other odd settings, call open on it, and write out your byte[]s. After all the setup, the SerialPort object acts very similar to any networked stream, so it should be easy enough to figure out.
And as ibrandy states, you need to know all these settings, like baud rate, before you even start attempting to communicate to any serial device.
[1]: http://www.mono-project.com/HowToSystemIOPorts
[2]: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx |
Calling a Function From a String With the Function's Name in Python |
I think there's probably a bug somewhere in your composition of sec and usec. I can't really say what exactly without knowing the kinds of errors you're seeing. A rough guess would be that usec can never be > 999999, so you're relying on overflow to know when to adjust sec. It could also just be a problem with your duration output format.
Anyway. Why not store the utime and stime components as float seconds rather than trying to build your own rusage on output? I'm pretty sure the following will give you proper seconds.
static int timeval_diff_ms(timeval const& end, timeval const& start) {
int micro_seconds = (end.tv_sec - start.tv_sec) * 1000000
+ end.tv_usec - start.tv_usec;
return micro_seconds;
}
static float timeval_diff(timeval const& end, timeval const& start) {
return (timeval_diff_ms(end, start)/1000000.0f);
}
If you want to decompose this back into an rusage, you can always int-div and modulo.
|
From a security perspective, I know that it is possible to spoof a MAC, though I am not entirely sure how difficult it is or what it entails.
Otherwise, if the customers don't have easy access to the hardware or the OS, you should be fairly safe doing this... probably best to put a warning sticker on saying that messing with anything will disrupt communication to the server. |
I'm not using a custom "new form", so this might not apply. I added an event receiver to my custom content type and then do my custom code in the ItemAdded or ItemAdding events. This code fires when the event is added to a list. You can use the event receiver properties to get to the parent List, Web, and Site. |
G'day,
I guess one thing that nobody seems to have asked is if you have a legal requirement to store history of changes to the doc's?
Whether you do or don't is going to have an impact on what solutions you can consider.
Also a notification mechanism for out of date copies is also a bundle of fun. If engineer A has a copy of a document and engineer B then edits it and commits the changes you want engineer A to be notified that his copy is out of date.
Document control can become a real can of worms quite easily.
Maybe keep the doc's under CVS or SVN and set it up so that emails are generated to whoever has checked out a copy when updates for the same doc. are checked in to the repository?
HTH
cheers,
Rob |
G'day,
I guess one thing that nobody seems to have asked is if you have a legal requirement to store history of changes to the doc's?
Whether you do or don't is going to have an impact on what solutions you can consider.
Also a notification mechanism for out of date copies is also a bundle of fun. If engineer A has a copy of a document and engineer B then edits it and commits the changes you want engineer A to be notified that his copy is out of date.
Document control can become a real can of worms quite easily.
Maybe keep the doc's under CVS or SVN and set it up so that emails are generated to whoever has checked out a copy when updates for the same doc. are checked in to the repository?
HTH
cheers,
Rob
Edit: I forgot to add don't forget to use the binary switch, e.g. -kb for CVS, when adding the new doc. Otherwise, you will get any sequences of data that happen to match the ascii for keyword strings having the relevant config management data appended thereby corrupting your doc. data. |
|c#|dispose|using|idisposable| |
I've got a C# class with a Dispose function via IDisposable. Its intended to be used inside a using block so the expensive resource it handles can be released right away.
Problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.
<rant><br/>
In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.
<br/></rant>
Is there anyway to for a using block to be automatically used in C#?
Many thanks.
UPDATE:
I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.
Here's the bug I found, reduced to the essentials...
try
{
PleaseDisposeMe a = new PleaseDisposeMe();
throw new Exception();
a.Dispose();
}
catch (Exception ex)
{
Log(ex);
}
// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone? |
As far as I can tell, the only reason why Chrome installs into the Application Data folder is so that non-admin users can install it.
The Chrome installer currently does not allow the user to pick where the application is to be installed. Don't do that – instead, give the user a choice between a per-user (somewhere like App Data) and computer-wide (Program Files) installation. |
Yes, they are. I'd personally recommend looking at [SSW's rules to better unit tests][1]. It contains some very helpful naming guidelines.
[1]: http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterUnitTests.aspx |
One I used with my kids is [CEEBot][1]. It's not python, but it teaches C / Java style programming in a fun, robot-programming kind of game. It is aimed at 10-15 year olds, but it is a really good one.
[1]: http://www.ceebot.com/ceebot/index-e.php |
~ClassName()
{
}
If will get called when the object is moved out of scope and is tidied by the garbage collector.
This is called a Finalizer. All objects with a finaliser get put on a special finalise queue by the garbage collector where the finalise method is invoked on them (so it's technically a performance hit to declare empty finalisers).
The "accepted" dispose pattern as per the Framework Guidelines is as follows with unmanaged resources:
public class DisposableFinalisableClass : IDisposable
{
~DisposableFinalisableClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// tidy managed resources
}
// tidy unmanaged resources
}
}
So the above means that if someone calls Dispose the unmanaged resources are tidied. However in the case of someone forgetting to call Dispose or an exception preventing Dispose from being called the unmanaged resources will still be tidied away, only slightly later on when the GC gets its grubby mitts on it (which includes the application closing down or unexpectedly ending). |
I refer to [A List Apart][1] articles all the time for those sorts of things. They do a lot of trial-and-error research to come up with really creative ways to handle those common CSS problems in the cleanest most portable way possible.
[1]: http://www.alistapart.com/ |
To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField). |
Ruby "is" equivalent |
|python|ruby|identical| |
Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location). |
Use `a.equal? b`
http://www.ruby-doc.org/core/classes/Object.html
> Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b). |
Dot notation for property access in Objective-C **is** a message send, just as bracket notation. That is, given this:
@interface Foo : NSObject
@property BOOL bar;
@end
Foo *foo = [[Foo alloc] init];
foo.bar = YES;
[foo setBar:YES];
The last two lines will compile exactly the same. The only thing that changes this is if a property has a `getter` and/or `setter` attribute specified; however, all it does is change what message gets sent, not whether a message is sent:
@interface MyView : NSView
@property(getter=isEmpty) BOOL empty;
@end
if ([someView isEmpty]) { /* ... */ }
if (someView.empty) { /* ... */ }
Both of the last two lines will compile identically. |
First, there is no such thing as "the Unix file system".
Second, upon what premise does your argument rest? Did you hear someone say it was superior? Perhaps if you offered some source, we could critique the specific argument. |
First, there is no such thing as "the Unix file system".
Second, upon what premise does your argument rest? Did you hear someone say it was superior? Perhaps if you offered some source, we could critique the specific argument.
**Edit:** Okay, according to [http://en.wikipedia.org/wiki/Comparison_of_file_systems][1], NTFS has more green boxes than both UFS1 and UFS2. If green boxes are your measure of "better", then NTFS is "better".
Still a stupid question. :-p
[1]: http://en.wikipedia.org/wiki/Comparison_of_file_systems |
What makes the Unix file system more superior to the Windows file system? |
|unix|filesystems| |
I'll admit that I don't know the inner workings of the unix operating system, so I was hoping someone could shed some light on this topic.
Why is the unix file system better than the windows file system?
Would grep work just as well on windows, or is their something fundamentally different that makes it more powerful on a unix box? |
I'll admit that I don't know the inner workings of the unix operating system, so I was hoping someone could shed some light on this topic.
Why is the unix file system better than the windows file system?
Would grep work just as well on windows, or is their something fundamentally different that makes it more powerful on a unix box?
e.g. I have heard that in a unix system, the number of files in a given directory will not slow file access, while on windows direct file access will degrade as the # of files increase in the given folder, true?
Updates:
Brad, no such thing as the <a href="http://en.wikipedia.org/wiki/Unix_File_System">unix file system</a>? |
The biggest single difference, I think, is function prototyping and the syntax for describing the types of function arguments.
|
ASP.NET gzip compression corrupting CSS |
|asp.net|compression|gzip| |
I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using [this implementation][1] (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again.
Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not.
Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.
[1]: http://www.stardeveloper.com/articles/display.html?article=2007110401&page=1 |
I would try a framework. *Zend Framework* has been cited. [Symfony][1] seems interesting. It's based on ideas from *Ruby on Rails*.
[1]: http://www.symfony-project.org/ |
I don't know if there is a way to optimize UpdatePanels, but my company has found its performance to be pretty poor. jQuery is much much faster at doing pretty much anything.
There can be a lot of lag between the time when an UpdatePanel triggers an update and when the UpdatePanel actually updates the page.
The only reason we use UpdatePanels is because of the ease of development. Almost nothing needs to be done to make them work. |
What a good machine for iPhone development? |
|iphone|apple|macos|imac| |
I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on?
If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser.
Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have? |
What's a good machine for iPhone development? |
|macos|iphone|apple|imac| |
There are some minor differences, but I think later editions of K&R are for ANSI C, so there's no real difference anymore.
"C Classic" for lack of a better terms had a slightly different way of defining functions, i.e.
int f( p, q, r )
int p, float q, double r;
{
// Code goes here
}
I believe the other difference was function prototypes. Prototypes didn't have to - in fact they couldn't - take a list of arguments or types. In ANSI C they do.
|
~ClassName()
{
}
EDIT (bold):
If will get called when the object is moved out of scope and is tidied by the garbage collector **however this is not deterministic and is not guaranteed to happen at any particular time**.
This is called a Finalizer. All objects with a finaliser get put on a special finalise queue by the garbage collector where the finalise method is invoked on them (so it's technically a performance hit to declare empty finalisers).
The "accepted" dispose pattern as per the Framework Guidelines is as follows with unmanaged resources:
public class DisposableFinalisableClass : IDisposable
{
~DisposableFinalisableClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// tidy managed resources
}
// tidy unmanaged resources
}
}
So the above means that if someone calls Dispose the unmanaged resources are tidied. However in the case of someone forgetting to call Dispose or an exception preventing Dispose from being called the unmanaged resources will still be tidied away, only slightly later on when the GC gets its grubby mitts on it (which includes the application closing down or unexpectedly ending). |
Windows still lacks a convention for per-user installation.
* When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide `%PROGRAMFILES%`.
* Microsoft's own ClickOnce works around this by creating a completely non-standard `%USERPROFILE%\Local Settings\Apps` (`%USERPROFILE%\AppData\Roaming` on Vista / Server 2008) directory, with both program files and configuration data in there.
(I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a `~/Applications`, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.)
What you probably *should* do: if the user is not an admin, install in the user directory; if they do, give them both options. |
Yes, the names are totally important, specially when you are running the tests in console or continuous integration servers. Jay Fields wrote a [post about it][1].
Moreover, put good test names with [one assertion per test][2] and your suite will give you great reports when a test fails.
Kind Regards
[1]: http://blog.jayfields.com/2008/05/testing-value-of-test-names.html
[2]: http://blog.jayfields.com/2007/06/testing-one-assertion-per-test.html |
java String concatenation |
|java|string| |
I'm curious and wasn't sure, so i thought id ask:
assuming String a and b.
a+=b
a.concat(b)
Under the hood are they the same thing? |
I'm curious and wasn't sure, so i thought id ask:
assuming String a and b.
a+=b
a.concat(b)
Under the hood are they the same thing?
Edit:
Here is concat decompiled as reference, I'd like to be able to decompile the + operator as well to see what that does, not sure how to do that yet.
public String concat(String s)
{
int i = s.length();
if(i == 0)
{
return this;
} else
{
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
} |
What kibbee said.
For the part of your question about existing on a release build, it depends on what kind of web site you have. If you have a pre-compiled web site, then _none_ of code files (.vb, .cs, etc) need to be deployed the server. They are compiled into .dlls (assemblies) and deployed that way along with the .as*x files. |
All versions of the .Net Framework from 2.0 onwards (i.e. 3.0 and 3.5) use exactly the same core framework files (i.e. the CLR, you'll notice there are no directories relating to 3.0 or 3.5 in the C:\Windows\Microsoft.Net\Framework directory) therefore you shouldn't worry too much about any performance issues.
The Core parts are referred to in Microsoft Speak as the 'Red Bits' and the rest as the 'Green Bits'. |
Avoiding repeated constants in CSS |
|css| |
Are there any useful techniques for reducing the repetition of constants in a CSS file?
(For example, a bunch of different selectors which should all apply the same colour, or the same font size)? |
Here's what I ended up with. I have never found another solution out there for this, so if you have something better, by all means, contribute.
First, the long array definition in the wsdl:types area:
<xsd:complexType name="ArrayOf_xsd_long">
<xsd:complexContent mixed="false">
<xsd:restriction base="soapenc:Array">
<xsd:attribute wsdl:arrayType="soapenc:long[]" ref="soapenc:arrayType" />
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
Next, we create a SoapExtensionAttribute that will perform the fix. It seems that the problem was that .NET wasn't following the multiref id to the element containing the double value. So, we process the array item, go find the value, and then insert it the value into the element:
[AttributeUsage(AttributeTargets.Method)]
public class LongArrayHelperAttribute : SoapExtensionAttribute
{
private int priority = 0;
public override Type ExtensionType
{
get { return typeof (LongArrayHelper); }
}
public override int Priority
{
get { return priority; }
set { priority = value; }
}
}
public class LongArrayHelper : SoapExtension
{
private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper));
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
private Stream originalStream;
private Stream newStream;
public override void ProcessMessage(SoapMessage m)
{
switch (m.Stage)
{
case SoapMessageStage.AfterSerialize:
newStream.Position = 0; //need to reset stream
CopyStream(newStream, originalStream);
break;
case SoapMessageStage.BeforeDeserialize:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = false;
settings.NewLineOnAttributes = false;
settings.NewLineHandling = NewLineHandling.None;
settings.NewLineChars = "";
XmlWriter writer = XmlWriter.Create(newStream, settings);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(originalStream);
List<XmlElement> longArrayItems = new List<XmlElement>();
Dictionary<string, XmlElement> multiRefs = new Dictionary<string, XmlElement>();
FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs);
FixLongArrays(longArrayItems, multiRefs);
xmlDocument.Save(writer);
newStream.Position = 0;
break;
}
}
private static void FindImportantNodes(XmlElement element, List<XmlElement> longArrayItems,
Dictionary<string, XmlElement> multiRefs)
{
string val = element.GetAttribute("soapenc:arrayType");
if (val != null && val.Contains(":long["))
{
longArrayItems.Add(element);
}
if (element.Name == "multiRef")
{
multiRefs[element.GetAttribute("id")] = element;
}
foreach (XmlNode node in element.ChildNodes)
{
XmlElement child = node as XmlElement;
if (child != null)
{
FindImportantNodes(child, longArrayItems, multiRefs);
}
}
}
private static void FixLongArrays(List<XmlElement> longArrayItems, Dictionary<string, XmlElement> multiRefs)
{
foreach (XmlElement element in longArrayItems)
{
foreach (XmlNode node in element.ChildNodes)
{
XmlElement child = node as XmlElement;
if (child != null)
{
string href = child.GetAttribute("href");
if (href == null || href.Length == 0)
{
continue;
}
if (href.StartsWith("#"))
{
href = href.Remove(0, 1);
}
XmlElement multiRef = multiRefs[href];
if (multiRef == null)
{
continue;
}
child.RemoveAttribute("href");
child.InnerXml = multiRef.InnerXml;
if (log.IsDebugEnabled)
{
log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml);
}
}
}
}
}
public override Stream ChainStream(Stream s)
{
originalStream = s;
newStream = new MemoryStream();
return newStream;
}
private static void CopyStream(Stream from, Stream to)
{
TextReader reader = new StreamReader(from);
TextWriter writer = new StreamWriter(to);
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
}
}
Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute:
[SoapRpcMethod("", RequestNamespace="http://some.service.provider",
ResponseNamespace="http://some.service.provider")]
[return : SoapElement("getFooReturn")]
[LongArrayHelper]
public Foo getFoo()
{
object[] results = Invoke("getFoo", new object[0]);
return ((Foo) (results[0]));
}
This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem. |
Editing User Profile w/ Forms Authentication |
|moss|wss| |
We're using Forms Authentication in SharePoint. When the account is created, the administrator can add some information, like name and address. But the required fields are username and email address.
When a user goes to their profile page, all the fields are blank and they are unable to edit them. I have read a number of articles discussing how to import profiles from another data store, or to sync profiles. This doesn't work for us, because we don't have another data store where these profiles are stored.
Will I just have to recreate the edit profile page and build a custom profile editor? Is this information exposed via SharePoint API? I don't think directly editing the database is a good solution. |
|sharepoint|moss|wss| |
> The original prefix was meant to be
> used to spot problems in equations,
> but has somehow devolved into making
> the code slightly easier to read since
> you don't have to go look for the
> variable declaration. With todays
> smart editors where you can simply
> hover over any variable to find the
> full type, and not just an
> abbreviation for it, this type of
> hungarian notation has lost a lot of
> its meaning.
I'm breaking the habit a little bit but prefixing with the type can be useful in JavaScript that doesn't have strong variable typing. |