instruction stringlengths 0 30k ⌀ |
|---|
First, synchronize all clocks in the system using NTP.
Second, if you are collecting the logs in a single location (like the UDP appender you mention) make sure the logs have enough information to actually help. I would include at least the server that generated the log, the time it happened, and the message. If there is any sort of transaction id, or job id type concept, include that also.
Since you mentioned a UDP Appender I am guessing you are using log4j (or one of it's siblings). Log4j has an MDC class that allows extra information to be passed along through a processing thread. it can help collect some of the extra information and pass it along. |
This is a Windows Forms application? I was able to make a very fat and thick scrollbar by adjusting the "Width" property of my scroll bar control.
![Fat Scroll Bar][1]
Is your scroll bar something you have programmatic access to (i.e. it is a control you added to the form)?
[1]: http://www.smips.com/brad/stackoverflow/fatscrollbar.png |
My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might find it useful (despite the fact that this is a total hack).
#!/usr/bin/python
"""A CGI script to produce an RSS feed of top-level Gallery2 albums."""
#import cgi
#import cgitb; cgitb.enable()
from time import gmtime, strftime
import MySQLdb
ALBUM_QUERY = '''
select g_id, g_title, g_originationTimestamp
from g_Item
where g_canContainChildren = 1
order by g_originationTimestamp desc
limit 0, 20
'''
RSS_TEMPLATE = '''Content-Type: text/xml
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>TITLE</title>
<link>http://example.com/gallery2/main.php</link>
<description>DESCRIPTION</description>
<ttl>1440</ttl>
%s
</channel>
</rss>
'''
ITEM_TEMPLATE = '''
<item>
<title>%s</title>
<link>http://example.com/gallery2/main.php?g2_itemId=%s</link>
<description>%s</description>
<pubDate>%s</pubDate>
</item>
'''
def to_item(row):
item_id = row[0]
title = row[1]
date = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(row[2]))
return ITEM_TEMPLATE % (title, item_id, title, date)
conn = MySQLdb.connect(host = "HOST",
user = "USER",
passwd = "PASSWORD",
db = "DATABASE")
curs = conn.cursor()
curs.execute(ALBUM_QUERY)
print RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])
curs.close() |
WPF Databinding |
|wpf| |
Can anyone point me to a good resource (or throw me a clue) to show me how to do databinding to controls (combobox, listbox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with...
Many Thanks, my fellow Stackies. |
The best resource I've found for WPF data binding is [Bea Costa's blog][1]. Start from the first post and read forward. It's awesome.
[1]: http://www.beacosta.com |
<? require 'auth.php' ?>
<.ul.>
<.li.><a href="">Home</a></.li.>
<.li.><a href="">Products</a></.li.>
<? if( loggedin() ) ?><li><.a href="">Secret area</a.></.li.><? endif; ?>
</.ul.>
Then in pages that require auth just do this:
<?php
require 'auth.php';
require_login();
?>
Where auth.php may contain:
<?php
function loggedin(){
return isset( $_SESSION['loggedin'] );
}
function require_login(){
if( !loggedin() ){
header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );
exit;
}
}
?> |
Outside the scope of your question so I debated not posting this but in Java there are actually 2 types of exceptions, checked and unchecked. The basic difference is that, much like in c[++], you dont have to catch an unchecked exception.
For a good reference [try this][1]
[1]: http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html |
This isn't much better:
public function createShipment($startZip, $endZip, $weight=null){
$weight = !$weight ? $this->getDefaultWeight() : $weight;
}
// or...
public function createShipment($startZip, $endZip, $weight=null){
if ( !$weight )
$weight = $this->getDefaultWeight();
} |
Modify Address Bar URL in AJAX App to Match Current State |
|ajax|rest|url|address-bar| |
I'm writing an AJAX app, but as the user moves through the app, I'd like the URL in the address bar to update despite the lack of page reloads. Basically, I'd like for them to be able to bookmark at any point and thereby return to the current state.
How are people handling maintaining RESTfulness in AJAX apps? Thanks in advance. |
The way I typically go about coding permission systems is having 6 tables.
- Users - this is pretty straight forward it is your typical users table
- Groups - this would be synonymous to your departments
- Roles - this is a table with all permissions generally also including a human readable name and a description
- Users_have_Groups - this is a many-to-many table of what groups a user belongs to
- Users_have_Roles - another many-to-many table of what roles are assigned to an individual user
- Groups_have_Roles - the final many-to-many table of what roles each group has
At the beginning of a users session you would run some logic that pulls out every role they have assigned, either directory or through a group. Then you code against those roles as your security permissions.
Like I said this is what I typically do but your millage may vary. |
An approach I've used in various applications is to have a generic PermissionToken class which has a changeable Value property. Then you query the requested application, it tells you which PermissionTokens are needed in order to use it.
For example, the Shipping application might tell you it needs:
new PermissionToken()
{
Target = PermissionTokenTarget.Application,
Action = PermissionTokenAction.View,
Value = "ShippingApp"
};
This can obviously be extended to Create, Edit, Delete etc and, because of the custom Value property, any application, module or widget can define its own required permissions. YMMV, but this has always been an efficient method for me which I have found to scale well. |
The way to do this is to manipulate location.hash when AJAX updates result in a state change that you'd like to have a discreet URL. For example, this page's URL is:
> http://stackoverflow.com/questions/1457/modify-address-bar-url-in-ajax-app-to-match-current-state
If a client side function executed this code:
// AJAX code to display the "foo" state goes here.
location.hash = 'foo';
Then, the URL displayed in the browser would be updated to:
> http://stackoverflow.com/questions/1457/modify-address-bar-url-in-ajax-app-to-match-current-state#foo
This allows users to bookmark the "foo" state of the page, and use the browser history to navigate between states.
With this mechanism in place, you'll then just need to parse out the hash portion of the URL on the server side and display the appropriate initial state. |
Easy: [BCrypt][1].
[1]: http://www.mindrot.org/projects/ |
Just to clarify Greg's point 1. IIS Manager > Site properties > Directory Security > Secure Communications > Require Secure Channel (SSL) |
Hmm... I know that WebSphere is kind of hard to configure. Thats part of the reason we used ServiceMix for our ESB. Maybe its not enabled by default in WebSphere and you would have to turn it on in the config somewhere. |
using too much static bad or good ? |
|c++|static| |
i like to use static functions in c++ as a way to categorize them, like c# does.
Console::WriteLine("hello")
but is it good or bad ?
if the functions are often used i guess it doesn't matter, but if not do they put pressure on memory ?
The same goes for static const... |
> If I understand correctly, Perforce makes all files that are not checked out read-only.
This is only the default behaviour. If required, frequently changing files can be set to be read-write instead. See a full list of file modifiers [here](http://www.perforce.com/perforce/doc.current/manuals/p4guide/ab_filetypes.html).
Also, for my environment, I am using Eclipse with the [Perforce Plugin](http://www.perforce.com/perforce/products/p4wsad.html). With this plugin, editing a file immediately opens the file for edit. |
Pass reference to element in C# Array |
|c#|arrays| |
I build up an array of strings with
string[] parts = string.spilt(" ");
And get an array with X parts in it, I would like to get a copy of the array of strings starting at element
parts[x-2]
Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?
|
[I used this][1] in one of my internal tools at work.
[1]: http://einaros.blogspot.com/2006/11/put-hex-on-that-dump.html |
I think the best way for larger project is optparse, but if you are looking for an easy way, maybe http://werkzeug.pocoo.org/documentation/script is something for you.
from werkzeug import script
# actions go here
def action_foo(name=""):
"""action foo does foo"""
pass
def action_bar(id=0, title="default title"):
"""action bar does bar"""
pass
if __name__ == '__main__':
script.run()
So basically every function action_* is exposed to the command line and a nice
help message is generated for free.
python foo.py
usage: foo.py <action> [<options>]
foo.py --help
actions:
bar:
action bar does bar
--id integer 0
--title string default title
foo:
action foo does foo
--name string |
I think the best way for larger projects is optparse, but if you are looking for an easy way, maybe http://werkzeug.pocoo.org/documentation/script is something for you.
from werkzeug import script
# actions go here
def action_foo(name=""):
"""action foo does foo"""
pass
def action_bar(id=0, title="default title"):
"""action bar does bar"""
pass
if __name__ == '__main__':
script.run()
So basically every function action_* is exposed to the command line and a nice
help message is generated for free.
python foo.py
usage: foo.py <action> [<options>]
foo.py --help
actions:
bar:
action bar does bar
--id integer 0
--title string default title
foo:
action foo does foo
--name string |
I'm now using [ModelBinder](http://stackoverflow.com/questions/34709/how-do-you-use-the-new-modelbinder-classes-in-aspnet-mvc-preview-5#34725) so that my action method can look (basically) like:
public ActionResult Insert(Contact contact)
{
if (this.ViewData.ModelState.IsValid)
{
this.contactService.SaveContact(contact);
return this.RedirectToAction("Details", new { id = contact.ID });
}
else
{
return this.RedirectToAction("Create");
}
} |
**O(N) time, O(N) memory**
go over the list in order
for each item you see
if(HT.Contains(item)) -> HT.Remove(item)
else
ht.add(item)
at the end, the item in the HT is the item you are looking for.
|
**O(N) time, O(N) memory**
go over the list in order
for each item you see
if(HT.Contains(item)) -> HT.Remove(item)
else
ht.add(item)
at the end, the item in the HT is the item you are looking for.
----------
**comment**: I don't see how can people vote up solutions that give you NLogN performance. in which universe is that "better" ?
I am even more shocked you marked the accepted answer s NLogN solution... |
**O(N) time, O(N) memory**
go over the list in order
for each item you see
if(HT.Contains(item)) -> HT.Remove(item)
else
ht.add(item)
at the end, the item in the HT is the item you are looking for.
----------
**comment**: I don't see how can people vote up solutions that give you NLogN performance. in which universe is that "better" ?
I am even more shocked you marked the accepted answer s NLogN solution...
I do agree however that if memory is required to be constant, then NLogN would be (so far) the best solution. |
**O(N) time, O(N) memory**
HT= Hash Table
HT.clear()
go over the list in order
for each item you see
if(HT.Contains(item)) -> HT.Remove(item)
else
ht.add(item)
at the end, the item in the HT is the item you are looking for.
Note (credit @Jared Updike): This system will find all Odd instances of items.
----------
**comment**: I don't see how can people vote up solutions that give you NLogN performance. in which universe is that "better" ?
I am even more shocked you marked the accepted answer s NLogN solution...
I do agree however that if memory is required to be constant, then NLogN would be (so far) the best solution. |
I'm not sure Scrum is the central issue here; I'm guessing she feels threatened by the new guy bringing in a lot of new ideas and stirring things up. I've been in that situation before as the new person bringing in a new perspective on things, and sometimes it's just difficult to immediately bring those existing people around to a new way of thinking. It often requires a culture shift which doesn't happen overnight.
Try to get her input and opinion on things as much as possible, and try to show that you respect that she has been on the team longer than you. If after a while she still doesn't participate, then all you can do is mention it to your Manager and let them take it from there. |
What is the diffference between the | and || or operators? |
In your menu file or w/e you put:
<? require 'auth.php' ?>
<ul>
<li><a href="">Home</a></li>
<li><a href="">Products</a></li>
<? if( loggedin() ): ?><li><a href="">Secret area</a></li><? endif; ?>
</ul>
Then in pages that require auth just do this:
<?php
require 'auth.php';
require_login();
?>
Where auth.php may contain:
<?php
function loggedin(){
return isset( $_SESSION['loggedin'] );
}
function require_login(){
if( !loggedin() ){
header( 'Location: /login.php?referrer='.$_SERVER['REQUEST_URI'] );
exit;
}
}
?> |
in code behind -- set the DataContext of your list box equal to the collection you're binding to.
private void OnInit(object sender, EventArgs e)
{
//myDataSet is some IEnumerable
// myListBox is a ListBox control.
// Set the DataContext of the ListBox to myDataSet
myListBox.DataContext = myDataSet;
}
In XAML, Listbox can declare which properties it binds to using the "Binding" syntax.
<ListBox Name="myListBox" Height="200"
ItemsSource="{Binding Path=BookTable}"
ItemTemplate ="{StaticResource BookItemTemplate}"/> |
@akdom's question to me:
Looping would work fine on my previous suggestion, and you don't need to do any calculations to determine if a number is even; in your loop, simply skip every even number, as shown below:
//Assuming theInteger is the number to be tested for primality.
// Check if theInteger is divisible by 2. If not, run this loop.
// This loop skips all even numbers.
for( int i = 3; i < sqrt(theInteger); i + 2)
{
if( theInteger % i == 0)
{
//getting here denotes that theInteger is not prime
// somehow indicate that some number, i, divides it and break
break;
}
} |
You could also log to the Windows Event log or to a table in a database. How often are people looking at the event log? If it's being examined on a regualr basis, writing to a table amkes the reporting back much easier as it's trivial to reverse the order and only show the last X events for the current time period. The Windows Event log you can also query the Windows Event Log through [PowerShell][1] or with [LogParser][2].
[1]: http://en.wikipedia.org/wiki/Powershell
[2]: http://www.microsoft.com/downloads/details.aspx?FamilyID=890cd06b-abf8-4c25-91b2-f8d975cf8c07&displaylang=en |
Eclipse : Class file name must end with .class exception in Java Search |
|eclipse|java|search|bug| |
|java|eclipse|search| |
I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.
When using the java search on one particular project, I get an error message saying 'Class file name must end with .class' (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?
I have already tried Project -> Clean... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.
The only reference I've been able to find on Google for the problem is at [http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx][1], but unfortunately his solution (closing, deleting class files, restarting) did not work for me.
If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.
Version: 3.4.0
Build id: I20080617-2000
Also just found this thread - [http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html][2] - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.
Caused by: java.lang.IllegalArgumentException: Class file name must end with .class
at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)
at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)
at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)
at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)
at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)
at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)
at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)
at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)
at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)
at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)
at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
[1]: http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx
[2]: http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html |
Why do you need to fetch the sequence IDs in the first place? In most cases you would insert into a table and return the ID.
insert into t (my_pk, my_data) values (mysequence.nextval, :the_data)
returning my_pk into :the_pk;
It sounds like you are trying to pre-optimize the processing.
If you REALLY need to pre-fetch the IDs then just call the sequence 100 times. The entire point of a sequence is that it manages the numbering. You're not supposed to assume that you can get 100 consecutive numbers. |
If you don't want the button to submit the form, then be sure it has type 'button' rather than 'submit'. For example, you might do something like this:
<input type="button" value="Show My Password" onclick="toggleShowPassword()"/> |
If you get rid of the UpdatePanels do things work as expected with PostBacks? Chances are something in your Page_Load or other event higher up the chain are "resetting" things in some way before it gets to your click event. Could this be the case? |
How about Array.Copy?
http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx
(sorry, you'll need to copy the URL)
>Array.Copy Method (Array, Int32, Array, Int32, Int32)
>Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers. |
How about Array.Copy?
<http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx>
>Array.Copy Method (Array, Int32, Array, Int32, Int32)
>Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers. |
[http://gotcodesnippets.com/][1]
[1]: http://gotcodesnippets.com/ |
[http://gotcodesnippets.com/][1]
[http://www.codekeep.net/][2] has a VS add-in for their snippets, too
[1]: http://gotcodesnippets.com/
[2]: http://www.codekeep.net/ |
The only thing I'd add to <a href="http://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c#44428">Eric</a>'s response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). <code>NextDouble</code> only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and *range*.
So, this would give us random doubles between 0.0 and 2.0:
<pre>rng.NextDouble() * 2.0</pre>
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
<pre>2.5 + rng.NextDouble() * 2.0</pre>
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
<pre>double NextDouble(Random rng, double min, double max)
{
return min + (rng.NextDouble() * (max - min));
}</pre> |
Printing HTML |
|c#|html|printing| |
I want to print HTML from a C# web service. The Web Browser control is overkill, and does not function well in a service-environment, nor does it function well on a system with very tight security constraints. Is there any sort of free .NET library that will support the printing of a basic HTMl page? Here is the code I have so far, that is not running properly.
public void PrintThing(string document)
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread = new Thread((ThreadStart) delegate { PrintDocument(document); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
PrintDocument(document);
}
}
protected void PrintDocument(string document)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = document;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print();
}
This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing Print() to ShowPrintPreviewDialog() yields the following IE script error:
Error: 'dialogArguments.___IE_PrintType' is null or not an object
URL: res://ieframe.dll/preview.dlg
And a small empty print preview dialog appears. |
I want to print HTML from a C# web service. The Web Browser control is overkill, and does not function well in a service-environment, nor does it function well on a system with very tight security constraints. Is there any sort of free .NET library that will support the printing of a basic HTML page? Here is the code I have so far, that is not running properly.
public void PrintThing(string document)
{
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread = new Thread((ThreadStart) delegate { PrintDocument(document); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
else
{
PrintDocument(document);
}
}
protected void PrintDocument(string document)
{
WebBrowser browser = new WebBrowser();
browser.DocumentText = document;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Print();
}
This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing Print() to ShowPrintPreviewDialog() yields the following IE script error:
Error: 'dialogArguments.___IE_PrintType' is null or not an object
URL: res://ieframe.dll/preview.dlg
And a small empty print preview dialog appears. |
This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string. |
You can set a limit to memory consumption for APC, but that potentially limits its effectiveness. If you're just using it for silent opcode caching, then it should be fine. Once the memory allotment is full, no new files will be cached, but everything will work as expected. However, the user-space cache functions like apc_store() and apc_fetch() will fail silently and inexplicably if there is no memory available. This can be tricky to catch and debug since no error is reported and no exception is thrown. |
One option is to use serialization. Here's a blog post explaining it:
<http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html>
|
Turn that into a spec:
-that objects need to implement an interface in order to be allowed into the collection
Something like `ArrayList<ICloneable>()`
Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy.
I think that's the best you can do. |
I suppose it is an ovbious answer:
Make a requisite for the classes stored in the collection to be cloneable. You could check that at insertion time or at retrieval time, whatever makes more sense, and throw an exception.
Or if the item is not cloneable, just fail back to the return by reference option. |
Since you're looking at an entire application stack, you'll need to virtualize the entire server to provide your customers with a realistic demo experience. Thinstall is great for single apps, but not an entire stack....
Microsoft have licensing schemes for this type of situation, since it's only been used for demonstration purposes and not production use a TechNet subscription might just cover you. Give your local Microsoft licensing centre a call to discuss, unlike the offshore support teams they're really helpful and friendly.
For running the 'stack' with the least overhead for your clients, I suggest using VMware. The customers can download the free VMware player, load up the machines (or multiple machines) and get a feel for the system... Microsoft Virtual PC or Virtual Server is going to be a bit more intrusive and not quite the "plug n play" solution that you're looking for.
If you're only looking to ship the application, consider either thinstall or providing Citrix / Terminal services access - customers can remotely login to your own (test) machines and run what they need.
Personally if it's doable, a standalone system would be best - tell your customers install vmware player, then run this app... which launches the various parts of your application stack (maybe off of a DVD) and you've got a fully self contained demo for the marketing guys to pimp out :)
|
Go to **Environment > Fonts and Colors > Display Item**s and change
- Identifier
- String
|
Go to **Environment > Fonts and Colors > Display Item**s and change
- Identifier
- String
> I was hoping that their is I can be
> more specific with the colours - if
> their isn't then that's an acceptable
> answer - just disappointing for me.
Yeah, I don't think you can do that. :) |
Jesus wept.
OK, you asked about C++. Not C. Not frigging _macros_. C++.
C++ has proper strings. Not C's stupid NTBS nonsense. Proper strings. Use them! They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.
C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:
<pre>
std::string bool_as_text(bool b)
{
std::stringstream converter;
converter << b;
return converter.str();
}
</pre>
Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named [Boost](http://www.boost.org/) that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:
<pre>
boost::lexical_cast<std::string>(my_bool)
</pre>
Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.
And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, _that's_ when you should consider doing some macro horror.
|
In your HTML:
<input type="button" onclick="toggleShowPassword();">
You need to use "button" rather than "submit" to prevent your form from posting. |
I'll just throw this out there cuz it's been asked.
Mailto has a lot of disadvantages; mainly size. Since the sender needs to do alot of formatting on the email text, the html code generated can take up a lot of space that fails when using mailto.
thanks for the suggestion though. |
[JSON is valid YAML](http://redhanded.hobix.com/inspect/yamlIsJson.html) which could be very useful. Two for one! |
I did a quick example up of a working version:
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function toggleShowPassword() {
var textBox = $('PasswordText');
if (textBox)
{
alert(textBox.value);
}
}
</script>
</head>
<body>
<input type="password" id="PasswordText" /><input type="button" onclick="toggleShowPassword();" value="Show Password" />
</body>
</html>
The key is that the input is of type button and not submit. I used the [prototype][1] library for retrieving the element by ID.
[1]: http://prototypejs.org/ |
I have run into this before and resolved it, I just can't remember how. I will try to find my old code and get back to you. one thought, do you have EnablePartialRendering enabled in your scriptmanager? maybe try wrapping both containers in a third panel. |
Here is a snippet of how to get Cryographically safe random numbers:
This will fill in the 8 bytes with a crytographically strong sequence of random values.
byte[] salt = new byte[8];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt);
For more details see [How Random is your Random??"] [1] (inspired by a CodingHorror article on deck shuffling)
[1]: http://www.sharpdeveloper.net/content/archive/2007/12/05/how-random-is-your-random.aspx |
Most databases support BULK UPDATE or BULK DELETE operations. |
You cannot open something on the client from server side code. You'd have to use script on the page to do what you're wanting (or something else client-side like ActiveX or embedded .NET or something) |
You cannot open something on the client from server side code. You'd have to use script on the page to do what you're wanting (or something else client-side like ActiveX or embedded .NET or something)
Here's a sample Javascript that invokes an Outlook MailItem from an webpage. This could easily be injected into the page from your server-side code so it executes on the client.
<http://www.codeproject.com/KB/aspnet/EmailUsingJavascript.aspx> |
Log4Cxx should work for you. You need to implement a provider that allows the library user to catch the log output in callbacks. The library would export a function to install the callbacks. That function should, behind the scenes, reconfigure log4cxxx to get rid of all appenders and set up the "custom" appender.
Of course, the library user has an option to not install the callbacks and use log4cxx as is. |
|c#|php|conditional|operator|bool| |
I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasonally I see a single pipe used: | What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable? |
Others will probably pitch in with technical answers (e.g. the query syntax, use of caching, ease or otherwise of mapping to an existing database structure) -- but if you have an established ORM layer the answer is probably
"Why change"?
I've used XPO successfully for years in an established commercial product with several hundred users. I find that it's fast, flexible and does the job. I don't see any need to change at the moment, as our data volumes aren't particularly large and the foibles (caching, mostly) are things we can work around.
If I were starting afresh I'd definitely look at both NHibernate and the ADO.NET Entity Framework. In practice, though, all are good; I'd most likely look at the commercial situation for the project ahead of the technical questions.
For instance, NHibernate is open-source -- is there a viable community there to support the tool and to provide (if necessary) commercial support?
XPO comes from a tools vendor, are they likely to remain in business for the lifetime of the product?
ADO.NET Entity Framework comes from Microsoft, who are notorious for changing database technologies more often then Larry fills his fighter with jet fuel -- will this, too, fade away? |
One is a "bitwise or".
10011b | 01000b => 11011b
The other is a logic or.
true or false => true |
FlexUnit component testing patterns: use addAsync or manually initialize? |
|unit-testing|apache-flex| |
We've been using Flex for about 6 months here at work, and I found that my first batches of FlexUnit tests involving custom components would tend to follow this sort of pattern:
import mx.core.Application;
import mx.events.FlexEvent;
import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
private var component:CustomComponent;
public function testSomeAspect() : void {
component = new CustomComponent();
// set some properties...
component.addEventListener(FlexEvent.CREATION_COMPLETE,
addAsync(verifySomeAspect, 5000));
component.height = 0;
component.width = 0;
Application.application.addChild(component);
}
public function verifySomeAspect(event:FlexEvent) : void {
// Assert some things about component...
}
override public function tearDown() : void {
try {
if (component) {
Application.application.removeChild(component);
component = null;
}
} catch (e:Error) {
// ok to ignore
}
}
Basically, you need to make sure the component has been fully initialized before you can reliably verify anything about it, and in Flex this happens asynchronously after it has been added to the display list. So you need to setup a callback (using FlexUnit's addAsync function) to be notified when that's happened.
Lately i've been just manually calling the methods that the runtime would call for you in the necessary places, so now my tests tend to look more like this:
import flexunit.framework.TestCase;
public class CustomComponentTest extends TestCase {
public function testSomeAspect() : void {
var component:CustomComponent = new CustomComponent();
component.initialize();
// set some properties...
component.validateProperties();
// Assert some things about component...
}
This is much easier to follow, but it kinda feels like I'm cheating a little either way. The first case is slamming it into the current Application (which would be the unit test runner shell app), and the latter isn't a "real" environment.
I was wondering how other people would handle this sort of situation? |
Difference between a byte array and MemoryStream |
|performance|comparison| |
I am reading a binary file into a parsing program. I will need to iterate through the file and look for certain markers so I can split the file up and pass those parts into their respective object’s constructors.
Is there an advantage to holding the file as a stream, either MemoryStream or FileStream, or should it be converted into a byte[] array?
Keith
|
If I were in your shoes I would try to leverage what I knew (sprocs) with Linq2Sql. Linq2Sql can still use your sprocs but then you have the added bonus of putting a new tool in your belt. I think having a grap on the Linq2XXX (X being a random technology not adult entertainment....which isn't a bad idea now that I think of it) syntax and methodology is going to be a great addition to your skill set using Linq over a collection of objects is way sweet.
But ultimately something like NHibernate will suit you better in the long run. |
If I were in your shoes I would try to leverage what I knew (sprocs) with Linq2Sql. Linq2Sql can still use your sprocs but then you have the added bonus of putting a new tool in your belt. I think having a grasp on the Linq2XXX (X being a random technology not adult entertainment....which isn't a bad idea now that I think of it) syntax and methodology is going to be a great addition to your skill set using Linq over a collection of objects is way sweet.
But ultimately something like NHibernate will suit you better in the long run. |
You can right click on the tab strip and insert a new vertical (or horizontal) tab group.
This allows you to view multiple tabs at the same time. |
By the way you can use
> $_REQUEST['destroy']
which would work regardless if the data is passed in a POST or a GET request. |
What is the best way to rename (move) file system branches in .NET? |
|system.io.fileinfo|moveto|directory|branch| |
I would like to rename files and folders recursively by applying a string replacement operation.
E.g. The word "shark" in files and folders should be replaced by the word "orca".
C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe
should be moved to:
C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe
The same operation should be of course applied to each child object in each folder level as well.
I was experimenting with some of members of the System.IO.FileInfo and System.IO.DirectoryInfo classes, but didn't find an easy way to do it.
fi.MoveTo(fi.FullName.Replace("shark", "orca"));
Doesn't do the trick.
I was hoping there is some kind of "genious" way to perfom this kind of operation.
Klaus
|
|system.io.fileinfo|moveto|directory| |
|file|directory|system.io.fileinfo| |
I can appreciate the logic of not putting binaries in the repository but I think there is a huge advantage too. If you want to be able to pull a specific revision out from the past (usually an older tag) I like being able to have everything I need come from the svn checkout. Of course this doesn't include Visual Studio or the .NET framework but having the right version of nant, nunit, log4net, etc. makes it really easy to go from checkout to build. This way getting started is as easy as "svn co project" followed by "nant build".
One thing we do is put ThirdParty binaries in a separate tree and use svn:external to bring it the version we need. To make life easy, we'll have a folder for each version that has been used. For example, we might bring in the ThirdParty/Castle/v1.0.3 folder to the current project. This way everything need to build/test the product is inside or below the project root. The tradeoff in disk space is well worth it in our experience. |
This is similar to what Kevin said. You can have your client state as some javascript object, and when you want to save the state, you serialize the object (using JSON and base64 encoding). You can then set the fragment of the href to this string.
var encodedState = base64(json(state));
var newLocation = oldLocationWithoutFragment + "#" + encodedState;
document.location = newLocation; // adds new entry in browser history
document.location.replace(newLocation); // replaces current entry in browser history
The first way will treat the new state as a new location (so the back button will take them to the previous location). The latter does not. |
It has been a while, so this is not comprehensive.
**Character Sets**
Unicode is great, but you can't get away with ignoring other character sets. The default character set on Windows XP (English) is Cp1252. On the web, you don't know what a browser will send you (though hopefully your container will handle most of this). And don't be surprised when there are bugs in whatever implementation you are using. Character sets can have interesting interactions with filenames when they move to between machines.
**Translating Strings**
Translators are, generally speaking, not coders. If you send a source file to a translator, they will break it. Strings should be extracted to resource files (e.g. properties files in Java or resource DLLs in Visual C++). Translators should be given files that are difficult to break and tools that don't let them break them.
Translators do not know where strings come from in a product. It is difficult to translate a string without context. If you do not provide guidance, the quality of the translation will suffer.
While on the subject of context, you may see the same string "foo" crop up in multiple times and think it would be more efficient to have all instances in the UI point to the same resource. This is a bad idea. Words may be very context-sensitive in some languages.
Translating strings costs money. If you release a new version of a product, it makes sense to recover the old versions. Have tools to recover strings from your old resource files.
String concatenation and manual manipulation of strings should be minimized. Use the format functions where applicable.
If you have a translation process that requires someone to manually cut and paste strings at any time, you are asking for trouble.
**Dates, Times, Calendars, Currency, Number Formats, Time Zones**
These can all vary from country to country. A comma may be used to denote decimal places. Times may be in 24hour notation. Not everyone uses the Gregorian calendar. You need to be unambiguous, too. If you take care to display dates as MM/DD/YYYY for the USA and DD/MM/YYYY for the UK on your website, the dates are ambiguous unless the user knows you've done it.
**Especially Currency**
The Locale functions provided in the class libraries will give you the local currency symbol, but you can't just stick a pound (sterling) or euro symbol in front of a value that gives a price in dollars.
**User Interfaces**
Layout should be dynamic. Not only are strings likely to double in length on translation, the entire UI may need to be inverted (Hebrew; Arabic) so that the controls run from right to left. And that is before we get to Asia.
**Testing Prior To Translation**
- Use static analysis of your code to locate problems. At a bare minimum, leverage the tools built into your IDE. (Eclipse users can go to Window > Preferences > Java > Compiler > Errors/Warnings and check for non-externalised strings.)
- Smoke test by simulating translation. It isn't difficult to parse a resource file and replace strings with a pseudo-translated version that doubles the length and inserts funky characters. You don't have to speak a language to use a foreign operating system. Modern systems should let you log in as a foreign user with translated strings and foreign locale. If you are familiar with your OS, you can figure out what does what without knowing a single word of the language.
- Keyboard maps and character set references are very useful.
- Virtualisation would be very useful here.
**Non-technical Issues**
Sometimes you have to be sensitive to cultural differences (offence or incomprehension may result). A mistake you often see is the use of flags as a visual cue choosing a website language or geography. Unless you want your software to declare sides in global politics, this is a bad idea. If you were French and offered the option for English with St. George's flag (the flag of England is a red cross on a white field), this might result in confusion for many English speakers - assume similar issues will arise with foreign languages and countries. Icons need to be vetted for cultural relevance. What does a thumbs-up or a green tick mean? Language should be relatively neutral - addressing users in a particular manner may be acceptable in some regions, but considered rude in another.
**Resources**
C++ and Java programmers may find the ICU website useful: <http://www.icu-project.org/> |
It has been a while, so this is not comprehensive.
**Character Sets**
Unicode is great, but you can't get away with ignoring other character sets. The default character set on Windows XP (English) is Cp1252. On the web, you don't know what a browser will send you (though hopefully your container will handle most of this). And don't be surprised when there are bugs in whatever implementation you are using. Character sets can have interesting interactions with filenames when they move to between machines.
**Translating Strings**
Translators are, generally speaking, not coders. If you send a source file to a translator, they will break it. Strings should be extracted to resource files (e.g. properties files in Java or resource DLLs in Visual C++). Translators should be given files that are difficult to break and tools that don't let them break them.
Translators do not know where strings come from in a product. It is difficult to translate a string without context. If you do not provide guidance, the quality of the translation will suffer.
While on the subject of context, you may see the same string "foo" crop up in multiple times and think it would be more efficient to have all instances in the UI point to the same resource. This is a bad idea. Words may be very context-sensitive in some languages.
Translating strings costs money. If you release a new version of a product, it makes sense to recover the old versions. Have tools to recover strings from your old resource files.
String concatenation and manual manipulation of strings should be minimized. Use the format functions where applicable.
Translators need to be able to modify hotkeys. Ctrl+P is print in English; the Germans use Ctrl+D.
If you have a translation process that requires someone to manually cut and paste strings at any time, you are asking for trouble.
**Dates, Times, Calendars, Currency, Number Formats, Time Zones**
These can all vary from country to country. A comma may be used to denote decimal places. Times may be in 24hour notation. Not everyone uses the Gregorian calendar. You need to be unambiguous, too. If you take care to display dates as MM/DD/YYYY for the USA and DD/MM/YYYY for the UK on your website, the dates are ambiguous unless the user knows you've done it.
**Especially Currency**
The Locale functions provided in the class libraries will give you the local currency symbol, but you can't just stick a pound (sterling) or euro symbol in front of a value that gives a price in dollars.
**User Interfaces**
Layout should be dynamic. Not only are strings likely to double in length on translation, the entire UI may need to be inverted (Hebrew; Arabic) so that the controls run from right to left. And that is before we get to Asia.
**Testing Prior To Translation**
- Use static analysis of your code to locate problems. At a bare minimum, leverage the tools built into your IDE. (Eclipse users can go to Window > Preferences > Java > Compiler > Errors/Warnings and check for non-externalised strings.)
- Smoke test by simulating translation. It isn't difficult to parse a resource file and replace strings with a pseudo-translated version that doubles the length and inserts funky characters. You don't have to speak a language to use a foreign operating system. Modern systems should let you log in as a foreign user with translated strings and foreign locale. If you are familiar with your OS, you can figure out what does what without knowing a single word of the language.
- Keyboard maps and character set references are very useful.
- Virtualisation would be very useful here.
**Non-technical Issues**
Sometimes you have to be sensitive to cultural differences (offence or incomprehension may result). A mistake you often see is the use of flags as a visual cue choosing a website language or geography. Unless you want your software to declare sides in global politics, this is a bad idea. If you were French and offered the option for English with St. George's flag (the flag of England is a red cross on a white field), this might result in confusion for many English speakers - assume similar issues will arise with foreign languages and countries. Icons need to be vetted for cultural relevance. What does a thumbs-up or a green tick mean? Language should be relatively neutral - addressing users in a particular manner may be acceptable in some regions, but considered rude in another.
**Resources**
C++ and Java programmers may find the ICU website useful: <http://www.icu-project.org/> |
It has been a while, so this is not comprehensive.
**Character Sets**
Unicode is great, but you can't get away with ignoring other character sets. The default character set on Windows XP (English) is Cp1252. On the web, you don't know what a browser will send you (though hopefully your container will handle most of this). And don't be surprised when there are bugs in whatever implementation you are using. Character sets can have interesting interactions with filenames when they move to between machines.
**Translating Strings**
Translators are, generally speaking, not coders. If you send a source file to a translator, they will break it. Strings should be extracted to resource files (e.g. properties files in Java or resource DLLs in Visual C++). Translators should be given files that are difficult to break and tools that don't let them break them.
Translators do not know where strings come from in a product. It is difficult to translate a string without context. If you do not provide guidance, the quality of the translation will suffer.
While on the subject of context, you may see the same string "foo" crop up in multiple times and think it would be more efficient to have all instances in the UI point to the same resource. This is a bad idea. Words may be very context-sensitive in some languages.
Translating strings costs money. If you release a new version of a product, it makes sense to recover the old versions. Have tools to recover strings from your old resource files.
String concatenation and manual manipulation of strings should be minimized. Use the format functions where applicable.
Translators need to be able to modify hotkeys. Ctrl+P is print in English; the Germans use Ctrl+D.
If you have a translation process that requires someone to manually cut and paste strings at any time, you are asking for trouble.
**Dates, Times, Calendars, Currency, Number Formats, Time Zones**
These can all vary from country to country. A comma may be used to denote decimal places. Times may be in 24hour notation. Not everyone uses the Gregorian calendar. You need to be unambiguous, too. If you take care to display dates as MM/DD/YYYY for the USA and DD/MM/YYYY for the UK on your website, the dates are ambiguous unless the user knows you've done it.
**Especially Currency**
The Locale functions provided in the class libraries will give you the local currency symbol, but you can't just stick a pound (sterling) or euro symbol in front of a value that gives a price in dollars.
**User Interfaces**
Layout should be dynamic. Not only are strings likely to double in length on translation, the entire UI may need to be inverted (Hebrew; Arabic) so that the controls run from right to left. And that is before we get to Asia.
**Testing Prior To Translation**
- Use static analysis of your code to locate problems. At a bare minimum, leverage the tools built into your IDE. (Eclipse users can go to Window > Preferences > Java > Compiler > Errors/Warnings and check for non-externalised strings.)
- Smoke test by simulating translation. It isn't difficult to parse a resource file and replace strings with a pseudo-translated version that doubles the length and inserts funky characters. You don't have to speak a language to use a foreign operating system. Modern systems should let you log in as a foreign user with translated strings and foreign locale. If you are familiar with your OS, you can figure out what does what without knowing a single word of the language.
- Keyboard maps and character set references are very useful.
- Virtualisation would be very useful here.
**Non-technical Issues**
Sometimes you have to be sensitive to cultural differences (offence or incomprehension may result). A mistake you often see is the use of flags as a visual cue choosing a website language or geography. Unless you want your software to declare sides in global politics, this is a bad idea. If you were French and offered the option for English with St. George's flag (the flag of England is a red cross on a white field), this might result in confusion for many English speakers - assume similar issues will arise with foreign languages and countries. Icons need to be vetted for cultural relevance. What does a thumbs-up or a green tick mean? Language should be relatively neutral - addressing users in a particular manner may be acceptable in one region, but considered rude in another.
**Resources**
C++ and Java programmers may find the ICU website useful: <http://www.icu-project.org/> |
> Is there a way one can ensure that the
> exceptions thrown are always caught
> using try/catch by the calling
> function?
I find it rather funny, that the Java crowd - [including myself][1] - is trying to avoid checked Exceptions. They are trying to work their way around being forced to catch Exceptions by using [RuntimeExceptions][2].
[1]: http://dlinsin.blogspot.com/2008/01/wonderful-checked-exceptions.html
[2]: http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html |