instruction stringlengths 0 30k ⌀ |
|---|
|javascript|namespace| |
I've got a JavaScript "object", built this way:
function foo()
{
this.length = 0;
}
foo.prototype.getLength = function()
{
return this.length;
}
...
I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced?
I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced.
Thanks
rp |
Return collection as read-only |
|c#|.net|multithreading|collections|concurrency| |
I have an object in a multi-threaded environment that maintains a collection of information, e.g.:
public IList<string> Data {
get {
return data;
}
}
I currently have `return data;` wrapped by a `ReaderWriterLockSlim` to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible? |
Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code. |
If your underlying data is stored as list you can use [List(T).AsReadOnly][1] method.
If your data can be enumerated, you can use [Enumerable.ToList][2] method to cast your collection to List and call AsReadOnly on it.
[1]: http://msdn.microsoft.com/en-us/library/e78dcd75.aspx
[2]: http://msdn.microsoft.com/en-us/library/bb342261.aspx |
There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.:
1. Use an effective GUID generator - these are long and cannot be shrunk or only use part or **you FAIL**.
2. At least part of the number is sequentially generated off of a single sequence. You can add fluff to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence.
3. Generate them via some other means and then check them against the single history of previously generated values.
Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at).
**Note about GUIDS**: They gain their strength of uniqueness from their length and the method used to generate them. *Anything less than 128-bits is not secure.* There are usually 4 sources of data in a GUID - a sequence number, a random number, a location number (based on MAC address for example), and a time slice. Just generating an 128 bit random number is not secure.
**Update**: If you want 7 to 16 characters then you need to use either method 2 or 3. |
There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.:
1. Use an effective GUID generator - these are long and cannot be shrunk. If you only use part or **you FAIL**.
2. At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence.
3. Generate them via some other means and then check them against the single history of previously generated values.
Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at).
**Note about GUIDS**: They gain their strength of uniqueness from their length and the method used to generate them. *Anything less than 128-bits is not secure.* Beyond random number generation there are characteristics that go into a GUID to make it more unique. Keep in mind they are only practically unique, not completely unique. It is possible, although practically impossible to have a duplicate.
**Update**: If you want 7 to 16 characters then you need to use either method 2 or 3.
**Bottom line**: Frankly there is no such think as completely unique. Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point.
Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating. Take a quarter for example. It is a completely random bit generator, and its odds of repeating are 1 in 2.
So it all comes down to your threshold of uniqueness. You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it. Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique. |
If I'm using your site, "average" doesn't matter. All I care about is MY experience, and so you either need to make the site adaptive, design for a pretty low speed (iPhone 2G gets you 70-80 kbps if you're lucky, to take one common case), or be very clear about the requirements so I can decide whether or not my connection-of-the-moment will work or not.
What you don't want to subject your users to is unpredictably choppy, intermittent video and audio. |
Wow! Big question! :)
Correct me if I'm wrong. Your basic solution now is kind of an Observer pattern, where the data object (Account, etc) notifies about changes in their states. You think that the problem is that the subscribing plugin has to register in every object to be able to handle notifications.
That's not a problem per se, you can put the event control in the [Domain Model][1], but I suggest you create a [Service Layer][2] and do this event notifications in this layer. That way just one object would be responsible for publishing notifications.
Martin Fowler have a series of Event Patterns in his blog. [Check it out][3]! Very good reading.
[1]: http://martinfowler.com/eaaCatalog/domainModel.html
[2]: http://martinfowler.com/eaaCatalog/serviceLayer.html
[3]: http://www.martinfowler.com/eaaDev/ |
It will have to get a hell of a lot simpler, with easier-to-remember IDs. |
Or do a non-recursive checkout of /trunk, then just do a manual update on the 3 directories you need. |
Not in any especially useful way, no. You can check out subtrees (as in Bobby Jack's suggestion), but then you lose the ability to update/commit them atomically; to do that, they need to be placed under their common parent, and as soon as you check out the common parent, you'll download everything under that parent. Non-recursive isn't a good option, because you want updates and commits to be recursive.
|
Sort of. As Bobby says:
svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum
will get the folders, but you will get separate folders from a subversion perspective. You will have to go separate commits and updates on each subfolder.
I don't believe you can checkout a partial tree and then work with the partial tree as a single entity. |
the FK_Contraints are set up like this:
ALTER TABLE [dbo].[e2] WITH CHECK ADD CONSTRAINT [FK_e2_e1] FOREIGN KEY([E1Id]) REFERENCES [dbo].[e1] ([Id])
ALTER TABLE [dbo].[e3] WITH CHECK ADD CONSTRAINT [FK_e3_e2] FOREIGN KEY([E2Id]) REFERENCES [dbo].[e2] ([Id])
is this what you were asking for? |
As someone who primarily programs web apps in Java, I can't/won't use OpenID because the library support isn't there. [JOID][1] and [openid4java][2] are the only two that I know of. JOID is apparently not actively maintained, not including really important patches that have been on the mailing list for months; and openid4java requires >40 megabytes of external dependencies, including some that need to go into the endorsed classpath, which is, as [one user commented][3], ridiculous:
> Comment by witichis, Apr 28, 2008
>
> 46MB download for a simple redirect and de/encryp - are you f****n' drunk?
In my opinion, OpenID is not bad. It consolidates login credentials. It does solve a real problem, while it may not be the optimal solution The only two problems I can see are that you must trust the identity provider not to allow someone else to claim to be you, and that relying parties (web sites you log in to) can collude to link your identity on multiple sites together.
[1]: http://code.google.com/p/joid/
[2]: http://code.google.com/p/openid4java/
[3]: http://code.google.com/p/openid4java/wiki/Installation |
For this type of tasks, I use my own [AutoIt](http://www.autoitscript.com/autoit3/) script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen).
I use AutoIt because it's free, very easy to use, and can compile quickly into an .EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only.
$sCmd = "DIR E:\*.AU3 /S" ; Test command
$nAutoTimeout = 10 ; Time in seconds to close window after finish
$nDeskPct = 60 ; % of desktop size (if percent)
; $nHeight = 480 ; height/width of the main window (if fixed)
; $nWidth = 480
$sTitRun = "Executing process. Wait...." ;
$sTitDone = "Process done" ;
$sSound = @WindowsDir & "\Media\Ding.wav" ; End Sound
$sButRun = "Cancel" ; Caption of "Exec" button
$sButDone = "Close" ; Caption of "Close" button
#include <GUIConstants.au3>
#include <Constants.au3>
#Include <GuiList.au3>
Opt("GUIOnEventMode", 1)
if $nDeskPct > 0 Then
$nHeight = @DesktopHeight * ($nDeskPct / 100)
$nWidth = @DesktopWidth * ($nDeskPct / 100)
EndIf
If $CmdLine[0] > 0 Then
$sCmd = ""
For $nCmd = 1 To $CmdLine[0]
$sCmd = $sCmd & " " & $CmdLine[$nCmd]
Next
; MsgBox (1,"",$sCmd)
EndIf
; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10))
$nForm = GUICreate($sTitRun, $nWidth, $nHeight)
GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm")
$nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL)
GUICtrlSetFont (-1, 9, 0, 0, "Courier New")
$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30)
GUICtrlSetOnEvent (-1, "CloseForm")
GUISetState(@SW_SHOW) ;, $nForm)
$nPID = Run(@ComSpec & " /C " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD)
; $nPID = Run(@ComSpec & " /C _RunErrl.bat " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP
While 1
$sLine = StdoutRead($nPID)
If @error Then ExitLoop
If StringLen ($sLine) > 0 then
$sLine = StringReplace ($sLine, Chr(13), "|")
$sLine = StringReplace ($sLine, Chr(10), "")
if StringLeft($sLine, 1)="|" Then
$sLine = " " & $sLine
endif
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
EndIf
Wend
$sLine = " ||"
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
GUICtrlSetData ($nClose, $sButDone)
WinSetTitle ($sTitRun, "", $sTitDone)
If $sSound <> "" Then
SoundPlay ($sSound)
EndIf
$rInfo = DllStructCreate("uint;dword") ; # LASTINPUTINFO
DllStructSetData($rInfo, 1, DllStructGetSize($rInfo));
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
$nLastInput = DllStructGetData($rInfo, 2)
$nTime = TimerInit()
While 1
If $nAutoTimeout > 0 Then
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
If DllStructGetData($rInfo, 2) <> $nLastInput Then
; Tocó una tecla
$nAutoTimeout = 0
EndIf
EndIf
If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then
ExitLoop
EndIf
Sleep (100)
Wend
Func CloseForm()
Exit
EndFunc |
How can you find out where the style for a ASP .Net web page element came from? |
|c#|asp.net|css|themes| |
I have a quandary. My web application (C#, .Net 3.0, etc) has Themes, CSS sheets and, of course, inline style definitions. Now that's alot of chefs adding stuff to the soup. All of this results, not surprisingly, in my pages having bizarre styling on occasion.
I am sure that all these styles are applied in a hierarchical method (although I am not sure of that order). The issue is that each style is applied as a "transparent" layer which just masks what it is applying. This is, I feel, a good idea as you can specifiy styles for the whole and then one-off them as needed. Unfortunately I can't tell from which layer the style actually came from.
I could solve this issue by explicitly expressing the style at all layers but that gets bulky and hard to manage and the page(s) works 80% of the time. I just need to figure out where that squirrelly 20% came from. |
> What are the performance implications of doing this?
We use a system based on something like the above mentioned, where each C# script is compiled to an in-memory assembly and executed in a seperate AppDomain. There's no caching system yet, so they scripts are recompiled every time they run. I've done some simple testing and a very simple "Hello World" script compiles in about 0.7 seconds on my machine, including loading the script from disk. 0.7 seconds is fine for a scripting system, but might be too slow for responding to user input, in that case a dedicated parser/compiler like Flee might be better.
using System;
public class Test
{
static public void DoStuff( Scripting.IJob Job)
{
Console.WriteLine( "Heps" );
}
} |
You could create a helper class which wrapped the UriBuilder class in System.Net
public static class UriHelper
{
private static readonly UriBuilder _builder = new UriBuilder("http://localhost");
public static string NormalizeRelativePath(string path)
{
_builder.Path = path;
return _builder.Uri.AbsolutePath;
}
}
which could then be used like this:
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
It is a bit hacky but it would work for the specific example you gave. |
You could create a helper class which wrapped the UriBuilder class in System.Net
public static class UriHelper
{
public static string NormalizeRelativePath(string path)
{
UriBuilder _builder = new UriBuilder("http://localhost");
builder.Path = path;
return builder.Uri.AbsolutePath;
}
}
which could then be used like this:
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
It is a bit hacky but it would work for the specific example you gave.
**EDIT: Updated to reflect Andrew's comments.** |
One website I use has a translation method the owner calls "wiki + machine translation". This is a community based site so is obviously different to the needs of companies.
http://blog.bookmooch.com/2007/09/23/how-bookmooch-does-its-translations/ |
I haven't used Marlon's, but I have used [Kevin Moore's][1]. At the time I used it, there were a number of bugs I had to [work around][2]. Other than those issues, it did seem to work well enough.
HTH,
Kent
[1]: http://j832.com/bagotricks/
[2]: http://kentb.blogspot.com/2007/07/wpf-and-date-entry.html |
I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:
[How To: ClickOnce deployment for unmanaged app with COM component in managed assembly ][1]
[1]: http://blogs.msdn.com/g/archive/2008/06/06/sample-demonstrating-clickonce-deployment-of-com-component-implemented-in-managed-assembly-without-using-gac-or-registry-and-without-requiring-admin-rights.aspx |
You can have a look at what Ayende is saying here : [MultiTable Entities][1].
But since you have separate tables , i don't think it will work.
You can also check out [nhuser group][2]
[1]: http://www.ayende.com/Blog/archive/2007/04/24/Multi-Table-Entities-in-NHibernate.aspx
[2]: http://groups.google.com/group/nhusers |
[This article][1] explain an technique of #include removing by using the parsing of Doxygen. That's just a perl script, so that's quite easy to use.
[1]: http://www.gamesfromwithin.com/articles/0403/000011.html |
[This article][1] explains a technique of #include removing by using the parsing of Doxygen. That's just a perl script, so it's quite easy to use.
[1]: http://www.gamesfromwithin.com/articles/0403/000011.html |
[Ghost Docs][1]
> <summary>
GhostDoc is a free add-in for Visual Studio that automatically generates XML
documentation comments for C#. Either by using existing documentation inherited
from base classes or implemented interfaces, or by deducing comments from
name and type of e.g. methods, properties or parameters.
</summary>
[1]: ttp://www.roland-weigelt.de/ghostdoc/ |
[Ghost Docs][1]
> <summary>
GhostDoc is a free add-in for Visual Studio that automatically generates XML
documentation comments for C#. Either by using existing documentation inherited
from base classes or implemented interfaces, or by deducing comments from
name and type of e.g. methods, properties or parameters.
</summary>
[1]: http://www.roland-weigelt.de/ghostdoc/ |
You might have some luck using [OpenEmbedded][1]. If there's no precompiled version you can use right away, setting up an OE-cross compile environment is not that hard.
Another option could be to install gdb-server on the board, like described in [this blogpost][2].
[1]: http://wiki.openembedded.net/index.php/Main_Page
[2]: http://dominion.thruhere.net/koen/cms/using-gdbserver |
If you're using jQuery then you have loads of [CSS selectors and jQuery custome selectors][1] at your disposal to target elements on your page. So rather than picking out a submit button by it's id, you could do something like:
$('fieldset > input[type="submit"]').click(function() {...});
[1]: http://docs.jquery.com/Selectors |
XMLDataSource is designed to be used with data-bound controls. ASP.NET's TextBox is not a data-bound control. So to accomplish what you want you either have to find a textbox control with data binding or display the result in some other way.
For example, you could use a [Repeater control][1] and create your own rendering template for it.
<asp:Repeater id="Repeater1" runat="server" datasource="XMLds">
<ItemTemplate>
<input type="text" value="<%# XPath("<path to display field>")%>" />
</ItemTemplate>
</asp:Repeater>
[1]: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx |
I think the best thing that extension methods replace are all those utility classes that you find in every project.
At least for now, I feel that any other use of Extension methods would cause confusion in the workplace.
My two bits. |
I prefer to use the underscore prefix for private fields. I use lowercase first letter for the method parameters. I follow the guideline of having lowercase camelcase parameters for methods, which I regard as more important than the naming of private fields since it is part of the API for the class. . e.g.
Public Class Class1
Private _foo As String
Public Property Foo() As String
Get
Return _foo
End Get
Set(ByVal value As String)
_foo = value
End Set
End Property
Public Sub New(ByVal foo As String)
_foo = foo
End Sub
End Class
Using this pattern, you won't have any naming conflicts with the private field and your constructor parameter in C# or VB.NET. |
Printing from a Windows service is really painful. It seems to work... sometimes... but finally it craches or throws an exception from time to time, without any clear reason. It's really hopeless. Officially, it's even [not supported][1], without any explanation, nor any proposal for an alternate solution.
Recently, I have been confronted to the problem and after several unsuccessful trials and experimentations, I came finally with two viable solutions:
- Write your own printing DLL using the Win32 API (in C/C++ for instabce), then uses it from your service with P/Invoke (works fine)
- Write your own printing COM+ component, then uses it from your service. I have chosen this solution with success recently (but it was third party COM+ component, not own written) It works absolutely fine too.
[1]: http://msdn.microsoft.com/en-us/library/system.drawing.printing(VS.80).aspx |
The `__doPostBack()` method works well.
Another solution (very hackish) is to simply add an invisible ASP button in your markup and click it with a javascript method.
<div style="display: none;">
<asp:Button runat="server" ... OnClick="ButtonClickHandlerMethod" />
</div>
From your javascript, retrieve the reference to the button using its *ClientID* and then call the *.Click()* method on it.
var button = document.getElementByID(/* button client id */);
button.Click(); |
Through a combination of the suggestions I got, I came up with this:
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font);
g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
{
// Compute actual size, shrink if needed
while (true)
{
SizeF size = g.MeasureString(text, font);
// It fits, back out
if (size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.Name, (float)(font.Size * .9), font.Style);
oldFont.Dispose();
}
}
So far, this works flawlessly.
The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness. |
|javascript|namespaces| |
How do you check in Python under Linux if a process is running? |
|python|linux|process| |
The only *nice* way I've found is:
import sys
import os
try:
os.kill(int(sys.argv[1]), 0)
print "Running"
except:
print "Not running"
([Source](http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html))
But is this reliable? Does it work with every process and every distribution? |
How do you check in Linux with Python if a process is still running? |
|python|linux|processes| |
Create DB in Sql Server based on Visio Data Model |
|sql-server|database|script|visio| |
I have created a database model in Visio Professional (2003). I know that the Enterprise version has the ability to create a DB in Sql Server based on the data in Visio. I do not have the option to install Enterprise. Aside from going through the entire thing one table and relationship at a time and creating the whole database from scratch, by hand, can anyone recommend any tool/utility/method for converting the visio database model into a Sql Script that can be used to create a new DB in Sql Server? |
|sql-server|database|scripting|visio| |
How do you find the age of a long-running Linux process? |
|linux|bash|process| |
I have a problem with some zombie-like processes on a certain server that need to be killed every now and then. How can I best identify the ones that have run for longer than an hour or so? |
|linux|bash|processes| |
Passing switches to Xcode 3.1 user scripts |
|script|xcode|arguments| |
I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it.
I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either.
So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables)
Thanks! |
I have a user script that would be much more useful if it could dynamically change some of its execution dependent on what the user wanted. Passing simple switches would easily solve this problem but I don't see any way to do it.
I also tried embedding a keyword in the script name, but Xcode copies the script to a guid-looking filename before execution, so that won't work either.
So does anyone know of a way to call a user script with some sort of argument? (other that the normal %%%var%%% variables)
Thanks!
EDIT: User scripts are accessible via the script menu in Xcode's menubar (between the Window and Help menus). My question is not about "run script" build phase scripts. My apologies for leaving that somewhat ambiguous. |
Automated testing keeps humans from doing a machine's job.
Test-driven development maximizes the amount of automated testing.
Beyond a certain point, of course, a human is still required. You reach diminishing returns when you try to apply TDD beyond that point. |
TDD helps you design your software. The tests becomes the design. By writing the test first you think about your code from a consumer perspective, making a more user friendly and more compact software design.
Also, by applying TDD you typically end up writing your code in a way where you can supply test mocks and stubs. This leads to less coupled software, making it easier to change and maintain over time.
So I guess allot of the talk around TDD is about testing, but by doing that other big benefits follow, such as quality (coverage), flexibility (decoupling), better design (think as the consumer of the API).
|
The real benefit of TDD is *supposed* to be that it allows you to modify/refactor/enhance your application without worrying about whether you've broken existing functionality. The fact that writing unit tests tends to result in loosely coupled code and better architecture isn't necessarily the *point* of TDD, but I think it's hard to have one without the other.
You can't really experience the benefit of TDD unless you have unit tests with good coverage. In order to do that, you're going to have to write testable code. That's why the two are often used in conjunction or in place of one another. |
The real improvement is that it is a good way to force you to really think through the design and implementation. Then, once you've prepared the tests and written the code, solutions to unforeseen problems appear more easily.
Something that usually happens to me that is a good analogy: When I'm going to post a question to a forum or IRC channel, I like to have the problems well written and fully described, many times the process of preparing a well written and complete description of the problem magically makes the solution appear. |
It's early yet, but have you considered trying to use [MEF][1] instead of rolling your own?
[1]: http://www.codeplex.com/MEF |
Specifically, like this in C#:
#if (DEBUG)
Debug Stuff
#endif
C# has the following preprocessor directives:
#if
#else
#elif // Else If
#endif
#define
#undef // Undefine
#warning // Causes the preprocessor to fire warning
#error // Causes the preprocessor to fire a fatal error
#line // Lets the preprocessor know where this source line came from
#region // Codefolding
#endregion |
Making a lot of unwarranted assumptions, I think that the best approach would be to create a Factory that will receive the list of key value pairs and return the proper object or throw an exception if it's invalid (or create a dummy object, or whatever is better in the particular case).
`
private class Factory {
public static IConfigurationObject Factory(List<string> keyValuePair) {
switch (keyValuePair[0]) {
case "x":
return new x(keyValuePair[1]);
break;
/* etc. */
default:
throw new ArgumentException("Wrong parameter in the file");
}
}
}
`
The strongest assumption here is that all your objects can be treated partly like the same (ie, they implement the same interface (IConfigurationObject in the example) or belong to the same inheritance tree).
If they don't, then it depends on your program flow and what are you doing with them. But nonetheless, they should :)
|
The only way would be to convert your text field into an nvarchar field.
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
Otherwise, I suggest doing the concatenation in your application. |
If you think more objects is more object-oriented then yes.
When doing object oriented design there are a couple of forces you have to balance. Most of OO design is about reducing and handling complexity. So if you get very complex solutions you're not doing too much OO but you're doing it wrong. |
I like to sketch out a design with pen & paper. Seriously. No computer. Layout the home screen, including a navigation bar. From here, think about what you'd like 2nd and 3rd tier pages to look like.
I've found that this process of writing things out on paper really helps me think about what I want out of the site. Try to come up with templates for a few of the screens. Then create an outline of the content you would like to include.
|
Ctrl-P and Ctrl-N are kind of pseudo code completion. They basically search the file you are editing (and any open buffers, and if you are using TAGS anything in your TAG file) for words that start with what you are typing and add a drop down list. It works surprisingly well for variables and function names, even if it isn't intellisense. |
Ctrl-P (Get Previous Match) and Ctrl-N (Get Next Match) are kind of pseudo code completion. They basically search the file (Backwards for Ctrl-P, Forwards for Ctrl-N) you are editing (and any open buffers, and if you are using TAGS anything in your TAG file) for words that start with what you are typing and add a drop down list. It works surprisingly well for variables and function names, even if it isn't intellisense. Generally I use Ctrl-P as the variable or function I am looking for is usually behind in the code. Also if you keep the same copy of Vim open, it will search the files you have previously opened.
|
You can solve the Airspace problem by using .net 3.5 SP1:
> These types of airspace restrictions
> represent a huge limitation in a
> framework, like WPF, where element
> composition is used to create very
> rich user experiences. With a D3DImage
> solution, these restrictions are no
> longer present!
See [Introduction to D3DImage][1].
[1]: http://www.codeproject.com/KB/WPF/D3DImage.aspx |
The way we work it is: There must be a good reason to refactor the code, otherwise why?
If the reason is to allow another feature to use the same code, associate the changes with the other feature's request.
If it's to make something faster, create a feature request for faster 'xyz' and associate the changes with that - then the customers see you're improving the product.
If it's to design out a bug, log the bug.
It's worth noting that in my environment, the policy cannot be enforced either. But clever managers can get reports of changes and if they don't have a bug\request reference in the commit text it's followed up. |
The way we work it is: There must be a good reason to refactor the code, otherwise why?
If the reason is to allow another feature to use the same code, associate the changes with the other feature's request.
If it's to make something faster, create a feature request for faster 'xyz' and associate the changes with that - then the customers see you're improving the product.
If it's to design out a bug, log the bug.
It's worth noting that in my environment, the policy cannot be enforced. But managers can get reports of changes and if they don't have a bug\request reference in the commit text it's followed up. |
When do function-level static variables get allocated/initialized? |
|c++|c|variables| |
I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
int globalgarbage;
unsigned int anumber = 42;
But what about static ones defined within a function?
void doSomething()
{
static bool globalish = true;
// ...
}
When is the space for <code>globalish</code> allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when <code>doSomething()</code> is first called? |
This is really ugly and there may be some issues with the string replacement, but it produces the expected results:
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
};
string json = JavaScriptConvert.SerializeObject(items);
json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");
json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");
foreach (string column in columnNames)
{
json = json.Replace("\"" + column + "\":", "");
}
return json;
}
}
|
I had the exact same experience from Day One working with Oracle stored procedures - "I have to use NOTEPAD?! Oh HELL no."
So I hopped on the internets and what I found were people saying "Hey, I have to create stored procedures in Oracle, isn't there anything better than NOTEPAD?!"
And the canonical answer was: "Download TOAD, you'll be glad you did". So I followed their advice, was very happy with it, and I'm pleased (if a bit amazed) to see it is still a popular answer. |
If you mean extends in the Base class sense, then in Java... no.
But you can extend an enum value to have properties and methods if that's what you mean.
For example, the following uses a Bracket enum:
class Person {
enum Bracket {
Low(0, 12000),
Middle(12000, 60000),
Upper(60000, 100000);
private final int low;
private final int high;
Brackets(int low, int high) {
this.low = low;
this.high = high;
}
public int getLow() {
return low;
}
public int getHigh() {
return high;
}
public boolean isWithin(int value) {
return value >= low && value <= high;
}
public String toString() {
return "Bracket " + low + " to " + high;
}
}
private Bracket bracket;
private String name;
public Person(String name, Bracket bracket) {
this.bracket = bracket;
this.name = name;
}
public String toString() {
return name + " in " + bracket;
}
}
|
Making a lot of unwarranted assumptions, I think that the best approach would be to create a Factory that will receive the list of key value pairs and return the proper object or throw an exception if it's invalid (or create a dummy object, or whatever is better in the particular case).
private class Factory {
public static IConfigurationObject Factory(List<string> keyValuePair) {
switch (keyValuePair[0]) {
case "x":
return new x(keyValuePair[1]);
break;
/* etc. */
default:
throw new ArgumentException("Wrong parameter in the file");
}
}
}
The strongest assumption here is that all your objects can be treated partly like the same (ie, they implement the same interface (IConfigurationObject in the example) or belong to the same inheritance tree).
If they don't, then it depends on your program flow and what are you doing with them. But nonetheless, they should :)
EDIT: Given your explanation, you could have one Factory per file type, the switch in it would be the authoritative source on the allowed types per file type and they probably share something in common. Reflection is a possible, but it's riskier because it's less obvious and self documenting than this one. |
Making a lot of unwarranted assumptions, I think that the best approach would be to create a Factory that will receive the list of key value pairs and return the proper object or throw an exception if it's invalid (or create a dummy object, or whatever is better in the particular case).
private class Factory {
public static IConfigurationObject Factory(List<string> keyValuePair) {
switch (keyValuePair[0]) {
case "x":
return new x(keyValuePair[1]);
break;
/* etc. */
default:
throw new ArgumentException("Wrong parameter in the file");
}
}
}
The strongest assumption here is that all your objects can be treated partly like the same (ie, they implement the same interface (IConfigurationObject in the example) or belong to the same inheritance tree).
If they don't, then it depends on your program flow and what are you doing with them. But nonetheless, they should :)
EDIT: Given your explanation, you could have one Factory per file type, the switch in it would be the authoritative source on the allowed types per file type and they probably share something in common. Reflection is possible, but it's riskier because it's less obvious and self documenting than this one. |
I'd use it if I could do it per-site and aggregate the identity later on my own time and terms. As it is, it's a giant pain in the ass to even find a decent OpenID provider; by decent I mean stackoverflow.com isn't one so I'm not going to bother.
MSN |
It will take all the popular sites supporting it an making it transparent to the user.
"You can make a useraccount here, or if you use MySpace, Google Mail, Hotmail, etc then you can sign in using OpenID."
Don't sell it as a new service, sell it as being able to sign in using a different ID from another site.
The issue, however, is that with everyone supporting it each user will now have a myspace id, google id, etc. Now if they sign onto stackoverflow with their myspace id then later with google they may be perplaxed that stackoverflow doesn't recognize them.
I wonder if openid has a solution for linking openid accounts so they are one and the same - I doubt the technology allows for it, since they are essentially independant signing authorities. Google would have to share data with Myspace and vice versa to enable that...
-Adam |
For a .NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block.
- What do you use?
- Why?
## [System.Web.Caching](http://msdn.microsoft.com/en-us/library/system.web.caching.aspx)
Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really.
- [a KB article warning against 1.0 and 1.1 non web app use](http://support.microsoft.com/kb/917411)
- The 2.0 page has a *comment* that indicates it's OK: <http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx>
- [Scott Hanselman is creeped out by the notion](http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx)
- [The 3.5 page](http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx) includes a warning against such use
- Rob Howard [encouraged use outside of web apps](http://weblogs.asp.net/cschittko/archive/2004/07/04/172684.aspx)
I don't expect to use one of its highlights, [SqlCacheDependency](http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx), but the addition of [CacheItemUpdateCallback](http://msdn.microsoft.com/en-us/library/system.web.caching.cacheitemupdatecallback.aspx) in .NET 3.5 seems like a Really Good Thing.
## [Enterprise Library Caching Application Block](http://msdn.microsoft.com/en-us/library/aa480453.aspx)
- other blocks are already in use so the dependency already exists
- cache persistence isn't necessary; regenerating the cache on restart is OK
Some cache items should always be available, but be refreshed periodically. For these items, getting a callback *after* an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated.
## [Memcached for Win32](http://jehiah.cz/projects/memcached-win32/) + [.NET client](http://sourceforge.net/projects/memcacheddotnet/)
What are the pros and cons when you don't need a *distributed* cache?
|
Enterprise Library CacheFactory.GetCacheManager Throws Null Ref |
|c#|configuration|enterpriselibrary| |
I'm trying to convert an application using the 1.1 version of the Enterprise Library Caching block over to the 2.0 version. I think where I'm really having a problem is that the configuration for the different EntLib pieces was split out over several files. Apparently, this used to be handled by the **ConfigurationManagerSectionHandler**, but is now obsolete in favor of the built-in configuration mechanisms in .NET 2.0.
I'm having a hard time finding a good example of how to do this configuration file splitting, especially in the context of EntLib. Has anyone else dealt with this? |
|c#|configuration|enterprise-library| |
add preddefined data for typedef enums in c |
|c|enum|typedef| |
What is the best approach to define additional data for typedef enums in C?
Example:
typedef enum {
kVizsla = 0,
kTerrier = 3,
kYellowLab = 10
} DogType;
Now I would like to define names for each, for example kVizsla should be "vizsla".
I currently use a function that returns a srting using a large switch block.
|
MySQL replication for fallback scenario |
|mysql|replication|binary-log|fallback| |
When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"?
Obviously it's not possible to make a full database dump every x minutes.
I've read about the [Binary Log][1], is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed?
[1]: http://dev.mysql.com/doc/refman/5.0/en/binary-log.html |
Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. <http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)>
Edit: updated the link to the Java EE 5 docs |
Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. <http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)> |
> I would focus first on your indexes, than have a server admin look at your OS, and if all that doesn't help it might be time for a master/slave configuration.
That's true. Another thing that usually works is to just reduce the quantity of data that's repeadetly worked with. If you have "old data" and "new data" and 99% of your queries work with new data, just move all the old data to another table - and don't look at it ;)
-> Have a look at [partitioning][1].
[1]: http://dev.mysql.com/doc/refman/5.1/en/partitioning.html |
Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution.
Printing is a complex problem and I would love to see the day when better framework support is added for this. |
Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace _all_ of the bad characters.
A typical regular expression to find the comma and quotes (assuming just double quotes) is: *(Blacklist)*
/[,"]/
Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. *(Whitelist)*
/[^0-9\.]/
What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file. |
Binary log is definitely the way to go. However, you should be aware that with MySQL you can't just flip back and forth between servers like that.
One server will be the master and the other will be the slave. You write/read to the master, but can only read from the slave server. If you ever write to the slave, they'll be out of sync and there's no easy way to get them to sync up again (basically, you have to swap them so the master is the new slave, but this is a tedious manual process).
If you need true hot-swappable backup databases you might have to go to a system other than MySQL. If all you want is a read-only live backup that you can use instantly in the worst-case scenario (master is permanently destroyed), Binary Log will suit you just fine. |