text
stringlengths 8
267k
| meta
dict |
---|---|
Q: What is the best way to add an event in JavaScript? I see 2 main ways to set events in JavaScript:
*
*Add an event directly inside the tag like this:
<a href="" onclick="doFoo()">do foo</a>
*Set them by JavaScript like this:
<a id="bar" href="">do bar</a>
and add an event in a <script> section inside the <head> section or in an external JavaScript file, like that if you're using prototypeJS:
Event.observe(window, 'load', function() {
$('bar').observe('click', doBar);
}
I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).
The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.
Which method is the best?
A killer answer will be fully appreciated!
A:
I think the first method is easier to read and maintain
I've found the opposite to be true. Bear in mind that sometimes more than one event handler will be bound to a given control.
Declaring all events in one central place helps to organize the actions taking place on the site. If you need to change something you don't have to search for all places making a call to a function, you simply have to change it in one place. When adding more elements that should have the same functionality you don't have to remember to add the handlers to them; instead, it's often enough to let them declare a class, or even not change them at all because they logically belong to a container element of which all child elements get wired to an action. From an actual code:
$$('#itemlist table th > a').invoke('observe', 'click', performSort);
This wired an event handler to all column headers in a table to make the table sortable. Imagine the effort to make all column headers sortable separately.
A: In my experience, there are two major points to this:
1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.
2) The second kind, i.e. Event.observe() has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call.
A: I believe the second method is generally preferred because it keeps information about action (i.e. the JavaScript) separate from the markup in the same way CSS separates presentation from markup.
I agree that this makes it a little more difficult to see what's happening in your page, but good tools like firebug will help you with this a lot. You'll also find much better IDE support available if you keep the mixing of HTML and Javascript to a minimum.
This approach really comes into its own as your project grows, and you find you want to attach the same javascript event to a bunch of different element types on many different pages. In that case, it becomes much easier to have a single pace which attaches events, rather than having to search many different HTML files to find where a particular function is called.
A: You can also use addEventListener (not in IE) / attachEvent (in IE).
Check out: http://www.quirksmode.org/js/events_advanced.html
These allow you to attach a function (or multiple functions) to an event on an existing DOM object. They also have the advantage of allowing un-attachment later.
In general, if you're using a serious amount of javascript, it can be useful to make your javascript readable, as opposed to your html. So you could say that onclick=X in the html is very clear, but this is both a lack of separation of the code -- another syntactic dependency between pieces -- and a case in which you have to read both the html and the javascript to understand the dynamic behavior of the page.
A: Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. They also ensure that you can add multiple event handlers so that you can use scripts from different sources without the different event handlers overwriting each other.
So your practical choices are;
One. If your script is simple and the only one that will ever run on the page, create an init function like so:
window.onload = function () {
init();
}
function init() {
// actual function calls go here
doFoo();
}
Two. If you have many scripts or plan to mashup scripts from different sources, use a library and its onDOMReady method to safely add your event handlers
A: My personal preference is to use jQuery in external js files so the js is completely separate from the html. Javascript should be unobtrusive so inline (ie, the first example) is not really the best choice in my opinion. When looking at the html, the only sign that you are using js should be the script includes in the head.
An example of attaching (and handling) events might be something like this
var myObject = {
allLinkElements: null,
init: function()
{
// Set all the elements we need
myObject.setElements();
// Set event handlers for elements
myObject.setEventHandlers();
},
clickedLink: function()
{
// Handle the click event
alert('you clicked a link');
},
setElements: function()
{
// Find all <a> tags on the page
myObject.allLinkElements = $('a');
// Find other elements...
},
setEventHandlers: function()
{
// Loop through each link
myObject.allLinkElements.each(function(id)
{
// Assign the handler for the click event
$(this).click(myObject.clickedLink);
});
// Assign handlers for other elements...
}
}
// Wait for the DOM to be ready before initialising
$(document).ready(myObject.init);
I think this approach is useful if you want to keep all of your js organised, as you can use specific objects for tasks and everything is nicely contained.
Of course, the huge benefit of letting jQuery (or another well known library) do the hard work is that cross-browser support is (largely) taken care of which makes life much easier
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to you pass a variable amount of parmeters to web-service We are trying to create a web-service that we plan to pass a variable amount of variables to it.
Can this be done?
Basically instead of pass all possible parameters we wish to pass only the set values and use the defaults set in the web-service.
Here is an example of the XML we are looking to send, we would sent an unknown amount of functions depending on the needed return.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<WebMethod xmlns="http://tempuri.org/">
<domains>
<function1>
<title>Some Title</title>
<type>25</type>
</function1>
<function2 />
<function3>
<param>13</param>
</function3>
</domains>
</WebMethod>
</soap:Body>
</soap:Envelope>
Will this work or should we do a different way?
A: I would pass in an xml document instead of doing concreate functions for this.
The webservice in your example is leaky - the consumer needs to know too much about this interface and the implementation of the webservice internally.
XML Document and then tie that with an XSD. That way you can prevalidte the input to the webservice.
Take a look at these
IBM Developer
ASP.NET Forum
I would also recommend using this for testing webservices and its free
WSStudio
A: You can simply pass a variable-length array as a parameter.
A: If you dont like the idea of an Array (this is not slating Konrad's answer - you may have differing param types) you can pass complex objects (i.e. objects that you made yourself).. The downside is that you cannot then test using the ASMX page, but would need to do it all in code (which isn't really a bad thing, especially if you are used to it).
A: I agree with littlegeek. Do not make your web service is hard method. Make it a receiving end point to receive messages. Particularly, a Command Message.
http://www.eaipatterns.com/CommandMessage.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: In Maven 2, how do I know from which dependency comes a transitive dependency? I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.
To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.
A: If you use eclipse and the m2eclipse plugin then there is a graphical version of dependency tree where you can filter by scope etc.
A: Using the Maven Dependency Plugin:
mvn dependency:tree
A: If you run maven with "-x" switch, it will print out plenty of diagnostics, I guess the relevant dependency path can be picked up from there.
A: You can have many reports by
mvn site
One of them is the dependency report.
A: To add to @David Crow, here's a dependency:tree example from the Maven site:
mvn dependency:tree -Dincludes=velocity:velocity
might output
[INFO] [dependency:tree]
[INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT
[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile
[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile
[INFO] \- velocity:velocity:jar:1.4:compile
A: The dependency information is also included in the Project Information/Dependencies report if you have maven generate a site for the project, using mvn site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "122"
} |
Q: C++ Thread question - setting a value to indicate the thread has finished Is the following safe?
I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc
A: Instead of using a member variable to signal that the thread is done, why not use a condition? You are already are using the boost libraries, and condition is part of the thread library.
Check it out. It allows the worker thread to 'signal' that is has finished, and the main thread can check during execution if the condition has been signaled and then do whatever it needs to do with the completed work. There are examples in the link.
As a general case I would neve make the assumption that a resource will only be modified by the thread. You might know what it is for, however someone else might not - causing no ends of grief as the main thread thinks that the work is done and tries to access data that is not correct! It might even delete it while the worker thread is still using it, and causing the app to crash. Using a condition will help this.
Looking at the thread documentation, you could also call thread.timed_join in the main thread. timed_join will wait for a specified amount for the thread to 'join' (join means that the thread has finsihed)
A: If you really want to get into the details of communication between threads via shared memory, even declaring a variable volatile won't be enough, even if the compiler does use appropriate access semantics to ensure that it won't get a stale version of data after checking the flag. The CPU can issue reads and writes out of order as long (x86 usually doesn't, but PPC definitely does) and there is nothing in C++9x that allows the compiler to generate code to order memory accesses appropriately.
Herb Sutter's Effective Concurrency series has an extremely in depth look at how the C++ world intersects the multicore/multiprocessor world.
A: I don't mean to be presumptive, but it seems like the purpose of your finished_flag variable is to pause the main thread (at some point) until the thread thrd has completed.
The easiest way to do this is to use boost::thread::join
// launch the thread...
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
// ... do other things maybe ...
// wait for the thread to complete
thrd.join();
A: Having the thread set a flag (or signal an event) before it exits is a race condition. The thread has not necessarily returned to the OS yet, and may still be executing.
For example, consider a program that loads a dynamic library (pseudocode):
lib = loadLibrary("someLibrary");
fun = getFunction("someFunction");
fun();
unloadLibrary(lib);
And let's suppose that this library uses your thread:
void someFunction() {
volatile bool finished_flag = false;
thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);
while(!finished_flag) { // ignore the polling loop, it's besides the point
sleep();
}
delete thrd;
}
void myclass::mymethod() {
// do stuff
finished_flag = true;
}
When myclass::mymethod() sets finished_flag to true, myclass::mymethod() hasn't returned yet. At the very least, it still has to execute a "return" instruction of some sort (if not much more: destructors, exception handler management, etc.). If the thread executing myclass::mymethod() gets pre-empted before that point, someFunction() will return to the calling program, and the calling program will unload the library. When the thread executing myclass::mymethod() gets scheduled to run again, the address containing the "return" instruction is no longer valid, and the program crashes.
The solution would be for someFunction() to call thrd->join() before returning. This would ensure that the thread has returned to the OS and is no longer executing.
A: You never mentioned the type of finished_flag...
If it's a straight bool, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the finished_flag variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the bool volatile, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a CEvent in MFC (or equivilent in boost) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Looking for examples of "real" uses of continuations I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the Wikipedia article:
(define the-continuation #f)
(define (test)
(let ((i 0))
; call/cc calls its first function argument, passing
; a continuation variable representing this point in
; the program as the argument to that function.
;
; In this case, the function argument assigns that
; continuation to the variable the-continuation.
;
(call/cc (lambda (k) (set! the-continuation k)))
;
; The next time the-continuation is called, we start here.
(set! i (+ i 1))
i))
I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate.
So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.
Cheers!
A: Seaside:
*
*homepage
*wikipedia page
A: @Pat
Seaside
Yes, Seaside is a great example. I browsed its code quickly and found this message illustrating passing control between components in a seemingly statefull way accross the Web.
WAComponent >> call: aComponent
"Pass control from the receiver to aComponent. The receiver will be
temporarily replaced with aComponent. Code can return from here later
on by sending #answer: to aComponent."
^ AnswerContinuation currentDo: [ :cc |
self show: aComponent onAnswer: cc.
WARenderNotification raiseSignal ]
So nice!
A: I built my own unit testing software. Before executing the test, I store the continuation before executing the test, and then on failure, I (optionally) tell the scheme interpreter to drop into debug mode, and re-invoke the continuation. This way I can step through the problematic code really easily.
If your continuations are serializable, you can also store then on application failure, and then re-invoke them to get detailed information about variable values, stack traces, etc.
A: Continuations are used by some web servers and web frameworks to store session information. A continuation object is created for each session and then used by each request within the session.
There's an article about this approach here.
A: I came accross an implementation of the amb operator in this post from http://www.randomhacks.net, using continuations.
Here's what the amb opeerator does:
# amb will (appear to) choose values
# for x and y that prevent future
# trouble.
x = amb 1, 2, 3
y = amb 4, 5, 6
# Ooops! If x*y isn't 8, amb would
# get angry. You wouldn't like
# amb when it's angry.
amb if x*y != 8
# Sure enough, x is 2 and y is 4.
puts x, y
And here's the post's implementation:
# A list of places we can "rewind" to
# if we encounter amb with no
# arguments.
$backtrack_points = []
# Rewind to our most recent backtrack
# point.
def backtrack
if $backtrack_points.empty?
raise "Can't backtrack"
else
$backtrack_points.pop.call
end
end
# Recursive implementation of the
# amb operator.
def amb *choices
# Fail if we have no arguments.
backtrack if choices.empty?
callcc {|cc|
# cc contains the "current
# continuation". When called,
# it will make the program
# rewind to the end of this block.
$backtrack_points.push cc
# Return our first argument.
return choices[0]
}
# We only get here if we backtrack
# using the stored value of cc,
# above. We call amb recursively
# with the arguments we didn't use.
amb *choices[1...choices.length]
end
# Backtracking beyond a call to cut
# is strictly forbidden.
def cut
$backtrack_points = []
end
I like amb!
A: Continuations can be used in "real-life" examples whenever the program flow is not linear, or not even pre-determined. A familiar situation is web applications.
A: Continuations are a good alternative to thread-per-request in server programming (including web application frontends.
In this model, instead of launching a new (heavy) thread every time a request comes in, you just start some work in a function. Then, when you are ready to block on I/O (i.e. reading from the database), you pass a continuation into the networking response handler. When the response comes back, you execute the continuation. With this scheme, you can process lots of requests with just a few threads.
This makes the control flow more complex than using blocking threads, but under heavy load, it is more efficient (at least on today's hardware).
A: The amb operator is a good example that allows prolog-like declarative programming.
As we speak I'm coding a piece of music composition software in Scheme (I'm a musician with next to no knowledge of the theory behind music and I'm just analysing my own pieces to see how the maths behind it works.)
Using the amb operator I can just fill in constraints which a melody must satisfy and let Scheme figure out the result.
Continuations are probably put into Scheme because of the language philosophy, Scheme is a framework enabling you to realize about any programming paradigm found in other language by defining libraries in Scheme itself. Continuations are for making up your own abstract control structures like 'return', 'break' or to enable declarative programming. Scheme is more 'generalizing' and begs that such constructs should be able to be specified by the programmer too.
A: In Algo & Data II we used these all the times to "exit" or "return" from a (long) function
for example the BFS algorthm to traverse trees with was implemented like this:
(define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes)
(define visited (make-vector (graph.order graph) #f))
(define q (queue.new))
(define exit ())
(define (BFS-tree node)
(if (node-discovered node)
(exit node))
(graph.map-edges
graph
node
(lambda (node2)
(cond ((not (vector-ref visited node2))
(when (edge-discovered node node2)
(vector-set! visited node2 #t)
(queue.enqueue! q node2)))
(else
(edge-bumped node node2)))))
(if (not (queue.empty? q))
(BFS-tree (queue.serve! q))))
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
(cond ((null? nodes)
(graph.map-nodes
graph
(lambda (node)
(when (not (vector-ref visited node))
(vector-set! visited node #t)
(root-discovered node)
(BFS-tree node)))))
(else
(let loop-nodes
((node-list (car nodes)))
(vector-set! visited (car node-list) #t)
(root-discovered (car node-list))
(BFS-tree (car node-list))
(if (not (null? (cdr node-list)))
(loop-nodes (cdr node-list)))))))))
As you can see the algorithm will exit when the node-discovered function returns true:
(if (node-discovered node)
(exit node))
the function will also give a "return value": 'node'
why the function exits, is because of this statement:
(call-with-current-continuation
(lambda (my-future)
(set! exit my-future)
when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it.
So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work)
another smaller example doing the same with call-cc:
(define (connected? g node1 node2)
(define visited (make-vector (graph.order g) #f))
(define return ())
(define (connected-rec x y)
(if (eq? x y)
(return #t))
(vector-set! visited x #t)
(graph.map-edges g
x
(lambda (t)
(if (not (vector-ref visited t))
(connected-rec t y)))))
(call-with-current-continuation
(lambda (future)
(set! return future)
(connected-rec node1 node2)
(return #f))))
A: How about the Google Mapplets API? There are a bunch of functions (all ending in Async) to which you pass a callback. The API function does an async request, gets it's result, then passes that result to your callback (as the "next thing to do"). Sounds a lot like continuation passing style to me.
This example shows a very simple case.
map.getZoomAsync(function(zoom) {
alert("Current zoom level is " + zoom); // this is the continuation
});
alert("This might happen before or after you see the zoom level message");
As this is Javascript there's no tail call optimization, so the stack will grow with every call into a continuation, and you'll eventually return the thread of control to the browser. All the same, I think it's a nice abstraction.
A: If you have to invoke an asynchronous action, and suspend execution until you get the result, you would normally either poll for the result or put the rest of your code in a callback to be executed by the asynchronous action upon completion. With continuations you don't need to do the inefficient option of polling, and you don't need to wrap up all your code to be run after the asynch event in a callback - you just pass the current state of the code as your callback - and the code is effectively "woken up" as soon as the asynch action completes.
A: Continuations can be used to implement exceptions, a debugger.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Delete Records from Access database, error while deleting I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form).
A: If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.
This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:
DoCmd.RunCommand acCmdUndo
A: samjudson suggested:
DoCmd.RunCommand acCmdUndo
You can also use Me.Undo, to undo the last edit to the form in which the code runs.
Or, Me!MySubForm.Form.Undo to undo the last unsaved edit in the subform whose subform control is named "MySubForm".
You can also use Me!MyControl.Undo to cancel the last edit to a particular control.
"DoCmd.RunCommand acCmdUndo" will apply the Undo operation to the currently selected object, but you won't know for sure whether it will apply at the control or form level. Using the commands I suggested completely disambiguates what gets undone.
Keep in mind, though, that Undo will not undo edits to a control after the control's AfterUpdate event has fired, or to a form after its AfterUpdate event has fired (i.e., the data has been saved to the underlying data table).
A: Also check the "row locking mechanism" that you have. I haven't used Access in a while but I remember that you could use set that in the table properties. You can access those properties clicking in the famous "dot" in the upper left corner of the table to bring up its properties. Well if you're using Access, you know what I'm talking about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Alternatives for enhanced reading and parsing text files using .NET I need to read from a variety of different text files (I've some delimited files and some fixed width files). I've considered parsing the files line by line (slow using the File.ReadLine type methods) and reading the file using the ODBC text driver (faster) but does anyone have any other (better) suggestions? I'm using .NET/C#.
A: I'm not sure you could really do a text-and-Excel file parser, not unless by Excel file you mean a comma/pipe/tab delimited file, which is actually just another text file. Reading actual excel files require you to use the MS Office libraries.
For delimited text file parsing, you could look into FileHelpers -- open source and they pretty much have it covered. Not sure if it will match your speed requirements though.
A: Answering my own question:
I ended up using the Microsoft.VisualBasic.FileIO.TextFieldParser object, see:
http://msdn.microsoft.com/en-us/library/f68t4563.aspx
(example of implementation here)
This allows me to handle csv files without worrying about how to cope with whether fields are enclosed in quotes, contain commas, escaped quotes etc.
A: Ignoring the Excel part (which you say isn't important):
I've found LINQ to be fairly useful in parsing txt files (pipe-delimited or csv)
e.g. This reads a pipe-delimited file skipping the hader row and creates an IEnumerable as the result:
var records =
from line in File.ReadAllLines(@"c:\blah.txt").Skip(1)
let parts = line.Split('|')
select parts;
A: If the files are relatively small you can use the File class. It has these methods which may help you:
*
*ReadAllBytes
*ReadAllLines
*ReadAllText
A: Your question is a little vague. I assume that the text files contain structured data, not just random lines of text.
If you are parsing the files yourself then .NET has a library function to read all the lines from a text file into an array of strings (File.ReadAllLines). If you know your files are small enough to hold in memory, then you can use this method and iterate over the array using a regular expression to validate & extract the fields.
Excel files are a different ball game. .XLS files are binary, not text, so you would need to use a 3rd party library to access them. .XLSX files from Excel 2007 contain compressed XML data, so once again you would need to decompress the XML then use an XML parser to get at the data. I would not recommend writing your own XML parser, unless you feel the need for the intellectual exercise.
A: I agree with John,
For example:-
using System.IO;
...
public class Program {
public static void Main() {
foreach(string s in File.ReadAllLines(@"c:\foo\bar\something.txt") {
// Do something with each line...
}
}
}
A: The File reading process is not slow if you read all file at once using the File class and the methods suggested by John. Depending upon the file's size and what you want to do with them, it may use more or less memory. I'd suggest you try with File.ReadAllText (or whatever is appropriate for you)
A: Regarding reading XLS Files:
If you have Microsoft Office XP and above, you have access to the already included .NET SDK Office Libraries, where you can "natively" read XLS files, Word, PPT, etc. Please note that under Office XP you have to manually check that during install (unless you had .NET previously installed).
I don't know if these libraries are available as a separate package if you don't have Microsoft Office.
For some obscure reason, all these libraries (including the latest versions from Office 2007 -a.k.a.: Office 12), are COM components that are a pain to use, cause ugly dependencies and are not backwards compatible. I.E.: if you have some methods that work with Office XP (Office11), and you install that onto a customer with Office 12, it doesn't work, because some interfaces where changed. So you need to maintain two set of "libraries" and methods to deal with that. The same holds true if use Office 12 libraries to program, and you customer has Office 11. Your libraries don't work. :S
I don't know why Microsoft never created a Microsoft.Office.XXXX managed library (wrapper) around those ugly things.
Anyways, your question is quite strange, try to follow some advice here. Good luck!
A: The ODBC text driver is now rather out of date - it has no Unicode support.
Amazingly MS Excel still uses it, so if you open a Unicode CSV in Excel 2007 (rather than import it) you lose all non-ASCII chars.
You best bet is to use .Net's file reading methods, as others have suggested.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C#.Net: Why is my Process.Start() hanging? I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
psi.WorkingDirectory = @"c:\build";
psi.FileName = Environment.SystemDirectory + @"\cmd.exe";
psi.Arguments = "/q /c build.cmd";
psi.UseShellExecute = false;
psi.UserName = "builder";
psi.Password = password;
Process.Start(psi);
If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).
The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?
EDIT: See my answer below for the contents of the batch file.
*
*The output.txt never gets created.
I added these lines:
psi.RedirectStandardOutput = true;
Process p = Process.Start(psi);
String outp = p.StandardOutput.ReadLine();
and stepped through them in debug mode. The code hangs on the ReadLine(). I'm stumped!
A: I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:
http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx
That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.
A: Why not just do all the work in C# instead of using batch files?
I was bored so i wrote this real quick, it's just an outline of how I would do it since I don't know what the command line switches do or the file paths.
using System;
using System.IO;
using System.Text;
using System.Security;
using System.Diagnostics;
namespace asdf
{
class StackoverflowQuestion
{
private const string MSBUILD = @"path\to\msbuild.exe";
private const string BMAIL = @"path\to\bmail.exe";
private const string WORKING_DIR = @"path\to\working_directory";
private string stdout;
private Process p;
public void DoWork()
{
// build project
StartProcess(MSBUILD, "myproject.csproj /t:Build", true);
}
public void StartProcess(string file, string args, bool redirectStdout)
{
SecureString password = new SecureString();
foreach (char c in "mypassword".ToCharArray())
password.AppendChar(c);
ProcessStartInfo psi = new ProcessStartInfo();
p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = WORKING_DIR;
psi.FileName = file;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = redirectStdout;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.Start();
if (redirectStdout)
{
stdout = p.StandardOutput.ReadToEnd();
}
}
void p_Exited(object sender, EventArgs e)
{
if (p.ExitCode != 0)
{
// failed
StringBuilder args = new StringBuilder();
args.Append("-s k2smtpout.secureserver.net ");
args.Append("-f [email protected] ");
args.Append("-t [email protected] ");
args.Append("-a \"Build failed.\" ");
args.AppendFormat("-m {0} -h", stdout);
// send email
StartProcess(BMAIL, args.ToString(), false);
}
}
}
}
A: Without seeing the build.cmd it's hard to tell what is going on, however, you should build the path using Path.Combine(arg1, arg2); It's the correct way to build a path.
Path.Combine( Environment.SystemDirectory, "cmd.exe" );
I don't remember now but don't you have to set UseShellExecute = true ?
A: Another possibility to "debug" it is to use standardoutput and then read from it:
psi.RedirectStandardOutput = True;
Process proc = Process.Start(psi);
String whatever = proc.StandardOutput.ReadLine();
A: In order to "see" what's going on, I'd suggest you transform the process into something more interactive (turn off Echo off) and put some "prints" to see if anything is actually happening. What is in the output.txt file after you run this?
Does the bmail actually executes?
Put some prints after/before to see what's going on.
Also add "@" to the arguments, just in case:
psi.Arguments = @"/q /c build.cmd";
It has to be something very simple :)
A: My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command with the "> logfile.txt" operator at the end, it might help you find the problem.
A: Here's the contents of build.cmd:
@echo off
set path=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;%path%
msbuild myproject.csproj /t:Build > output.txt
IF NOT ERRORLEVEL 1 goto :end
:error
bmail -s k2smtpout.secureserver.net -f [email protected] -t [email protected] -a "Build failed." -m output.txt -h
:end
del output.txt
As you can see, I'm careful not to output anything. It all goes to a file that gets emailed to me if the build happens to fail. I've actually been running this file as a scheduled task nightly for quite a while now. I'm trying to build a web app that allows me to run it on demand.
Thanks for everyone's help so far! The Path.Combine tip was particularly useful.
A: I think cmd.exe hangs if the parameters are incorrect.
If the batch executes correctly then I would just shell execute it like this instead.
ProcessStartInfo psi = new ProcessStartInfo();
Process p = new Process();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.WorkingDirectory = @"c:\build";
psi.FileName = @"C:\build\build.cmd";
psi.UseShellExecute = true;
psi.UserName = "builder";
psi.Password = password;
p.StartInfo = psi;
p.Start();
Also it could be that cmd.exe just can't find build.cmd so why not give the full path to the file?
A: What are the endlines of you batch? If the code hangs on ReadLine, then the problem might be that it's unable to read the batch file…
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: ASP.NET MVC on IIS6 Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6?
I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S.
So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6.
Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work?
UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, no ISAPI and no IIS-settings, please.
A: Since you can't modify IIS settings to map .mvc to ASP.Net, you can use a different extension that's already mapped to ASP.Net. For example, you could use {controller}.ashx/{action} and it should work out of the box on IIS 6.
A: You don't have to live with that extension if you can install an ISAPI filter on the server.
Basically you route matched urls to the {controller}.mvc variety, then in ASP.NET you rewrite this url to remove .mvc -- doing this you don't have to define any extra routes or expose .mvc to your users.
I've written about this here:
http://www.flux88.com/UsingASPNETMVCOnIIS6WithoutTheMVCExtension.aspx
and Steve Sanderson has a good post here as well: http://blog.codeville.net/2008/07/04/options-for-deploying-aspnet-mvc-to-iis-6/
A: As mentioned in this blog post by Phil Hack, it is possible to setup extension-less URLs for ASP.NET MVC in IIS 6 using wildcard application mappings:
*
*In IIS 6, go to the Application Configuration Properties for your ASP.NET MVC web application.
*Click "Insert..." in the Wildcard application maps section.
*Set the Executable to the path of the aspnet_isapi.dll (on my machine this is c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll).
*Make sure NOT to check the "Verify that file exists" and click "OK".
However as also mentioned by Hack, there are some performance implications of doing this.
A: With IIS6 you can do one of two things:
*
*Setup an ISAPI filter to map MVC URLs to ASP.NET
*Include an extension in the URL. For example: htp://localhost/Home.mvc
Since option 1 is not available on most web-hosts, you have to go for number 2.
A: It took me a bit, but I figured out how to make the extensions work with IIS 6. First, you need to rework the base routing to include .aspx so that they will be routed through the ASP.NET ISAPI filter.
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you navigate to Home.aspx, for example, your site should be working fine. But Default.aspx and the default page address of http://[website]/ stop working correctly. So how is that fixed?
Well, you need to define a second route. Unfortunately, using Default.aspx as the route does not work properly:
routes.MapRoute(
"Default2", // Route name
"Default.aspx", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
So how do you get this to work? Well, this is where you need the original routing code:
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
When you do this, Default.aspx and http://[website]/ both start working again, I think because they become successfully mapped back to the Home controller. So the complete solution is:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}.aspx/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
And your site should start working just fine under IIS 6. (At least it does on my PC.)
And as a bonus, if you are using Html.ActionLink() in your pages, you should not have to change any other line of code throughout the entire site. This method takes care of properly tagging on the .aspx extension to the controller.
A: Url rewriting can help you to solve the problem. I've implemented solution allowing to deploy MVC application at any IIS version even when virtual hosting is used.
http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx
A: I have a sample application on IIS6.
I found quick-and-dirty solution. (Dirty, because it contains default view name with extension) It does not require additional route, or anything special. (Except, your default route must {controller}.aspx/{action}... format)
Here the default.aspx
<%@ Page Language="C#"%>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
HttpContext.Current.RewritePath("~/Home.aspx/index");
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
</script>
My sample applications default action was index, in Home directory.
Note : I saw this code at Phil Haack's blog. Thanks to Brian Lowe.
A: I have a detailed step by step guide, but it requires that you use isapi_rewrite. View it at: http://biasecurities.com/blog/2008/how-to-enable-pretty-urls-with-asp-net-mvc-and-iis6/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: How do I get latest from a Visual Studio solution from the command line? How do I get the latest version of my solution recursively like its done in the solution explorer context menu of Visual Studio? I want to do this from the command line or via a macro. I'm trying to automate a part of my daily routine by using a set of batch files. I am sure a lot of developers would love to have something like this.
tf get only gets contents of a folder recursively (not solution). It does not look at project dependencies and so on. That won't work.
A: TFS has a .Net SDK that allows you to create your own custom programs that interact with a TFS Server. You could write a small program that performs the task you need:
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer("MyServer");
VersionControlServer vcs = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
WorkSpace[] myWorkSpaces = vcs.QueryWorkSpaces("MyWorkSpaceName", "MyLoginName", "MyComputer");
myWorkSpaces[0].Get(VersionSpec.Latest, GetOptions.GetAll);
A: I agree that Solution Explorer will "by design" omit all those objects, but only if you do not include them as Solution items, which I believe you should include in your solutions, so that a newbie can open the solution, do a Get Latest, and know they have all the dependencies needed for that solution, and not have to learn how to do it via a command line tool, or use Source Control Explorer if they don't want to.
Including all the non-code dependencies as solution items (we organize the solution folders using the same folder structure as their source control folders) reduces "voodoo" knowledge required to open and compile the solution for new developers on a project.
It would be good if you could link entire folder trees to a solution folder in the VS solution.
A: If you have dependent projects under a different folder. Use this to loop through all of the sub directories to grab the latest for each project:
Start in the main directory C:\Project\SupportingProjects
FOR /D %%G IN ("*") DO ECHO ..from....%%G && tf get C:\Projects\SupportingProjects\%%G
::Get the latest for the Main project
tf get C:\Projects\MainProject /recursive
In my case the MainProject folder contains the solution file and the project file.
I found this easy and simple.
More on the FOR command: http://ss64.com/nt/for_d.html
A: Well... It looks like you have three options.
*
*In your batch file, issue a tf get at each directory branch you want.
*reorganize your solution so that all of the dependencies are under the same root path.
*Use the visual way of right clicking on the loaded project and issuing the get command.
The only time it's actually solution aware is when the project is loaded in the IDE; or when it's loaded by the build servers.
A: I know you mentioned batch files, but let me throw something else out for you.
I'm going to guess that you are using the 2005 version of TFS. 2008 has all of the scheduling stuff built in.
However, you could also use CruiseControl.net to do scheduled builds for you. I've used both TFS 2008 and CruiseControl and they both seem to work just fine.
A: One more possible solution is to use powershell. The following link is to a code project sample which shows how to get a solution from TFS and build it locally. Powershell is a much better solution than regular batch files.
http://www.codeproject.com/KB/install/ExtractAndBuild.aspx
A: Don't do this. VS is not nearly as smart as you think. (As evidenced by the mysterious & futile checkouts that everyone has experienced for 3+ product cycles, you & I included. This is not the mark of a reliable system!)
What you describe only works for project-to-project references. Running source control operations from Solution Explorer will "by design" omit:
*
*project-to-assembly references
*video, sound, PDFs, any other type of media that VS doesn't support but may play an integral role in the product
*MSBuild *.targets files that are referenced in your projects
*any files of any kind that are referenced from custom targets
*any 3rd party executables required by the build process
*etc
Just say no to incomplete synchronization. Down that path, only headaches lie.
Run 'tf get' with no path scope from the command line, or rightclick -> Get from the root $/ node in Source Control Explorer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Django ImageField core=False in newforms admin In the transition to newforms admin I'm having difficulty figuring out how specify core=False for ImageFields.
I get the following error:
TypeError: __init__() got an unexpected keyword argument 'core'
[Edit] However, by just removing the core argument I get a "This field is required." error in the admin interface on attempted submission. How does one accomplish what core=False is meant to do using newforms admin?
A: To get rid of "This field is required," you need to make it not required, by using blank=True (and possibly null=True as well, if it's not a CharField).
A: The core attribute isn't used anymore.
From Brian Rosner's Blog:
You can safely just remove any and all core arguments. They are no longer used. newforms-admin now provides a nice delete checkbox for exisiting instances in inlines.
A: This is simple. I started getting this problems a few revisions ago. Basically, just remove the "core=True" parameter in the ImageField in the models, and then follow the instructions here to convert to what the newforms admin uses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is it possible to persist (without reloading) AJAX page state across BACK button clicks? I am familiar with several approaches to making the back button work in AJAX applications in various situations, but I have not found a solution that will work gracefully in my specific scenario.
The pages I am working with are the search interface for a site. You enter terms in a normal search box, click "go and wind up at a search results page. On the search results page there are a ton of UI controls for filtering/sorting the search results to find what you are looking for. Some of the operations triggered by these controls may take a (relatively) long time to complete (e.g. several seconds).
This latency is fine in case where the user is initially filtering/sorting their results... there's a nice AJAX spinner and so on... however when the user clicks on a search result and then clicks on the BACK button, I would like the page to instantly be restored to the state it was in when they clicked through.
I can restore the states using IFRAMEs/fragment identifiers as a dictionary of page history, but what ends up happening is that when the user first hits the back button the initial page is loaded, then it (re) makes the AJAX query to get the page state back, which triggers the AJAX spinner and another wait of possible several seconds.
Is there any approach that does not require this kind of two-stage load of the page when the user returns to the page via the BACK button?
Edited to add: I am partial to jquery but I'd be happy with solutions that depend on other libraries/toolkits or that are standalone/raw javascript.
Edited to add: I should've added that I'm trying to avoid cookies/sessions because this prevents people having multiple brower windows/tabs open and manipulating different sets of search results at the same time.
Edit: Matt, can you elaborate on your proposed solution (triggering a page change event via fragment identifer)? I see how this would help with BACK button clicks across the same page but not coming BACK to the search results page after clicking on a specific result.
A: Just use a cookie.
A: Have you investigated the YUI Browser History Manager?
A: Would it help to trigger a page change event using the "Add some info to the # at the end of the URL approach".
That way, clicking the back button shouldn't actually change the page, and you should be able to restore state without the first page load.
A: Use something persistent that is tied to the user's profile.
Cookies and sessions are good ideas, but you can also keep those stuff in the database. That gives you an added advantage of being able to save the user's filtering preferences accross different browsing session.(if, for exampple, he was looking for something in the office and then decided to continue searching when he is back at home).
It all depends on the complexity of the filters and weather or not it is something you think that the user will want to use accross diffrent browsing sessions..
A:
Edited to add: I should've added that
I'm trying to avoid cookies/sessions
because this prevents people having
multiple brower windows/tabs open and
manipulating different sets of search
results at the same time.
You can create a random token and assign it to the fragment identifier.
*
*on first page load create a token if no fragment identifier is set
*before navigating out, store all the temporary ajax data in a cookie with that token as index.
*when hitting back, if you have a fragment identifier set, load the data from the corresponding token in the cookie.
*you can even add a "time" field to expire tokens, etc...
sample cookie (JSON):
{"ajaxcache":[{"token":<token>,"time":<time>,"data":<data>}, ... ]}
A: Try to use localStorage object. Here is crossbrower libs jStorage and WEBSHIMS json-storage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to hide the cancel button on an ASP.NET ChangePassword control I'm considering using the ChangePassword control on an ASP.NET 2.0 Webform. I don't want the 'cancel' button to show.
Is there a good way to hide it without resorting to silly "width = 0" sort of games?
Or perhaps there's a generic way to walk through the parts of a composite control like this
and hide individual parts?
A: Set CancelButtonStyle.CssClass to something like "hiddenItem" and set the CSS to "display:none".
Otherwise you can convert the control to a template and simply delete away the cancel-button manually. When you click the control in Design-mode in Visual Studio, you get a little arrow with options and one of them is "Convert to Template".
A: A quick an easy way just using your .aspx page is to set these cancel button properties on the changepassword control:
CancelButtonType="Link"
CancelButtonText=""
A: You can use the ChangePassword.CancelButtonStyle Property to set the CSS-class on the Cancel Button. Then just apply "display: none" on the specified class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python descriptor protocol analog in other languages? Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of the lookup overhead?
A: I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.
I wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.
A: Ruby and C# both easily let you create accessors by specifying getter/setter methods for an attribute, much like in Python. However, this isn't designed to naturally let you write the code for these methods in another class the way that Python allows. In practice, I'm not sure how much this matters, since every time I've seen an attribute defined through the descriptor protocol its been implemented in the same class.
EDIT: Darn my dyslexia (by which I mean careless reading). For some reason I've always read "descriptor" as "decorator" and vice versa, even when I'm the one typing both of them. I'll leave my post intact since it has valid information, albeit information which has absolutely nothing to do with the question.
The term "decorator" itself is actually the name of a design pattern described in the famous "Design Patterns" book. The Wikipedia article contains many examples in different programming languages of decorator usage: http://en.wikipedia.org/wiki/Decorator_pattern
However, the decorators in that article object-oriented; they have classes implementing a predefined interface which lets another existing class behave differently somehow, etc. Python decorators act in a functional way by replacing a function at runtime with another function, allowing you to effectively modify/replace that function, insert code, etc.
This is known in the Java world as Aspect-Oriented programming, and the AspectJ Java compiler lets you do these kinds of things and compile your AspectJ code (which is a superset of Java) into Java bytecode.
I'm not familiar enough with C# or Ruby to know what their version of decorators would be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Best algorithm to test if a linked list has a cycle What's the best (halting) algorithm for determining if a linked list has a cycle in it?
[Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.
[Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".
A: Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:
node* tortoise(begin), * hare(begin);
while(hare = hare->next)
{
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
hare = hare->next;
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
tortoise = tortoise->next;
}
O(n), which is as good as you can get.
A: Precondition: Keep track of the list size (update the size whenenver a node is added or deleted).
Loop detection:
*
*Keep a counter when traversing the list size.
*If the counter exceeds the list size, there is a possible cycle.
Complexity: O(n)
Note: the comparison between the counter and the list size, as well as the update operation of the list size, must be made thread-safe.
A: Take 2 pointer *p and *q , start traversing the linked list "LL" using both pointers :
1) pointer p will delete previous node each time and pointing to next node.
2) pointer q will go each time in forward direction direction only.
conditions:
1) pointer p is pointing to null and q is pointing to some node : Loop is present
2) both pointer pointing to null: no loop is there
A: What about using a hash table to store the already seen nodes (you look at them in order from the start of the list)? In practise, you could achieve something close to O(N).
Otherwise, using a sorted heap instead of a hash table would achieve O(N log(N)).
A: I wonder if there's any other way than just going iteratively - populate an array as you step forwards, and check if the current node is already present in the array...
A: Konrad Rudolph's algorithm won't work if the cycle isn't pointing to the beginning. The following list will make it an infinite loop: 1->2->3->2.
DrPizza's algorithm is definitely the way to go.
A:
In this case OysterD's code will be the fastest solution (vertex coloring)
That would really surprise me. My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass. With no hashing, no memory allocation, etc.
A:
In this case OysterD's code will be the fastest solution (vertex coloring)
That would really surprise me. My solution makes at most two passes through the list (if the last node is linked to the penultimate lode), and in the common case (no loop) will make only one pass. With no hashing, no memory allocation, etc.
Yes. I've noticed that the formulation wasn't perfect and have rephrased it. I still believe that a clever hashing might perform faster – by a hair. I believe your algorithm is the best solution, though.
Just to underline my point: the vertec coloring is used to detect cycles in dependencies by modern garbage collectors so there is a very real use case for it. They mostly use bit flags to perform the coloring.
A: You will have to visit every node to determine this. This can be done recursively. To stop you visiting already visited nodes, you need a flag to say 'already visited'. This of course doesn't give you loops. So instead of a bit flag, use a number. Start at 1. Check connected nodes and then mark these as 2 and recurse until the network is covered. If when checking nodes you encounter a node which is more than one less than the current node, then you have a cycle. The cycle length is given by the difference.
A: Two pointers are initialized at the head of list. One pointer forwards once at each step, and the other forwards twice at each step. If the faster pointer meets the slower one again, there is a loop in the list. Otherwise there is no loop if the faster one reaches the end of list.
The sample code below is implemented according to this solution. The faster pointer is pFast, and the slower one is pSlow.
bool HasLoop(ListNode* pHead)
{
if(pHead == NULL)
return false;
ListNode* pSlow = pHead->m_pNext;
if(pSlow == NULL)
return false;
ListNode* pFast = pSlow->m_pNext;
while(pFast != NULL && pSlow != NULL)
{
if(pFast == pSlow)
return true;
pSlow = pSlow->m_pNext;
pFast = pFast->m_pNext;
if(pFast != NULL)
pFast = pFast->m_pNext;
}
return false;
}
This solution is available on my blog. There is a more problem discussed in the blog: What is the entry node when there is cycle/loop in a list?
A: "Hack" solution (should work in C/C++):
*
*Traverse the list, and set the last bit of next pointer to 1.
*If find an element with flagged pointer -- return true and the first element of the cycle.
*Before returning, reset pointers back, though i believe dereferencing will work even with flagged pointers.
Time complexity is 2n. Looks like it doesn't use any temporal variables.
A: This is a solution using a Hash table ( just a list actually) to save the pointer address.
def hash_cycle(node):
hashl=[]
while(node):
if node in hashl:
return True
else:
hashl.append(node)
node=node.next
return False
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: Query TFS for updated files I want to get an overview of files that are updated in TFS (that someone else checked in) that I don't have the latest version for.
A: In Visual Studio Source Control Explorer, right click on the directory you want to compare, and select "Compare". It will pop up a dialog with a couple of filtering options, and then show you what's out of date.
A: if they checked them in as part of a single changeset then you can find them that way.
(right click file in solution explorer, view history, double-click on the relevant changeset and you'll see all the related files for that checkin)
Is your question about finding this info via the TFS API via the website, or via the visual studio interface?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: COMException "Library not registered." while using System.DirectoryServices I have only just started received the following error in my windows forms application under .NET 2 framework on windows 2000 when using System.DirectoryServices.
{System.Runtime.InteropServices.COMException}
System.Runtime.InteropServices.COMException: {"Library not registered."}
_className: Nothing
_COMPlusExceptionCode: -532459699
_data: Nothing
_dynamicMethods: Nothing
_exceptionMethod: Nothing
_exceptionMethodString: Nothing
_helpURL: Nothing
_HResult: -2147319779
_innerException: Nothing
_message: "Library not registered."
_remoteStackIndex: 0
_remoteStackTraceString: Nothing
_source: Nothing
_stackTrace: {System.Array}
_stackTraceString: Nothing
_xcode: -532459699
_xptrs: 0
Source: "System.DirectoryServices"
StackTrace: " at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindAll()
I have re-installed the framework and re-registered activeds.dll however this has not resolved the issue. I am guessing I need to find another dll and re-register it however it is not clear which dll this would be.
A: Having used Reflector to have a quick peak at the Directory Services code, it looks like your Active Directory Service Interfaces installation might be kaput.
You can download version 2.5 from Technet although I'm not sure if it's the latest version or if it works with Windows 2000.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fix build error in Visual Studio: '"LC.exe" exited with code -1' I get the following error when building my Windows Forms solution:
"LC.exe" exited with code -1
I use two commercial Windows Forms Libraries: Infragistics and the Gantt-Control from plexityhide.com, that's why I have licenses.licx files in my WinForms Projects. We also use Visual Sourcesafe as our Source Control.
When the licenses.licx files are in the Projects I cannot build without the above error. However, when I exclude them from my projects the build works fine. But I need the licenses.licx files when I want to work with the commercial controls in the designer.
This is a brand new developer machine with Windows XP SP3 (German) and Visual Studio 2005 Team Edition for Software Developers (German) with SP1.
It's Windows XP 32-Bit by the way.
Any suggestions?
A: We frequently encounter this error from our last project. The solution is to reinstall the libraries since we're using the trial version. This occurs when the libraries expire.
A: I reinstalled Infragistics and that seems to have fixed it.
A: Is there any more information in the error message?
When I had problems with LC.exe in the past, most times it was because the licensed component was upgraded (the version number increased), but the licx file still contained the old version.
In this case, you can try to update the version in the licx file manually, or change it to x.y.z.* to just work for further updates. You can also try to re-generate the licx file by deleting it and re-inserting the licensed windows forms controls into your form.
A: Problem mainly arises due to license file. Exclude the file licenses.licx from your project
A: seems the problem is due to updating the controls.
licenses.licx includes version 2 of .net controls. it works deleting lines with version 2 (after versioning).
Other times worked in this way:
add an empty form, then insert the control that caused the problem.
A: There should be a license.licx file in the properties folder when you use commercial components. It is often corrupted. If you clean its contents, the "LC.EXE" exited with code -1 disappears.
A: Had the same problem. Could not build with licenses.licx (even if blank) and had 3rd party licensing problems without licenses.licx. This problem appeared after I upgraded Visual Studio from 2015 to 2019 and changed my .NET Target Framework Version from v4.5.2 to v4.7.2. To do further testing I ran the command (from the error message) in cmd at the location of lc.exe. I got no useful errors but noticed a version mismatch. I didn't have lc.exe for 4.7.2 installed. ("C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools\lc.exe"). With some guidance from this answer, I installed the .NET 4.7.2 Developer Pack and could build with licenses.licx again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Visually Tag/Mark a Window I'm looking for a way to visually mark or tag a window (any OS) so that it stands out.
A while back, I accidentally replaced a live production database containing thousands of records with an empty dev version, simply because the two instances of Enterprise Manager looked identical to one another. I'd like to avoid that in the future!
A: None that I'm aware of, but perhaps a virtual desktop system for your OS of choice would help keep the separation a little better for you.
A: If you are using TOAD for your db access you can set a custom colour for each of your connections. (List of Quest products here scroll down page to the TOAD links)
The colour appears as a border around each TOAD window (at least it did on the Windows version I used in my last job)
I set production dbs to RED, pre-production to orange, and dev to green.
A: Since you didn't restrict your question, I'll answer with my solution to this type of problem. I often am logged into multiple different machines with PuTTY as different users (including as root). If I have a window that I want to distinguish from the others, for example when I need to make sure I know I am typing commands as root, I change the background of the window to a different colour. A window that is mostly red really stands out as being something extraordinary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: 64bit Memory allocation I've been asked to create a Delphi compatible dll in C++ to do simple 64bit memory management.
The background is that the system in Delphi needs to allocate a lots of chunks of memory that would go well outside 32bit addressable space. The Delphi developer explained to me that he could not allocate memory with the Delphi commands available to him. He says that he can hold a 64bit address, so he just wants to call a function I provide to allocate the memory and return a 64bit pointer to him. Then another function to free up the memory later.
Now, I only have VS 2008 at my disposal so firstly I'm not even sure I can create a Delphi compatible dll in the first place.
Any Delphi experts care to help me out. Maybe there is a way to achieve what he requires without re-inventing the wheel. Other developers must have come across this before in Delphi.
All comments appreciated.
A: Only 64 bit processes can address 64 bit memory. A 64 bit process can only load 64 bit dlls and 32 bits processes can only load 32 bits dlls. Delphi's compiler can only make 32 bits binaries.
So a 32 bits Delphi exe can not load your 64 bit c++ dll. It could load a 32 bit c++ dll, but then that dll wouldn't be able to address the 64 bit memory space. You are kind of stuck with this solution.
Delphi could, with the right compiler options and Windows switches address 3GB of memory without problems. Even more memory could be accessed by a 32 bits process if it uses Physical Address Extension. It then needs to swap memory pages in and out of the 32 bits memory through the use of Address Windowing Extensions.
A: Delphi pointers are 32-bit. Period. Your Delphi developer may be able to 'store' the 64-bit values you want to return to him, but he can't access the memory that they point to, so it's pretty futile.
Previously, I'd written:-
A 64-bit version of Delphi is on
Codegear/Embarcadero's road map
for "middle of 2009". Product quality
seems to be (at last!) taking
precedence over hitting ship dates
exactly, so don't hold your breath...
But, in August 2010, Embarcadero published a new roadmap here. This doesn't give specific dates, but mentions a 64-bit Compiler Preview, with Projected Availability, 1st Half of 2011.
A: You might take a look at Free Pascal as it includes a 64 bit version and is mostly Delphi compatible syntax.
A: In order to allocate memory shared by multiple process, you should use a memory mapped file.
The code available at http://www.delphifaq.com/faq/delphi_windows_API/f348.shtml can be used to communicate between a 32 bit and a 64 bit process.
Here are the steps:
*
*Create a memory mapped file, either on disk, either on memory;
*Create a mutex to notify file change;
*One end write some data to the memory mapped file;
*Then it flags the mutex;
*Other end receive the mutex notification;
*Then it reads the data from the memory mapped file.
It's up to you to create a custom binary layout in the memory mapped file, in order to share any data.
By design, memory mapped files are fast (it's a kernel-level / x86 CPU feature), and can handle huge memory (up to 1 GB for a 32 bit process, from my experiment).
This kind of communication is used by http://cc.embarcadero.com/Author/802978 to call any 64 bit dll from a 32 bit Delphi program.
A: You might also want to add a way to pin and unpin that 64-bit pointer to a 32-bit memory address. Since this is Delphi, I'm pretty sure it's Windows specific, so you might as well use Address Windowing Extensions. That way, you can support allocating, freeing, and pinning and unpinning memory to a 32-bit address range and still take advantage of a 64-bit memory allocation space. Assuming that the user will actually commit the memory such that it fits in the 32-bit virtual address space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Has .NET made raw COM and DCOM programming redundant? Has the introduction of the .net framework made raw programming in COM and DCOM redundant ?
(Except for using some COM+ services, e.g. for transaction management through the System.EnterpriseServices namespace)
A: COM was the last major technology that MS actually dogfooded. MS are continuing to build new APIs that depend on COM; for example, Vista's new Media Foundation (a kind of successor to DirectShow, which was also COM-based) is a COM API. So is Direct3D10 (and I would assume D3D11). I don't think it's going to disappear any time soon, and for a lot of Windows programming tasks it's not at all redundant.
A: Not yet, but I'd say in the long term, it aims to. Obviously there will always be a place for the lower levels, but from what I understand of Microsoft's strategy, the move is towards replacing as much with managed code as possible.
A: Not yet, because the OS is still unmanaged.
If MS finally do what their labs have been talking about for years and produce a fully managed OS then it will.
That OS won't be backwards compatible though. They would have to produce managed versions of Office, IE, etc first. They will have to produce a virtual machine to run unmanaged apps.
The pain would be something similar to the move from Mac OS9 to OSX.
A: I suppose that depends on what you mean by 'raw'. I still find the need to expose COM APIs from .Net class libraries on occasion. Makes the process of migrating from certain platforms to .Net a lot easier since I can replace small pieces via COM.
A: .NET has been deliberately designed to replace COM (and, consequently, DLL Hell) so while .NET applications still can access COM components, all new development are encouraged to move to .NET except if you have a very good reason to stick with COM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Multiple web-sites running in IIS simulatenously At work, we have multiple branches that we may be working on at any time.
Our solution so far as been to create multiple web-sites but you can only run one web-site at a time. This makes switching between branches more of a pain that in should be.
I just want to go to the URL, mapped in my hosts file, for that branch and it just work.
Our client machines are XP machines with IIS 5.1. Is there any way to make IIS 5.1 run more than one web-site simultaneously?
A: Yes, it is a restriction and this one website can have only 10 simultanious connections.
Buy a Windows 2003 or 2008 Small Business Edition, it is quite cost-effective in this scenario.
A: Are virtual directories an option for you? I run multiple versions of the same website this way.
A: I believe it is a restriction of IIS that you can only run more than one website on server versions of the windows OS.
A: Oddly enough, this is something I remember Jeff covering ages ago, but I guess it's still relevant if you're on IIS 5.1:
http://www.codinghorror.com/blog/archives/000329.html
A: One way you could solve this without reinstalling your computer is to create each branch in a virtual subdirectory under you current web-root. Then at the top-level website, create a default.asp(x) the reads Request.ServerVariables["SERVER-NAME"] (should be underscore) and redirects the browser to whatever virtual directory/application you want to access. That way you can create all the "virtual" domains you want in your hosts file.
A: With Windows XP and IIS 5.1 you cannot run moultiple web sites.
You can however run multiple ASP.NET hosts. You would probably have to write the host your self.
Something like this should get you started:
string FileLoction = "..Path to the branch..";
HttpListenerWrapper lw = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(
typeof(HttpListenerWrapper), "/", FileLocation);
string[] prefixes = new string[]
{
"http://localhost:8081/",
"http://127.0.0.1:8081/"
};
lw.Configure(prefixes, "/", FileLocation);
lw.Start();
A: Picking up on Biri's answer rather than choose SBS there is a specific Windows Server Web edition which is the cheapest of all, around $399 and doesn't require CALs.
Otherwise, if it's just for developer machines Vista Ultimate allows multiple IIS sites hosted simultaneously.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What types of testing do you include in your build process? I use TFS 2008. We run unit tests as part of our continuous integration build and integration tests nightly.
What other types of testing do you automate and include in your build process? what technologies do you use to do so?
I'm thinking about smoke tests, performance tests, load tests but don't know how realistic it is to integrate these with Team Build.
A: First, we have check-in (smoke) tests that must run before code can be checked in. It's done automatically by running a job that runs the tests and then makes the check-in to source control upon successful test completion. Second, cruise control kicks off build and regression tests. The product is built then several sets of integration tests are run. The number of tests vary by where we are in the release cycle. More testing is added late in the cycle during ramp down. Cruise control takes all submissions within a certain time window (12 minutes) so your changes may be built and tested with a small number of others. Third, there's an automated nightly build and tests that are quite extensive. We have load or milestone points every 2 or 3 weeks. At a load point, all automated tests are run plus manual testing is done. Performance testing is also done for each milestone. Performance tests can be kicked off on request but the hardware available is limited so people have to queue up for performance tests. Usually people rely on the load performance tests unless they are making changes specifically to improve performance. Finally, stress tests are also done for each load. These tests are focussed on making sure the product has no memory leaks or anything else that prevents 24/7 running of the product as opposed to performance. All of this is done with ant, cruise control, and Python scripts.
A: Integrating load testing during you build process is a bad idea, just do your normal unit testing to make sure that all your codes work as expected. Load and performance testing should be done separately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SimpleTest vs PHPunit I was wondering if anyone that has experience in both this stuff can shed some light on the significant difference between the two if any?
Any specific strength of each that makes it suitable for any specific case?
A: This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions.
I'm really really baffled that SimpleTest still is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen:
*
*PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit).
*PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely.
*Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else.
*PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports.
*Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously).
*PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests.
*(Subjective) PHPUnit provides much nicer code coverage reports than Simpletest
*With PHPUnit you also get these reports inside your IDE (Netbeans, Eclipse, ...)
*Also there are a couple of suggestings for a web interface to phpunit tests.
I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear:
pear channel-discover pear.phpunit.de
pear install phpunit/PHPUnit
and the "first test" looks pretty much the same.
As of PHPUnit 3.7 it's even easier to install it by just using the PHAR Archive
wget http://pear.phpunit.de/get/phpunit.phar
chmod +x phpunit-3.7.6.phar
or for windows just downloading the phar and running:
php phpunit-.phar
or when using the supported composer install ways like
"require-dev": {
"phpunit/phpunit": "3.7.*"
}
to your composer.json.
For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) )
Please correct me if I've stated something wrong or forgot something :)
Overview of PHP Testing tools
Video: http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/
Slides: http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011
It mentions stuff like Atoum which calls its self: "A simple, modern and intuitive unit testing framework for PHP!"
Full disclosure
I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit.
A: Well I made a phpUnit web based UI test case runner and made it available on sourceforge. Uses ajax and has quite cool interface as well if you want to give it a shot check it at sourceforge. The project name is phpunitwebui and the website is http://phpunitwebui.sourceforge.net/
A: As it has been pointed, it's mostly a preference choice, as both will run the tests you write for it and report back the results.
The Simpletest web UI is very useful, but it can also sometimes get cumbersome. In my current project, I would have had to put more work into a system to make my application (an API) work with the web interface (set up apache correctly, copy files to the public_html root, etc.) than it would have been to simply run phpunit from the eclipse workspace. Therefore I choose PHPUnit. Also, the use of PEAR was a big plus since you don't need to manually track updates. Simply run pear upgrade once in a while and PHPUnit will be kept up-to-date.
A: I prefer PHPUnit now, but when I started out I used SimpleTest as I didn't always have access to the command line. SimpleTest is nice, but the only thing it really has over PHPUnit, in my opinion, is the web runner.
The reasons I like PHPUnit are that it integrates with other PHP developer tools such as phing (as does SimpleTest), phpUnderControl, and Xinc. As of version 3.0 it has mocking support, is being actively developed, and the documentation is excellent.
Really the only way to answer this question for yourself is to try both out for a time, and see which fits your style better.
EDIT: Phing now integrates with SimpleTest as well.
A: This is from the point of view of a very casual PHP developer:
It took me two days to grasp PHPUnit, mostly trying to debug under Eclipse that I finally gave up.
It took me two hours to setup Simpletest including debug under Eclipse.
Maybe I will find the shortfalls of Simpletest in the future but so far it does well what I need: TestClasses, Mock objects, test-code debugging, and web interface for a quick snapshot of the situation.
Again: This from the point of view of a very casual PHP user (not even developer :-)
A: *
*I could NOT understand how to download and install PHPUnit.
*I could, however, easily understand how to install SimpleTest.
(As far as i can remember the instructions for PHPUnit said something along the lines of "install it via PEAR and we won't give any instructions on how to do it any other way")
see:
*http://www.phpunit.de/manual/current/en/installation.html
For SimpleTest, just download it and point to it from your code.
So Simpletest won for me.
A: Half of the mentioned points in the accepted answer are simply not true:
SimpleTest has
*
*the easier setup (extract to folder, include and run)
*simply check the folder into version control (try to do that with phpunit nowadays :))
*less dependencies and lots of extensions (webtester, formtester, auth)
*a good code coverage reporter, which is easy to extend (dots, function names, colors)
*a code coverage summary (finally landed in PHPUnit 4.x)
*a decent web runner and an ajax web runner, with groups and single file executions
*still better diff tool (with no whitespace or newline problems)
*an adapter/wrapper to run SimpleTests by phpUnit and vice versa
*compatibility PHP5.4+
The downside:
*
*not industry standard (PHPUnit)
*not actively maintained
A: Baphled has a nice article on SimpleTest vs PHPUnit3.
A: I found SimpleTest was even easier than PHPUnit to set up. Just extract it and you are good to go. A benefit of this is if you are working at more than one machine, since you can store the whole testing framework the same way as your source code, and thereby know that you are using the same framework code. Especially if you modify it in any way.
So, I would say that a strength of SimpleTest is that it is very light weight and portable.
SimpleTest also ships with a very simple HTML GUI, which is quite easy to extend if you want to. As far as I know, PHPUnit does not include a HTML GUI, but there are GUI:s available to download, such as Cool.
A: I haven't checked Simple Test for a while, last time it had an eclipse plugin, which is a major factor for me, but it hasn't been updated for a long time.
Sebastian Bergmann is still very actively working on PHPUnit, but it still lacks a good plugin for eclipse - but it is included for the new Zend Studio.
A: This question is old, but I want to add my experience: PHPUnit seems to be the standard now, but if you work with a legacy system that uses lots and lots of global variables, you may get stuck from the get go. It seems like there is no good way to do tests with global vars in PHPUnit, you seem to have to set your variables via $GLOBALS which is NO GOOD if you have tons of files setting global variables everywhere. OK some may say that the problem is in the legacy system but that doesn't mean we cannot do tests on such system. With SimpleTest such thing is simple. I suppose if PHPUnit allows us to include a file globally, not within any class/function scope then it wouldn't be too much of an issue as well.
Another promising solution is http://www.enhance-php.com, looks nice :)
A: when there are thousands functions to test at one go, phpunit is way to go, simple test is falling short as it web based.
I am still using simple web to for small scale test .
But both are good
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "128"
} |
Q: How do I implement Search Functionality in a website? I want to implement search functionality for a website (assume it is similar to SO). I don't want to use Google search of stuff like that.
My question is:
How do I implement this?
There are two methods I am aware of:
*
*Search all the databases in the application when the user gives his query.
*Index all the data I have and store it somewhere else and query from there (like what Google does).
Can anyone tell me which way to go? What are the pros and cons?
Better, are there any better ways to do this?
A: Use lucene,
http://lucene.apache.org/java/docs/
Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
It is available in java and .net. It is also in available in php in the form of a zend framework module.
Lucene does what you wanted(indexing of the searched items), you have to keep track of a lucene index but it is much better than doing a database search in terms of performance. BTW, SO search is powered by lucene. :D
A: You might want to have a look at xapian and the omega front end. It's essentially a toolkit on which you can build search functionality.
A: It depends on how comprehensive your web site is and how much you want to do yourself.
If you are running a a small website without further possibilities to add a custom search, let google do the work (maybe add a sitemap) and use the google custom search.
If you run a medium site with an sql engine use the search features of your sql engine.
If you run some heavier software stack like J2EE or .Net use Lucene, a great, powerful search engine or its .Net clone lucene.Net
If you want to abstract your search from your application and be able to query it in a language neutral way with XML/HTTP and JSON APIs, have a look at solr. Solr runs lucene in the background, but adds a nice web interface to it.
A: The best way to approach this will depend on how you construct your pages.
If they're frequently composed from a lot of different records (as I imagine stack overflow pages are), the indexing approach is likely to give better results unless you put a lot of work into effectively reconstructing the pages on the database side.
The disadvantage you have with the indexing approach is the turn around time. There are workarounds (like the Google's sitemap stuff), but they're also complex to get right.
If you go with database path, also be aware that modern search engine systems function much better if they have link data to process, so finding a system which can understand links between 'pages' in the database will have a positive effect.
A: If you are on Microsoft plattform you could use the Indexing service. This integrates very easliy with IIS websites.
It has all the basic features like full text search, ranking, exlcude and include certain files types and you can add your own meta information as well via meta tags in the html pages.
Do a google and you'll find tons!
A: This is somewhat orthogonal to your question, but I highly recommend the idea of a RESTful search. That is, to perform a search that has never been performed, the website POSTs a query to /searches/. To re-run a search, the website GETs /searches/{some id}
There are some good documents to be found regarding this, for example here.
(That said, I like indexing where possible, though it is an optimization, and thus can be premature.)
A: If you application uses the Java EE stack and you are using Hibernate you can use the Compass Framework maintain a searchable index of your database. The Compass Framework uses Lucene under the hood.
The only catch is that you cannot replicate your search index. So you need to use a clustered database to hold the index tables or use the newer grid based index storage mechanisms that have been added to the Compass Framework 2.x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
} |
Q: Do webtests need VS tester edition on the build server? Using the TFS build server without VS 2008 Team System Tester Edition installed - is it possible to run a series of webtests as part of a build?
I know that Webtests can only be recorded using the Tester Edition of VS. Here's a post about this from Jeff, back when he was at Vertigo.
I'm just trying to run the tests, though. Does that require the Tester Edition of VS to be installed, as well?
A: You don't have to have the tester's edition; the Developer Edition works, as long as you can code and run those tests locally.
I believe with the standard MSDN license, if you have Developer Edition, you can run a single build server with a copy of it. There might be some extra limitations, such as who can run builds on the server; you should review your license agreement to see if there are any issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I use a cross-platform GUI-toolkit or rely on the native ones? On my side job as programmer, I am to write a program in C++ to convert audio files from/to various formats. Probably, this will involve building a simple GUI.
Will it be a great effort to build seperate GUIs for Mac and Windows using Cocoa and WinForms instead of a cross-platform toolkit like Qt or GTK? (I will have to maintain a seperate Windows-version and Mac-Version anyway)
The GUI will probably be very simple and only need very basic functionality.
I always felt that native GUIs feel far more intuitive than its cross-platform brethren...
A: If you have the expertise, use native frontends, it'll effectively double the job you have to do for UI but from my experience non-native UI is a little bit clunkier than their native counterparts.
A: Have you looked at wxWidgets? Cross platform native controls.
A: I would agree that if possible, native front-ends are the way to go. I've not used wxWidgets recently, and I've heard it's come a long way, but back when it was wxWindows, we built an app with it that was spec'd to be built in X/Motif. When we finished the effort and delivered it, the customer said it did not look enough like X/Motif, and we had to re-work the entire UI at our expense... Joel Spolsky wrote a good article on this, but I can't remember the title. What he did say, IIRC, was the problem with Java and some other cross-platform UI was that "your dog barks at my app" - it's the little inconsistencies that annoy folks.
A: Cross-platform toolkits, more or less, all make the incorrect assumption that the difference between platforms is a matter of button placement and widget styling. In some cases you can get away with this - a Qt app will feel fairly native on both Windows (where UI conventions are very lax) and on Linux, particularly a KDE environment. In general, you can move between Linux and Windows relatively easily; conventions are similar, and the Windows community is lax about them.
Mac is the hard one. Its UI is built around an entirely different paradigm than either Windows or most Linux environments.
But in general, in a native app it's easier to speak the native language of the platform in more ways than just widget style.
A: Yes.
But seriously, it depends on your goals. I agree that the native UI libraries, with a bunch of effort put into them, will give vastly better results, but for lots of apps, a very basic UI is sufficient and a lot less effort if you take one of the existing cross platform frameworks.
Maybe starting with the CLI and getting functionality working makes the most sense for an audio conversion application.
A: I'm going to write my own cross platform application GUI layer for this soon.
Depending on the complexity of your application this can be a fraction of what is required for QT, GTK or FOX.
Reason is that we see a tendency that the platform vendors (Apple first) tries to design there system so that it looks unique. This makes it much harder for QT, GTK, FOX and other platform tools to constantly keep in sync with the latest widgets.
When the underlaying technique becomes more and more the same the OS vendors have no option then branding on look and feel of the platform.
A: wxWidgets used standard c++ syntax and preprocessor thus make you easily alter from plain C or C++. And will produce very native look where is appear, be it on GTK, X11, MS-Windows or Mac.
It's mature since 20yrs of 1rst release, has complete documentation with easy navigating, and supported by large community arround the world.
Coding in your favorite IDE or use prominent Eclipse-IDE and wxFormBuilder as GUI designer. Build wx library and IDE/Toolchain setup could be found on this link: http://yasriady.blogspot.co.id/2016/01/raspberry-pi-toolchain.html
Develop your application in Linux desktop and also provided compiler for Raspberry Pi2 (target application tested work smootly on Raspbian Jessie) ............
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I make Windows aware of a service I have written in Python? In another question I posted yesterday, I got very good advice on how a Python script could be run as a service in Windows. What I'm left wondering is: How is Windows aware of the services that can be managed in the native tools ("services" window in "administrative tools"). I. e. what is the Windows equivalent of putting a start/stop script in /etc/init.d under Linux?
A: Don't muck with the registry directly. User the SC command-line tool. Namely, SC CREATE
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc [command] [service name] ...
The option has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE:
sc start MyService
A: Here is code to install a python-script as a service, written in python :)
http://code.activestate.com/recipes/551780/
This post could also help you out:
http://essiene.blogspot.com/2005/04/python-windows-services.html
A: As with most "aware" things in Windows, the answer is "Registry".
Take a look at this Microsoft Knowledge Base article: http://support.microsoft.com/kb/103000
Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in.
The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
\myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as.
As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you.
A: You can use srvany.exe from Windows NT Resource Kit to create a user defined service that will show up in the admin tools...
http://support.microsoft.com/kb/137890
I am using this method to run tracd (a python script / server) for trac.
Here are some very clear instructions: http://www.tacktech.com/display.cfm?ttid=197
It does require some registry editing (very minimal and easy) but will allow you to make any command line / script a windows service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Finding your own number in a box 100 (or some even number 2N :-) ) prisoners are in a room A. They are numbered from 1 to 100.
One by one (from prisoner #1 to prisoner #100, in order), they will be let into a room B in which 100 boxes (numbered from 1 to 100) await them. Inside the (closed) boxes are numbers from 1 to 100 (the numbers inside the boxes are randomly permuted!).
Once inside room B, each prisoner gets to open 50 boxes (he chooses which one he opens). If he finds the number that was assigned to him in one of these 50 boxes, the prisoner gets to walk into a room C and all boxes are closed again before the next one walks into room B from room A. Otherwise, all prisoners (in rooms A, B and C) gets killed.
Before entering room B, the prisoners can agree on a strategy (algorithm). There is no way to communicate between rooms (and no message can be left in room B!).
Is there an algorithm that maximizes the probability that all prisoners survive? What probability does that algorithm achieve?
Notes:
*
*Doing things randomly (what you call 'no strategy') indeed gives a probability of 1/2 for each prisoner, but then the probability of all of them surviving is 1/2^100 (which is quite low). One can do much better!
*The prisoners are not allowed to reorder the boxes!
*All prisoners are killed the first time a prisoner fails to find his number. And no communication is possible.
*Hint: one can save more than 30 prisoners on average, which is much more that (50/100) * (50/99) * [...] * 1
A: This puzzle is explained at http://www.math.princeton.edu/~wwong/blog/blog200608191813.shtml and that person does a much better job of explaining the problem.
The "all prisoners are killed" statement is wrong.
The "you can save 30+ on average" is also wrong, the article says that 30% of the time you can save 100% of the prisoners.
A: I find a low tech solution to this type of problem is always the best way to go.
first we make some assumptions about the situation
*
*The prisoners are not all programmers or mathematicians
*They don't want to die
*The guards are well armed
So with a 0.005% chance that they will see tomorrow, there is a very simple and low tech solution to this problem. RIOT
its all about losses v potential gain, the chances are the prisoners far out number the guards, and using each other as human shields, as they are all dead men anyway if they don't, they can increase the chances they will over power a guard, once they have his weapon there chance goes up, helping them over power more guards to get more fire power to further increase there survival rate. once the guards realise what's happening, they will probably run for the hills and lock down the prison, this will give the media a heads up and then its a human rights issue.
A: Implement a sorting algorithm and sort the boxes according to the numbers inside them.
First prisoner sorts 50 boxes, and the second prisoner sorts the other 50 and merges with the first one. (Note that the second prisoner can guess the values inside the first 50 boxes)
After the 2nd prisoner, all of the boxes will be in a sorted order !!!
Everybody else can open the boxes containing their numbers easily then.
A: I don't know if this is allowed but the best approximation I can find is:
EDIT: Ok, I think this makes it. Of course I'm treating this as a computing problem, I don't think any prisioner will be able to perform this, although is pretty straight forward if you don't.
Find the first 50 primes, let's asume we hold them in an array called primes.
*
*The first prissioner enters room B and opens the first box and finds the number m.
*Wait primes[1]^m (that would be 3^m)
*Open box 2 and read the number --> n
*Wait (primes[2]^n - 1) * primes[1]^m, that would be (5^n - 1) * 3^m and the total time he has been waiting would be 3^n * 5^n
Repeat. After the first prisioner the total time for him would be:
3^m * 5^n * 7^p ... = X
Before the second prisioner enters the room factorize X. You know beforehand the prime numbers that have been used so the factorization is trivial. Doing so you obtain m, n, p, etc so the second prisioner knows every box/number combination the previous prisioner used.
The probability of the first one getting everybody killed is 1/2, the second one will have a 50 / (100 - n) (being n the numbers of attemps of the first one) the third one will have 50 / (100 - n - m) (if n + m = 100 then all positions are known) and so on.
Obviously the next prissioner must skip the already known boxes (except for the last choice if the box which contains his number is already known)
I don't know what's the exact possibility as it dependes on how many choices they have to do but I'd say it's pretty high.
EDIT: Rereading, if the prissioner does not have to stop when he obtains his number then the probability for the whole group is vastly improved, exactly 50%.
EDIT2: @OysterD see it this way. If the first prisioner can open 50 boxes then the second one know if its number is in any of that boxes. If it is, then he can open other 49 (and by doing so learning the box/number comination of the 100 boxes) and finally open his one. So if the first prissioner succeds then everyone succeds. Remember that each prisioner provides a way for the other to know exactly the boxes/number combination for every box he opens.
A: Maybe I'm not reading it right, but the question seems to be badly constructed or missing information.
If he finds the number that was
assigned to him in one of these 50
boxes, the prisoner gets to walk into
a room C and all boxes are closed
again before the next one walks into
room B from room A. Otherwise, all
prisoners (in rooms A, B and C) gets
killed.
Does the last sentence there mean that all prisoners are killed the first time a prisoner fails to find their number? If not, what happens to prisoners that don't find their number?
If no communication is possible, and whenever a prisoner enters room B it is always in an identical state then there is no possibility for a strategy.
The prisoners could could say before they leave room A which number box they are going to open. But without subsequent prisoners knowing whether they were successful or not (assuming failure for one isn't failure for all) when the next prisoner enters room B they still have the same odds of picking their number as the previous prisoner (always 1:100).
If failure for one is failure for all, then by knowing which box the previous prisoners opened, and by dint of the fact that they haven't all been killed, each successive prisoner could reduce the odds of picking the wrong box by one box. i.e. 1:100 for the first prisoner, 1:99 for the second, down to 1:1 for the last.
A: The prisoners could agree that prisoner 1 open boxes 1-50.
If they're all still alive, they agree that the next prisoner opens boxes 2-51. (the 2 is arbitrary, but simple to remember this rule) His odds of surviving given that P1 survived are now 50/99. You want to eliminate opening a box when you know that the previous guy found his.
I don't know if that's optimal, but it's lot better than random.
The probability of surviving that looks like
50/100 * 50/99 * 50/98 *. . .50/51 * 1
A: I think since no communication is possible, the best strategy would involve
distributing the probability of each prisoners as evenly as possible
Am I on the right path or not?
Information available for each prisoner:
*
*The number of survivied prisoners, so if you have an efficient box picking system that utilizes the order any prisoner enters room B, then a strategy is definitely possible
*Which boxes the earlier prisoners picked. Of course, no communication is possible during the run and it wouldn't be possible to remember any 100s box picking permutation. But you could use this information to compute in a system before the run starts.
My take:
*
*Draw a table of numbers with 2 columns, the first column contains the box number (from box #1 to box#100). Each prisoner then gets to pick 50 boxes and whatever box they pick, they should put 1 mark on the corresponding row in the second column.
*All prisoners are however required to never pick any box twice. And no box may be marked more than 50. Some prisoners may get less options than others since some box may get filled to 50 marks first.
*When a prisoner is moved to room B he/she opens whatever boxes he has marked on.
A: Same concept.
Aonther take:
*
*Write down a list of the first 100 binary numbers which has fifty 1s and fifty 0s.
*Sort them from lowest to highest.
*Prisoner #1 gets the first number, prisoner #2 gets the second, prisoner #3 gets the third and so on...
*Each prisoner remembers his/her binary number.
*When any prisoner is moved to room B, he/she then match the binary digits of the number he remembered with each of the box, the highest bit is matched with the leftmost box, the next highest bit is matched with the second leftmost box ... the lowest bit is matched with the rightmost box.
*He/she opens whatever boxes matched with 1 and leave closed boxes matched with 0.
This would minimizes the probability because early prisoners will get digits that are different from the later prisoners and prisoners which has number close together would get digits close together. This doesn't guarantee survivability but if the early prisoners do survive, chances are the later prisoners would have a higher probability of surviving as well.
I haven't thought out the exact figures and rationale though, but this is one quick solution I can think of at the moment.
A: If all prisoners are killed when someone fails to find their number then you either save 100 or 0. There is no way to save 30 people.
A: There aren't any time limits in the question so I suggest that prisoners should decide to take 1 hour per box and open them in the order presented. If the second prisoner is allowed into the room after 2 hours then he knows that the first prisoner found his own number in box 2. Therefore he knows to skip box 2 in his sequence and opens boxes 1, 3, 4...51
First prisoners odds on losing are 50/100
Give that the first prisoner survived then the second prisoners chance of winning are 50/99
So answer appears to be ((50 ^51)*49!)/100!
which according to google makes 2.89*10^-9
which is pretty much nil
So even if the prisoners knew the boxes the previously lucky ones found their number in there'd be no hope
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: What if analysis on multi dimensional cubes (OLAP) I have a multi dimensional OLAP cube with a number of dimensions. Some of these dimensions have hierarchies. The users would like to perform 'what-if' analysis on the measures in the cube by changing the hierarchies in the dimensions.
For example, they want to know the impact on departmental resource budgets by moving employees between departments or the movement in cost of manufacture if a product is moved from one factory to another.
Does anyone have a straight forward way to do this in a modern OLAP engine?
A: have you taken a look here? http://office.microsoft.com/en-us/excel/HA011265551033.aspx if you are using sql server and excel, you want the "Excel Add-in for SQL Server Analysis Services" and you can perform writeback to the cubes. Might not be exactly what you want, but it is the closest I have come across.
"What-if analysis and writeback What-if analysis enables you to initiate a "what-if" scenario by updating data and analyzing the effects of changes on your data. You can save the scenario for future analysis. When you save the scenario, changes you made to data (known as writeback data) are written to the cube. Once you write back changes, the data is available for future analysis and can be viewed by and shared with others who have access to the cube."
A: SSAS in SQL Server 2008 allows you to have multiple hierarchies. Although this will not allow your users to build and change hierarchies on the fly, you can still collect their requirements and rebuild the cube with those additional hierarchies
A: There may be tools that allow this sort of analysis, but I only have experience of writing MDX, which ought to be able to help you.
Typical 'what if' analysis is more about changing values in the OLAP cube (e.g. change net sales from 845.45 to 700.00 and see what happens to gross profit). Your case is a bit different as you want to move members within a hierarhy, but keep the same values.
I haven't worked through a full solution, but the way I would approach it would be to create a new 'calculated member' or set (on the fly) and use that to build up the new hierarchy that you want. Your query can then use that on one axis.
Look carefully into 'visual totals' as there may be potential pitfalls there!
A: Andy - It depends on the tool you're using. Some, for example, set the hierarchies at cube build time. Others have dynamic hierarchies. What tool are you working in?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Updating/Intercepting HttpContext.Current.Request.QueryString Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?
A: Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring.
Using an IHttpModule, it might look something like:
context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);
Hope this helps!
A: Ditto Espo's answer and I would like to add that usually in medium trust (specific to many shared hostings) you will not have access to reflection so ... RewritePath will remain your probably only choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to make user controls know about css classes in ASP.NET Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?
Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?
A: Here's what I did:
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" />
It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.
Here's an even more concise way to do this with multiple references;
<% if (false) { %>
<link rel="Stylesheet" type="text/css" href="Stylesheet.css" />
<script type="text/javascript" src="js/jquery-1.2.6.js" />
<% } %>
As seen in this blog post from Phil Haack.
A: Add the style on your usercontrol and import css in it.
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WCReportCalendar.ascx.vb"
Inherits="Intra.WCReportCalender" %>
<style type='text/css'>
@import url("path of file.css");
// This is how i used jqueryui css
@import url("http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css");
</style>
your html
A: If you are creating composite UserControl, then you can set the CSSClass property on the child controls..
If not, then you need to expose properties that are either of the Style type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a style attribute to the HTML tags when rendering).
A: You Can use CSS direct in userControl.
Use this in UserControl:
<head>
<title></title>
<style type="text/css">
.wrapper {
margin: 0 auto -142px;
/* the bottom margin is the negative value of the footer's height */
}
</style>
</head>
This will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: How would you abbriviate XHTML to an arbitrary number of words? How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags?
i.e.
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
hendrerit, <em>justo</em>.
</p>
Abbreviated to 25 words would be:
<p>
Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
</p>
<p>
Proin semper, orci at mattis blandit, augue justo blandit nulla.
<span>Quisque ante congue...</span>
</p>
A: Recurse through the DOM tree, keeping a word count variable up to date. When the word count exceeds your maximum word count, insert "..." and remove all following siblings of the current node, then, as you go back up through the recursion, remove all the following siblings of each of its ancestors.
A: You need to think of the XHTML as a hierarchy of elements and treat it as such. This is basically the way XML is meant to be treated. Then just go through the hierarchy recursively, adding the number of words together as you go. When you hit your limit throw everything else away.
I work mainly in PHP, and I would use the DOMDocument class in PHP to help me do this, you need to find something like that in your chosen language.
To make things clearer, here is the hierarchy for your sample:
- p
- Proin tristique dapibus neque. Nam eget purus sit amet leo
tincidunt accumsan.
- p
- Proin semper, orci at mattis blandit, augue justo blandit nulla.
- span
- Quisque ante congue justo
- , ultrices aliquet, mattis eget, hendrerit,
- em
- justo
- .
You hit the 25 word limit inside the span element, so you remove all remaining text within the span and add the ellipsis. All other child elements (both text and tags) can be discarded, and all subsequent elements can be discarded.
This should always leave you with valid markup as far as I can see, because you are treating it as a hierarchy and not just plain text, all closing tags that are required will still be there.
Of course if the XHTML you are dealing with is invalid to begin with, don't expect the output to be valid.
Sorry for the poor hierarchy example, couldn't work out how to nest lists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I truncate a string while converting to bytes in C#? I would like to put a string into a byte array, but the string may be too big to fit. In the case where it's too large, I would like to put as much of the string as possible into the array. Is there an efficient way to find out how many characters will fit?
A: In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:
static string Truncate(string s, int maxLength) {
if (Encoding.UTF8.GetByteCount(s) <= maxLength)
return s;
var cs = s.ToCharArray();
int length = 0;
int i = 0;
while (i < cs.Length){
int charSize = 1;
if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
charSize = 2;
int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
if ((byteSize + length) <= maxLength){
i = i + charSize;
length += byteSize;
}
else
break;
}
return s.Substring(0, i);
}
The returned string can then be safely transferred to a byte array of length maxLength.
A: You should be using the Encoding class to do your conversion to byte array correct? All Encoding objects have an overridden method GetMaxCharCount, which will give you "The maximum number of characters produced by decoding the specified number of bytes." You should be able to use this value to trim your string and properly encode it.
A: Efficient way would be finding how much (pessimistically) bytes you will need per character with
Encoding.GetMaxByteCount(1);
then dividing your string size by the result, then converting that much characters with
public virtual int Encoding.GetBytes (
string s,
int charIndex,
int charCount,
byte[] bytes,
int byteIndex
)
If you want to use less memory use
Encoding.GetByteCount(string);
but that is a much slower method.
A: The Encoding class in .NET has a method called GetByteCount which can take in a string or char[]. If you pass in 1 character, it will tell you how many bytes are needed for that 1 character in whichever encoding you are using.
The method GetMaxByteCount is faster, but it does a worst case calculation which could return a higher number than is actually needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How should I model a field that can contain both numeric and string values in SQL Server 2005? I have a new database table I need to create...
It logically contains an ID, a name, and a "value".
That value field could be either numeric or a character string in nature.
I don't think I want to just make the field a varchar, because I also want to be able to query with filters like WHERE value > 0.5 and such.
What's the best way to model this concept in SQL Server 2005?
EDIT:
I'm not opposed to creating multiple fields here (one for numbers, one for non-numbers), but since they're all really the same concept, I wasn't sure that was a great idea.
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column.
Any opinions on that?
What I want to achieve is really pretty simple... usually this data will just be blindly displayed in a grid-type view.
I want to be also able to filter on the numeric values in that grid. This table will end up being in the tens of millions of records, so I don't want to paint myself into a corner with querying performance.
That querying performance is my main concern.
A: A good way to get the query support you want is to have two columns: numvalue that stores a number and textvalue that stores characters. They should be nullable or at least have some default that represents no value. Your application can then decide which column to store its value and which to leave with no value.
A: Your issue with mixing data may be how Sql 2005 sorts text data. It's not a 'natural' sort.
If you have a varchar field and you do:
where value > '20.5'
Values like "5" will be in your result (as in a character based sort "5" comes after "20.5")
You're going to be better off with separate columns for storage.
Use Coalesce to merge them into one column if you need them merged in your results:
select [ID], [Name], Coalesce( [value_str], [value_num] )
from [tablename]
A: If you want to store numeric and string values in the same column, I am not sure you can avoid doing a lot of casts and converts when using that column as a query filter.
A: two columns.
Table: (ValueLable as char(x), Value as numerica(p,s))
A: I don't think it's possible to have a column with both varchar and int type. You could save your value as a varchar and cast it to int during your query. But this way you could get an exception if your value does contain any character. What are you trying to achieve?
A: If you want it to be able to hold a character string, I think you have to make the column varchar, or similar.
An alternative could be to have 2 or 3 columns instead of the one value column. Maybe have the three columns, value_type (enum between "number" and "string"), number_value, string_value. Then you could reconstruct that query to be
WHERE value_type = 'number' AND number_value > 0.5
A: I don't think you're going to be able to get around using VARCHAR or NVARCHAR as your data type. With mixed data like you're describing, you'll have to test the value when you pull the field out of the db and perform the appropriate CAST or CONVERT based on the data type.
A:
I guess I could create separate fields, then have a view that sort of coalesces them into a single logical column. Any opinions on that?
It depends on the source of the data. If you are getting the data from users (or some other system) in some free-form manner and don't really care what type of data it is, then the best way to store it is the most generic manner (varchar, etc). If the incoming data is more structured and you care about that structure, then it makes more sense to keep that structure in the database by using separate fields.
From the viewpoint of a SELECT it doesn't really matter; you can store it either way and read it as the same schema. Once you get into filters (as you mention) things get a bit more hairy, but still easily doable. However, you don't mention if you need to be able to update this data and if so, if you need to enforce any validation on the data.
From the sounds of it, you need to do different types of searches based on the "type" of value being stored. As such, it may make sense to add a Type field so that any filters can be quickly limited to the type of values that you care about. Note, by Type I mean a more logical, application scope, Type; not the actual datatype being stored.
My recommendation would be to use a single field with a Type column if you need to easily support UPDATEs or use multiple fields (or tables, if these are totally different data sets) if SELECTing and filtering is all that is needed.
A: You might consider using two columns, one "string" and one "numeric" (whatever variants of those are appropriate) with the "string" column NOT NULL and the "numeric" column allowing NULL values. When inserting a value, always populate the "string" column indpendent of the type, however if the value is numeric, ALSO store it in the "numeric" column. Now you have a built in indicator as to the type (if the "numeric" column is populated it is numeric, if not it is a string), can always just pull the value for display from the "string" column, and can use the "numeric" value in calculations or for proper numeric sorting / comparison as needed. You could always add a third column indicating the value type, but this approach eliminates the need for that. Note that you might consider maintaining the numeric and string values using a set of INSERT and UPDATE triggers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to dispay unordered list inline with bullets? I have an html file with an unordered list. I want to show the list items horizontally but still keep the bullets. No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display.
A: You could also use a background image on the <li> elements, with a padding to keep the text from overlapping it.
li {
background-image: url(i/bullet.gif) no-repeat center left;
padding-left: 20px;
display: inline;
}
A: The best option I saw in other answers was to use float:left;. Unfortunately, it doesn't work in IE7 which is a requirement here* — you still lose the bullet. I'm not really keen on using a background image either.
What I'm gonna do instead (that no one else suggested, hence the self-answer) is go with manually adding • to the my html, rather than styling this. It's less than ideal, but it's the most compatible option I found.
edit: *Current readers take note of the original post date. IE7 is unlikely to be a concern anymore.
A: The browser displays the bullets because the style property "display" is initially set to "list-item". Changing the display property to "inline" cancels all the special styles that list items get. You should be able to simulate it with the :before selector and the content property, but IE (at least through version 7) doesn't support them. Simulating it with a background image is probably the best cross-browser way to do it.
A: Keep them display blocked, give them a width and float left.
That will make them sit by side, which is like inline, and should maintain the list style.
A: It's actually a very simple fix. Add the following to the ul:
display:list-item;
Adding this CSS line will add the bullet points.
A: I had the same problem, but only in Internet Explorer (I tested version 7) - not in Firefox 3 or Safari 3. Using the :before selector works for me:
ul.tabs li {
list-style: none;
float: left;
}
ul.tabs li:before {
content: '\ffed';
margin-right: 0.5em;
}
I'm using a square bullet here, but a normal bullet \2022 would work the same.
A: I was just messing around and I ran into the same issue with the same browser constraints; when I searched for an answer your post came up without the answer. This is probably too late to help you, but I thought for posterity's sake I should post it.
All I did to solve my problem was to embed another list with one item within each list item of the first list; like so...
HTML:
<div class="block-list">
<ul>
<li><ul><li>a</li></ul></li>
<li><ul><li>b</li></ul></li>
<li><ul><li>c</li></ul></li>
</ul>
</div>
CSS:
.block-list > ul > li { display: inline; float: left; }
IE7 Page:
o a o b o c
...it is a dumb solution, but it seems to work.
A: Did you try float: left on your <li/>? Something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css">
ul li {
float: left;
margin-left: 2em;
}
</style>
</head>
<body>
<ul>
<li>test</li>
<li>test2</li>
</ul>
</body>
</html>
I only tested Firefox 3.0.1, works there. The margin is set because else your bullet overlaps the previous item.
addition:
Be wary that when you float the items you remove them from the normal flow, which in turn causes the <ul/> to have no height. If you want to add a border or something, you'll get weird results.
One way to fix that is to add the following to your styles:
ul {
overflow: auto;
background: #f0f;
}
A: You may set <ul> as a CSS grid and <li> as cells to get similar layout to inline <li> and keep bullets easily:
ul {
display: grid;
grid-template-columns: 100px 100px 100px; /* or a smarter width setting */
}
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
A: You could use Character entities, see reference : http://dev.w3.org/html5/html-author/charref
<ul class="inline-list>
<li> • Your list item </li>
</ul>
A: In HTML, I added a break after each li like this:
<li>Water is Sacred</li><br>
<li>Water is Sacred</li><br>
<li>Water is Sacred</li><br>
<li>Water is Sacred</li><br>
<li>Water is Sacred</li><br>
<li>Water is Sacred</li><br>
And CSS:
li { float:left; }
A: Using float: left didn't work very well for me because it made the content box of the ul element 0 pixels high. Flexboxes worked better:
ul {
display: flex;
flex-wrap: wrap;
}
li {
margin-right: 24px;
}
A: You can use following code
li {
background-image: url(img.gif) no-repeat center left;
padding-left: 20px;
display: inline;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Send email from Elmah? Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine?
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/>
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/>
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings>
<add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" />
</connectionStrings>
<elmah>
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" >
</errorLog>
<errorMail from="[email protected]"
to="[email protected]"
subject="Application Exception"
async="false"
smtpPort="25"
smtpServer="***"
userName="***"
password="***">
</errorMail>
</elmah>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx">
<error statusCode="403" redirect="NotAuthorized.aspx" />
<!--<error statusCode="404" redirect="FileNotFound.htm" />-->
</customErrors>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
</httpModules>
</system.web>
</configuration>
A: You need the ErrorMail httpModule.
add this line inside the <httpModules> section
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server.
A: Yes, if you are not using remote SMTP server you must have SMTP Server configured locally. You can also configure email for elmah in web.config as follows:
<configSections>
<sectionGroup name="elmah">
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah">
</sectionGroup>
</configSections>
<elmah>
<errorMail from="from Mail Address" to="to mail address"
async="true" smtpPort="0" useSsl="true" />
</elmah>
<system.net>
<mailSettings>
<smtp deliveryMethod ="Network">
<network host="smtp.gmail.com" port="587" userName="yourgmailEmailAddress" password="yourGmailEmailPassword" />
</smtp>
</mailSettings>
</system.net>
A: I have used Elmah myself in this configuration and I had to setup the server with SMTP locally. It is a straight-forward install on you local IIS server. This should do the trick.
Good point above, you need the errorMail module BUT if you are not using a remote SMTP server you need SMTP locally, just to clarify.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "90"
} |
Q: How do I generate a friendly URL in Symfony PHP? I always tend to forget these built-in Symfony functions for making links.
A: If your goal is to have user-friendly URLs throughout your application, use the following approach:
1) Create a routing rule for your module/action in the application's routing.yml file. The following example is a routing rule for an action that shows the most recent questions in an application, defaulting to page 1 (using a pager):
recent_questions:
url: questions/recent/:page
param: { module: questions, action: recent, page: 1 }
2) Once the routing rule is set, use the url_for() helper in your template to format outgoing URLs.
<a href="<?php echo url_for('questions/recent?page=1') ?>">Recent Questions</a>
In this example, the following URL will be constructed: http://myapp/questions/recent/1.html.
3) Incoming URLs (requests) will be analyzed by the routing system, and if a pattern match is found in the routing rule configuration, the named wildcards (ie. the :/page portion of the URL) will become request parameters.
You can also use the link_to() helper to output a URL without using the HTML <a> tag.
A: This advice is for symfony 1.0. It probably will work for later versions.
Within your sfAction class:
string genUrl($parameters = array(), $absolute = false)
eg.
$this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true);
In a template:
This will generate a normal link.
string link_to($name, $internal_uri, $options = array());
eg.
link_to('My link name', 'yourmodule/youraction?key=value&key2=value');
A: In addition, if you actually want a query string with that url, you use this:
link_to('My link name', 'yourmodule/youraction?key=value&key2=value',array('query_string'=>'page=2'));
Otherwise, it's going to try to route it as part of the url and likely break your action.
A: You can generate URL directly without define the rule first.
If you want to generate URL in the actions, you can use generateUrl() helper:
$this->generateUrl('default', array('module'=>'[ModuleName]','action'=>'[ActionName]'))
If you want to generate URL in the templates, you can use url_for() helper:
url_for('[ModuleName]/[ActionName]', $absolute)
set $absolute as true/false, dont forget to use echo if you want to display it.
But if you want to make a link (something like <a href=""></a>), link_to() helper will do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why am I getting a NoClassDefFoundError in Java? I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
A: One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
*
*throw a RuntimeException in the static block of your class Example
*Intercept it (or if it just doesn't matter like it is thrown in a test case)
*Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
A: This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
*
*HelloWorld (main class)
*SupportClass
*UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
A: I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
@xli's answer gave me insight into what may be wrong in my code.
A: NoClassDefFoundError In Java
Definition:
*
*Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
*If a class was present during compile time but not available in java classpath during runtime.
Examples:
*
*The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
*A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
*Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
*Permission issue on JAR file can also cause NoClassDefFoundError in Java.
*Typo on XML Configuration can also cause NoClassDefFoundError in Java.
*when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
*
*The class is not available in Java Classpath.
*If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
*Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
*Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
*Any start-up script is overriding Classpath environment variable.
*You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
A: I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
A: The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
A: Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
A: I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
A: In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
A: This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
A: Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
A: While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
*
*java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
*java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
A: Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
A: I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
A: NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
A: I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
A: In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
A: Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
A: I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
A: If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
A: This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
A: I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
A: It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
A: Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
A: I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
A: I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
A: My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
A: Make sure this matches in the module:app and module:lib:
android {
compileSdkVersion 23
buildToolsVersion '22.0.1'
packagingOptions {
}
defaultConfig {
minSdkVersion 17
targetSdkVersion 23
versionCode 11
versionName "2.1"
}
A: I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)
A: I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
A: Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "653"
} |
Q: How to Format Numbers in WinForms 1.1 DataGrid? Is there a simple way to format numbers in a Winforms 1.1 datagrid? The Format property of the DataGridTextBoxColumn seems to be completely ignored. I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work.
A: My personal opinion is that a datagridcolumnstyle is the way to go. Without seeing the code that you have, I can't say for certain why your formatting isn't taking hold when no style is defined - but mixing in formatting with data calculations and other parts of the code can get very messy very quickly.
Creating a new column style class is very clean, and if you have to use the same formatting again in another datagrid, it's as easy as pie to reuse it.
Here's the Microsoft Documentation that may get you started in the right direction.
A: I did subclass and it was easy and did work. I still don't like it so much. I was already subclassing column styles for other reasons. I'd rather handle all databinding myself, where I can more easily change it and test it. This whole mixing of the UI with the data is old school, and not in a good way.
Thanks very much for your answers, it's good to have second opinions.
Mike
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Finding what methods a Python object has Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?
Or if this is not possible, is there at least an easy way to check if it has a particular method, other than checking if an error occurs when the method is called?
A: For many objects, you can use this code, replacing 'object' with the object you're interested in:
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
I discovered it at diveintopython.net (now archived), that should provide some further details!
If you get an AttributeError, you can use this instead:
getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo'])
A: I believe that you want something like this:
a list of attributes from an object
The built-in function dir() can do this job.
Taken from help(dir) output on your Python shell:
dir(...)
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
*
*for a module object: the module's attributes.
*for a class object: its attributes, and recursively the attributes of its bases.
*for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
For example:
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
A: There is no reliable way to list all object's methods. dir(object) is usually useful, but in some cases it may not list all methods. According to dir() documentation: "With an argument, attempt to return a list of valid attributes for that object."
Checking that method exists can be done by callable(getattr(object, method)) as already mentioned there.
A: You can use the built in dir() function to get a list of all the attributes a module has. Try this at the command line to see how it works.
>>> import moduleName
>>> dir(moduleName)
Also, you can use the hasattr(module_name, "attr_name") function to find out if a module has a specific attribute.
See the Python introspection for more information.
A: To check if it has a particular method:
hasattr(object,"method")
A: import moduleName
for x in dir(moduleName):
print(x)
This should work :)
A: On top of the more direct answers, I'd be remiss if I didn't mention IPython.
Hit Tab to see the available methods, with autocompletion.
And once you've found a method, try:
help(object.method)
to see the pydocs, method signature, etc.
Ahh... REPL.
A: The simplest way to get a list of methods of any object is to use the help() command.
help(object)
It will list out all the available/important methods associated with that object.
For example:
help(str)
A: Suppose we have a Python obj. Then to see all the methods it has, including those surrounded by __ (magic methods):
print(dir(obj))
To exclude magic builtins one would do:
[m for m in dir(obj) if not m.startswith('__')]
A: If you specifically want methods, you should use inspect.ismethod.
For method names:
import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]
For the methods themselves:
import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]
Sometimes inspect.isroutine can be useful too (for built-ins, C extensions, Cython without the "binding" compiler directive).
A: I have done the following function (get_object_functions), which receives an object (object_) as its argument, and returns a list (functions) containing all of the methods (including static and class methods) defined in the object's class:
def get_object_functions(object_):
functions = [attr_name
for attr_name in dir(object_)
if str(type(getattr(object_,
attr_name))) in ("<class 'function'>",
"<class 'method'>")]
return functions
Well, it just checks if the string representation of the type of a class' attribute equals "<class 'function'>" or "<class 'method'>" and then includes that attribute in the functions list if that's True.
Demo
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f'My name is {self.name}')
@staticmethod
def say_hi():
print('hi')
@classmethod
def reproduce(cls, name):
return cls(name, 0)
person = Person('Rafael', 27)
print(get_object_functions(person))
Output
['__init__', 'introduce', 'reproduce', 'say_hi']
For a cleaner version of the code: https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py
A: The simplest method is to use dir(objectname). It will display all the methods available for that object.
A: Open a Bash shell (Ctrl + Alt + T on Ubuntu). Start a Python 3 shell in it. Create an object to observe the methods of. Just add a dot after it and press Tab twice and you'll see something like this:
user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__( s.__rmod__( s.istitle(
s.__class__( s.__rmul__( s.isupper(
s.__contains__( s.__setattr__( s.join(
s.__delattr__( s.__sizeof__( s.ljust(
s.__dir__( s.__str__( s.lower(
s.__doc__ s.__subclasshook__( s.lstrip(
s.__eq__( s.capitalize( s.maketrans(
s.__format__( s.casefold( s.partition(
s.__ge__( s.center( s.replace(
s.__getattribute__( s.count( s.rfind(
s.__getitem__( s.encode( s.rindex(
s.__getnewargs__( s.endswith( s.rjust(
s.__gt__( s.expandtabs( s.rpartition(
s.__hash__( s.find( s.rsplit(
s.__init__( s.format( s.rstrip(
s.__iter__( s.format_map( s.split(
s.__le__( s.index( s.splitlines(
s.__len__( s.isalnum( s.startswith(
s.__lt__( s.isalpha( s.strip(
s.__mod__( s.isdecimal( s.swapcase(
s.__mul__( s.isdigit( s.title(
s.__ne__( s.isidentifier( s.translate(
s.__new__( s.islower( s.upper(
s.__reduce__( s.isnumeric( s.zfill(
s.__reduce_ex__( s.isprintable(
s.__repr__( s.isspace(
A: The problem with all methods indicated here is that you can't be sure that a method doesn't exist.
In Python you can intercept the dot calling through __getattr__ and __getattribute__, making it possible to create method "at runtime"
Example:
class MoreMethod(object):
def some_method(self, x):
return x
def __getattr__(self, *args):
return lambda x: x*2
If you execute it, you can call non-existing methods in the object dictionary...
>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10
And it's why you use the Easier to ask for forgiveness than permission paradigms in Python.
A:
...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called
While "Easier to ask for forgiveness than permission" is certainly the Pythonic way, you may be looking for:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
A: One can create a getAttrs function that will return an object's callable property names
def getAttrs(object):
return filter(lambda m: callable(getattr(object, m)), dir(object))
print getAttrs('Foo bar'.split(' '))
That'd return
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
'remove', 'reverse', 'sort']
A: Take a list as an object
obj = []
list(filter(lambda x:callable(getattr(obj,x)),obj.__dir__()))
You get:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__delitem__',
'__dir__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__gt__',
'__iadd__',
'__imul__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__reversed__',
'__rmul__',
'__setattr__',
'__setitem__',
'__sizeof__',
'__str__',
'__subclasshook__',
'append',
'clear',
'copy',
'count',
'extend',
'index',
'insert',
'pop',
'remove',
'reverse',
'sort']
A: In order to search for a specific method in a whole module
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")
A: If you are, for instance, using shell plus you can use this instead:
>> MyObject??
that way, with the '??' just after your object, it'll show you all the attributes/methods the class has.
A: Most of the time, I want to see the user-defined methods and I don't want to see the built-in attributes that start with '__', if you want that you can use the following code:
object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name]
For example, for this class:
class Person:
def __init__(self, name):
self.name = name
def print_name(self):
print(self.name)
Above code will print: ['print_name']
A: You can make use of dir() which is pre-defined in Python.
import module_name
dir(module_name)
You can also pass an object to dir() as
dir(object_name)
If the object is an object of a pre-defined class such as int, str, etc. it displays the methods in it (you may know those methods as built in functions). If that object is created for a user-defined class, it displays all the methods given in that class.
A: Here's a nice one liner (but will get attributes as well):
print(*dir(obj), sep='\n')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "642"
} |
Q: Technical Hurdles for Win32 rsync port Despite primarily being a windows user, I am a huge fan of rsync. Now, I don't want to argue the virtues of rsync vs any other tool...this is not my point.
The only way I've ever found of running rsync on windows is via a version that is built to run on top of Cygwin, and as Cygwin has issues with Unicode, so does rsync.
Is anyone familiar enough with the workings of rsync to say if there are any real technical programming hurdles to porting rsync to a native Win32 binary?
Or is it maybe that there has just never been enough interest from windows users to care to port it over?
Partly I ask because I'm am considering trying to take on the task of starting a port, but I want to make sure there's not something I'm missing in terms of why it may not be possible.
A: The way that windows locks open files might cause an issue requiring you to hook into the Volume Shadowcopy Service.
About two years ago this fellow ported the algorithm to C#. I haven't taken a look at the code (or the provided binary), but it might be a place to start looking or someone to try contacting.
http://www.russiantequila.com/wordpress/?p=8
A: I've been evaluating an effort to undertake a win32 port as well. I don't believe anything major would block it, but evidence from both the rsync mailing list and another discussion points to a heavy reliance on unix fork() system calls. Using threads appears the way to go for win32.
Threads vs. Fork discussion
A: (disclaimer: i promise, i don't google myself, but google analytics brought me here)
i went through porting rsync to .net (sig11's link is my blog). there are no technical hurdles, just practical ones. as was already said, the code is rather... dense. difficult to follow, and complete lack of comments. i'm more than happy to make my work available, but unfortunately, since it was part of a commercial effort, it's not in significantly better shape.
i have, on a number of occasions, messed around with the idea of reverse-engineering the protocol and doing a ground-up implementation that's wire-compatible with the existing one, but ... a bit cleaner to work with. i've even started a wiki to that effect, but... as you can see from the lack of contents there, other item have taken priority. if anyone would like to work with me on this, that may be the impetus i need to get going.
the concept of the tool is great, as is the functionality it offers, however it's rather limited outside the *ix space, and could definitely benefit from an api.
wiki link for reference:
http://www.russiantequila.com/wiki/index.php?title=Main_Page
A: Have you seen this:
http://www.itefix.no/i2/taxonomy/term/39
I have used cwrsync without any problem (and with the much of the usual cygwin misery), but I haven't had any need for unicode filenames, so I've not seen that problem.
I don't really know why there isn't a native Win32 port, but I did look at the source a while back because I implemented a similar delta-copy system in C#. As one would expect from the world of brilliant *nix hackers, the source is largely single-character variable names and a total absence of comments, which isn't terrible helpful and might be rather off-putting to would-be porters.
A: I would really appreciate a port of rsync to MS-Windows such that it can be built using Visual Studio. I am encountering various protocol errors at random, somewhat intermittently. I am using rsync to distribute sw to a grid of around 200 machines and typically get around a a dozen failures. I am using GCC 4.4.2 and the latest cygwin to build rsync v3.0.7. It would help me alot if I could experiment with a version that does not require cygwin. This is because the machines in the grid already have another cygwin-based app running that is a different version to the one I have.
Having spent some time on the rsynv mailing list opinion seems to be divided as to cause of protocol errors on MS-Windows. Some say it is a bug in rsync where it failed to do a clean socket shutdown, a bug that was fixed a while ago. Others say that it is a fundamental protocol error in rsync where the client does not tell the server that it is finished, it just shuts down, causing MW-windows servers to get a RST signal on the socket, something that does not happen on Unix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is in your JavaScript development toolbox? I have to do some JavaScript in the future, so it is time to update my toolbox. Right now I use Firefox with some addons:
*
*JavaScript Shell from https://www.squarefree.com/bookmarklets/webdevel.html
*Firefox Dom Inspector
*Firebug
*Greasemonkey
*Stylish
I plan to use Venkman Javascript debugger as well as jsunit and js-lint.
For programming I'm stick with vim.
So what other tools do you use when developing JavaScript?
A: I use both Firefox and IE for Web Development and a few add-ons in each:
Firefox:
*
*Firebug
*Web Developer Toolbar
Internet Explorer:
*
*IE Developer Toolbar
*Fiddler
*Visual Studio for JS Debugging
A: I sometimes use Emacs with Steve Yegge's js2-mode, evaluating code with Rhino & John Resig's env.js to load jQuery or Prototype in my standalone scripts.
This allows me to explore javascript, jQuery, and Prototype outside of a browser.
Example:
var window;
load("Library/env.js");
window.location = 'index.html'; // Load the page 'index.html'
print($('aForm').id); // Play with the Dom in a standalone script!
A: *
*Web Developer Toolbar (Firefox Addon)
*Nikhil's Web Development Helper (IE Toolbar)
A: Firefox:
*
*Firebug - Invaluable for debugging markup and code while testing ideas directly in the browser
*
*Rainbow for Firebug - JavaScript syntax highlighting
*Pixel Perfect - Overlay images on any page, make it match the design on every pixel
*Web Developer Toolbar - Just about any tool you can think of
*Firecookie - Manage your cookies
*YSlow - Suggests how to boost the download performance
Windows-only:
*
*Fiddler - A great HTTP proxy with debugging capabilities
Internet Explorer:
- Web Developer Toolbar - Missing a few things but still very complete
A: *
*Firebug on Firefox
*IE Web Developer toolbar on IE
*JS Lint
A: A couple more::
*
*IE Explorer Toolbar
*Firefox Developer Toolbar
A: Best way to debug JavaScript in Internet Explorer is to use Visual Web Developer Express.
If you like a cross browser logging solution check out Firebug Lite!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: What more is needed for Ajax than this function I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
A: I would remove this line.
alert("Your browser does not support AJAX!")
Shouting at the user in a language he probably doesn't understand is worse than failure. :-)
A: I've never been a fan of nested try/catch blocks, so I'd do it something like:
var xmlHttp;
if (window.XMLHttpRequest) {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (xmlHttp) {
// No errors, do whatever you need.
}
I think that'll work. But as has been mentioned before - why reinvent the wheel, use a library. Even better - find out how they do it.
A: I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax.
A: jQuery is probably one of the lightest popular libraries out there.
A: The same thing in prototype:
function loadPage(pagePath, displayElement) {
new Ajax.Updater(displayElement, pagePath);
}
Ajax.Updater in Prototype API
A: If you really want to see what you are missing, read the jQuery or Prototype source code for their ajax routines. If there are bug numbers in the comments, look those up as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Does limiting a query to one record improve performance Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?
for example
select * from people where name = "Re0sless" limit 1
if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?
A: If the column has
a unique index: no, it's no faster
a non-unique index: maybe, because it will prevent sending any additional rows beyond the first matched, if any exist
no index: sometimes
*
*if 1 or more rows match the query, yes, because the full table scan will be halted after the first row is matched.
*if no rows match the query, no, because it will need to complete a full table scan
A: If you have a slightly more complicated query, with one or more joins, the LIMIT clause gives the optimizer extra information. If it expects to match two tables and return all rows, a hash join is typically optimal. A hash join is a type of join optimized for large amounts of matching.
Now if the optimizer knows you've passed LIMIT 1, it knows that it won't be processing large amounts of data. It can revert to a loop join.
Based on the database (and even database version) this can have a huge impact on performance.
A: To answer your questions in order:
1) yes, if there is no index on name. The query will end as soon as it finds the first record. take off the limit and it has to do a full table scan every time.
2) no. primary/unique keys are guaranteed to be unique. The query should stop running as soon as it finds the row.
A: I believe the LIMIT is something done after the data set is found and the result set is being built up so I wouldn't expect it to make any difference at all. Making name the primary key will have a significant positive effect though as it will result in an index being made for the column.
A: If "name" is unique in the table, then there may still be a (very very minimal) gain in performance by putting the limit constraint on your query. If name is the primary key, there will likely be none.
A: Yes, you will notice a performance difference when dealing with the data. One record takes up less space than multiple records. Unless you are dealing with many rows, this would not be much of a difference, but once you run the query, the data has to be displayed back to you, which is costly, or dealt with programmatically. Either way, one record is easier than multiple.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How do I create a SHA1 hash in ruby? SHA Hash functions
A: For a Base64 encoded hash, to validated an Oauth signature, I used
require 'base64'
require 'hmac-sha1'
Base64.encode64((HMAC::SHA1.new('key') << 'base').digest).strip
A: I created a helper gem which is a simple wrapper around some sha1 code
require 'rickshaw'
> Rickshaw::SHA1.hash('LICENSE.txt')
=> "4659d94e7082a65ca39e7b6725094f08a413250a"
> "hello world".to_sha1
=> "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"
A: require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
A: Where 'serialize' is some user function defined elsewhere.
def generateKey(data)
return Digest::SHA1.hexdigest ("#{serialize(data)}")
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "164"
} |
Q: Excel: list ranges targeted by INDIRECT formulas We have a few very large Excel workbooks (dozens of tabs, over a MB each, very complex calculations) with many dozens, perhaps hundreds of formulas that use the dreaded INDIRECT function. These formulas are spread out throughout the workbook, and target several tables of data to look-up for values.
Now I need to move the ranges of data that are targeted by these formulas to a different location in the same workbook.
(The reason is not particularly relevant, but interesting on its own. We need to run these things in Excel Calculation Services and the latency hit of loading each of the rather large tables one at a time proved to be unacceptably high. We are moving the tables in a contiguous range so we can load them all in one shot.)
Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?
I don't need to do this on-line. I'll happily take something that takes 4 hours to run as long as it is reliable.
Be aware that the .Precedent, .Dependent, etc methods only track direct formulas.
(Also, rewriting the spreadsheets in whatever is not an option for us).
Thanks!
A: You could iterate over the entire Workbook using vba (i've included the code from @PabloG and @euro-micelli ):
Sub iterateOverWorkbook()
For Each i In ThisWorkbook.Worksheets
Set rRng = i.UsedRange
For Each j In rRng
If (Not IsEmpty(j)) Then
If (j.HasFormula) Then
If InStr(oCell.Formula, "INDIRECT") Then
j.Value = Replace(j.Formula, "INDIRECT(D4)", "INDIRECT(C4)")
End If
End If
End If
Next j
Next i
End Sub
This example substitues every occurrence of "indirect(D4)" with "indirect(C4)". You can easily swap the replace-function with something more sophisticated, if you have more complicated indirect-functions. Performance is not that bad, even for bigger Workbooks.
A: Q: "Is there any way to locate all the INDIRECT formulas that currently refer to the tables we want to move?"
As I read it, you want to look inside the arguments of INDIRECT for references to areas of interest.
OTTOMH I'd write VBA to use a regular expression parser, or even a simple INSTR to find INDIRECT( read forward to the matching ), then EVALUATE() the string inside to convert it to the actual address, repeat as required for multiple INDIRECT(...) calls and dump the formula and its translation to two columns in a sheet.
A: You can use something like this in VBA:
Sub ListIndirectRef()
Dim rRng As Range
Dim oSh As Worksheet
Dim oCell As Range
For Each oSh In ThisWorkbook.Worksheets
Set rRng = oSh.UsedRange
For Each oCell In rRng
If InStr(oCell.Formula, "INDIRECT") Then
Debug.Print oCell.Address, oCell.Formula
End If
Next
Next
End Sub
Instead of Debug.Print you can add code to suit your taste
A:
Unfortunately, the arguments of
INDIRECT are usually more complex than
that. Here's an actual formula from
one of the sheets, not the most
complex formula we have:
=IF(INDIRECT("'"&$B$5&"'!"&$O5&"1")="","",INDIRECT("'"&$B$5&"'!"&$O5&"1"))
hm, you could write a simple parser by ignoring most of the characters and just looking for the relevant parts (in this example: "A..Z", "0..9" and "!:" etc.) but you will run into troubles if the arguments in "indirect" are functions.
maybe the safer approach would be to print every occurence of "indirect" in a third sheet. you could then add the desired output and write a small search and replace program to write your changes back.
If you "get" every cell in a huge
spreadsheet you might end up needing
monstrous amounts of memory. I am
still willing to try and take that
risk.
PabloG's method of selecting the used range is the way to go (added it into my original code). The speed is pretty good, especially if you check whether the current cell contains a formula. Obviously, this all depends on the size of your workbook.
A: I'm not sure what the etiquette of SO is concerning mention of products with which the writer is connected, but OAK, the Operis Analysis Kit, an Excel add-in, can replace the INDIRECT functions by the cell references they resolve to. You can then use Excel's audit tools to determine what dependents each range has.
You would, of course, do this to a temporary copy of the workbook.
More at
*
*http://www.operisanalysiskit.com/oakpruning.htm
*http://www.operisanalysiskit.com/help/2007/index.html?oakconceptpruning.htm
Given the age of this question you may well have found an alternative solution or workaround.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is Object.GetHashCode() unique to a reference or a value? The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work.
*
*If two objects of the same type represent the same value, the hash function must return the same constant value for either object.
*For the best performance, a hash function must generate a random distribution for all input.
*The hash function must return exactly the same value regardless of any changes that are made to the object.
Rules 1 & 3 are contradictory to me.
Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows.
A: Not sure what MSDN documentation you are referring to. Looking at the current documentation on Object.GetHashCode (http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) provides the following "rules":
*
*If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
*The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
*For the best performance, a hash function must generate a random distribution for all input.
If you are referring to the second bullet point, the key phrases here are "as long as there is no modification to the object state" and "true only for the current execution of an application".
Also from the documentation,
A hash function is used to quickly generate a number (hash code) that corresponds to the value of an object. Hash functions are usually specific to each Type and must use at least one of the instance fields as input. [Emphasis added is mine.]
As for the actual implementation, it clearly states that derived classes can defer to the Object.GetHashCode implementation if and only if that derived class defines value equality to be reference equality and the type is not a value type. In other words, the default implementation of Object.GetHashCode is going to be based on reference equality since there are no real instance fields to use and, therefore, does not guarantee unique return values for different objects. Otherwise, your implementation should be specific to your type and should use at least one of your instance fields. As an example, the implementation of String.GetHashCode returns identical hash codes for identical string values, so two String objects return the same hash code if they represent the same string value, and uses all the characters in the string to generate that hash value.
A: Rules 1 & 3 aren't really a contradiction.
For a reference type the hash code is derived from a reference to the object - change an object's property and the reference is the same.
For value types the hash code is derived from the value, change a property of a value type and you get a completely new instance of the value type.
A:
Rules 1 & 3 are contradictory to me.
To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value.
To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value.
Consider the following example:
struct Person {
public readonly string FirstName;
public readonly string Name;
public readonly DateTime Birthday;
public int ShoeSize;
}
People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this:
public int GetHashCode() {
return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();
}
A: A very good explanation on how to handle GetHashCode (beyond Microsoft rules) is given in Eric Lipperts (co. Designer of C#) Blog with the article "Guidelines and rules for GetHashCode". It is not good practice to add hyperlinks here (since they can get invalid) but this one is worth it, and provided the information above one will probably still find it in case the hyperlink is lost.
A: By default it does it based on the reference to the object, but that means that it's the exact same object, so both would return the same hash. But a hash should be based on the value, like in the case of the string class. "a" and "b" would have a different hash, but "a" and "a" would return the same hash.
A: I can't know for sure how Object.GetHashCode is implemented in real .NET Framework, but in Rotor it uses SyncBlock index for the object as hashcode. There are some blog posts about it on the web, however most of them are from 2005.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Simulating a virtual static member of a class in c++? Is there anyway to have a sort of virtual static member in C++?
For example:
class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?
class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.
Any idea?
A: Here is one solution:
struct BaseData
{
const string my_word;
const int my_number;
};
class Base
{
public:
Base(const BaseData* apBaseData)
{
mpBaseData = apBaseData;
}
const string getMyWord()
{
return mpBaseData->my_word;
}
int getMyNumber()
{
return mpBaseData->my_number;
}
private:
const BaseData* mpBaseData;
};
class Derived : public Base
{
public:
Derived() : Base(&sBaseData)
{
}
private:
static BaseData sBaseData;
}
BaseData Derived::BaseData = { "Foo", 42 };
A: It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class.
If you insist on having the "shared" members implemented as static members of the derived class, you might be able to auto-generate the code of the derived classes. XSLT is a great tool for auto-generating simple classes.
In general, the example doesn't show a need for "virtual static" members, because for purposes like these you don't actually need inheritance - instead you should use the base class and have it accept the appropriate values in the constructor - maybe creating a single instance of the arguments for each "sub-type" and passing a pointer to it to avoid duplication of the shared data. Another similar approach is to use templates and pass as the template argument a class that provides all the relevant values (this is commonly referred to as the "Policy" pattern).
To conclude - for the purpose of the original example, there is no need for such "virtual static" members. If you still think they are needed for the code you are writing, please try to elaborate and add more context.
Example of what I described above:
class BaseClass {
public:
BaseClass(const Descriptor& desc) : _desc(desc) {}
string GetName() const { return _desc.name; }
int GetId() const { return _desc.Id; }
X GetX() connst { return _desc.X; }
virtual void UseClass() = 0;
private:
const Descriptor _desc;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(Descriptor("abc", 1,...)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass("Wowzer", 843,...) {}
virtual void UseClass() { /* do something */ }
};
I'd like to elaborate on this solution, and maybe give a solution to the de-initialization problem:
With a small change, you can implement the design described above without necessarily create a new instance of the "descriptor" for each instance of a derived class.
You can create a singleton object, DescriptorMap, that will hold the single instance of each descriptor, and use it when constructing the derived objects like so:
enum InstanceType {
Yellow,
Big,
BananaHammoc
}
class DescriptorsMap{
public:
static Descriptor* GetDescriptor(InstanceType type) {
if ( _instance.Get() == null) {
_instance.reset(new DescriptorsMap());
}
return _instance.Get()-> _descriptors[type];
}
private:
DescriptorsMap() {
descriptors[Yellow] = new Descriptor("Yellow", 42, ...);
descriptors[Big] = new Descriptor("InJapan", 17, ...)
...
}
~DescriptorsMap() {
/*Delete all the descriptors from the map*/
}
static autoptr<DescriptorsMap> _instance;
map<InstanceType, Descriptor*> _descriptors;
}
Now we can do this:
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}
virtual void UseClass() { /* do something */ }
};
class DerDerClass : public BaseClass {
public:
DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}
virtual void UseClass() { /* do something */ }
};
At the end of execution, when the C runtime performs uninitializations, it also calls the destructor of static objects, including our autoptr, which in deletes our instance of the DescriptorsMap.
So now we have a single instance of each descriptor that is also being deleted at the end of execution.
Note that if the only purpose of the derived class is to supply the relevant "descriptor" data (i.e. as opposed to implementing virtual functions) then you should make do with making the base class non-abstract, and just creating an instance with the appropriate descriptor each time.
A: @Hershi: the problem with that approach is that each instance of each derived class has a copy of the data, which may be expensive in some way.
Perhaps you could try something like this (I'm spit-balling without a compiling example, but the idea should be clear).
#include <iostream>
#include <string>
using namespace std;
struct DerivedData
{
DerivedData(const string & word, const int number) :
my_word(word), my_number(number) {}
const string my_word;
const int my_number;
};
class Base {
public:
Base() : m_data(0) {}
string getWord() const { return m_data->my_word; }
int getNumber() const { return m_data->my_number; }
protected:
DerivedData * m_data;
};
class Derived : public Base {
public:
Derived() : Base() {
if(Derived::s_data == 0) {
Derived::s_data = new DerivedData("abc", 1);
}
m_data = s_data;
}
private:
static DerivedData * s_data;
};
DerivedData * Derived::s_data = 0;
int main()
{
Base * p_b = new Derived();
cout getWord() << endl;
}
Regarding the follow-up question on deleting the static object: the only solution that comes to mind is to use a smart pointer, something like the Boost shared pointer.
A: I agree with Hershi's suggestion to use a template as the "base class". From what you're describing, it sounds more like a use for templates rather then subclassing.
You could create a template as follows ( have not tried to compile this ):
template <typename T>
class Object
{
public:
Object( const T& newObject ) : yourObject(newObject) {} ;
T GetObject() const { return yourObject } ;
void SetObject( const T& newObject ) { yourObject = newObject } ;
protected:
const T yourObject ;
} ;
class SomeClassOne
{
public:
SomeClassOne( const std::vector& someData )
{
yourData.SetObject( someData ) ;
}
private:
Object<std::vector<int>> yourData ;
} ;
This will let you use the template class methods to modify the data as needed from within your custom classes that use the data and share the various aspects of the template class.
If you're intent on using inheritance, then you might have to resort to the "joys" of using a void* pointer in your BaseClass and dealing with casting, etc.
However, based on your explanation, it seems like you need templates and not inheritance.
A: It sounds as if you're trying to avoid having to duplicate the code at the leaf classes, so why not just derive an intermediate base class from the base class. this intermediate class can hold the static data, and have all your leaf classes derive from the intermediate base class. This presupposes that one static piece of data held over all the derived classes is desired, which seems so from your example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Natural (human alpha-numeric) sort in Microsoft SQL 2005 We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.
Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.
While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.
For instance, sorting by a string record id gives something like:
rec1
rec10
rec14
rec2
rec20
rec3
rec4
...and so on.
I want this to take account of the number, so:
rec1
rec2
rec3
rec4
rec10
rec14
rec20
I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".
I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.
Does anyone know a way to quickly apply a natural sort in Sql server?
We're using:
ROW_NUMBER() over (order by {field name} asc)
And then we're paging by that.
We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.
We have valid user input that follows different formats for different clients.
One might go rec1, rec2, rec3, ... rec100, rec101
While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301
When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.
These formats vary a lot, but are often mixtures of letters and numbers.
Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn.
However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.
SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.
@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.
A: Here's a solution written for SQL 2000. It can probably be improved for newer SQL versions.
/**
* Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings.
*
* @author Alexandre Potvin Latreille (plalx)
* @param {nvarchar(4000)} string The formatted string.
* @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10.
* @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string.
*
* @return {nvarchar(4000)} A string for natural sorting.
* Example of use:
*
* SELECT Name FROM TableA ORDER BY Name
* TableA (unordered) TableA (ordered)
* ------------ ------------
* ID Name ID Name
* 1. A1. 1. A1-1.
* 2. A1-1. 2. A1.
* 3. R1 --> 3. R1
* 4. R11 4. R11
* 5. R2 5. R2
*
*
* As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it.
* We can use this function to fix this.
*
* SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-')
* TableA (unordered) TableA (ordered)
* ------------ ------------
* ID Name ID Name
* 1. A1. 1. A1.
* 2. A1-1. 2. A1-1.
* 3. R1 --> 3. R1
* 4. R11 4. R2
* 5. R2 5. R11
*/
ALTER FUNCTION [dbo].[udf_NaturalSortFormat](
@string nvarchar(4000),
@numberLength int = 10,
@sameOrderChars char(50) = ''
)
RETURNS varchar(4000)
AS
BEGIN
DECLARE @sortString varchar(4000),
@numStartIndex int,
@numEndIndex int,
@padLength int,
@totalPadLength int,
@i int,
@sameOrderCharsLen int;
SELECT
@totalPadLength = 0,
@string = RTRIM(LTRIM(@string)),
@sortString = @string,
@numStartIndex = PATINDEX('%[0-9]%', @string),
@numEndIndex = 0,
@i = 1,
@sameOrderCharsLen = LEN(@sameOrderChars);
-- Replace all char that have the same order by a space.
WHILE (@i <= @sameOrderCharsLen)
BEGIN
SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' ');
SET @i = @i + 1;
END
-- Pad numbers with zeros.
WHILE (@numStartIndex <> 0)
BEGIN
SET @numStartIndex = @numStartIndex + @numEndIndex;
SET @numEndIndex = @numStartIndex;
WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1)
BEGIN
SET @numEndIndex = @numEndIndex + 1;
END
SET @numEndIndex = @numEndIndex - 1;
SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex);
IF @padLength < 0
BEGIN
SET @padLength = 0;
END
SET @sortString = STUFF(
@sortString,
@numStartIndex + @totalPadLength,
0,
REPLICATE('0', @padLength)
);
SET @totalPadLength = @totalPadLength + @padLength;
SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex));
END
RETURN @sortString;
END
A: RedFilter's answer is great for reasonably sized datasets where indexing is not critical, however if you want an index, several tweaks are required.
First, mark the function as not doing any data access and being deterministic and precise:
[SqlFunction(DataAccess = DataAccessKind.None,
SystemDataAccess = SystemDataAccessKind.None,
IsDeterministic = true, IsPrecise = true)]
Next, MSSQL has a 900 byte limit on the index key size, so if the naturalized value is the only value in the index, it must be at most 450 characters long. If the index includes multiple columns, the return value must be even smaller. Two changes:
CREATE FUNCTION Naturalize(@str AS nvarchar(max)) RETURNS nvarchar(450)
EXTERNAL NAME ClrExtensions.Util.Naturalize
and in the C# code:
const int maxLength = 450;
Finally, you will need to add a computed column to your table, and it must be persisted (because MSSQL cannot prove that Naturalize is deterministic and precise), which means the naturalized value is actually stored in the table but is still maintained automatically:
ALTER TABLE YourTable ADD nameNaturalized AS dbo.Naturalize(name) PERSISTED
You can now create the index!
CREATE INDEX idx_YourTable_n ON YourTable (nameNaturalized)
I've also made a couple of changes to RedFilter's code: using chars for clarity, incorporating duplicate space removal into the main loop, exiting once the result is longer than the limit, setting maximum length without substring etc. Here's the result:
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
public static class Util
{
[SqlFunction(DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.None, IsDeterministic = true, IsPrecise = true)]
public static SqlString Naturalize(string str)
{
if (string.IsNullOrEmpty(str))
return str;
const int maxLength = 450;
const int padLength = 15;
bool isDecimal = false;
bool wasSpace = false;
int numStart = 0;
int numLength = 0;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
char c = str[i];
if (c >= '0' && c <= '9')
{
if (numLength == 0)
numStart = i;
numLength++;
}
else
{
if (numLength > 0)
{
sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));
numLength = 0;
}
if (c != ' ' || !wasSpace)
sb.Append(c);
isDecimal = c == '.';
if (sb.Length > maxLength)
break;
}
wasSpace = c == ' ';
}
if (numLength > 0)
sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));
if (sb.Length > maxLength)
sb.Length = maxLength;
return sb.ToString();
}
private static string pad(string num, bool isDecimal, int padLength)
{
return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');
}
}
A: I know this is a bit old at this point, but in my search for a better solution, I came across this question. I'm currently using a function to order by. It works fine for my purpose of sorting records which are named with mixed alpha numeric ('item 1', 'item 10', 'item 2', etc)
CREATE FUNCTION [dbo].[fnMixSort]
(
@ColValue NVARCHAR(255)
)
RETURNS NVARCHAR(1000)
AS
BEGIN
DECLARE @p1 NVARCHAR(255),
@p2 NVARCHAR(255),
@p3 NVARCHAR(255),
@p4 NVARCHAR(255),
@Index TINYINT
IF @ColValue LIKE '[a-z]%'
SELECT @Index = PATINDEX('%[0-9]%', @ColValue),
@p1 = LEFT(CASE WHEN @Index = 0 THEN @ColValue ELSE LEFT(@ColValue, @Index - 1) END + REPLICATE(' ', 255), 255),
@ColValue = CASE WHEN @Index = 0 THEN '' ELSE SUBSTRING(@ColValue, @Index, 255) END
ELSE
SELECT @p1 = REPLICATE(' ', 255)
SELECT @Index = PATINDEX('%[^0-9]%', @ColValue)
IF @Index = 0
SELECT @p2 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255),
@ColValue = ''
ELSE
SELECT @p2 = RIGHT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),
@ColValue = SUBSTRING(@ColValue, @Index, 255)
SELECT @Index = PATINDEX('%[0-9,a-z]%', @ColValue)
IF @Index = 0
SELECT @p3 = REPLICATE(' ', 255)
ELSE
SELECT @p3 = LEFT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),
@ColValue = SUBSTRING(@ColValue, @Index, 255)
IF PATINDEX('%[^0-9]%', @ColValue) = 0
SELECT @p4 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255)
ELSE
SELECT @p4 = LEFT(@ColValue + REPLICATE(' ', 255), 255)
RETURN @p1 + @p2 + @p3 + @p4
END
Then call
select item_name from my_table order by fnMixSort(item_name)
It easily triples the processing time for a simple data read, so it may not be the perfect solution.
A: order by LEN(value), value
Not perfect, but works well in a lot of cases.
A: Here is an other solution that I like:
http://www.dreamchain.com/sql-and-alpha-numeric-sort-order/
It's not Microsoft SQL, but since I ended up here when I was searching for a solution for Postgres, I thought adding this here would help others.
EDIT: Here is the code, in case the link goes away.
CREATE or REPLACE FUNCTION pad_numbers(text) RETURNS text AS $$
SELECT regexp_replace(regexp_replace(regexp_replace(regexp_replace(($1 collate "C"),
E'(^|\\D)(\\d{1,3}($|\\D))', E'\\1000\\2', 'g'),
E'(^|\\D)(\\d{4,6}($|\\D))', E'\\1000\\2', 'g'),
E'(^|\\D)(\\d{7}($|\\D))', E'\\100\\2', 'g'),
E'(^|\\D)(\\d{8}($|\\D))', E'\\10\\2', 'g');
$$ LANGUAGE SQL;
"C" is the default collation in postgresql; you may specify any collation you desire, or remove the collation statement if you can be certain your table columns will never have a nondeterministic collation assigned.
usage:
SELECT * FROM wtf w
WHERE TRUE
ORDER BY pad_numbers(w.my_alphanumeric_field)
A: Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was way too slow.
Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics:
*
*will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter)
*properly sorts decimals, so 123.333 comes before 123.45
*because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code
*supports sorting a string with an arbitrary number of numbers within it
*will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter)
The code is here:
using System;
using System.Data.SqlTypes;
using System.Text;
using Microsoft.SqlServer.Server;
public class UDF
{
[SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]
public static SqlString Naturalize(string val)
{
if (String.IsNullOrEmpty(val))
return val;
while(val.Contains(" "))
val = val.Replace(" ", " ");
const int maxLength = 1000;
const int padLength = 25;
bool inNumber = false;
bool isDecimal = false;
int numStart = 0;
int numLength = 0;
int length = val.Length < maxLength ? val.Length : maxLength;
//TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength
var sb = new StringBuilder();
for (var i = 0; i < length; i++)
{
int charCode = (int)val[i];
if (charCode >= 48 && charCode <= 57)
{
if (!inNumber)
{
numStart = i;
numLength = 1;
inNumber = true;
continue;
}
numLength++;
continue;
}
if (inNumber)
{
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
inNumber = false;
}
isDecimal = (charCode == 46);
sb.Append(val[i]);
}
if (inNumber)
sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));
var ret = sb.ToString();
if (ret.Length > maxLength)
return ret.Substring(0, maxLength);
return ret;
}
static string PadNumber(string num, bool isDecimal, int padLength)
{
return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');
}
}
To register this so that you can call it from SQL Server, run the following commands in Query Analyzer:
CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here
go
CREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000)
EXTERNAL NAME SqlServerClr.UDF.Naturalize
go
Then, you can use it like so:
select *
from MyTable
order by dbo.Naturalize(MyTextField)
Note: If you get an error in SQL Server along the lines of Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option., follow the instructions here to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration.
Note2: This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome!
Edit: Renamed the function to Naturalize instead of NaturalSort, since it does not do any actual sorting.
A: For the following varchar data:
BR1
BR2
External Location
IR1
IR2
IR3
IR4
IR5
IR6
IR7
IR8
IR9
IR10
IR11
IR12
IR13
IR14
IR16
IR17
IR15
VCR
This worked best for me:
ORDER BY substring(fieldName, 1, 1), LEN(fieldName)
A: I know this is an old question but I just came across it and since it's not got an accepted answer.
I have always used ways similar to this:
SELECT [Column] FROM [Table]
ORDER BY RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))), 1000)
The only common times that this has issues is if your column won't cast to a VARCHAR(MAX), or if LEN([Column]) > 1000 (but you can change that 1000 to something else if you want), but you can use this rough idea for what you need.
Also this is much worse performance than normal ORDER BY [Column], but it does give you the result asked for in the OP.
Edit: Just to further clarify, this the above will not work if you have decimal values such as having 1, 1.15 and 1.5, (they will sort as {1, 1.5, 1.15}) as that is not what is asked for in the OP, but that can easily be done by:
SELECT [Column] FROM [Table]
ORDER BY REPLACE(RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))) + REPLICATE('0', 100 - CHARINDEX('.', REVERSE(LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX))))), 1)), 1000), '.', '0')
Result: {1, 1.15, 1.5}
And still all entirely within SQL. This will not sort IP addresses because you're now getting into very specific number combinations as opposed to simple text + number.
A: If you're having trouble loading the data from the DB to sort in C#, then I'm sure you'll be disappointed with any approach at doing it programmatically in the DB. When the server is going to sort, it's got to calculate the "perceived" order just as you would have -- every time.
I'd suggest that you add an additional column to store the preprocessed sortable string, using some C# method, when the data is first inserted. You might try to convert the numerics into fixed-width ranges, for example, so "xyz1" would turn into "xyz00000001". Then you could use normal SQL Server sorting.
At the risk of tooting my own horn, I wrote a CodeProject article implementing the problem as posed in the CodingHorror article. Feel free to steal from my code.
A: Simply you sort by
ORDER BY
cast (substring(name,(PATINDEX('%[0-9]%',name)),len(name))as int)
##
A: You can use the following code to resolve the problem:
Select *,
substring(Cote,1,len(Cote) - Len(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1)))alpha,
CAST(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1) AS INT)intv
FROM Documents
left outer join Sites ON Sites.IDSite = Documents.IDSite
Order BY alpha, intv
regards,
[email protected]
A: I've just read a article somewhere about such a topic. The key point is: you only need the integer value to sort data, while the 'rec' string belongs to the UI. You could split the information in two fields, say alpha and num, sort by alpha and num (separately) and then showing a string composed by alpha + num. You could use a computed column to compose the string, or a view.
Hope it helps
A: I'm fashionably late to the party as usual. Nevertheless, here is my attempt at an answer that seems to work well (I would say that). It assumes text with digits at the end, like in the original example data.
First a function that won't end up winning a "pretty SQL" competition anytime soon.
CREATE FUNCTION udfAlphaNumericSortHelper (
@string varchar(max)
)
RETURNS @results TABLE (
txt varchar(max),
num float
)
AS
BEGIN
DECLARE @txt varchar(max) = @string
DECLARE @numStr varchar(max) = ''
DECLARE @num float = 0
DECLARE @lastChar varchar(1) = ''
set @lastChar = RIGHT(@txt, 1)
WHILE @lastChar <> '' and @lastChar is not null
BEGIN
IF ISNUMERIC(@lastChar) = 1
BEGIN
set @numStr = @lastChar + @numStr
set @txt = Substring(@txt, 0, len(@txt))
set @lastChar = RIGHT(@txt, 1)
END
ELSE
BEGIN
set @lastChar = null
END
END
SET @num = CAST(@numStr as float)
INSERT INTO @results select @txt, @num
RETURN;
END
Then call it like below:
declare @str nvarchar(250) = 'sox,fox,jen1,Jen0,jen15,jen02,jen0004,fox00,rec1,rec10,jen3,rec14,rec2,rec20,rec3,rec4,zip1,zip1.32,zip1.33,zip1.3,TT0001,TT01,TT002'
SELECT tbl.value --, sorter.txt, sorter.num
FROM STRING_SPLIT(@str, ',') as tbl
CROSS APPLY dbo.udfAlphaNumericSortHelper(value) as sorter
ORDER BY sorter.txt, sorter.num, len(tbl.value)
With results:
fox
fox00
Jen0
jen1
jen02
jen3
jen0004
jen15
rec1
rec2
rec3
rec4
rec10
rec14
rec20
sox
TT01
TT0001
TT002
zip1
zip1.3
zip1.32
zip1.33
A: I still don't understand (probably because of my poor English).
You could try:
ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)
But it won't work for millions of records.
That why I suggested to use trigger which fills separate column with human value.
Moreover:
*
*built-in T-SQL functions are really
slow and Microsoft suggest to use
.NET functions instead.
*human value is constant so there is no point calculating it each time
when query runs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: What is a race condition? When writing multithreaded applications, one of the most common problems experienced is race conditions.
My questions to the community are:
*
*What is the race condition?
*How do you detect them?
*How do you handle them?
*Finally, how do you prevent them from occurring?
A: There is an important technical difference between race conditions and data races. Most answers seem to make the assumption that these terms are equivalent, but they are not.
A data race occurs when 2 instructions access the same memory location, at least one of these accesses is a write and there is no happens before ordering among these accesses. Now what constitutes a happens before ordering is subject to a lot of debate, but in general ulock-lock pairs on the same lock variable and wait-signal pairs on the same condition variable induce a happens-before order.
A race condition is a semantic error. It is a flaw that occurs in the timing or the ordering of events that leads to erroneous program behavior.
Many race conditions can be (and in fact are) caused by data races, but this is not necessary. As a matter of fact, data races and race conditions are neither the necessary, nor the sufficient condition for one another. This blog post also explains the difference very well, with a simple bank transaction example. Here is another simple example that explains the difference.
Now that we nailed down the terminology, let us try to answer the original question.
Given that race conditions are semantic bugs, there is no general way of detecting them. This is because there is no way of having an automated oracle that can distinguish correct vs. incorrect program behavior in the general case. Race detection is an undecidable problem.
On the other hand, data races have a precise definition that does not necessarily relate to correctness, and therefore one can detect them. There are many flavors of data race detectors (static/dynamic data race detection, lockset-based data race detection, happens-before based data race detection, hybrid data race detection). A state of the art dynamic data race detector is ThreadSanitizer which works very well in practice.
Handling data races in general requires some programming discipline to induce happens-before edges between accesses to shared data (either during development, or once they are detected using the above mentioned tools). this can be done through locks, condition variables, semaphores, etc. However, one can also employ different programming paradigms like message passing (instead of shared memory) that avoid data races by construction.
A: A sort-of-canonical definition is "when two threads access the same location in memory at the same time, and at least one of the accesses is a write." In the situation the "reader" thread may get the old value or the new value, depending on which thread "wins the race." This is not always a bug—in fact, some really hairy low-level algorithms do this on purpose—but it should generally be avoided. @Steve Gury give's a good example of when it might be a problem.
A: A race condition is a situation on concurrent programming where two concurrent threads or processes compete for a resource and the resulting final state depends on who gets the resource first.
A: You can prevent race condition, if you use "Atomic" classes. The reason is just the thread don't separate operation get and set, example is below:
AtomicInteger ai = new AtomicInteger(2);
ai.getAndAdd(5);
As a result, you will have 7 in link "ai".
Although you did two actions, but the both operation confirm the same thread and no one other thread will interfere to this, that means no race conditions!
A: A race condition is a kind of bug, that happens only with certain temporal conditions.
Example:
Imagine you have two threads, A and B.
In Thread A:
if( object.a != 0 )
object.avg = total / object.a
In Thread B:
object.a = 0
If thread A is preempted just after having check that object.a is not null, B will do a = 0, and when thread A will gain the processor, it will do a "divide by zero".
This bug only happen when thread A is preempted just after the if statement, it's very rare, but it can happen.
A: Many answers in this discussion explains what a race condition is. I try to provide an explaination why this term is called race condition in software industry.
Why is it called race condition?
Race condition is not only related with software but also related with hardware too. Actually the term was initially coined by the hardware industry.
According to wikipedia:
The term originates with the idea of two signals racing each other to
influence the output first.
Race condition in a logic circuit:
Software industry took this term without modification, which makes it a little bit difficult to understand.
You need to do some replacement to map it to the software world:
*
*"two signals" ==> "two threads"/"two processes"
*"influence the output" ==> "influence some shared state"
So race condition in software industry means "two threads"/"two processes" racing each other to "influence some shared state", and the final result of the shared state will depend on some subtle timing difference, which could be caused by some specific thread/process launching order, thread/process scheduling, etc.
A: A "race condition" exists when multithreaded (or otherwise parallel) code that would access a shared resource could do so in such a way as to cause unexpected results.
Take this example:
for ( int i = 0; i < 10000000; i++ )
{
x = x + 1;
}
If you had 5 threads executing this code at once, the value of x WOULD NOT end up being 50,000,000. It would in fact vary with each run.
This is because, in order for each thread to increment the value of x, they have to do the following: (simplified, obviously)
Retrieve the value of x
Add 1 to this value
Store this value to x
Any thread can be at any step in this process at any time, and they can step on each other when a shared resource is involved. The state of x can be changed by another thread during the time between x is being read and when it is written back.
Let's say a thread retrieves the value of x, but hasn't stored it yet. Another thread can also retrieve the same value of x (because no thread has changed it yet) and then they would both be storing the same value (x+1) back in x!
Example:
Thread 1: reads x, value is 7
Thread 1: add 1 to x, value is now 8
Thread 2: reads x, value is 7
Thread 1: stores 8 in x
Thread 2: adds 1 to x, value is now 8
Thread 2: stores 8 in x
Race conditions can be avoided by employing some sort of locking mechanism before the code that accesses the shared resource:
for ( int i = 0; i < 10000000; i++ )
{
//lock x
x = x + 1;
//unlock x
}
Here, the answer comes out as 50,000,000 every time.
For more on locking, search for: mutex, semaphore, critical section, shared resource.
A: Race conditions occur in multi-threaded applications or multi-process systems. A race condition, at its most basic, is anything that makes the assumption that two things not in the same thread or process will happen in a particular order, without taking steps to ensure that they do. This happens commonly when two threads are passing messages by setting and checking member variables of a class both can access. There's almost always a race condition when one thread calls sleep to give another thread time to finish a task (unless that sleep is in a loop, with some checking mechanism).
Tools for preventing race conditions are dependent on the language and OS, but some comon ones are mutexes, critical sections, and signals. Mutexes are good when you want to make sure you're the only one doing something. Signals are good when you want to make sure someone else has finished doing something. Minimizing shared resources can also help prevent unexpected behaviors
Detecting race conditions can be difficult, but there are a couple signs. Code which relies heavily on sleeps is prone to race conditions, so first check for calls to sleep in the affected code. Adding particularly long sleeps can also be used for debugging to try and force a particular order of events. This can be useful for reproducing the behavior, seeing if you can make it disappear by changing the timing of things, and for testing solutions put in place. The sleeps should be removed after debugging.
The signature sign that one has a race condition though, is if there's an issue that only occurs intermittently on some machines. Common bugs would be crashes and deadlocks. With logging, you should be able to find the affected area and work back from there.
A: I made a video that explains this.
Essentially it is when you have a state with is shared across multiple threads and before the first execution on a given state is completed, another execution starts and the new thread’s initial state for a given operation is wrong because the previous execution has not completed.
Because the initial state of the second execution is wrong, the resulting computation is also wrong. Because eventually the second execution will update the final state with the wrong result.
You can view it here.
https://youtu.be/RWRicNoWKOY
A:
What is a Race Condition?
You are planning to go to a movie at 5 pm. You inquire about the availability of the tickets at 4 pm. The representative says that they are available. You relax and reach the ticket window 5 minutes before the show. I'm sure you can guess what happens: it's a full house. The problem here was in the duration between the check and the action. You inquired at 4 and acted at 5. In the meantime, someone else grabbed the tickets. That's a race condition - specifically a "check-then-act" scenario of race conditions.
How do you detect them?
Religious code review, multi-threaded unit tests. There is no shortcut. There are few Eclipse plugin emerging on this, but nothing stable yet.
How do you handle and prevent them?
The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronization, and actor based concurrency will help.
The best resource for concurrency is JCIP. You can also get some more details on above explanation here.
A: A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:
if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
// y will not be equal to 10.
}
The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.
In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:
// Obtain lock for x
if (x == 5)
{
y = x * 2; // Now, nothing can change x until the lock is released.
// Therefore y = 10
}
// release lock for x
A: Microsoft actually have published a really detailed article on this matter of race conditions and deadlocks. The most summarized abstract from it would be the title paragraph:
A race condition occurs when two threads access a shared variable at
the same time. The first thread reads the variable, and the second
thread reads the same value from the variable. Then the first thread
and second thread perform their operations on the value, and they race
to see which thread can write the value last to the shared variable.
The value of the thread that writes its value last is preserved,
because the thread is writing over the value that the previous thread
wrote.
A:
What is a race condition?
The situation when the process is critically dependent on the sequence or timing of other events.
For example,
Processor A and processor B both needs identical resource for their execution.
How do you detect them?
There are tools to detect race condition automatically:
*
*Lockset-Based Race Checker
*Happens-Before Race Detection
*Hybrid Race Detection
How do you handle them?
Race condition can be handled by Mutex or Semaphores. They act as a lock allows a process to acquire a resource based on certain requirements to prevent race condition.
How do you prevent them from occurring?
There are various ways to prevent race condition, such as Critical Section Avoidance.
*
*No two processes simultaneously inside their critical regions. (Mutual Exclusion)
*No assumptions are made about speeds or the number of CPUs.
*No process running outside its critical region which blocks other processes.
*No process has to wait forever to enter its critical region. (A waits for B resources, B waits for C resources, C waits for A resources)
A: Here is the classical Bank Account Balance example which will help newbies to understand Threads in Java easily w.r.t. race conditions:
public class BankAccount {
/**
* @param args
*/
int accountNumber;
double accountBalance;
public synchronized boolean Deposit(double amount){
double newAccountBalance=0;
if(amount<=0){
return false;
}
else {
newAccountBalance = accountBalance+amount;
accountBalance=newAccountBalance;
return true;
}
}
public synchronized boolean Withdraw(double amount){
double newAccountBalance=0;
if(amount>accountBalance){
return false;
}
else{
newAccountBalance = accountBalance-amount;
accountBalance=newAccountBalance;
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BankAccount b = new BankAccount();
b.accountBalance=2000;
System.out.println(b.Withdraw(3000));
}
A: Try this basic example for better understanding of race condition:
public class ThreadRaceCondition {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Account myAccount = new Account(22222222);
// Expected deposit: 250
for (int i = 0; i < 50; i++) {
Transaction t = new Transaction(myAccount,
Transaction.TransactionType.DEPOSIT, 5.00);
t.start();
}
// Expected withdrawal: 50
for (int i = 0; i < 50; i++) {
Transaction t = new Transaction(myAccount,
Transaction.TransactionType.WITHDRAW, 1.00);
t.start();
}
// Temporary sleep to ensure all threads are completed. Don't use in
// realworld :-)
Thread.sleep(1000);
// Expected account balance is 200
System.out.println("Final Account Balance: "
+ myAccount.getAccountBalance());
}
}
class Transaction extends Thread {
public static enum TransactionType {
DEPOSIT(1), WITHDRAW(2);
private int value;
private TransactionType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
};
private TransactionType transactionType;
private Account account;
private double amount;
/*
* If transactionType == 1, deposit else if transactionType == 2 withdraw
*/
public Transaction(Account account, TransactionType transactionType,
double amount) {
this.transactionType = transactionType;
this.account = account;
this.amount = amount;
}
public void run() {
switch (this.transactionType) {
case DEPOSIT:
deposit();
printBalance();
break;
case WITHDRAW:
withdraw();
printBalance();
break;
default:
System.out.println("NOT A VALID TRANSACTION");
}
;
}
public void deposit() {
this.account.deposit(this.amount);
}
public void withdraw() {
this.account.withdraw(amount);
}
public void printBalance() {
System.out.println(Thread.currentThread().getName()
+ " : TransactionType: " + this.transactionType + ", Amount: "
+ this.amount);
System.out.println("Account Balance: "
+ this.account.getAccountBalance());
}
}
class Account {
private int accountNumber;
private double accountBalance;
public int getAccountNumber() {
return accountNumber;
}
public double getAccountBalance() {
return accountBalance;
}
public Account(int accountNumber) {
this.accountNumber = accountNumber;
}
// If this method is not synchronized, you will see race condition on
// Remove syncronized keyword to see race condition
public synchronized boolean deposit(double amount) {
if (amount < 0) {
return false;
} else {
accountBalance = accountBalance + amount;
return true;
}
}
// If this method is not synchronized, you will see race condition on
// Remove syncronized keyword to see race condition
public synchronized boolean withdraw(double amount) {
if (amount > accountBalance) {
return false;
} else {
accountBalance = accountBalance - amount;
return true;
}
}
}
A: You don't always want to discard a race condition. If you have a flag which can be read and written by multiple threads, and this flag is set to 'done' by one thread so that other thread stop processing when flag is set to 'done', you don't want that "race condition" to be eliminated. In fact, this one can be referred to as a benign race condition.
However, using a tool for detection of race condition, it will be spotted as a harmful race condition.
More details on race condition here, http://msdn.microsoft.com/en-us/magazine/cc546569.aspx.
A: Consider an operation which has to display the count as soon as the count gets incremented. ie., as soon as CounterThread increments the value DisplayThread needs to display the recently updated value.
int i = 0;
Output
CounterThread -> i = 1
DisplayThread -> i = 1
CounterThread -> i = 2
CounterThread -> i = 3
CounterThread -> i = 4
DisplayThread -> i = 4
Here CounterThread gets the lock frequently and updates the value before DisplayThread displays it. Here exists a Race condition. Race Condition can be solved by using Synchronzation
A: A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1277"
} |
Q: What is a deadlock? When writing multi-threaded applications, one of the most common problems experienced are deadlocks.
My questions to the community are:
*
*What is a deadlock?
*How do you detect them?
*Do you handle them?
*And finally, how do you prevent them from occurring?
A: You can take a look at this wonderful articles, under section Deadlock. It is in C# but the idea is still the same for other platform. I quote here for easy reading
A deadlock happens when two threads each wait for a resource held by
the other, so neither can proceed. The easiest way to illustrate this
is with two locks:
object locker1 = new object();
object locker2 = new object();
new Thread (() => {
lock (locker1)
{
Thread.Sleep (1000);
lock (locker2); // Deadlock
}
}).Start();
lock (locker2)
{
Thread.Sleep (1000);
lock (locker1); // Deadlock
}
A: Deadlock is a common problem in multiprocessing/multiprogramming problems in OS.
Say there are two processes P1, P2 and two globally shareable resource R1, R2 and in critical section both resources need to be accessed
Initially, the OS assigns R1 to process P1 and R2 to process P2.
As both processes are running concurrently they may start executing their code but the PROBLEM arises when a process hits the critical section.
So process R1 will wait for process P2 to release R2 and vice versa...
So they will wait for forever (DEADLOCK CONDITION).
A small ANALOGY...
Your Mother(OS),
You(P1),
Your brother(P2),
Apple(R1),
Knife(R2),
critical section(cutting apple with knife).
Your mother gives you the apple and the knife to your brother in the beginning.
Both are happy and playing(Executing their codes).
Anyone of you wants to cut the apple(critical section) at some point.
You don't want to give the apple to your brother.
Your brother doesn't want to give the knife to you.
So both of you are going to wait for a long very long time :)
A: Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.
Ways to avoid having deadlocks are:
*
*avoid having locks (if possible),
*avoid having more than one lock
*always take the locks in the same order.
A: A lock occurs when multiple processes try to access the same resource at the same time.
One process loses out and must wait for the other to finish.
A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish.
So, an example:
Resource A and resource B are used by process X and process Y
*
*X starts to use A.
*X and Y try to start using B
*Y 'wins' and gets B first
*now Y needs to use A
*A is locked by X, which is waiting for Y
The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.
In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.
A: To define deadlock, first I would define process.
Process : As we know process is nothing but a program in execution.
Resource : To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.
Deadlock : Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.
Deadlock condition or situation
In the above diagram there are two process P1 and p2 and there are two resources R1 and R2.
Resource R1 is allocated to process P1 and resource R2 is allocated to process p2.
To complete execution of process P1 needs resource R2, so P1 request for R2, but R2 is already allocated to P2.
In the same way Process P2 to complete its execution needs R1, but R1 is already allocated to P1.
both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a DEADLOCK Condition.
In order for deadlock to occur, four conditions must be true.
*
*Mutual exclusion - Each resource is either currently allocated to exactly one process or it is available. (Two processes cannot
simultaneously control the same resource or be in their critical
section).
*Hold and Wait - processes currently holding resources can request new resources.
*No preemption - Once a process holds a resource, it cannot be taken away by another process or the kernel.
*Circular wait - Each process is waiting to obtain a resource which is held by another process.
and all these condition are satisfied in above diagram.
A: Deadlock occurs when two threads aquire locks which prevent either of them from progressing. The best way to avoid them is with careful development. Many embedded systems protect against them by using a watchdog timer (a timer which resets the system whenever if it hangs for a certain period of time).
A: A deadlock occurs when there is a circular chain of threads or processes which each hold a locked resource and are trying to lock a resource held by the next element in the chain. For example, two threads that hold respectively lock A and lock B, and are both trying to acquire the other lock.
A: Lock-based concurrency control
Using locking for controlling access to shared resources is prone to deadlocks, and the transaction scheduler alone cannot prevent their occurrences.
For instance, relational database systems use various locks to guarantee transaction ACID properties.
No matter what relational database system you are using, locks will always be acquired when modifying (e.g., UPDATE or DELETE) a certain table record. Without locking a row that was modified by a currently running transaction, Atomicity would be compromised).
What is a deadlock
A deadlock happens when two concurrent transactions cannot make progress because each one waits for the other to release a lock, as illustrated in the following diagram.
Because both transactions are in the lock acquisition phase, neither one releases a lock prior to acquiring the next one.
Recovering from a deadlock situation
If you're using a Concurrency Control algorithm that relies on locks, then there is always the risk of running into a deadlock situation. Deadlocks can occur in any concurrency environment, not just in a database system.
For instance, a multithreading program can deadlock if two or more threads are waiting on locks that were previously acquired so that no thread can make any progress. If this happens in a Java application, the JVM cannot just force a Thread to stop its execution and release its locks.
Even if the Thread class exposes a stop method, that method has been deprecated since Java 1.1 because it can cause objects to be left in an inconsistent state after a thread is stopped. Instead, Java defines an interrupt method, which acts as a hint as a thread that gets interrupted can simply ignore the interruption and continue its execution.
For this reason, a Java application cannot recover from a deadlock situation, and it is the responsibility of the application developer to order the lock acquisition requests in such a way that deadlocks can never occur.
However, a database system cannot enforce a given lock acquisition order since it's impossible to foresee what other locks a certain transaction will want to acquire further. Preserving the lock order becomes the responsibility of the data access layer, and the database can only assist in recovering from a deadlock situation.
The database engine runs a separate process that scans the current conflict graph for lock-wait cycles (which are caused by deadlocks).
When a cycle is detected, the database engine picks one transaction and aborts it, causing its locks to be released, so that the other transaction can make progress.
Unlike the JVM, a database transaction is designed as an atomic unit of work. Hence, a rollback leaves the database in a consistent state.
A: Let me explain a real world (not actually real) example for a deadlock situation from the crime movies. Imagine a criminal holds an hostage and against that, a cop also holds an hostage who is a friend of the criminal. In this case, criminal is not going to let the hostage go if cop won't let his friend to let go. Also the cop is not going to let the friend of criminal let go, unless the criminal releases the hostage. This is an endless untrustworthy situation, because both sides are insisting the first step from each other.
Criminal & Cop Scene
So simply, when two threads needs two different resources and each of them has the lock of the resource that the other need, it is a deadlock.
Another High Level Explanation of Deadlock : Broken Hearts
You are dating with a girl and one day after an argument, both sides are heart-broken to each other and waiting for an I-am-sorry-and-I-missed-you call. In this situation, both sides want to communicate each other if and only if one of them receives an I-am-sorry call from the other. Because that neither of each is going to start communication and waiting in a passive state, both will wait for the other to start communication which ends up in a deadlock situation.
A: A deadlock happens when a thread is waiting for something that never occurs.
Typically, it happens when a thread is waiting on a mutex or semaphore that was never released by the previous owner.
It also frequently happens when you have a situation involving two threads and two locks like this:
Thread 1 Thread 2
Lock1->Lock(); Lock2->Lock();
WaitForLock2(); WaitForLock1(); <-- Oops!
You generally detect them because things that you expect to happen never do, or the application hangs entirely.
A: A classic and very simple program for understanding Deadlock situation :-
public class Lazy {
private static boolean initialized = false;
static {
Thread t = new Thread(new Runnable() {
public void run() {
initialized = true;
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(initialized);
}
}
When the main thread invokes Lazy.main, it checks whether the class Lazy
has been initialized and begins to initialize the class. The
main thread now sets initialized to false , creates and starts a background
thread whose run method sets initialized to true , and waits for the background thread to complete.
This time, the class is currently being initialized by another thread.
Under these circumstances, the current thread, which is the background thread,
waits on the Class object until initialization is complete. Unfortunately, the thread
that is doing the initialization, the main thread, is waiting for the background
thread to complete. Because the two threads are now waiting for each other, the
program is DEADLOCKED.
A: A deadlock is a state of a system in which no single process/thread is capable of executing an action. As mentioned by others, a deadlock is typically the result of a situation where each process/thread wishes to acquire a lock to a resource that is already locked by another (or even the same) process/thread.
There are various methods to find them and avoid them. One is thinking very hard and/or trying lots of things. However, dealing with parallelism is notoriously difficult and most (if not all) people will not be able to completely avoid problems.
Some more formal methods can be useful if you are serious about dealing with these kinds of issues. The most practical method that I'm aware of is to use the process theoretic approach. Here you model your system in some process language (e.g. CCS, CSP, ACP, mCRL2, LOTOS) and use the available tools to (model-)check for deadlocks (and perhaps some other properties as well). Examples of toolset to use are FDR, mCRL2, CADP and Uppaal. Some brave souls might even prove their systems deadlock free by using purely symbolic methods (theorem proving; look for Owicki-Gries).
However, these formal methods typically do require some effort (e.g. learning the basics of process theory). But I guess that's simply a consequence of the fact that these problems are hard.
A: Deadlock is a situation occurs when there is less number of available resources as it is requested by the different process. It means that when the number of available resources become less than it is requested by the user then at that time the process goes in waiting condition .Some times waiting increases more and there is not any chance to check out the problem of lackness of resources then this situation is known as deadlock .
Actually, deadlock is a major problem for us and it occurs only in multitasking operating system .deadlock can not occur in single tasking operating system because all the resources are present only for that task which is currently running......
A: Above some explanations are nice. Hope this may also useful:
https://ora-data.blogspot.in/2017/04/deadlock-in-oracle.html
In a database, when a session (e.g. ora) wants a resource held by another session (e.g. data), but that session (data) also wants a resource which is held by the first session (ora). There can be more than 2 sessions involved also but idea will be the same.
Actually, Deadlocks prevent some transactions from continuing to work.
For example:
Suppose, ORA-DATA holds lock A and requests lock B
And SKU holds lock B and requests lock A.
Thanks,
A: Deadlock occurs when a thread is waiting for other thread to finish and vice versa.
How to avoid?
- Avoid Nested Locks
- Avoid Unnecessary Locks
- Use thread join()
How do you detect it?
run this command in cmd:
jcmd $PID Thread.print
reference : geeksforgeeks
A: Deadlocks does not just occur with locks, although that's the most frequent cause. In C++, you can create deadlock with two threads and no locks by just having each thread call join() on the std::thread object for the other.
A: Let's say one thread wants to transfer money from "A Account => B Account" and another thread wants to transfer money from "B Account => A Account", simultaneously. This can cause a deadlock.
The first thread will take a lock on "Account A" and then it has to take a lock on "Account B" but it cannot because second thread will already took lock on "Account B". Similarly second thread cannot take a lock on A Account because it is locked by the first thread. so this transaction will remain incomplete and our system will lose 2 threads. To prevent this, we can add a rule that locks the database records in sorted order. So thread should look at accounts name or IDs and decide to lock in a sorted order: A => B. There will be a race condition here and whoever wins, process its code and the second thread will take over. This is the solution for this specific case but deadlocks may occur in many reasons so each case will have a different solution.
Os has a deadlock detection mechanism with a certain interval of time, and when it detects the deadlock, it starts a recovery approach. More on deadlock detection
In the example we lost 2 threads but if we get more deadlocks, those deadlocks can bring down the system.
A: The best solution to the deadlock is not to fall into the deadlock
*
*system resources or critical space should be used in a balanced way.
*give priority to key variables.
*If more than one lock object will be used, the sequence number should be given.
*Deadlock occurs as a result of incorrect use of synchronization objects.
For Example Deadlock with C#:
public class Deadlock{
static object o1 = new Object();
static object o2 = new Object();
private static void y1()
{
lock (o1)
{
Console.WriteLine("1");
lock (o2)
{
Console.WriteLine("2");
}
}
}
private static void y2()
{
lock (o2)
{
Console.WriteLine("3");
lock (o1)
{
Console.WriteLine("4");
}
}
}
public static void Main(string[] args)
{
Thread thread1 = new Thread(y1);
Thread thread2 = new Thread(y2);
thread1.Start();
thread2.Start();
}
}
A: Mutex in essence is a lock, providing protected access to shared resources. Under Linux, the thread mutex data type is pthread_mutex_t. Before use, initialize it.
To access to shared resources, you have to lock on the mutex. If the mutex already on the lock, the call will block the thread until the mutex is unlocked. Upon completion of the visit to shared resources, you have to unlock them.
Overall, there are a few unwritten basic principles:
*
*Obtain the lock before using the shared resources.
*Holding the lock as short time as possible.
*Release the lock if the thread returns an error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "193"
} |
Q: Is there a standard (like phpdoc or python's docstring) for commenting C# code? Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?
A: You can use XML style comments, and use tools to pull those comments out into API documentation.
Here is an example of the comment style:
/// <summary>
/// Authenticates a user based on a username and password.
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>
/// True, if authentication is successful, otherwise False.
/// </returns>
/// <remarks>
/// For use with local systems
/// </remarks>
public override bool Authenticate(string username, string password)
Some items to facilitate this are:
GhostDoc, which give a single shortcut key to automatically generate comments for a class or method.
Sandcastle, which generates MSDN style documentation from XML comments.
A: /// <summary>
///
/// </summary>
/// <param name="strFilePath"></param>
http://msdn.microsoft.com/en-us/magazine/cc302121.aspx
A: C# has built in documentation commands
Have fun!
A: Microsoft uses "XML Documentation Comments" which will give IDE intellisense descriptions and also allow you to auto-generate MSDN-style documentation using a tool such as Sandcastle if you turn on the generation of the XML file output.
To turn on the generation of the XML file for documentation, right click on a project in visual studio, click "Properties" and go to the "Build" tab. Towards the bottom you can specify a location for your XML comments output file.
A: The previous answers point out the XML syntax perfectly. I just wanted to throw in my recommendation for the free (and open-source) nDoc help library generator that parses all comments in a project.
A: I was always told to use block comments opened with 2 or more asterisks do delimit documentation comments.
/**
Documentation goes here.
(flowerboxes optional)
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: Natural Sorting algorithm How do you sort an array of strings naturally in different programming languages? Post your implementation and what language it is in in the answer.
A: Here's how you can get explorer-like behaviour in Python:
#!/usr/bin/env python
"""
>>> items = u'a1 a003 b2 a2 a10 1 10 20 2 c100'.split()
>>> items.sort(explorer_cmp)
>>> for s in items:
... print s,
1 2 10 20 a1 a2 a003 a10 b2 c100
>>> items.sort(key=natural_key, reverse=True)
>>> for s in items:
... print s,
c100 b2 a10 a003 a2 a1 20 10 2 1
"""
import re
def natural_key(astr):
"""See http://www.codinghorror.com/blog/archives/001018.html"""
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', astr)]
def natural_cmp(a, b):
return cmp(natural_key(a), natural_key(b))
try: # use explorer's comparison function if available
import ctypes
explorer_cmp = ctypes.windll.shlwapi.StrCmpLogicalW
except (ImportError, AttributeError):
# not on Windows or old python version
explorer_cmp = natural_cmp
if __name__ == '__main__':
import doctest; doctest.testmod()
To support Unicode strings, .isdecimal() should be used instead of .isdigit().
.isdigit() may also fail (return value that is not accepted by int()) for a bytestring on Python 2 in some locales e.g., '\xb2' ('²') in cp1252 locale on Windows.
A: JavaScript
Array.prototype.alphanumSort = function(caseInsensitive) {
for (var z = 0, t; t = this[z]; z++) {
this[z] = [], x = 0, y = -1, n = 0, i, j;
while (i = (j = t.charAt(x++)).charCodeAt(0)) {
var m = (i == 46 || (i >=48 && i <= 57));
if (m !== n) {
this[z][++y] = "";
n = m;
}
this[z][y] += j;
}
}
this.sort(function(a, b) {
for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
if (caseInsensitive) {
aa = aa.toLowerCase();
bb = bb.toLowerCase();
}
if (aa !== bb) {
var c = Number(aa), d = Number(bb);
if (c == aa && d == bb) {
return c - d;
} else return (aa > bb) ? 1 : -1;
}
}
return a.length - b.length;
});
for (var z = 0; z < this.length; z++)
this[z] = this[z].join("");
}
Source
A: For MySQL, I personally use code from a Drupal module, which is available at hhttp://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/natsort.install.mysql
Basically, you execute the posted SQL script to create functions, and then use ORDER BY natsort_canon(field_name, 'natural')
Here's a readme about the function:
http://drupalcode.org/project/natsort.git/blob/refs/heads/5.x-1.x:/README.txt
A: Here's a cleanup of the code in the article the question linked to:
def sorted_nicely(strings):
"Sort strings the way humans are said to expect."
return sorted(strings, key=natural_sort_key)
def natural_sort_key(key):
import re
return [int(t) if t.isdigit() else t for t in re.split(r'(\d+)', key)]
But actually I haven't had occasion to sort anything this way.
A: If the OP is asking about idomatic sorting expressions, then not all languages have a natural expression built in. For c I'd go to <stdlib.h> and use qsort. Something on the lines of :
/* non-functional mess deleted */
to sort the arguments into lexical order. Unfortunately this idiom is rather hard to parse for those not used the ways of c.
Suitably chastened by the downvote, I actually read the linked article. Mea culpa.
In anycase the original code did not work, except in the single case I tested. Damn. Plain vanilla c does not have this function, nor is it in any of the usual libraries.
The code below sorts the command line arguments in the natural way as linked. Caveat emptor as it is only lightly tested.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int naturalstrcmp(const char **s1, const char **s2);
int main(int argc, char **argv){
/* Sort the command line arguments in place */
qsort(&argv[1],argc-1,sizeof(char*),
(int(*)(const void *, const void *))naturalstrcmp);
while(--argc){
printf("%s\n",(++argv)[0]);
};
}
int naturalstrcmp(const char **s1p, const char **s2p){
if ((NULL == s1p) || (NULL == *s1p)) {
if ((NULL == s2p) || (NULL == *s2p)) return 0;
return 1;
};
if ((NULL == s2p) || (NULL == *s2p)) return -1;
const char *s1=*s1p;
const char *s2=*s2p;
do {
if (isdigit(s1[0]) && isdigit(s2[0])){
/* Compare numbers as numbers */
int c1 = strspn(s1,"0123456789"); /* Could be more efficient here... */
int c2 = strspn(s2,"0123456789");
if (c1 > c2) {
return 1;
} else if (c1 < c2) {
return -1;
};
/* the digit strings have equal length, so compare digit by digit */
while (c1--) {
if (s1[0] > s2[0]){
return 1;
} else if (s1[0] < s2[0]){
return -1;
};
s1++;
s2++;
};
} else if (s1[0] > s2[0]){
return 1;
} else if (s1[0] < s2[0]){
return -1;
};
s1++;
s2++;
} while ( (s1!='\0') || (s2!='\0') );
return 0;
}
This approach is pretty brute force, but it is simple and can probably be duplicated in any imperative language.
A: In C++ I use this example code to do natural sorting. The code requires the boost library.
A: I just use StrCmpLogicalW. It does exactly what Jeff is wanting, since it's the same API that explorer uses. Admittedly, it's not portable.
In C++:
bool NaturalLess(const wstring &lhs, const wstring &rhs)
{
return StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 0;
}
vector<wstring> strings;
// ... load the strings
sort(strings.begin(), strings.end(), &NaturalLess);
A: Just a link to some nice work in Common Lisp by Eric Normand:
http://www.lispcast.com/wordpress/2007/12/human-order-sorting/
A: In C, this solution correctly handles numbers with leading zeroes:
#include <stdlib.h>
#include <ctype.h>
/* like strcmp but compare sequences of digits numerically */
int strcmpbynum(const char *s1, const char *s2) {
for (;;) {
if (*s2 == '\0')
return *s1 != '\0';
else if (*s1 == '\0')
return 1;
else if (!(isdigit(*s1) && isdigit(*s2))) {
if (*s1 != *s2)
return (int)*s1 - (int)*s2;
else
(++s1, ++s2);
} else {
char *lim1, *lim2;
unsigned long n1 = strtoul(s1, &lim1, 10);
unsigned long n2 = strtoul(s2, &lim2, 10);
if (n1 > n2)
return 1;
else if (n1 < n2)
return -1;
s1 = lim1;
s2 = lim2;
}
}
}
If you want to use it with qsort, use this auxiliary function:
static int compare(const void *p1, const void *p2) {
const char * const *ps1 = p1;
const char * const *ps2 = p2;
return strcmpbynum(*ps1, *ps2);
}
And you can do something on the order of
char *lines = ...;
qsort(lines, next, sizeof(lines[0]), compare);
A: Note that for most such questions, you can just consult the Rosetta Code Wiki. I adapted my answer from the entry for sorting integers.
In a system's programming language doing something like this is generally going to be uglier than with a specialzed string-handling language. Fortunately for Ada, the most recent version has a library routine for just this kind of task.
For Ada 2005 I believe you could do something along the following lines (warning, not compiled!):
type String_Array is array(Natural range <>) of Ada.Strings.Unbounded.Unbounded_String;
function "<" (L, R : Ada.Strings.Unbounded.Unbounded_String) return boolean is
begin
--// Natural ordering predicate here. Sorry to cheat in this part, but
--// I don't exactly grok the requirement for "natural" ordering. Fill in
--// your proper code here.
end "<";
procedure Sort is new Ada.Containers.Generic_Array_Sort
(Index_Type => Natural;
Element_Type => Ada.Strings.Unbounded.Unbounded_String,
Array_Type => String_Array
);
Example use:
using Ada.Strings.Unbounded;
Example : String_Array := (To_Unbounded_String ("Joe"),
To_Unbounded_String ("Jim"),
To_Unbounded_String ("Jane"),
To_Unbounded_String ("Fred"),
To_Unbounded_String ("Bertha"),
To_Unbounded_String ("Joesphus"),
To_Unbounded_String ("Jonesey"));
begin
Sort (Example);
...
end;
A: Python, using itertools:
def natural_key(s):
return tuple(
int(''.join(chars)) if isdigit else ''.join(chars)
for isdigit, chars in itertools.groupby(s, str.isdigit)
)
Result:
>>> natural_key('abc-123foo456.xyz')
('abc-', 123, 'foo', 456, '.xyz')
Sorting:
>>> sorted(['1.1.1', '1.10.4', '1.5.0', '42.1.0', '9', 'banana'], key=natural_key)
['1.1.1', '1.5.0', '1.10.4', '9', '42.1.0', 'banana']
A: My implementation on Clojure 1.1:
(ns alphanumeric-sort
(:import [java.util.regex Pattern]))
(defn comp-alpha-numerical
"Compare two strings alphanumerically."
[a b]
(let [regex (Pattern/compile "[\\d]+|[a-zA-Z]+")
sa (re-seq regex a)
sb (re-seq regex b)]
(loop [seqa sa seqb sb]
(let [counta (count seqa)
countb (count seqb)]
(if-not (not-any? zero? [counta countb]) (- counta countb)
(let [c (first seqa)
d (first seqb)
c1 (read-string c)
d1 (read-string d)]
(if (every? integer? [c1 d1])
(def result (compare c1 d1)) (def result (compare c d)))
(if-not (= 0 result) result (recur (rest seqa) (rest seqb)))))))))
(sort comp-alpha-numerical ["a1" "a003" "b2" "a10" "a2" "1" "10" "20" "2" "c100"])
Result:
("1" "2" "10" "20" "a1" "a2" "a003" "a10" "b2" "c100")
A: For Tcl, the -dict (dictionary) option to lsort:
% lsort -dict {a b 1 c 2 d 13}
1 2 13 a b c d
A: php has a easy function "natsort" to do that,and I implements it by myself:
<?php
$temp_files = array('+====','-==',"temp15-txt","temp10.txt",
"temp1.txt","tempe22.txt","temp2.txt");
$my_arr = $temp_files;
natsort($temp_files);
echo "Natural order: ";
print_r($temp_files);
echo "My Natural order: ";
usort($my_arr,'my_nat_func');
print_r($my_arr);
function is_alpha($a){
return $a>='0'&&$a<='9' ;
}
function my_nat_func($a,$b){
if(preg_match('/[0-9]/',$a)){
if(preg_match('/[0-9]/',$b)){
$i=0;
while(!is_alpha($a[$i])) ++$i;
$m = intval(substr($a,$i));
$i=0;
while(!is_alpha($b[$i])) ++$i;
$n = intval(substr($b,$i));
return $m>$n?1:($m==$n?0:-1);
}
return 1;
}else{
if(preg_match('/[0-9]/',$b)){
return -1;
}
return $a>$b?1:($a==$b?0:-1);
}
}
A: Java solution:-
This can be achieved by implementing new Comparator<String> and pass it to Collections.sort(list, comparator) method.
@Override
public int compare(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int lim = Math.min(len1, len2);
char v1[] = s1.toCharArray();
char v2[] = s2.toCharArray();
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
if(this.isInteger(c1) && this.isInteger(c2)) {
int i1 = grabContinousInteger(v1, k);
int i2 = grabContinousInteger(v2, k);
return i1 - i2;
}
return c1 - c2;
}
k++;
}
return len1 - len2;
}
private boolean isInteger(char c) {
return c >= 48 && c <= 57; // ascii value 0-9
}
private int grabContinousInteger(char[] arr, int k) {
int i = k;
while(i < arr.length && this.isInteger(arr[i])) {
i++;
}
return Integer.parseInt(new String(arr, k, i - k));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: What is a semaphore? A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community:
What is a semaphore and how do you use it?
A: Mutex: exclusive-member access to a resource
Semaphore: n-member access to a resource
That is, a mutex can be used to syncronize access to a counter, file, database, etc.
A sempahore can do the same thing but supports a fixed number of simultaneous callers. For example, I can wrap my database calls in a semaphore(3) so that my multithreaded app will hit the database with at most 3 simultaneous connections. All attempts will block until one of the three slots opens up. They make things like doing naive throttling really, really easy.
A: A semaphore is an object containing a natural number (i.e. a integer greater or equal to zero) on which two modifying operations are defined. One operation, V, adds 1 to the natural. The other operation, P, decreases the natural number by 1. Both activities are atomic (i.e. no other operation can be executed at the same time as a V or a P).
Because the natural number 0 cannot be decreased, calling P on a semaphore containing a 0 will block the execution of the calling process(/thread) until some moment at which the number is no longer 0 and P can be successfully (and atomically) executed.
As mentioned in other answers, semaphores can be used to restrict access to a certain resource to a maximum (but variable) number of processes.
A: Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.
It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.
Here is a very pedagogic example in C# :-)
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}
A: Consider, a taxi that can accommodate a total of 3(rear)+2(front) persons including the driver. So, a semaphore allows only 5 persons inside a car at a time.
And a mutex allows only 1 person on a single seat of the car.
Therefore, Mutex is to allow exclusive access for a resource (like an OS thread) while a Semaphore is to allow access for n number of resources at a time.
A: A hardware or software flag. In multi tasking systems , a semaphore is as variable with a value that indicates the status of a common resource.A process needing the resource checks the semaphore to determine the resources status and then decides how to proceed.
A: Semaphores are act like thread limiters.
Example: If you have a pool of 100 threads and you want to perform some DB operation. If 100 threads access the DB at a given time, then there may be locking issue in DB so we can use semaphore which allow only limited thread at a time.Below Example allow only one thread at a time. When a thread call the acquire() method, it will then get the access and after calling the release() method, it will release the acccess so that next thread will get the access.
package practice;
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
Semaphore s = new Semaphore(1);
semaphoreTask s1 = new semaphoreTask(s);
semaphoreTask s2 = new semaphoreTask(s);
semaphoreTask s3 = new semaphoreTask(s);
semaphoreTask s4 = new semaphoreTask(s);
semaphoreTask s5 = new semaphoreTask(s);
s1.start();
s2.start();
s3.start();
s4.start();
s5.start();
}
}
class semaphoreTask extends Thread {
Semaphore s;
public semaphoreTask(Semaphore s) {
this.s = s;
}
@Override
public void run() {
try {
s.acquire();
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" Going to perform some operation");
s.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
A: The article Mutexes and Semaphores Demystified by Michael Barr is a great short introduction into what makes mutexes and semaphores different, and when they should and should not be used. I've excerpted several key paragraphs here.
The key point is that mutexes should be used to protect shared resources, while semaphores should be used for signaling. You should generally not use semaphores to protect shared resources, nor mutexes for signaling. There are issues, for instance, with the bouncer analogy in terms of using semaphores to protect shared resources - you can use them that way, but it may cause hard to diagnose bugs.
While mutexes and semaphores have some similarities in their implementation, they should always be used differently.
The most common (but nonetheless incorrect) answer to the question posed at the top is that mutexes and semaphores are very similar, with the only significant difference being that semaphores can count higher than one. Nearly all engineers seem to properly understand that a mutex is a binary flag used to protect a shared resource by ensuring mutual exclusion inside critical sections of code. But when asked to expand on how to use a "counting semaphore," most engineers—varying only in their degree of confidence—express some flavor of the textbook opinion that these are used to protect several equivalent resources.
...
At this point an interesting analogy is made using the idea of bathroom keys as protecting shared resources - the bathroom. If a shop has a single bathroom, then a single key will be sufficient to protect that resource and prevent multiple people from using it simultaneously.
If there are multiple bathrooms, one might be tempted to key them alike and make multiple keys - this is similar to a semaphore being mis-used. Once you have a key you don't actually know which bathroom is available, and if you go down this path you're probably going to end up using mutexes to provide that information and make sure you don't take a bathroom that's already occupied.
A semaphore is the wrong tool to protect several of the essentially same resource, but this is how many people think of it and use it. The bouncer analogy is distinctly different - there aren't several of the same type of resource, instead there is one resource which can accept multiple simultaneous users. I suppose a semaphore can be used in such situations, but rarely are there real-world situations where the analogy actually holds - it's more often that there are several of the same type, but still individual resources, like the bathrooms, which cannot be used this way.
...
The correct use of a semaphore is for signaling from one task to another. A mutex is meant to be taken and released, always in that order, by each task that uses the shared resource it protects. By contrast, tasks that use semaphores either signal or wait—not both. For example, Task 1 may contain code to post (i.e., signal or increment) a particular semaphore when the "power" button is pressed and Task 2, which wakes the display, pends on that same semaphore. In this scenario, one task is the producer of the event signal; the other the consumer.
...
Here an important point is made that mutexes interfere with real time operating systems in a bad way, causing priority inversion where a less important task may be executed before a more important task because of resource sharing. In short, this happens when a lower priority task uses a mutex to grab a resource, A, then tries to grab B, but is paused because B is unavailable. While it's waiting, a higher priority task comes along and needs A, but it's already tied up, and by a process that isn't even running because it's waiting for B. There are many ways to resolve this, but it most often is fixed by altering the mutex and task manager. The mutex is much more complex in these cases than a binary semaphore, and using a semaphore in such an instance will cause priority inversions because the task manager is unaware of the priority inversion and cannot act to correct it.
...
The cause of the widespread modern confusion between mutexes and semaphores is historical, as it dates all the way back to the 1974 invention of the Semaphore (capital "S", in this article) by Djikstra. Prior to that date, none of the interrupt-safe task synchronization and signaling mechanisms known to computer scientists was efficiently scalable for use by more than two tasks. Dijkstra's revolutionary, safe-and-scalable Semaphore was applied in both critical section protection and signaling. And thus the confusion began.
However, it later became obvious to operating system developers, after the appearance of the priority-based preemptive RTOS (e.g., VRTX, ca. 1980), publication of academic papers establishing RMA and the problems caused by priority inversion, and a paper on priority inheritance protocols in 1990, 3 it became apparent that mutexes must be more than just semaphores with a binary counter.
Mutex: resource sharing
Semaphore: signaling
Don't use one for the other without careful consideration of the side effects.
A: So imagine everyone is trying to go to the bathroom and there's only a certain number of keys to the bathroom. Now if there's not enough keys left, that person needs to wait. So think of semaphore as representing those set of keys available for bathrooms (the system resources) that different processes (bathroom goers) can request access to.
Now imagine two processes trying to go to the bathroom at the same time. That's not a good situation and semaphores are used to prevent this. Unfortunately, the semaphore is a voluntary mechanism and processes (our bathroom goers) can ignore it (i.e. even if there are keys, someone can still just kick the door open).
There are also differences between binary/mutex & counting semaphores.
Check out the lecture notes at http://www.cs.columbia.edu/~jae/4118/lect/L05-ipc.html.
A: @Craig:
A semaphore is a way to lock a
resource so that it is guaranteed that
while a piece of code is executed,
only this piece of code has access to
that resource. This keeps two threads
from concurrently accesing a resource,
which can cause problems.
This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.
A: Semaphore can also be used as a ... semaphore.
For example if you have multiple process enqueuing data to a queue, and only one task consuming data from the queue. If you don't want your consuming task to constantly poll the queue for available data, you can use semaphore.
Here the semaphore is not used as an exclusion mechanism, but as a signaling mechanism.
The consuming task is waiting on the semaphore
The producing task are posting on the semaphore.
This way the consuming task is running when and only when there is data to be dequeued
A: There are two essential concepts to building concurrent programs - synchronization and mutual exclusion. We will see how these two types of locks (semaphores are more generally a kind of locking mechanism) help us achieve synchronization and mutual exclusion.
A semaphore is a programming construct that helps us achieve concurrency, by implementing both synchronization and mutual exclusion. Semaphores are of two types, Binary and Counting.
A semaphore has two parts : a counter, and a list of tasks waiting to access a particular resource. A semaphore performs two operations : wait (P) [this is like acquiring a lock], and release (V)[ similar to releasing a lock] - these are the only two operations that one can perform on a semaphore. In a binary semaphore, the counter logically goes between 0 and 1. You can think of it as being similar to a lock with two values : open/closed. A counting semaphore has multiple values for count.
What is important to understand is that the semaphore counter keeps track of the number of tasks that do not have to block, i.e., they can make progress. Tasks block, and add themselves to the semaphore's list only when the counter is zero. Therefore, a task gets added to the list in the P() routine if it cannot progress, and "freed" using the V() routine.
Now, it is fairly obvious to see how binary semaphores can be used to solve synchronization and mutual exclusion - they are essentially locks.
ex. Synchronization:
thread A{
semaphore &s; //locks/semaphores are passed by reference! think about why this is so.
A(semaphore &s): s(s){} //constructor
foo(){
...
s.P();
;// some block of code B2
...
}
//thread B{
semaphore &s;
B(semaphore &s): s(s){} //constructor
foo(){
...
...
// some block of code B1
s.V();
..
}
main(){
semaphore s(0); // we start the semaphore at 0 (closed)
A a(s);
B b(s);
}
In the above example, B2 can only execute after B1 has finished execution. Let's say thread A comes executes first - gets to sem.P(), and waits, since the counter is 0 (closed). Thread B comes along, finishes B1, and then frees thread A - which then completes B2. So we achieve synchronization.
Now let's look at mutual exclusion with a binary semaphore:
thread mutual_ex{
semaphore &s;
mutual_ex(semaphore &s): s(s){} //constructor
foo(){
...
s.P();
//critical section
s.V();
...
...
s.P();
//critical section
s.V();
...
}
main(){
semaphore s(1);
mutual_ex m1(s);
mutual_ex m2(s);
}
The mutual exclusion is quite simple as well - m1 and m2 cannot enter the critical section at the same time. So each thread is using the same semaphore to provide mutual exclusion for its two critical sections. Now, is it possible to have greater concurrency? Depends on the critical sections. (Think about how else one could use semaphores to achieve mutual exclusion.. hint hint : do i necessarily only need to use one semaphore?)
Counting semaphore: A semaphore with more than one value. Let's look at what this is implying - a lock with more than one value?? So open, closed, and ...hmm. Of what use is a multi-stage-lock in mutual exclusion or synchronization?
Let's take the easier of the two:
Synchronization using a counting semaphore: Let's say you have 3 tasks - #1 and 2 you want executed after 3. How would you design your synchronization?
thread t1{
...
s.P();
//block of code B1
thread t2{
...
s.P();
//block of code B2
thread t3{
...
//block of code B3
s.V();
s.V();
}
So if your semaphore starts off closed, you ensure that t1 and t2 block, get added to the semaphore's list. Then along comes all important t3, finishes its business and frees t1 and t2. What order are they freed in? Depends on the implementation of the semaphore's list. Could be FIFO, could be based some particular priority,etc. (Note : think about how you would arrange your P's and V;s if you wanted t1 and t2 to be executed in some particular order, and if you weren't aware of the implementation of the semaphore)
(Find out : What happens if the number of V's is greater than the number of P's?)
Mutual Exclusion Using counting semaphores: I'd like you to construct your own pseudocode for this (makes you understand things better!) - but the fundamental concept is this : a counting semaphore of counter = N allows N tasks to enter the critical section freely. What this means is you have N tasks (or threads, if you like) enter the critical section, but the N+1th task gets blocked (goes on our favorite blocked-task list), and only is let through when somebody V's the semaphore at least once. So the semaphore counter, instead of swinging between 0 and 1, now goes between 0 and N, allowing N tasks to freely enter and exit, blocking nobody!
Now gosh, why would you need such a stupid thing? Isn't the whole point of mutual exclusion to not let more than one guy access a resource?? (Hint Hint...You don't always only have one drive in your computer, do you...?)
To think about : Is mutual exclusion achieved by having a counting semaphore alone? What if you have 10 instances of a resource, and 10 threads come in (through the counting semaphore) and try to use the first instance?
A: I've created the visualization which should help to understand the idea. Semaphore controls access to a common resource in a multithreading environment.
ExecutorService executor = Executors.newFixedThreadPool(7);
Semaphore semaphore = new Semaphore(4);
Runnable longRunningTask = () -> {
boolean permit = false;
try {
permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
if (permit) {
System.out.println("Semaphore acquired");
Thread.sleep(5);
} else {
System.out.println("Could not acquire semaphore");
}
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} finally {
if (permit) {
semaphore.release();
}
}
};
// execute tasks
for (int j = 0; j < 10; j++) {
executor.submit(longRunningTask);
}
executor.shutdown();
Output
Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore
Sample code from the article
A: This is an old question but one of the most interesting uses of semaphore is a read/write lock and it has not been explicitly mentioned.
The r/w locks works in simple fashion: consume one permit for a reader and all permits for writers.
Indeed, a trivial implementation of a r/w lock but requires metadata modification on read (actually twice) that can become a bottle neck, still significantly better than a mutex or lock.
Another downside is that writers can be started rather easily as well unless the semaphore is a fair one or the writes acquire permits in multiple requests, in such case they need an explicit mutex between themselves.
Further read:
A: Mutex is just a boolean while semaphore is a counter.
Both are used to lock part of code so it's not accessed by too many threads.
Example
lock.set()
a += 1
lock.unset()
Now if lock was a mutex, it means that it will always be locked or unlocked (a boolean under the surface) regardless how many threads try access the protected snippet of code. While locked, any other thread would just wait until it's unlocked/unset by the previous thread.
Now imagine if instead lock was under the hood a counter with a predefined MAX value (say 2 for our example). Then if 2 threads try to access the resource, then lock would get its value increased to 2. If a 3rd thread then tried to access it, it would simply wait for the counter to go below 2 and so on.
If lock as a semaphore had a max of 1, then it would be acting exactly as a mutex.
A: A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "414"
} |
Q: What is a mutex? A mutex is a programming concept that is frequently used to solve multi-threading problems. My question to the community:
What is a mutex and how do you use it?
A: When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.
The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.
How to use them is language specific, but is often (if not always) based on a operating system mutex.
Some languages doesn't need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).
A: Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).
In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.
pthread library provides support for Mutex.
typedef union
{
struct __pthread_mutex_s
{
***int __lock;***
unsigned int __count;
int __owner;
#ifdef __x86_64__
unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
short __spins;
short __elision;
__pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV 1
# define __PTHREAD_SPINS 0, 0
#else
unsigned int __nusers;
__extension__ union
{
struct
{
short __espins;
short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS { 0, 0 }
} __elision_data;
__pthread_slist_t __list;
};
#endif
This is the structure for mutex data type i.e pthread_mutex_t.
When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.
This ensure that no two processes/threads can access the critical section at same time.
A: What is a Mutex?
The mutex (In fact, the term mutex is short for mutual exclusion) also known as spinlock is the simplest synchronization tool that is used to protect critical regions and thus prevent race conditions. That is a thread must acquire a lock before entering into a critical section (In critical section multi threads share a common variable, updating a table, writing a file and so on), it releases the lock when it leaves critical section.
What is a Race Condition?
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.
Real life example:
When I am having a big heated discussion at work, I use a rubber
chicken which I keep in my desk for just such occasions. The person
holding the chicken is the only person who is allowed to talk. If you
don't hold the chicken you cannot speak. You can only indicate that
you want the chicken and wait until you get it before you speak. Once
you have finished speaking, you can hand the chicken back to the
moderator who will hand it to the next person to speak. This ensures
that people do not speak over each other, and also have their own
space to talk.
Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.
@Xetius
Usage in C#:
This example shows how a local Mutex object is used to synchronize access to a protected resource. Because each calling thread is blocked until it acquires ownership of the mutex, it must call the ReleaseMutex method to release ownership of the thread.
using System;
using System.Threading;
class Example
{
// Create a new Mutex. The creating thread does not own the mutex.
private static Mutex mut = new Mutex();
private const int numIterations = 1;
private const int numThreads = 3;
static void Main()
{
// Create the threads that will use the protected resource.
for(int i = 0; i < numThreads; i++)
{
Thread newThread = new Thread(new ThreadStart(ThreadProc));
newThread.Name = String.Format("Thread{0}", i + 1);
newThread.Start();
}
// The main thread exits, but the application continues to
// run until all foreground threads have exited.
}
private static void ThreadProc()
{
for(int i = 0; i < numIterations; i++)
{
UseResource();
}
}
// This method represents a resource that must be synchronized
// so that only one thread at a time can enter.
private static void UseResource()
{
// Wait until it is safe to enter.
Console.WriteLine("{0} is requesting the mutex",
Thread.CurrentThread.Name);
mut.WaitOne();
Console.WriteLine("{0} has entered the protected area",
Thread.CurrentThread.Name);
// Place code to access non-reentrant resources here.
// Simulate some work.
Thread.Sleep(500);
Console.WriteLine("{0} is leaving the protected area",
Thread.CurrentThread.Name);
// Release the Mutex.
mut.ReleaseMutex();
Console.WriteLine("{0} has released the mutex",
Thread.CurrentThread.Name);
}
}
// The example displays output like the following:
// Thread1 is requesting the mutex
// Thread2 is requesting the mutex
// Thread1 has entered the protected area
// Thread3 is requesting the mutex
// Thread1 is leaving the protected area
// Thread1 has released the mutex
// Thread3 has entered the protected area
// Thread3 is leaving the protected area
// Thread3 has released the mutex
// Thread2 has entered the protected area
// Thread2 is leaving the protected area
// Thread2 has released the mutex
MSDN Reference Mutex
A: There are some great answers here, here is another great analogy for explaining what mutex is:
Consider single toilet with a key. When someone enters, they take the key and the toilet is occupied. If someone else needs to use the toilet, they need to wait in a queue. When the person in the toilet is done, they pass the key to the next person in queue. Make sense, right?
Convert the toilet in the story to a shared resource, and the key to a mutex. Taking the key to the toilet (acquire a lock) permits you to use it. If there is no key (the lock is locked) you have to wait. When the key is returned by the person (release the lock) you're free to acquire it now.
A: In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.
private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
lock(instanceLock)
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.
Any sort of synchronization of a static member may use the lock statement similarly.
A: When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.
Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.
Of course, there is no such thing as a rubber mutex. Only rubber chicken. My cats once had a rubber mouse, but they ate it.
Of course, before you use the rubber chicken, you need to ask yourself whether you actually need 5 people in one room and would it not just be easier with one person in the room on their own doing all the work. Actually, this is just extending the analogy, but you get the idea.
A: A Mutex is a Mutually exclusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controlled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done. :)
A: To understand MUTEX at first you need to know what is "race condition" and then only you will understand why MUTEX is needed. Suppose you have a multi-threading program and you have two threads. Now, you have one job in the job queue. The first thread will check the job queue and after finding the job it will start executing it. The second thread will also check the job queue and find that there is one job in the queue. So, it will also assign the same job pointer. So, now what happens, both the threads are executing the same job. This will cause a segmentation fault. This is the example of a race condition.
The solution to this problem is MUTEX. MUTEX is a kind of lock which locks one thread at a time. If another thread wants to lock it, the thread simply gets blocked.
The MUTEX topic in this pdf file link is really worth reading.
A: Mutexes are useful in situations where you need to enforce exclusive access to a resource accross multiple processes, where a regular lock won't help since it only works accross threads.
A: Mutual Exclusion. Here's the Wikipedia entry on it.
The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.
Specific details of how this is accomplished obviously varies greatly by programming language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "900"
} |
Q: How do you swap DIVs on mouseover (jQuery)? This most be the second most simple rollover effect, still I don't find any simple solution.
Wanted: I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.
The following code works, but is awful. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.
<script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
A: Here's my light-markup jQuery version:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function switchTo(i) {
$('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold');
$('#slides div').css('display','none').eq(i).css('display','block');
}
$(document).ready(function(){
$('#switches li').mouseover(function(event){
switchTo($('#switches li').index(event.target));
});
switchTo(0);
});
</script>
<ul id="switches">
<li>First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div>Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
This has the advantage of showing all the slides if the user has javascript turned off, uses very little HTML markup and the javascript is pretty readable. The switchTo function takes an index number of which <li> / <div> pair to activate, resets all the relevant elements to their default styles (non-bold for list items, display:none for the DIVs) and the sets the desired list-item and div to bold and display. As long as the client has javascript enabled, the functionality will be exactly the same as your original example.
A: Here's the jQuery version:
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>
<script type="text/javascript">
$(function () {
$("#switches li").mouseover(function () {
var $this = $(this);
$("#slides div").hide();
$("#slide" + $this.attr("id").replace(/switch/, "")).show();
$("#switches li").css("font-weight", "normal");
$this.css("font-weight", "bold");
});
});
</script>
<ul id="switches">
<li id="switch1" style="font-weight:bold;">First slide</li>
<li id="switch2">Second slide</li>
<li id="switch3">Third slide</li>
<li id="switch4">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
A: <html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$( '#switches li' ).mouseover(
function(){
$( "#slides div" ).hide();
$( '#switches li' ).css( 'font-weight', 'normal' );
$( this ).css( 'font-weight', 'bold' );
$( '#slide' + $( this ).attr( 'id' ).replace( 'switch', '' ) ).show();
}
);
}
);
</script>
</head>
<body>
<ul id="switches">
<li id="switch1" style="font-weight:bold;">First slide</li>
<li id="switch2">Second slide</li>
<li id="switch3">Third slide</li>
<li id="switch4">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
</body>
</html>
A: Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.
$(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
});
#switches .active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
}
<html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="switch.js"></script>
</head>
<body>
<ul id="switches">
<li class="active">First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div class="active">Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
</body>
</html>
A: The only thing that's wrong with this code (at least to me) is that you're not using a loop to process all elements. Other than that, why not to it like that?
And with loop, I mean grabbing the container element via a JQuery and iterating over all child elements – basically a one-liner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Detect DOM modification in Internet Explorer I am writing a Browser Helper Object for ie7, and I need to detect DOM modification (i.e. via AJAX).
So far I couldn't find any feasible solution.
A: You want to use IMarkupContainer2::CreateChangeLog.
A: The best thing I could recommend is the Internet Explorer Developer Toolbar which allow you to view changes in the DOM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I generate a random 10 digit number in ruby? Additionally, how can I format it as a string padded with zeros?
A: To generate the number call rand with the result of the expression "10 to the power of 10"
rand(10 ** 10)
To pad the number with zeros you can use the string format operator
'%010d' % rand(10 ** 10)
or the rjust method of string
rand(10 ** 10).to_s.rjust(10,'0')
A: Just because it wasn't mentioned, the Kernel#sprintf method (or it's alias Kernel#format in the Powerpack Library) is generally preferred over the String#% method, as mentioned in the Ruby Community Style Guide.
Of course this is highly debatable, but to provide insight:
The syntax of @quackingduck's answer would be
# considered bad
'%010d' % rand(10**10)
# considered good
sprintf('%010d', rand(10**10))
The nature of this preference is primarily due to the cryptic nature of %. It's not very semantic by itself and without any additional context it can be confused with the % modulo operator.
Examples from the Style Guide:
# bad
'%d %d' % [20, 10]
# => '20 10'
# good
sprintf('%d %d', 20, 10)
# => '20 10'
# good
sprintf('%{first} %{second}', first: 20, second: 10)
# => '20 10'
format('%d %d', 20, 10)
# => '20 10'
# good
format('%{first} %{second}', first: 20, second: 10)
# => '20 10'
To make justice for String#%, I personally really like using operator-like syntaxes instead of commands, the same way you would do your_array << 'foo' over your_array.push('123').
This just illustrates a tendency in the community, what's "best" is up to you.
More info in this blogpost.
A: I would like to contribute probably a simplest solution I know, which is a quite a good trick.
rand.to_s[2..11]
=> "5950281724"
A: I ended up with using Ruby kernel srand
srand.to_s.last(10)
Docs here: Kernel#srand
A: Here is an expression that will use one fewer method call than quackingduck's example.
'%011d' % rand(1e10)
One caveat, 1e10 is a Float, and Kernel#rand ends up calling to_i on it, so for some higher values you might have some inconsistencies. To be more precise with a literal, you could also do:
'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals
A: ('%010d' % rand(0..9999999999)).to_s
or
"#{'%010d' % rand(0..9999999999)}"
A: This is a fast way to generate a 10-sized string of digits:
10.times.map{rand(10)}.join # => "3401487670"
A: I just want to modify first answer. rand (10**10) may generate 9 digit random no if 0 is in first place. For ensuring 10 exact digit just modify
code = rand(10**10)
while code.to_s.length != 10
code = rand(11**11)
end
A: Try using the SecureRandom ruby library.
It generates random numbers but the length is not specific.
Go through this link for more information: http://ruby-doc.org/stdlib-2.1.2/libdoc/securerandom/rdoc/SecureRandom.html
A: Simplest way to generate n digit random number -
Random.new.rand((10**(n - 1))..(10**n))
generate 10 digit number number -
Random.new.rand((10**(10 - 1))..(10**10))
A: This technique works for any "alphabet"
(1..10).map{"0123456789".chars.to_a.sample}.join
=> "6383411680"
A: Just use straightforward below.
rand(10 ** 9...10 ** 10)
Just test it on IRB with below.
(1..1000).each { puts rand(10 ** 9...10 ** 10) }
A: To generate a random, 10-digit string:
# This generates a 10-digit string, where the
# minimum possible value is "0000000000", and the
# maximum possible value is "9999999999"
SecureRandom.random_number(10**10).to_s.rjust(10, '0')
Here's more detail of what's happening, shown by breaking the single line into multiple lines with explaining variables:
# Calculate the upper bound for the random number generator
# upper_bound = 10,000,000,000
upper_bound = 10**10
# n will be an integer with a minimum possible value of 0,
# and a maximum possible value of 9,999,999,999
n = SecureRandom.random_number(upper_bound)
# Convert the integer n to a string
# unpadded_str will be "0" if n == 0
# unpadded_str will be "9999999999" if n == 9_999_999_999
unpadded_str = n.to_s
# Pad the string with leading zeroes if it is less than
# 10 digits long.
# "0" would be padded to "0000000000"
# "123" would be padded to "0000000123"
# "9999999999" would not be padded, and remains unchanged as "9999999999"
padded_str = unpadded_str.rjust(10, '0')
A: The most straightforward answer would probably be
rand(1e9...1e10).to_i
The to_i part is needed because 1e9 and 1e10 are actually floats:
irb(main)> 1e9.class
=> Float
A: DON'T USE rand.to_s[2..11].to_i
Why? Because here's what you can get:
rand.to_s[2..9] #=> "04890612"
and then:
"04890612".to_i #=> 4890612
Note that:
4890612.to_s.length #=> 7
Which is not what you've expected!
To check that error in your own code, instead of .to_i you may wrap it like this:
Integer(rand.to_s[2..9])
and very soon it will turn out that:
ArgumentError: invalid value for Integer(): "02939053"
So it's always better to stick to .center, but keep in mind that:
rand(9)
sometimes may give you 0.
To prevent that:
rand(1..9)
which will always return something withing 1..9 range.
I'm glad that I had good tests and I hope you will avoid breaking your system.
A: Random number generation
Use Kernel#rand method:
rand(1_000_000_000..9_999_999_999) # => random 10-digits number
Random string generation
Use times + map + join combination:
10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)
Number to string conversion with padding
Use String#% method:
"%010d" % 123348 # => "0000123348"
Password generation
Use KeePass password generator library, it supports different patterns for generating random password:
KeePass::Password.generate("d{10}") # => random 10-digit string (may start with 0!)
A documentation for KeePass patterns can be found here.
A: rand(9999999999).to_s.center(10, rand(9).to_s).to_i
is faster than
rand.to_s[2..11].to_i
You can use:
puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}
and
puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}
in Rails console to confirm that.
A: An alternative answer, using the regexp-examples ruby gem:
require 'regexp-examples'
/\d{10}/.random_example # => "0826423747"
There's no need to "pad with zeros" with this approach, since you are immediately generating a String.
A: This will work even on ruby 1.8.7:
rand(9999999999).to_s.center(10, rand(9).to_s).to_i
A: A better approach is use Array.new() instead of .times.map. Rubocop recommends it.
Example:
string_size = 9
Array.new(string_size) do
rand(10).to_s
end
Rubucop, TimesMap:
https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Performance/TimesMap
A: In my case number must be unique in my models, so I added checking block.
module StringUtil
refine String.singleton_class do
def generate_random_digits(size:)
proc = lambda{ rand.to_s[2...(2 + size)] }
if block_given?
loop do
generated = proc.call
break generated if yield(generated) # check generated num meets condition
end
else
proc.call
end
end
end
end
using StringUtil
String.generate_random_digits(3) => "763"
String.generate_random_digits(3) do |num|
User.find_by(code: num).nil?
end => "689"(This is unique in Users code)
A: I did something like this
x = 10 #Number of digit
(rand(10 ** x) + 10**x).to_s[0..x-1]
A: Random 10 numbers:
require 'string_pattern'
puts "10:N".gen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
} |
Q: How do I test a class that has private methods, fields or inner classes? How do I use JUnit to test a class that has internal private methods, fields or nested classes?
It seems bad to change the access modifier for a method just to be able to run a test.
A: I recently had this problem and wrote a little tool, called Picklock, that avoids the problems of explicitly using the Java reflection API, two examples:
Calling methods, e.g. private void method(String s) - by Java reflection
Method method = targetClass.getDeclaredMethod("method", String.class);
method.setAccessible(true);
return method.invoke(targetObject, "mystring");
Calling methods, e.g. private void method(String s) - by Picklock
interface Accessible {
void method(String s);
}
...
Accessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);
a.method("mystring");
Setting fields, e.g. private BigInteger amount; - by Java reflection
Field field = targetClass.getDeclaredField("amount");
field.setAccessible(true);
field.set(object, BigInteger.valueOf(42));
Setting fields, e.g. private BigInteger amount; - by Picklock
interface Accessible {
void setAmount(BigInteger amount);
}
...
Accessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);
a.setAmount(BigInteger.valueOf(42));
A: The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true:
*
*The private method is dead code
*There is a design smell near the class that you are testing
*The method that you are trying to test should not be private
A: Just two examples of where I would want to test a private method:
*
*Decryption routines - I would not
want to make them visible to anyone to see just for
the sake of testing, else anyone can
use them to decrypt. But they are
intrinsic to the code, complicated,
and need to always work (the obvious exception is reflection which can be used to view even private methods in most cases, when SecurityManager is not configured to prevent this).
*Creating an SDK for community
consumption. Here public takes on a
wholly different meaning, since this
is code that the whole world may see
(not just internal to my application). I put
code into private methods if I don't
want the SDK users to see it - I
don't see this as code smell, merely
as how SDK programming works. But of
course I still need to test my
private methods, and they are where
the functionality of my SDK actually
lives.
I understand the idea of only testing the "contract". But I don't see one can advocate actually not testing code—your mileage may vary.
So my trade-off involves complicating the JUnit tests with reflection, rather than compromising my security and SDK.
A: For Java I'd use reflection, since I don't like the idea of changing the access to a package on the declared method just for the sake of testing. However, I usually just test the public methods which should also ensure the private methods are working correctly.
you can't use reflection to get private methods from outside the owner class, the private modifier affects reflection also
This is not true. You most certainly can, as mentioned in Cem Catikkas's answer.
A: In C++: before including the class header that has a private function that you want to test.
Use this code:
#define private public
#define protected public
A: The private methods are called by a public method, so the inputs to your public methods should also test private methods that are called by those public methods. When a public method fails, then that could be a failure in the private method.
A: In the Spring Framework you can test private methods using this method:
ReflectionTestUtils.invokeMethod()
For example:
ReflectionTestUtils.invokeMethod(TestClazz, "createTest", "input data");
A: You can turn off Java access restrictions for reflection so that private means nothing.
The setAccessible(true) call does that.
The only restriction is that a ClassLoader may disallow you from doing that.
See Subverting Java Access Protection for Unit Testing (Ross Burton) for a way to do this in Java.
A: Another approach I have used is to change a private method to package private or protected then complement it with the @VisibleForTesting annotation of the Google Guava library.
This will tell anybody using this method to take caution and not access it directly even in a package. Also a test class need not be in same package physically, but in the same package under the test folder.
For example, if a method to be tested is in src/main/java/mypackage/MyClass.java then your test call should be placed in src/test/java/mypackage/MyClassTest.java. That way, you got access to the test method in your test class.
A: To test legacy code with large and quirky classes, it is often very helpful to be able to test the one private (or public) method I'm writing right now.
I use the junitx.util.PrivateAccessor-package for Java. It has lots of helpful one-liners for accessing private methods and private fields.
import junitx.util.PrivateAccessor;
PrivateAccessor.setField(myObjectReference, "myCrucialButHardToReachPrivateField", myNewValue);
PrivateAccessor.invoke(myObjectReference, "privateMethodName", java.lang.Class[] parameterTypes, java.lang.Object[] args);
A: Android has the @VisibleForTesting annotation from android.support.annotation package.
The @VisibleForTesting annotation indicates that an annotated method is more visible than normally necessary to make the method testable. This annotation has an optional otherwise argument that lets you designate what the visibility of the method should have been if not for the need to make it visible for testing. Lint uses the otherwise argument to enforce the intended visibility.
In practice, it means that you should make a method open for testing and the @VisibleForTesting annotation will show a warning.
For example
package com.mypackage;
public class ClassA {
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
static void myMethod() {
}
}
And when you call ClassA.myMethod() within the same package(com.mypackage) you will see the warning.
A: Use this utility class if you are on Spring:
ReflectionTestUtils.invokeMethod(new ClassName(), "privateMethodName");
A: I think most answers are too crude. It depends on your code if you should test private methods or not.
I used private method testing in the past, and I did this by reflection. It works for me. I realize the problems with it, but for me it was the best solution.
I have a heavy application that simulates human behaviour in a population of over a million persons. Every person is represented by an object. The main purpose of the application is to follow how something (disease, information, ideas) spreads through the population.
For this I have methods that pass on the disease or information from one object to another. There is absolutely no reason to make these methods public, for the end user is not interested in one pass from person to person. The end user is only interested in the grand picture of how it spreads through the population. So those methods are private.
But I want to know for sure if the single act of passing one bit of information from one person to another is doing what it should. Testing it via public user interfaces is also not possible, because it's just not public, and I think it's awkward to make it public just for the purpose of testing. The end output of the application is defined by hundreds of millions of such single steps being performed all the time. I cannot test the end output either, because that has complicated stochastability involved, which makes it too unpredictable to test.
So the way for me to test the application is by testing a single step of passing information from one person to another person. These are all private methods. And so I use reflection to test that.
I'm telling this story to show that it's not that plain black and white story. It depends on your application what is best. Under some circumstances, testing private methods via reflection might be your best option.
If some people here know better solutions in my use case, I'd happily stand corrected of course....
A: When I have private methods in a class that are sufficiently complicated that I feel the need to test the private methods directly, that is a code smell: my class is too complicated.
My usual approach to addressing such issues is to tease out a new class that contains the interesting bits. Often, this method and the fields it interacts with, and maybe another method or two can be extracted in to a new class.
The new class exposes these methods as 'public', so they're accessible for unit testing. The new and old classes are now both simpler than the original class, which is great for me (I need to keep things simple, or I get lost!).
Note that I'm not suggesting that people create classes without using their brain! The point here is to use the forces of unit testing to help you find good new classes.
A: Having tried Cem Catikkas' solution using reflection for Java, I'd have to say his was a more elegant solution than I have described here. However, if you're looking for an alternative to using reflection, and have access to the source you're testing, this will still be an option.
There is possible merit in testing private methods of a class, particularly with test-driven development, where you would like to design small tests before you write any code.
Creating a test with access to private members and methods can test areas of code which are difficult to target specifically with access only to public methods. If a public method has several steps involved, it can consist of several private methods, which can then be tested individually.
Advantages:
*
*Can test to a finer granularity
Disadvantages:
*
*Test code must reside in the same
file as source code, which can be
more difficult to maintain
*Similarly with .class output files, they must remain within the same package as declared in source code
However, if continuous testing requires this method, it may be a signal that the private methods should be extracted, which could be tested in the traditional, public way.
Here is a convoluted example of how this would work:
// Import statements and package declarations
public class ClassToTest
{
private int decrement(int toDecrement) {
toDecrement--;
return toDecrement;
}
// Constructor and the rest of the class
public static class StaticInnerTest extends TestCase
{
public StaticInnerTest(){
super();
}
public void testDecrement(){
int number = 10;
ClassToTest toTest= new ClassToTest();
int decremented = toTest.decrement(number);
assertEquals(9, decremented);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(StaticInnerTest.class);
}
}
}
The inner class would be compiled to ClassToTest$StaticInnerTest.
See also: Java Tip 106: Static inner classes for fun and profit
A: I have used reflection to do this for Java in the past, and in my opinion it was a big mistake.
Strictly speaking, you should not be writing unit tests that directly test private methods. What you should be testing is the public contract that the class has with other objects; you should never directly test an object's internals. If another developer wants to make a small internal change to the class, which doesn't affect the classes public contract, he/she then has to modify your reflection based test to ensure that it works. If you do this repeatedly throughout a project, unit tests then stop being a useful measurement of code health, and start to become a hindrance to development, and an annoyance to the development team.
What I recommend doing instead is using a code coverage tool, such as Cobertura, to ensure that the unit tests you write provide decent coverage of the code in private methods. That way, you indirectly test what the private methods are doing, and maintain a higher level of agility.
A: As others have said... don't test private methods directly. Here are a few thoughts:
*
*Keep all methods small and focused (easy to test, easy to find what is wrong)
*Use code coverage tools. I like Cobertura (oh happy day, it looks like a new version is out!)
Run the code coverage on the unit tests. If you see that methods are not fully tested add to the tests to get the coverage up. Aim for 100% code coverage, but realize that you probably won't get it.
A: I am not sure whether this is a good technique, but I developed the following pattern to unit test private methods:
I don't modify the visibility of the method that I want to test and add an additional method. Instead I am adding an additional public method for every private method I want to test. I call this additional method Test-Port and denote them with the prefix t_. This Test-Port method then simply accesses the according private method.
Additionally, I add a Boolean flag to the Test-Port method to decide whether I grant access to the private method through the Test-Port method from outside. This flag is then set globally in a static class where I place e.g. other global settings for the application. So I can switch the access to the private methods on and off in one place, e.g., in the corresponding unit test.
A: A quick addition to Cem Catikka's answer, when using ExpectedException:
Keep in mind that your expected exception will be wrapped in an InvocationTargetException, so in order to get to your exception you will have to throw the cause of the InvocationTargetException you received. Something like (testing private method validateRequest() on BizService):
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired(required = true)
private BizService svc;
@Test
public void testValidateRequest() throws Exception {
thrown.expect(BizException.class);
thrown.expectMessage(expectMessage);
BizRequest request = /* Mock it, read from source - file, etc. */;
validateRequest(request);
}
private void validateRequest(BizRequest request) throws Exception {
Method method = svc.getClass().getDeclaredMethod("validateRequest", BizRequest.class);
method.setAccessible(true);
try {
method.invoke(svc, request);
}
catch (InvocationTargetException e) {
throw ((BizException)e.getCause());
}
}
A: If you are worried by not testing private methods as many of the posts suggest, consider that a code coverage tool will determine exactly how much of your code is tested and where it leaks, so it is quantifiably acceptable to do this.
Answers that direct the author of the question towards a 'workaround' are doing a massive disservice to the community. Testing is a major part of all engineering disciplines. You would not want to buy a car that is not properly tested, and tested in a meaningful way, so why would anyone want to buy or use software that is tested poorly? The reason people do this anyway is probably because the effects of badly tested software are felt way after the fact, and we don't usually associate them with bodily harm.
This is a very dangerous perception which will be difficult to change, but it is our responsibility to deliver safe products regardless of what even management is bullying us to do. Think the Equifax hack...
We must strive to build an environment that encourages good software engineering practices. This does not mean ostracizing the weak/lazy among us who do not take their craft seriously, but rather, to create a status quo of accountability and self reflection that would encourage everyone to pursue growth, both mentally and skillfully.
I am still learning, and may have wrong perceptions/opinions myself, but I do firmly believe that we need to hold ourselves accountable to good practices and shun irresponsible hacks or workarounds to problems.
A: Here is my Lombok sample:
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Student student = new Student();
Field privateFieldName = Student.class.getDeclaredField("name");
privateFieldName.setAccessible(true);
privateFieldName.set(student, "Naruto");
Field privateFieldAge = Student.class.getDeclaredField("age");
privateFieldAge.setAccessible(true);
privateFieldAge.set(student, "28");
System.out.println(student.toString());
Method privateMethodGetInfo = Student.class.getDeclaredMethod("getInfo", String.class, String.class);
privateMethodGetInfo.setAccessible(true);
System.out.println(privateMethodGetInfo.invoke(student, "Sasuke", "29"));
}
@Setter
@Getter
@ToString
class Student {
private String name;
private String age;
private String getInfo(String name, String age) {
return name + "-" + age;
}
}
A: Private methods are consumed by public ones. Otherwise, they're dead code. That's why you test the public method, asserting the expected results of the public method and thereby, the private methods it consumes.
Testing private methods should be tested by debugging before running your unit tests on public methods.
They may also be debugged using test-driven development, debugging your unit tests until all your assertions are met.
I personally believe it is better to create classes using TDD; creating the public method stubs, then generating unit tests with all the assertions defined in advance, so the expected outcome of the method is determined before you code it. This way, you don't go down the wrong path of making the unit test assertions fit the results. Your class is then robust and meets requirements when all your unit tests pass.
A: If using Spring, ReflectionTestUtils provides some handy tools that help out here with minimal effort. For example, to set up a mock on a private member without being forced to add an undesirable public setter:
ReflectionTestUtils.setField(theClass, "theUnsettableField", theMockObject);
A: If you're trying to test existing code that you're reluctant or unable to change, reflection is a good choice.
If the class's design is still flexible, and you've got a complicated private method that you'd like to test separately, I suggest you pull it out into a separate class and test that class separately. This doesn't have to change the public interface of the original class; it can internally create an instance of the helper class and call the helper method.
If you want to test difficult error conditions coming from the helper method, you can go a step further. Extract an interface from the helper class, add a public getter and setter to the original class to inject the helper class (used through its interface), and then inject a mock version of the helper class into the original class to test how the original class responds to exceptions from the helper. This approach is also helpful if you want to test the original class without also testing the helper class.
A: From this article: Testing Private Methods with JUnit and SuiteRunner (Bill Venners), you basically have 4 options:
*
*Don't test private methods.
*Give the methods package access.
*Use a nested test class.
*Use reflection.
A: Testing private methods breaks the encapsulation of your class because every time you change the internal implementation you break client code (in this case, the tests).
So don't test private methods.
A: The answer from JUnit.org FAQ page:
But if you must...
If you are using JDK 1.3 or higher, you can use reflection to subvert
the access control mechanism with the aid of the PrivilegedAccessor.
For details on how to use it, read this article.
If you are using JDK 1.6 or higher and you annotate your tests with
@Test, you can use Dp4j to inject reflection in your test methods. For
details on how to use it, see this test script.
P.S. I'm the main contributor to Dp4j. Ask me if you need help. :)
A: In C# you could have used System.Reflection, though in Java I don't know. If you "feel you need to unit test private methods", my guess is that there is something else which is wrong...
I would seriously consider looking at my architecture again with fresh eyes...
A: What if your test classes are in the same package as the class that should be tested?
But in a different directory of course, src & classes for your source code, test/src and test/classes for your test classes. And let classes and test/classes be in your classpath.
A: The best and proper legal way to test a Java private method from a test framework is the @VisibleForTesting annotation over the method, so the same method will be visible for the test framework like a public method.
A: PowerMock.Whitebox is the best option I have seen, but when I read its source code, it reads private fields with reflection, so I think I have my answer:
*
*test private internal states (fields) with PowerMock, or just reflection without the overhead of introducing another independency
*for private methods: actually, the upvote for this question itself, and the huge number of comments and answers, shows that it is a very concurrent and controversial topic where no definite answer could be given to suit every circumstance. I understand that only the contract should be tested, but we also have coverage to consider. Actually, I doubt that only testing contracts will 100% make a class immune to errors. Private methods are those who process data in the class where it is defined and thus does not interest other classes, so we cannot simply expose to make it testable. I will try not to test them, but when you have to, just go for it and forget all the answers here. You know better your situation and restrictions than any other one on the Internet. When you have control over your code, use that. With consideration, but without overthinking.
After some time, when I reconsider it, I still believe this is true, but I saw better approaches.
First of all, Powermock.Whitebox is still usable.
And, Mockito Whitebox has been hidden after v2 (the latest version I can find with Whitebox is testImplementation 'org.mockito:mockito-core:1.10.19') and it has always been part of org.mockito.internal package, which is prone of breaking changes in the future (see this post). So now I tend not to use it.
In Gradle/Maven projects, if you define private methods or fields, there aren't any other ways than reflection to get access to them, so the first part stays true. But, if you change the visibility to "package private", the tests following the same structure in test package will have access to them. That is also another important reason why we are encouraged to create the same hierarchy in main and test package. So, when you have control over production code as well as tests, delete that private access modifier may be the best option for you because relatively it does not cause huge impact. And, that makes testing as well as private method spying possible.
@Autowired
private SomeService service; // With a package private method "doSomething()"
@Test
void shouldReturnTrueDoSomething() {
assertThat(doSomething(input), is(true)); // Package private method testing
}
@Test
void shouldReturnTrueWhenServiceThrowsException() {
SomeService spy = Mockito.spy(service); // Spying real object
doThrow(new AppException()).when(spy).doSomething(input); // Spy package private method
...
}
When it comes to internal fields, in Spring you have ReflectionUtils.setField().
At last, sometimes we can bypass the problem itself: if there is a coverage requirement to meet, maybe you can move these private methods into an inner static class and ignore this class in Jacoco. I just found some way to ignore the inner class in Jacoco Gradle tasks. Another question.
A: If you want to test private methods of a legacy application where you can't change the code, one option for Java is jMockit, which will allow you to create mocks to an object even when they're private to the class.
A: PowerMockito is made for this.
Use a Maven dependency:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
Then you can do
import org.powermock.reflect.Whitebox;
...
MyClass sut = new MyClass();
SomeType rval = Whitebox.invokeMethod(sut, "myPrivateMethod", params, moreParams);
A: If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.
Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection.
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
Notes:
*
*TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for
getDeclaredField.
*The setAccessible(true) is required to play around with privates.
A: I tend not to test private methods. There lies madness. Personally, I believe you should only test your publicly exposed interfaces (and that includes protected and internal methods).
A: If you're using JUnit, have a look at junit-addons. It has the ability to ignore the Java security model and access private methods and attributes.
A: Generally a unit test is intended to exercise the public interface of a class or unit. Therefore, private methods are implementation detail that you would not expect to test explicitly.
A: Here is my generic function to test private fields:
protected <F> F getPrivateField(String fieldName, Object obj)
throws NoSuchFieldException, IllegalAccessException {
Field field =
obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return (F)field.get(obj);
}
A: Please see below for an example;
The following import statement should be added:
import org.powermock.reflect.Whitebox;
Now you can directly pass the object which has the private method, method name to be called, and additional parameters as below.
Whitebox.invokeMethod(obj, "privateMethod", "param1");
A: I would suggest you refactoring your code a little bit. When you have to start thinking about using reflection or other kind of stuff, for just testing your code, something is going wrong with your code.
You mentioned different types of problems. Let's start with private fields. In case of private fields I would have added a new constructor and injected fields into that. Instead of this:
public class ClassToTest {
private final String first = "first";
private final List<String> second = new ArrayList<>();
...
}
I'd have used this:
public class ClassToTest {
private final String first;
private final List<String> second;
public ClassToTest() {
this("first", new ArrayList<>());
}
public ClassToTest(final String first, final List<String> second) {
this.first = first;
this.second = second;
}
...
}
This won't be a problem even with some legacy code. Old code will be using an empty constructor, and if you ask me, refactored code will look cleaner, and you'll be able to inject necessary values in test without reflection.
Now about private methods. In my personal experience when you have to stub a private method for testing, then that method has nothing to do in that class. A common pattern, in that case, would be to wrap it within an interface, like Callable and then you pass in that interface also in the constructor (with that multiple constructor trick):
public ClassToTest() {
this(...);
}
public ClassToTest(final Callable<T> privateMethodLogic) {
this.privateMethodLogic = privateMethodLogic;
}
Mostly all that I wrote looks like it's a dependency injection pattern. In my personal experience it's really useful while testing, and I think that this kind of code is cleaner and will be easier to maintain. I'd say the same about nested classes. If a nested class contains heavy logic it would be better if you'd moved it as a package private class and have injected it into a class needing it.
There are also several other design patterns which I have used while refactoring and maintaining legacy code, but it all depends on cases of your code to test. Using reflection mostly is not a problem, but when you have an enterprise application which is heavily tested and tests are run before every deployment everything gets really slow (it's just annoying and I don't like that kind of stuff).
There is also setter injection, but I wouldn't recommended using it. I'd better stick with a constructor and initialize everything when it's really necessary, leaving the possibility for injecting necessary dependencies.
A: A private method is only to be accessed within the same class. So there is no way to test a “private” method of a target class from any test class. A way out is that you can perform unit testing manually or can change your method from “private” to “protected”.
And then a protected method can only be accessed within the same package where the class is defined. So, testing a protected method of a target class means we need to define your test class in the same package as the target class.
If all the above does not suits your requirement, use the reflection way to access the private method.
A: As many above have suggested, a good way is to test them via your public interfaces.
If you do this, it's a good idea to use a code coverage tool (like EMMA) to see if your private methods are in fact being executed from your tests.
A: Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.
If you got some code with private methods or fields or constructors, you can use BoundBox. It does exactly what you are looking for.
Here below is an example of a test that accesses two private fields of an Android activity to test it:
@UiThreadTest
public void testCompute() {
// Given
boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());
// When
boundBoxOfMainActivity.boundBox_getButtonMain().performClick();
// Then
assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}
BoundBox makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, but everything is checked at compile time.
It is ideal for testing some legacy code. Use it carefully. ;)
A: First, I'll throw this question out: Why do your private members need isolated testing? Are they that complex, providing such complicated behaviors as to require testing apart from the public surface? It's unit testing, not 'line-of-code' testing. Don't sweat the small stuff.
If they are that big, big enough that these private members are each a 'unit' large in complexity—consider refactoring such private members out of this class.
If refactoring is inappropriate or infeasible, can you use the strategy pattern to replace access to these private member functions / member classes when under unit test? Under unit test, the strategy would provide added validation, but in release builds it would be simple passthrough.
A: I want to share a rule I have about testing which particularly is related to this topic:
I think that you should never adapt production code in order to
indulge easer writing of tests.
There are a few suggestions in other posts saying you should adapt the original class in order to test a private method - please red this warning first.
If we change the accessibility of a method/field to package private or protected, just in order to have it accessible to tests, then we defeat the purpose of existence of private access directive.
Why should we have private fields/methods/classes at all when we want to have test-driven development? Should we declare everything as package private, or even public then, so we can test without any effort?—I don't think so.
From another point of view: Tests should not burden performance and execution of the production application.
If we change production code just for the sake of easier testing, that may burden performance and the execution of the application in some way.
If someone starts to change private access to package private, then a developer may eventually come up to other "ingenious ideas" about adding even more code to the original class. This would make additional noise to readability and can burden the performance of the application.
With changing of a private access to some less restrictive, we are opening the possibility to a developer for misusing the new situation in the future development of the application. Instead of enforcing him/her to develop in the proper way, we are tempting him/her with new possibilities and giving him ability to make wrong choices in the future.
Of course there might be a few exceptions to this rule, but with clear understanding, what is the rule and what is the exception? We need to be absolutely sure we know why that kind of exception is introduced.
A: JML has a spec_public comment annotation syntax that allows you to specify a method as public during tests:
private /*@ spec_public @*/ int methodName(){
...
}
This syntax is discussed at 2.4 Privacy Modifiers and Visibility. There also exists a program that translates JML specifications into JUnit tests. I'm not sure how well that works or what its capabilities are, but it doesn't appear to be necessary since JML is a viable testing framework on its own.
A: You can use PowerMockito to set return values for private fields and private methods that are called/used in the private method you want to test:
For example, setting a return value for a private method:
MyClient classUnderTest = PowerMockito.spy(new MyClient());
// Set the expected return value
PowerMockito.doReturn(20).when(classUnderTest, "myPrivateMethod", anyString(), anyInt());
// This is very important. Otherwise, it will not work
classUnderTest.myPrivateMethod();
// Setting the private field value as someValue:
Whitebox.setInternalState(classUnderTest, "privateField", someValue);
Then finally you can validate your private method under test is returning the correct value based on set values above by:
String msg = Whitebox.invokeMethod(obj, "privateMethodToBeTested", "param1");
Assert.assertEquals(privateMsg, msg);
Or
If the classUnderTest private method does not return a value, but it sets another private field then you can get that private field value to see if it was set correctly:
// To get the value of a private field
MyClass obj = Whitebox.getInternalState(classUnderTest, "foo");
assertThat(obj, is(notNull(MyClass.class))); // Or test value
A: My team and I are using Typemock, which has an API that allows you to fake non-public methods.
Recently they added the ability to fake non-visible types and to use xUnit.
A: If you have a case where you really need to test a private method/class etc.. directly, you can use reflection as already mentioned in other answers. However if it comes to that, instead of dealing directly with reflection I'd rather use utility classes provided by your framework. For instance, for Java we have:
*
*ReflectionUtils in Spring Framework
*ReflectionUtils in JUnit
As per how to use them, you can find plenty of articles online. Here one that I particularly liked:
*
*Java Code Examples for org.springframework.util.ReflectionUtils
A: You can create a special public method to proxy the private method to test.
The @TestOnly annotation is out of the box available when using IntelliJ.
The downside is is that if somebody want to to use the private method in a public context, he can do it. But he will be warned by the annotation and the method name. On IntelliJ a warning will appear when doing it.
import org.jetbrains.annotations.TestOnly
class MyClass {
private void aPrivateMethod() {}
@TestOnly
public void aPrivateMethodForTest() {
aPrivateMethod()
}
}
A: If you are only using Mockito:
You can consider the private method as a part of public method being tested. You can make sure you cover all the cases in private method when testing public method.
Suppose you are a Mockito-only user (you are not allowed or don't want to use PowerMock or reflection or any such tools) and you don’t want to change the existing code or libraries being tested, this might be the best way.
The only thing you need to handle if you choose this way is the variables (user-defined objects) declared locally within private methods. If the private method depends on locally declared variable objects and their methods, make sure you declare those user-defined objects globally as private object instead of locally declared objects. You can instantiate these objects locally.
This allows you to mock these objects and inject them back to testing object. You can also mock (using when/then) their methods.
This will allow you test private method without errors when testing the public method.
Advantages
*
*Code coverage
*Able to test the complete private method.
Disadvantages
*
*Scope of the object—if you don't want the object to be exposed to other methods within same class, this might not be your way.
*You might end up testing the private method multiple times when invoked at different public methods and/or in the same method multiple times.
A: I feel exactly the same ... change the access modifier for a method just to be able to run a test looks for me as a bad idea. Also in our company we had a lot of discussions about it and in my opinion, really nice way to test a private method is to using Java reflection or another framework which making the method testable. I did so multiple times for complex private methods and this helped me to keep the test small, readable and maintainable.
After I have read all the answers here, I just disagree with persons who say "if you need to test a private method, then there is a code smell" or even "don´t test private methods" ... so I have a little example for you:
Imagine I have a class with one public method and a couple of private methods:
public class ConwaysGameOfLife {
private boolean[][] generationData = new boolean[128][128];
/**
* Compute the next generation and return the new state
* Also saving the new state in generationData
*/
public boolean[][] computeNextGeneration() {
boolean[][] tempData = new boolean[128][128];
for (int yPos=0; yPos<=generationData.length; yPos++) {
for (int xPos=0; xPos<=generationData[yPos].length; xPos++) {
int neighbors = countNeighbors(yPos, xPos);
tempData[yPos][xPos] = determineCellState(neighbors, yPos, xPos);
}
}
generationData = tempData;
return generationData;
}
/**
* Counting the neighbors for a cell on given position considering all the edge cases
*
* @return the amount of found neighbors for a cell
*/
private int countNeighbors(int yPos, int xPos) {}
/**
* Determine the cell state depending on the amount of neighbors of a cell and on a current state of the cell
*
* @return the new cell state
*/
private boolean determineCellState(int neighborsAmount, int yPos, int xPos) {}
}
So at least for the method "countNeighbors" I need to test eight edge cases and also some general cases (cells directly in the corners, cells directly on the edges of the matrix and cells somewhere in the middle). So if I am only trying to cover all the cases through the "computeNextGeneration" method and after refactoring, some tests are red, it is probably time consuming to identify the place where the bug is.
If I am testing "determineCellState" and "countNeighbors" separately and after refactoring and optimization, tests of "computeNextGeneration" and "determineCellState" are red, I am pretty sure that the error will be in the "determineCellState" method.
Also, if you write unit tests for those methods from the beginning, this tests will help you to develop the methods / the algorithms without a need to considering and wrapping other method calls and cases inside the public method. You can just write fast small tests covering your cases in the method ... for example if the test with the name "countNeighbors_should_return_right_amount_of_neighbors_for_the_right_top_corner_cell()" fails, then it is pretty clear where to look for the bug.
A: I only test the public interface, but I have been known to make specific private methods protected so I can either mock them out entirely, or add in additional steps specific for unit testing purposes. A general case is to hook in flags I can set from the unit test to make certain methods intentionally cause an exception to be able to test fault paths; the exception triggering code is only in the test path in an overridden implementation of the protected method.
I minimize the need for this though and I always document the precise reasons to avoid confusion.
A: Groovy has a bug/feature, through which you can invoke private methods as if they were public. So if you're able to use Groovy in your project, it's an option you can use in lieu of reflection. Check out this page for an example.
A: There is another approach to test your private methods.
If you "enable assertion" in run configurations then you can unit test your method inside the method itself. For example;
assert ("Ercan".equals(person1.name));
assert (Person.count == 2);
A: For C++ (since C++11) adding the test class as a friend works perfectly and does not break production encapsulation.
Let's suppose that we have some class Foo with some private functions which really require testing, and some class FooTest that should have access to Foo's private members. Then we should write the following:
// prod.h: some production code header
// forward declaration is enough
// we should not include testing headers into production code
class FooTest;
class Foo
{
// that does not affect Foo's functionality
// but now we have access to Foo's members from FooTest
friend FooTest;
public:
Foo();
private:
bool veryComplicatedPrivateFuncThatReallyRequiresTesting();
}
// test.cpp: some test
#include <prod.h>
class FooTest
{
public:
void complicatedFisture() {
Foo foo;
ASSERT_TRUE(foo.veryComplicatedPrivateFuncThatReallyRequiresTesting());
}
}
int main(int /*argc*/, char* argv[])
{
FooTest test;
test.complicatedFixture(); // and it really works!
}
A: The following Reflection TestUtil could be used generically to test the private methods for their atomicity.
import com.google.common.base.Preconditions;
import org.springframework.test.util.ReflectionTestUtils;
/**
* <p>
* Invoker
* </p>
*
* @author
* @created Oct-10-2019
*/
public class Invoker {
private Object target;
private String methodName;
private Object[] arguments;
public <T> T invoke() {
try {
Preconditions.checkNotNull(target, "Target cannot be empty");
Preconditions.checkNotNull(methodName, "MethodName cannot be empty");
if (null == arguments) {
return ReflectionTestUtils.invokeMethod(target, methodName);
} else {
return ReflectionTestUtils.invokeMethod(target, methodName, arguments);
}
} catch (Exception e) {
throw e;
}
}
public Invoker withTarget(Object target) {
this.target = target;
return this;
}
public Invoker withMethod(String methodName) {
this.methodName = methodName;
return this;
}
public Invoker withArguments(Object... args) {
this.arguments = args;
return this;
}
}
Object privateMethodResponse = new Invoker()
.withTarget(targetObject)
.withMethod(PRIVATE_METHOD_NAME_TO_INVOKE)
.withArguments(arg1, arg2, arg3)
.invoke();
Assert.assertNotNutll(privateMethodResponse)
A: In your class:
namespace my_namespace {
#ifdef UNIT_TEST
class test_class;
#endif
class my_class {
public:
#ifdef UNIT_TEST
friend class test_class;
#endif
private:
void fun() { cout << "I am private" << endl; }
}
}
In your unit test class:
#ifndef UNIT_TEST
#define UNIT_TEST
#endif
#include "my_class.h"
class my_namespace::test_class {
public:
void fun() { my_obj.fun(); }
private:
my_class my_obj;
}
void my_unit_test() {
test_class test_obj;
test_obj.fun(); // here you accessed the private function ;)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3152"
} |
Q: MySQL "Error 1005" when adding tables I've recently been working with a MySQL database, and using MySQL workbench to design the Database.
When I use the export to SQL function, so I can actually get the layout in to the Database, I get:
"Error 1005: Cannot create table"
This appears to be related to Foreign Keys in the create table statement.
Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database.
A: When you get this (and other errors out of the InnoDB engine) issue:
SHOW ENGINE INNODB STATUS;
It will give a more detailed reason why the operation couldn't be completed. Make sure to run that from something that'll allow you to scroll or copy the data, as the response is quite long.
A: I ran into this situation recently when I attempted (in InnoDB tables) to make a foreign key reference to a column that had a different data type.
MySQL 5.1 Documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: inline-block on span I expected the two span tags in the following sample to display next to each other, instead they display one below the other. If I set the width of the class span.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible padding/margin which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?
* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}
<html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html>
Thanks for the explanation. The float:left works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge
A: float: left;
Try adding that to span.left
It will cause it to float to the left (as suggested by the syntax).
I am not a CSS expert by any means so please don't take this as unarguable fact but I find that when something is floated, it makes no difference to the vertical position of things below it.
If you float the span.right to the right then add text beneath them you should get some interesting results, to stop these "interesting results" you can use "clear: left/right/both" which will cause the block with the clear styling to be under anything floated to the left/right/both. W3Schools have a page on this property too.
And welcome to Stackoverflow.
A: This is because inline and inline-block include whitespace (in your case the line break) between the elements. In your case the combined width of the elements is 50%+50%+whitespace > 100%.
You should either put the two elements on the same row in your HTML document (without space)
<div class='header'>
<span class='left'>Left Span 50% width</span><span class='right'>Right Span 50% width</span>
</div>
Or use HTML comments
<div class='header'>
<span class='left'>Left Span 50% width</span><!--
--><span class='right'>Right Span 50% width</span>
</div>
I myself prefer the latter.
A: I don't like this hack but it seems to do the job both in Firefox and IE6:
span.right {
vertical-align:top;
display:inline-block;
text-align:right;
height:80px;
width:50%;
*width:100%;
background-color:red;
}
Note the *width: 100% which seems to satisfy IE6's requirement and is ignored by Firefox.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I change the number of open files limit in Linux? When running my application I sometimes get an error about too many files open.
Running ulimit -a reports that the limit is 1024. How do I increase the limit above 1024?
Edit
ulimit -n 2048 results in a permission error.
A: If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited into /etc/init.d/httpd. This does not require a server reboot.
A: 1) Add the following line to /etc/security/limits.conf
webuser hard nofile 64000
then login as webuser
su - webuser
2) Edit following two files for webuser
append .bashrc and .bash_profile file by running
echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile
3) Log out, then log back in and verify that the changes have been made correctly:
$ ulimit -a | grep open
open files (-n) 64000
Thats it and them boom, boom boom.
A: You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit
Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.
set rlim_fd_max = 166384
set rlim_fd_cur = 8192
On OS X, this same data must be set in /etc/sysctl.conf.
kern.maxfilesperproc=166384
kern.maxfiles=8192
Under Linux, these settings are often in /etc/security/limits.conf.
There are two kinds of limits:
*
*soft limits are simply the currently enforced limits
*hard limits mark the maximum value which cannot be exceeded by setting a soft limit
Soft limits could be set by any user while hard limits are changeable only by root.
Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.
There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.
A: If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf or /etc/security/limits.conf file (where the file is located depends on your specific Linux distribution).
For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf file.
* hard nofile 10000
Then logout and relogin to your system and you should be able to do:
ulimit -n 10000
without a permission error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "212"
} |
Q: What is a good Hash Function? What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:
function Hash(key)
return key mod PrimeNumber
end
(mod is the % operator in C and similar languages)
with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?
A: This is an example of a good one and also an example of why you would never want to write one.
It is a Fowler / Noll / Vo (FNV) Hash which is equal parts computer science genius and pure voodoo:
unsigned fnv_hash_1a_32 ( void *key, int len ) {
unsigned char *p = key;
unsigned h = 0x811c9dc5;
int i;
for ( i = 0; i < len; i++ )
h = ( h ^ p[i] ) * 0x01000193;
return h;
}
unsigned long long fnv_hash_1a_64 ( void *key, int len ) {
unsigned char *p = key;
unsigned long long h = 0xcbf29ce484222325ULL;
int i;
for ( i = 0; i < len; i++ )
h = ( h ^ p[i] ) * 0x100000001b3ULL;
return h;
}
Edit:
*
*Landon Curt Noll recommends on his site the FVN-1A algorithm over the original FVN-1 algorithm: The improved algorithm better disperses the last byte in the hash. I adjusted the algorithm accordingly.
A: There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean.
Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash.
Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste.
This is actually one of the cases where I advise to read what Knuth has to say in The Art of Computer Programming, vol. 3. Another good read is Julienne Walker's The Art of Hashing.
A: I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.
A: For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I've ever used.
http://www.azillionmonkeys.com/qed/hash.html
If you care about cryptographically secure or anything else more advanced, then YMMV. If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you're looking for.
A: There are two major purposes of hashing functions:
*
*to disperse data points uniformly into n bits.
*to securely identify the input data.
It's impossible to recommend a hash without knowing what you're using it for.
If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.
If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.
A: A good hash function has the following properties:
*
*Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.
*Given a pair of message, m' and m, it is computationally infeasible to find two such that that h(m) = h(m')
The two cases are not the same. In the first case, there is a pre-existing hash that you're trying to find a collision for. In the second case, you're trying to find any two messages that collide. The second task is significantly easier due to the birthday "paradox."
Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you'll secure yourself against these.
Don't use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you're not careful.
A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks.
Hope that helps!
A: What you're saying here is you want to have one that uses has collision resistance. Try using SHA-2. Or try using a (good) block cipher in a one way compression function (never tried that before), like AES in Miyaguchi-Preenel mode. The problem with that is that you need to:
1) have an IV. Try using the first 256 bits of the fractional parts of Khinchin's constant or something like that.
2) have a padding scheme. Easy. Barrow it from a hash like MD5 or SHA-3 (Keccak [pronounced 'ket-chak']).
If you don't care about the security (a few others said this), look at FNV or lookup2 by Bob Jenkins (actually I'm the first one who reccomends lookup2) Also try MurmurHash, it's fast (check this: .16 cpb).
A: A good hash function should
*
*be bijective to not loose information, where possible, and have the least collisions
*cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.
*if used in a cryptographic context there should not exist an efficient way to invert it.
A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).
To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.
Useful permutations, among others, are:
*
*multiplication with an uneven integer
*binary rotations
*xorshift
Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.
If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:
First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k many applications of (n*(n+1)/2) mod 2^k interspersed with an xorshift when k is the number of bits in the resulting hash.
A: I highly recommend the SMhasher GitHub project https://github.com/rurban/smhasher which is a test suite for hash functions. The fastest state-of-the-art non-cryptographic hash functions without known quality problems are listed here: https://github.com/rurban/smhasher#summary.
A: Different application scenarios have different design requirements for hash algorithms, but a good hash function should have the following three points:
*
*Collision Resistance: try to avoid conflicts. If it is difficult to find two inputs that are hashed to the same output, the hash function is anti-collision
*Tamper Resistant: As long as one byte is changed, its hash value will be very different.
*Computational Efficiency: Hash table is an algorithm that can make a trade-off between time consumption and space consumption.
In 2022, we can choose the SHA-2 family to use in secure encryption, SHA-3 it is safer but has greater performance loss. A safer approach is to add salt and mix encryption., we can choose the SHA-2 family to use in secure encryption, SHA-3 it is safer but has greater performance loss. A safer approach is to add salt and mix encryption.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "147"
} |
Q: Toolkit Options for 2D Python Game Programming What are some toolkits for developing 2D games in Python? An option that I have heard of is Pygame, but is there anything that has more range to do more things? What are the good and bad parts about the modules?
A: I have used and would highly recommend pyglet, which provides 2D sprite graphics, hooks into OpenGL effects, audio support, file asset management, and excellent text layout and display support (not something you always find in a 2D game library). The API is sane, well-documented, and easy to get started with, and goes deep (especially if you're an OpenGL wizard).
As a companion to pyglet, I have used and would also suggest Cocos2D, which adds scene management, improved sprites, tiled map support, and fancy (accelerated) effects to add a little polish. Cocos is still young, but taking shape quickly, and already has fairly solid documentation.
A: A blog post covering several of the alternatives, including PyGame, PyCap, SpriteCraft, and ika. I have also seen pyglet mentioned.
You may also want to look at Panda, which is a very easy to use 3D engine with Python bindings. It is used for rapid prototyping at Carnegie Mellon's ETC.
A: I think pygame is the standard for game development in Python, I don't know of any others. A book you may be interested in is Game Programming with Python, Lua, and Ruby. Not only does it cover Python (and, I believe, the pygame module), but it also gives you exposure to Lua and Ruby. It's also available on books24x7 if you have a subscription there.
A: I use pygame myself and it is very good. It has good documentation and tutorials, and is quite well designed. I've also heard wonderful reviews of pyglet.
A: Another option is pycap which is a wrapper for the popcap framework with Python.
A: If you're already familiar with using OpenGL in another language (probably C or C++) then PyOpenGL is awesome. I was surprised as to how easy it was to switch from OpenGL/C to OpenGL/Python. The performance isn't half bad either.
I've heard good things about PyGame and Pyglet though I must admit I haven't really done much messing around with either one.
A: I've only heard people talk about pygame. It has tons of followers & plenty of functionality.
Recently I saw this book at barnes & noble which I might check out one day. It looked good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Why is HTML form redirection used in OpenID 2? Why would you do an automatic HTML post rather than a simple redirect?
Is this so developers can automatically generate a login form that posts directory to the remote server when the OpenID is known?
eg.
*
*User is not logged in and visits your login page.
*You detect the user's openID from a cookie.
*Form is generated that directly posts to remote OpenID server.
*Remote server redirects user back to website.
*Website logs in the user.
If this is the case I can see the benefit. However this assumes that you keep the user's openID in a cookie when they log out.
I can find very little information on how this spec should be best implemented.
See HTML FORM Redirection in the official specs:
http://openid.net/specs/openid-authentication-2_0.html#indirect_comm
I found this out from looking at the PHP OpenID Library (version 2.1.1).
// Redirect the user to the OpenID server for authentication.
// Store the token for this authentication so we can verify the
// response.
// For OpenID 1, send a redirect. For OpenID 2, use a Javascript
// form to send a POST request to the server.
if ($auth_request->shouldSendRedirect()) {
$redirect_url = $auth_request->redirectURL(getTrustRoot(),
getReturnTo());
// If the redirect URL can't be built, display an error
// message.
if (Auth_OpenID::isFailure($redirect_url)) {
displayError("Could not redirect to server: " . $redirect_url->message);
} else {
// Send redirect.
header("Location: ".$redirect_url);
}
} else {
// Generate form markup and render it.
$form_id = 'openid_message';
$form_html = $auth_request->htmlMarkup(getTrustRoot(), getReturnTo(),
false, array('id' => $form_id));
// Display an error if the form markup couldn't be generated;
// otherwise, render the HTML.
if (Auth_OpenID::isFailure($form_html)) {
displayError("Could not redirect to server: " . $form_html->message);
} else {
print $form_html;
}
}
A: I can think of a couple of reasons:
*
*A modicum of security by obscurity - it's slightly more work to tamper with POST submissions than GET
*Caching and resubmit rules are more restrictive for POST than GET. I'm not entirely sure this would matter for the OpenID use case, though.
*Bots wouldn't follow the POST form, but would follow the redirect. This could impact server load.
*Different browsers have different max lengths for GET requests - but none of them are as large as POST.
*Some browsers will warn on redirect to another domain. They'll also warn if you're submitting POST to a non-HTTPS url.
*By turning JavaScript off, I can have a relatively secure experience, and not be silently redirected to another domain.
I don't know that any of these are a slam-dunk reason to choose POST - unless the amount of data being sent exceeds the querystring length for some major browser.
A: The primary motivation was, as Mark Brackett says, the limits on payload size imposed by using redirects and GET. Some implementations are smart enough to only use POST when the message goes over a certain size, as there are certainly disadvantages to the POST technique. (Chief among them being the fact that your Back button doesn't work.) Other implementations, like the example code you cited, go for simplicity and consistency and leave out that conditional.
A: The same approach is used for the SAML Web Browser SSO profile. The primary motivations of using HTML Post redirection are :
*
*Virtually unlimited length of the payload : in SAML the payload is a XML document signed with XMLDSig and base64 encoded. It is larger than the usual 1024 characters limitation of URL (a best practice to support not only any browsers but intermediary network devices like Firewall, Reverse Proxy, Load Balancer as well).
*W3C HTTP standard says that GET is idempotent (the same URL GET executed multiple times should always result in same response) and consequently can be cached along the way while POST is not and must reach the URL target. Response of an OpenID HTML Form POST or SAML HTML Form POST should not be cached. It must reach the target in order to initiate the authenticated session.
You could argue that using a HTTP GET redirection would work as well since the URL query always change and you would be right is practice. However, this would be a workaround of the W3C standard, and therefore, should not be a standard but an alternate implementation whenever both end agree with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I get the assembler output from a C file in VS2005 I think the file that is produced is an .asm file, any idea how to produce this in Visual Studio when you do a build?
A: Project->Properties->Configuration Properties->C/C++->Output Files
There you should see an option for Assembler Output.
John.
A: *
*Open the Properties page for a project
*Select the Configuration Properties -> C/C++ -> Output Files branch
*Change the Assembler Output option to something other than No Listing
*Make sure ASM List Location is set to a valid path or sub-path
*Build.
A: Or if using the Visual Studio command line,
cl.exe /Fa[assembler code filename]
If you just want to view the assembler code in the IDE you can start the debugger and then select the Go To Dissassembly choice on the right click menu.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: data 'security' with java and hibernate The system I am currently working on requires some role-based security, which is well catered for in the Java EE stack. The system intends to be a framework for business domain experts to write their code on top of.
However, there is also a requirement for data security. That is, what information is visible to an end user.
This effectively means reducing visibility to rows (and perhaps even columns) in the database.
We are using Hibernate for our persistence. However, we are using our own annotations so as not to expose our persistence choice to the business domain experts.
For row based security this means we could add an annotation such as @Secured at the entity level, which would cause an extra column to be added to the underlying table to constrain our selects?
For column based security, we could perhaps have @Secured to either assist in query generation, or perhaps use an aspect to filter the information returned?
I'm curious to know how this might affect hibernate's caching mechanisms as well?
I'm sure a lot of others will have had the same issue, and I was wondering how you approached this?
Much appreciated...
A: Hibernate has a filter mechanism that may work for you. The filters will rewrite the queries hibernate generates to include an additional clause to limit the rows returned. I'm not aware of anything in hibernate to mask/hide columns.
Your database may also have support for this functionality. Oracle, for example, has the Virtual Private Database (VPD) which will rewrite your queries at the database level. This solution has the added benefit that any external program (e.g. reporting tools) that goes against your db will have your security restrictions enforced. VPD also has support to mask restricted columns with NULLs.
Unfortunately, the above solutions have not been adequate to support the security requirements for the types projects I typically work on. There is usually some sort of context that cannot be easily expressed in the above solutions. For example, users can view data that they have created, or that have been been marked as public, or belong to a project which they manage.
We typically create query/finder/DAO objects where we pass in the values required to enforce the security and then create the query accordingly.
I hope this helps
A: When using Hibernate filters you need to be aware that the additional restrictions will not be applied to SQL statements generted by the load() or get() methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Making an iframe take vertical space I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?
Are there any workarounds?
A: This should set the IFRAME height to its content's height:
<script type="text/javascript">
the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;
document.getElementById('the_iframe').height = the_height;
</script>
You may want to add scrolling="no" to your IFRAME to turn off the scrollbars.
edit: Oops, forgot to declare the_height.
A: This CSS snippet should remove the vertical scrollbar:
body {
overflow-x: hidden;
overflow-y: hidden;
}
I'm not sure yet about having it take up as much vertical space as it needs, but I'll see if I can't figure it out.
A: Adding a DOCTYPE declaration to the IFRAME source document will help to calculate the correct value from the line
document.getElementById('the_iframe').contentWindow.document.body.scrollHeight
see W3C DOCTYPE for examples
I was having problems with both IE and FF as it was rendering the iframe document in 'quirks' mode, until I added the DOCTYPE.
FF/IE/Chrome support: The .scrollHeight doesnt work with Chrome so I have come up with a javascript example using jQuery to set all IFRAME heights on a page based on the iframes content. NOTE: This is for reference pages within the your current domain.
<script type="text/javascript">
$(document).ready(function(){
$('iframe').each(function(){
var context = $(this);
context.load(function(event){ // attach the onload event to the iframe
var body = $(this.contentWindow.document).find('body');
if (body.length > 0 && $(body).find('*').length > 0) { // check if iframe has contents
context.height($(body.get(0)).height() + 20);
} else {
context.hide(); // hide iframes with no contents
}
});
});
});
</script>
A: The workaround is not to use <iframe> and preprocess code on server-side.
A: Also check out this thread: How does the DiggBar dynamically resize its iframe's height based on content not on their domain?.
It addresses the same question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Automate test of web service communication I have an application that sends messages to an external web service. I build and deploy this application using MSBuild and Cruisecontrol.NET. As CCNET build and deploys the app it also runs a set of test using NUnit. I'd now like to test the web service communication as well.
My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service).
Are there any existing utilities out there that easily mock a web service based on a WSDL? Anyone done something similar using MSBuild?
Are there other ways of testing this scenario?
A: I just started looking into http://www.soapui.org/ and it seems like it will work nicely for testing web services.
Also, maybe look at adding an abstraction layer in your web service, each service call would directly call a testable method (outside of the web scope)? I just did this with a bigger project I'm working on, and it's testability is working nicely.
A: In general, a very good way to test things like this is to use mock objects.
At work, we use the product TypeMock to test things like Web Service communication and other outside dependencies. It costs money, so for that reason it may not be suitable for your needs, but I think it's a fantastic product. I can tell you from personal experience that it integrates very well with NUnit and CCNet.
It's got a really simple syntax where you basically say "when this method/property is called, I want you to return this value instead." It's great for testing things like network failures, files not being present, and of course, web services.
A: Take a look at NMock2. It's a open-source mocking product and allows you to create "virtual" implementations for interfaces that support rich and deep interaction.
For example, if your WS interface is called IService and has a Data GetData() method, you can create a mock that requires the method to be called once and returns a new Data object:
var testService = mockery.NewMock<IService>();
Expect
.Once
.On(testService)
.Method("GetService")
.WithNoArguments()
.Will(
Return.Value(new Data());
At the end of the test, call mockery.VerifyAllExpectationsHaveBeenMet() to assure that the GetData method was actually called.
P.S.: don't confuse the "NMock2" project with the "NMock RC2", which is also called "nmock2" on sourceforge. NMock2-the-project seems to have superseded NMock.
A: This might also be something - MockingBird. Look useful.
A: At my work place we are using Typemock and nUnit for our unit testing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: DesignMode with nested Controls Has anyone found a useful solution to the DesignMode problem when developing controls?
The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.
The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.
The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.
A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!
A: Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows:
System.ComponentModel.DesignMode property
System.ComponentModel.LicenseManager.UsageMode property
private string ServiceString()
{
if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return "Present";
else
return "Not present";
}
public bool IsDesignerHosted
{
get
{
Control ctrl = this;
while(ctrl != null)
{
if((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
public static bool IsInDesignMode()
{
return System.Reflection.Assembly.GetExecutingAssembly()
.Location.Contains("VisualStudio"))
}
To try and get a hang on the three solutions proposed, I created a little test solution - with three projects:
*
*TestApp (winforms application),
*SubControl (dll)
*SubSubControl (dll)
I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form.
This screenshot shows the result when running.
This screenshot shows the result with the form open in Visual Studio:
Conclusion: It would appear that without reflection the only one that is reliable within the constructor is LicenseUsage, and the only one which is reliable outside the constructor is 'IsDesignedHosted' (by BlueRaja below)
PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that IsDesignerHosted answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is test LicenseManager in constructor and cache the result."
A: This is the method I use inside forms:
/// <summary>
/// Gets a value indicating whether this instance is in design mode.
/// </summary>
/// <value>
/// <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.
/// </value>
protected bool IsDesignMode
{
get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }
}
This way, the result will be correct, even if either of DesignMode or LicenseManager properties fail.
A: I use the LicenseManager method, but cache the value from the constructor for use throughout the lifetime of the instance.
public MyUserControl()
{
InitializeComponent();
m_IsInDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
}
private bool m_IsInDesignMode = true;
public bool IsInDesignMode { get { return m_IsInDesignMode; } }
VB version:
Sub New()
InitializeComponent()
m_IsInDesignMode = (LicenseManager.UsageMode = LicenseUsageMode.Designtime)
End Sub
Private ReadOnly m_IsInDesignMode As Boolean = True
Public ReadOnly Property IsInDesignMode As Boolean
Get
Return m_IsInDesignMode
End Get
End Property
A: From this page:
([Edit 2013] Edited to work in constructors, using the method provided by @hopla)
/// <summary>
/// The DesignMode property does not correctly tell you if
/// you are in design mode. IsDesignerHosted is a corrected
/// version of that property.
/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305
/// and http://stackoverflow.com/a/2693338/238419 )
/// </summary>
public bool IsDesignerHosted
{
get
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
return true;
Control ctrl = this;
while (ctrl != null)
{
if ((ctrl.Site != null) && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return false;
}
}
I've submitted a bug-report with Microsoft; I doubt it will go anywhere, but vote it up anyways, as this is obviously a bug (whether or not it's "by design").
A: Since none of the methods are reliable (DesignMode, LicenseManager) or efficient (Process, recursive checks) I'm using a public static bool Runtime { get; private set } at program level and explicitly setting it inside the Main() method.
A: We use this code with success:
public static bool IsRealDesignerMode(this Control c)
{
if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
return true;
else
{
Control ctrl = c;
while (ctrl != null)
{
if (ctrl.Site != null && ctrl.Site.DesignMode)
return true;
ctrl = ctrl.Parent;
}
return System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";
}
}
A: My suggestion is an optimization of @blueraja-danny-pflughoeft reply.
This solution doesn't calculate result every time but only at the first time (an object cannot change UsageMode from design to runtime)
private bool? m_IsDesignerHosted = null; //contains information about design mode state
/// <summary>
/// The DesignMode property does not correctly tell you if
/// you are in design mode. IsDesignerHosted is a corrected
/// version of that property.
/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305
/// and https://stackoverflow.com/a/2693338/238419 )
/// </summary>
[Browsable(false)]
public bool IsDesignerHosted
{
get
{
if (m_IsDesignerHosted.HasValue)
return m_IsDesignerHosted.Value;
else
{
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
m_IsDesignerHosted = true;
return true;
}
Control ctrl = this;
while (ctrl != null)
{
if ((ctrl.Site != null) && ctrl.Site.DesignMode)
{
m_IsDesignerHosted = true;
return true;
}
ctrl = ctrl.Parent;
}
m_IsDesignerHosted = false;
return false;
}
}
}
A: Why don't you check LicenseManager.UsageMode.
This property can have the values LicenseUsageMode.Runtime or LicenseUsageMode.Designtime.
Is you want code to only run in runtime, use the following code:
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
bla bla bla...
}
A: I've never been caught by this myself, but couldn't you just walk back up the Parent chain from the control to see if DesignMode is set anywhere above you?
A: DesignMode is a private property (from what I can tell). The answer is to provide a public property that exposes the DesignMode prop. Then you can cascasde back up the chain of user controls until you run into a non-user control or a control that is in design mode. Something like this....
public bool RealDesignMode()
{
if (Parent is MyBaseUserControl)
{
return (DesignMode ? true : (MyBaseUserControl) Parent.RealDesignMode;
}
return DesignMode;
}
Where all your UserControls inherit from MyBaseUserControl. Alternatively you could implement an interface that exposes the "RealDeisgnMode".
Please note this code is not live code, just off the cuff musings. :)
A: I hadn't realised that you can't call Parent.DesignMode (and I have learned something about 'protected' in C# too...)
Here's a reflective version: (I suspect there might be a performance advantage to making designModeProperty a static field)
static bool IsDesignMode(Control control)
{
PropertyInfo designModeProperty = typeof(Component).
GetProperty("DesignMode", BindingFlags.Instance | BindingFlags.NonPublic);
while (designModeProperty != null && control != null)
{
if((bool)designModeProperty.GetValue(control, null))
{
return true;
}
control = control.Parent;
}
return false;
}
A: I had to fight this problem recently in Visual Studio 2017 when using nested UserControls. I combine several of the approaches mentioned above and elsewhere, then tweaked the code until I had a decent extension method which works acceptably so far. It performs a sequence of checks, storing the result in static boolean variables so so each check is only performed at most only once at run time. The process may be overkill, but it is keeping the code from executing in studio. Hope this helps someone.
public static class DesignTimeHelper
{
private static bool? _isAssemblyVisualStudio;
private static bool? _isLicenseDesignTime;
private static bool? _isProcessDevEnv;
private static bool? _mIsDesignerHosted;
/// <summary>
/// Property <see cref="Form.DesignMode"/> does not correctly report if a nested <see cref="UserControl"/>
/// is in design mode. InDesignMode is a corrected that property which .
/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305
/// and https://stackoverflow.com/a/2693338/238419 )
/// </summary>
public static bool InDesignMode(
this Control userControl,
string source = null)
=> IsLicenseDesignTime
|| IsProcessDevEnv
|| IsExecutingAssemblyVisualStudio
|| IsDesignerHosted(userControl);
private static bool IsExecutingAssemblyVisualStudio
=> _isAssemblyVisualStudio
?? (_isAssemblyVisualStudio = Assembly
.GetExecutingAssembly()
.Location.Contains(value: "VisualStudio"))
.Value;
private static bool IsLicenseDesignTime
=> _isLicenseDesignTime
?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime)
.Value;
private static bool IsDesignerHosted(
Control control)
{
if (_mIsDesignerHosted.HasValue)
return _mIsDesignerHosted.Value;
while (control != null)
{
if (control.Site?.DesignMode == true)
{
_mIsDesignerHosted = true;
return true;
}
control = control.Parent;
}
_mIsDesignerHosted = false;
return false;
}
private static bool IsProcessDevEnv
=> _isProcessDevEnv
?? (_isProcessDevEnv = Process.GetCurrentProcess()
.ProcessName == "devenv")
.Value;
}
A: I solved this in .NET 5 with the following:
public static bool InDesignMode()
{
return Process.GetCurrentProcess().ProcessName.Contains("DesignToolsServer");
}
A: In .Net 6, the Control.IsAncestorSiteInDesignMode property is available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "93"
} |
Q: How to keep a "things done" count in a recursive algorithm in Java? I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types.
I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object)
Is there a way to get something similar to work which won't pollute my code?
A: It's kind of a hack, but sometimes I use an AtomicInteger, which is mutable, to do things like this. I've also seen cases where an int[] of size 1 is passed in.
A: The current solution I am using is:
int[] counter = {0};
and then pass it to the recursive algorithm:
public List<Thing> doIt (String aString, int[] counter) { ... }
and when I want to increment it:
counter[0]++;
Not super elegant, but it works...
A: Integers are immutable, which means that when you pass it as an argument it creates a copy rather than a reference to the same item. (explanation).
To get the behavior you're looking for, you can write your own class which is like Integer only mutable. Then, just pass it to the recursive function, it is incremented within the recursion, and when you access it again after the recursion is over it will still maintain its new values.
Edit: Note that using an int[] array is a variation on this method... In Java, arrays are also passed by reference rather than copied like primitives or immutable classes.
A: Since you've already discovered the pseudo-mutable integer "hack," how about this option:
Does it make sense for you to make a separate Parser class? If you do this, you can store the current state in a member variable. You probably need to think about how you're going to handle any thread safety issues, and it might be overkill for this particular application, but it might work for you.
A: You could just use a static int class variable that gets incremented each time your doIt method is called.
A: You could also do:
private int recurse (int i) {
if (someConditionkeepOnGoing) {
i = recurse(i+1);
}
return i;
}
A: To be honest I would recode the function to make it a linear algorithm that uses a loop. This way you have no chance of running out of heap space if you are stepping through an extremely large string. Also, you would not need to have a the extra parameter just to keep track of the count.
This also would probably have the result of making the algorithm faster because it does not need to make a function call for every character.
Unless of course there is a specific reason it needs to be recursive.
A: One possibility I can think of is to store the count in a member variable of the class. This of course assumes that the public doIt method is only called by a single thread.
Another option is to refactor the public method to call a private helper method. The private method takes the list as a parameter and returns the count. For example:
public List<Thing> doIt(String aString) {
List<Thing> list = new ArrayList<Thing>();
int count = doItHelper(aString, list, 0);
// ...
return list;
}
private int doItHelper(String aString, List<Thing> list, int count) {
// ...
// do something that updates count
count = doItHelper(aString, list, count);
// ...
return count;
}
This assumes that you can do the error handling in the public doIt method, since the count variable isn't actually passed back to the caller. If you need to do that, you could of course throw an exception:
public List<Thing> doIt(String aString) throws SomeCustomException {
List<Thing> list = new ArrayList<Thing>();
int count = doItHelper(aString, list, 0);
// ...
if (someErrorOccurred) {
throw new SomeCustomException("Error occurred at chracter index " + count, count);
}
return list;
}
It's difficult to know whether that will help without knowing more about how your algorithm actually works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Performance difference between dot notation versus method call in Objective-C You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.
myObject.property = YES;
or
[myObject setProperty:YES];
Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style?
A: Check out article from Cocoa is My Girlfriend. The gist of it, is that there is no performance penalty of using one over the other.
However, the notation does make it more difficult to see what is happening with your variables and what your variables are.
A: The only time you'll see a performance difference is if you do not mark a property as "nonatomic". Then @synthesize will automatically add synchronization code around the setting of your property, keeping it thread safe - but slower to set and access.
Thus mostly you probably want to define a property like:
@property (nonatomic, retain) NSString *myProp;
Personally I find the dot notation generally useful from the standpoint of you not having to think about writing correct setter methods, which is not completely trivial even for nonatomic setters because you must also remember to release the old value properly. Using template code helps but you can always make mistakes and it's generally repetitious code that clutters up classes.
A pattern to be aware of: if you define the setter yourself (instead of letting @synthesize create it) and start having other side effects of setting a value you should probably make the setter a normal method instead of calling using the property notation.
Semantically using properties appears to be direct access to the actual value to the caller and anything that varies from that should thus be done via sending a message, not accessing a property (even though they are really both sending messages).
A: Dot notation for property access in Objective-C is a message send, just as bracket notation. That is, given this:
@interface Foo : NSObject
@property BOOL bar;
@end
Foo *foo = [[Foo alloc] init];
foo.bar = YES;
[foo setBar:YES];
The last two lines will compile exactly the same. The only thing that changes this is if a property has a getter and/or setter attribute specified; however, all it does is change what message gets sent, not whether a message is sent:
@interface MyView : NSView
@property(getter=isEmpty) BOOL empty;
@end
if ([someView isEmpty]) { /* ... */ }
if (someView.empty) { /* ... */ }
Both of the last two lines will compile identically.
A: As far as I've seen, there isn't a significant performance difference between the two. I'm reasonably certain that in most cases it will be 'compiled' down to the same code.
If you're not sure, try writing a test application that does each method a million times or so, all the while timing how long it takes. That's the only way to be certain (although it may vary on different architecture.)
A: Also read this blog post on Cocoa with Love:
http://cocoawithlove.com/2008/06/speed-test-nsmanagedobject-objc-20.html
There the author compares the speed of custom accessor and dot notations for NSManagedObject, and finds no difference. However, KVC access (setValue:forKey:) appears to be about twice as slow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Subversion ignoring "--password" and "--username" options When I try to do any svn command and supply the --username and/or --password options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by --username. Neither --no-auth-cache nor --non-interactive have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.
For example, logged in as user1:
# $ svn update --username 'user2' --password 'password'
# [email protected]'s password:
Other options work correctly:
# $ svn --version --quiet
# 1.3.2
Why does it prompt me?
And why is it asking for user1's password instead of user2's?
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?
Or is it something else entirely?
I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).
Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:
# HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
A: Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache and --non-interactive
Here is what I use (no single quotes)
--non-interactive --no-auth-cache --username XXXX --password YYYY
See the Client Credentials Caching documentation in the svnbook for more information.
A: The prompt you're getting doesn't look like Subversion asking you for a password, it looks like ssh asking for a password. So my guess is that you have checked out an svn+ssh:// checkout, not an svn:// or http:// or https:// checkout.
IIRC all the options you're trying only work for the svn/http/https checkouts. Can you run svn info to confirm what kind of repository you are using ?
If you are using ssh, you should set up key-based authentication so that your scripts will work without prompting for a password.
A: I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:
Host server.hostname
User username
I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html
A: Best I can give you is a "works for me" on SVN 1.5. You may try adding --no-auth-cache to your svn update to see if that lets you override more easily.
If you want to permanently switch from user2 to user1, head into ~/.subversion/auth/ on *nix and delete the auth cache file for domain.com (most likely in ~/.subversion/auth/svn.simple/ -- just read through them and you'll find the one you want to drop). While it is possible to update the current auth cache, you have to make sure to update the length tokens as well. Simpler just to get prompted again next time you update.
A: The problem was that the working copy was checked out via svn+ssh (thanks, Thomas). Instead of setting up ssh keys as was suggested, I just checked out a new working copy using svn://domain.com/path/to/repo rather than svn+ssh://domain.com/path/to/repo. Because this working copy is on the same machine as the repository itself, I'm not really missing out on anything, and I can now use the --password and --username options gratuitously. Seems obvious now that I think about it.
A: Look to your local svn repo and look into directory .svn .
there is file: entries look into them and you'll see lines begins with:
svn+ssh://
this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'
if you want to change this, te best way is completly refresh this repository.
update/commit what you should for save work. then remove completly directory
and last step is create this by
svn co/checkout 'URI-for-main-repo' [optionally local directory for store]
you should select connection method to repo file:// svn+ssh:// http:// https:// or other
described in documentation.
after that you use svn update/commit as usual.
this topic looks like out of topic. better you go to superuser pages.
A: I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:
svn switch --relocate \
svn+ssh://olduser@svnserver/path/to/repo \
svn+ssh://newuser@svnserver/path/to/repo
where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.
Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "56"
} |
Q: How to turn off sounds in TortoiseSVN? I do not want TortoiseSVN to alert me with sounds - e.g. when it fails to update.
How do I turn off sounds in TortoiseSVN?
A: Right click > TortoiseSVN > Settings > System Sounds..
Scroll down to the bottom.
A: You can do this from the Sounds panel in Control Panel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best practices with jQuery form binding code in an application We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question.
*
*What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed.
*Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?
A: You should probably look into a framework like knockout.js This way you can just update your models and the forms will update automatically.
A: Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data.
I don't know what more there is to say - writing UI code for the browser in JavaScript is no different than writing UI code for other types of apps, as far as I am concerned. Build classes and instantiate them as needed, populate them with data, have them throw events, etc. etc.
Am I up in the night on this? :)
EDIT: In other words, yes - do what you are doing, for the most part. I see too many novice JavaScript hackers write a bunch of poorly-cohesive functions that don't appear to be a part of anything specific other than they are all in a single file. Hope that makes sense.
A: I think there are multiple challanges for you. The first question is how to structure javascript code, i.e. how to build namespaces so that you don't fight name clashes or have to name your functions like
form1validate
form1aftersubmit
form2validate
form2aftersubmit
One of the proven patterns for modules in javascript is to use an anonymous function to build a new naming scope. The basic idea is shon in the following code
(function() {
var foo = 1;
})();
(function() {
if(foo == 1) alert("namespace separation failed!")
})();
I think this blog entry is a good introduction.
The second question you face is how to avoid all the repetition in javascript code.
You have a couple of weapons against this.
*
*functions - this seams obvious but it's often forgotten to refactor common code into functions where it can be done. In you case this will be functions to copy values from the json response into the forms and like that
*higher order function - or functions as data - or callback, as they are often called in javascript. These are the mightiest weapon in javascript. In case for form and ajax handling you can use callback to avoid repetition in the control flow of your forms.
Let me construct an example out of my head (using jquery for convinence)
// this is a validator for one form
var form1validator = function() {
if($("input[name=name]",this).attr("value").length < 1 &&
$("input[name=organisation]",this).attr("value").length < 1)
return "Either name or organisation required"
}
// and this for a second form
var form2validator = function() {
if($("input[name=age]",this).attr("value").length < 21
return "Age of 21 required"
}
// and a function to display a validation result
var displayResult = function(r) {
$(this).prepend("<span></span>").text(r);
}
// we use them as higher order functions like that
$("#form1").onSubmit(validator(form1validator, displayResult, function() {
//on submit
...send some xhr request or like that
});
$("#form2").onSubmit(validator(form2validator, displayResult, function() {
this.submit() // simply submit form
});
$("#form1b").onSubmit(validator(form1validator, function(r) {
alert("There was an validation error " + r);
}, function() {
//on submit
...send some xhr request or like that
});
// the validator function itself would be defined as
function validator(formValidator, displayResult, onSubmit) {
var r = formValidator.apply(this)
if(typeof(r) === 'undefined')
onSubmit(this)
else
displayResult(r)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How can I generate a unique, small, random, and user-friendly key? A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).
It ended up generating values that looked something like this:
Af3nT5Xf2
Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.
Here's what we ended up doing:
We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.
The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.
I was never satisfied with this particular implementation. What would you guys have done?
A: In .NET you can use the RNGCryptoServiceProvider method GetBytes() which will "fill an array of bytes with a cryptographically strong sequence of random values" (from ms documentation).
byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
You can increase the lengh of the byte array and pluck out the character values you want to allow.
A: In C#, I have used the 'System.IO.Path.GetRandomFileName() : String' method... but I was generating salt for debug file names. This method returns stuff that looks like your first example, except with a random '.xyz' file extension too.
If you're in .NET and just want a simpler (but not 'nicer' looking) solution, I would say this is it... you could remove the random file extension if you like.
A: At the time of this writing, this question's title is:
How can I generate a unique, small, random, and user-friendly key?
To that, I should note that it's not possible in general to create a random value that's also unique, at least if each random value is generated independently of any other. In addition, there are many things you should ask yourself if you want to generate unique identifiers (which come from my section on unique random identifiers):
*
*Can the application easily check identifiers for uniqueness within the desired scope and range (e.g., check whether a file or database record with that identifier already exists)?
*Can the application tolerate the risk of generating the same identifier for different resources?
*Do identifiers have to be hard to guess, be simply "random-looking", or be neither?
*Do identifiers have to be typed in or otherwise relayed by end users?
*Is the resource an identifier identifies available to anyone who knows that identifier (even without being logged in or authorized in some way)?
*Do identifiers have to be memorable?
In your case, you have several conflicting goals: You want identifiers that are—
*
*unique,
*easy to type by end users (including small), and
*hard to guess (including random).
Important points you don't mention in the question include:
*
*How will the key be used?
*Are other users allowed to access the resource identified by the key, whenever they know the key? If not, then additional access control or a longer key length will be necessary.
*Can your application tolerate the risk of duplicate keys? If so, then the keys can be completely randomly generated (such as by a cryptographic RNG). If not, then your goal will be harder to achieve, especially for keys intended for security purposes.
Note that I don't go into the issue of formatting a unique value into a "user-friendly key". There are many ways to do so, and they all come down to mapping unique values one-to-one with "user-friendly keys" — if the input value was unique, the "user-friendly key" will likewise be unique.
A: Here's how I would do it.
I'd obtain a list of common English words with usage frequency and some grammatical information (like is it a noun or a verb?). I think you can look around the intertubes for some copy. Firefox is open-source and it has a spellchecker... so it must be obtainable somehow.
Then I'd run a filter on it so obscure words are removed and that words which are too long are excluded.
Then my generation algorithm would pick 2 words from the list and concatenate them and add a random 3 digits number.
I can also randomize word selection pattern between verb/nouns like
eatCake778
pickBasket524
rideFlyer113
etc..
the case needn't be camel casing, you can randomize that as well. You can also randomize the placement of the number and the verb/noun.
And since that's a lot of randomizing, Jeff's The Danger of Naïveté is a must-read. Also make sure to study dictionary attacks well in advance.
And after I'd implemented it, I'd run a test to make sure that my algorithms should never collide. If the collision rate was high, then I'd play with the parameters (amount of nouns used, amount of verbs used, length of random number, total number of words, different kinds of casings etc.)
A: If by user friendly, you mean that a user could type the answer in then I think you would want to look in a different direction. I've seen and done implementations for initial random passwords that pick random words and numbers as an easier and less error prone string.
If though you're looking for a way to encode a random code in the URL string which is an issue I've dealt with for awhile then I what I have done is use 64-bit encoded GUIDs.
A: You could load your list of words as chakrit suggested into a data table or xml file with a unique sequential key. When getting your random word, use a random number generator to determine what words to fetch by their key. If you concatenate 2 of them, I don't think you need to include the numbers in the string unless "true randomness" is part of the goal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How do you use the new ModelBinder classes in ASP.NET MVC Preview 5 You'll notice that Preview 5 includes the following in their release notes:
Added support for custom model binders. Custom binders allow you to define complex types as parameters to an action method. To use this feature, mark the complex type or the parameter declaration with [ModelBinder(…)].
So how do you go about actually using this facility so that I can have something like this work in my Controller:
public ActionResult Insert(Contact contact)
{
if (this.ViewData.ModelState.IsValid)
{
this.contactService.SaveContact(contact);
return this.RedirectToAction("Details", new { id = contact.ID}
}
}
A: Well I looked into this. ASP.NET provides a common location for registering the implementation of IControlBinders. They also have the basics of this working via the new Controller.UpdateModel method.
So I essentially combined these two concepts by creating an implementation of IModelBinder that does the same thing as Controller.UpdateModel for all public properties of the modelClass.
public class ModelBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
{
object model = Activator.CreateInstance(modelType);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(model);
foreach (PropertyDescriptor descriptor in properties)
{
string key = modelName + "." + descriptor.Name;
object value = ModelBinders.GetBinder(descriptor.PropertyType).GetValue(controllerContext, key, descriptor.PropertyType, modelState);
if (value != null)
{
try
{
descriptor.SetValue(model, value);
continue;
}
catch
{
string errorMessage = String.Format("The value '{0}' is invalid for property '{1}'.", value, key);
string attemptedValue = Convert.ToString(value);
modelState.AddModelError(key, attemptedValue, errorMessage);
}
}
}
return model;
}
}
In your Global.asax.cs you'd need to add something like this:
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Google Talk's Graphics Toolkit? What graphics toolkit is used for the Window's Google Talk application?
A: There isn't much information on this out there but it seems to be their own customized controls plus an IE component (and not Qt like Google Earth). This forum thread has a little bit of information.
A: I'm not positive but I believe it's QT.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: .Net - Detecting the Appearance Setting (Classic or XP?) I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.
Any ideas about how to detect which mode the user is in and re-format the forms on the fly?
Post Answer Edit:
Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.
I'm doing the following:
Function Declaration:
Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
Code Body:
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)
GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.
A: Try using a combination of GetCurrentThemeName (MSDN Page) and DwmIsCompositionEnabled
I linked the first to PInvoke so you can just drop it in your code, and for the second one you can use the code provided in the MSDN comment:
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
See what results you get out of those two functions; they should be enough to determine when you want to use a different theme!
A: Personally, I use the following to see if the app is running under themed:
if (Application.RenderWithVisualStyles)
{
// you're themed
}
A: There's the IsThemeActive WinAPI function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can an audio object be embedded in an InfoPath form? Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form ?
If it is, how do you do it ?
A: @Martin
That works for local forms that open in InfoPath. Nathan was asking about web-enabled forms. ActiveX controls are disabled for web forms, as evidenced by the informational label at the bottom of the design controls when the form compatability has been set to the web.
Now, I will admit that I know nothing about the HTML tags to play audio in a browser, but I have something else that might work. I had an InfoPath form that I needed to dynamically load an image into for a web-enabled form. Similar to the ActiveX issue, the Picture control was also disabled. What I did was put some managed code behind the form and execute the following when the form loaded.
public void FormEvents_Loading(object sender, LoadingEventArgs e)
{
string imgPath = "http://yoursite/yourimage.jpeg";
XPathNodeIterator xpni = MainDataSource.CreateNavigator().SelectSingleNode("/my:FormName/my:RichTextControlName", NamespaceManager).SelectChildren(XPathNodeType.All);
xpni.Current.InnerXml = "<img xmlns=\"http://www.w3.org/1999/xhtml\" src=\"" + filePath + "\" width=\"200px\" height=\"55px\" />";
}
I don't see why you couldn't take the same approach and load audio rather than an image.
A: It looks like you can't embed <object> tags in a richtext field. I'm getting nothing when I do it.
A: Edit: My apologies, I missed that the question was about Web forms - for which the below does not work. Must learn to read the question fully!
*
*Go to menu View
*Click on Design Tasks
*Select Controls in the 'Design Tasks' Task pane
*Click on the 'add or remove custom controls' button to install your custom
control
*Click on the Add button and select ActiveX Control
*Select the Windows Media Player control
*Select the necessary properties for databinding and finish the wizard.
After you have added the control, you can drag and drop the control on your screen.
Right-Click on the control and select the 'Windows Media Player properties'
Fill in the URL to automatically embed the file to play.
A: Have you tried manually modifying the XSL in order to generate HTML which embedds your audio file?
I don't think there is a way to do this using the InfoPath Designer, but if it ends up in the XSL; it may just get passed through to the web enabled form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trouble using JRun to Host Java Servlets I am deploying new versions of java servlets with JRun as the host. I am having difficulty finding good sources for information about JRun and tutorials about how to configure and manage it.
After installing JRun and opening the launcher it can't start the admin server that it creates by default...so obviously I'm running into some issues just getting started.
edit for clarity: I'm not looking for an answer or help with a specific error but if anyone knows of good sources for information about JRun and how to work with it so I can quickly bring myself up to speed on it.
A: Jrun development has pretty much stopped. You should look into running another application server. Jboss or Glassfish are good alternatives.
A: This is probably going to be difficult to resolve unless you post either the error message from the log file or the list of steps that you took so far.
I have JRun 3.1 configured on my machine so maybe I can duplicate your issue if you give us more information.
A: I didn't know JRun was even still in existence since 1999 or something like that. Anyway, Tomcat or Jetty would be my easy replacements. Tomcat for its scriptability from ANT etc and Jetty for its pure simplicity (start an instance in 5 lines of code!).
Glassfish is a huge system with many components, if you just want to host vanilla servlets and JSPs etc. then I would go for one of the above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SharePoint List Scalability I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...?
*
*What is the maximum number of items that a SharePoint list can contain?
*What is the maximum number of lists that a single SharePoint server can host?
*When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it?
A: Link To Resource
A: The whitepaper I found most useful was linked from the resource posted by user mbowles above.
The direct link is...
http://go.microsoft.com/fwlink/?LinkId=95450&clcid=0x409
A: In SharePoint v.2:
*
*Max # list items : 2000 (per folder level)
*Max lists per site : 2000 is a "reasonable" number
*Effect when we reach the limit : Exponential degradation of performance.
More info: http://technet.microsoft.com/en-us/library/cc287743.aspx
In SharePoint v.3:
*
*Max # list items : 2000 (per view, you can have million items as long as you don't display in a single view more than 2000 items)
*Max lists per site : 2000 is a "reasonable" number
*Effect when we reach the limit : Exponential degradation of performance when we enumerate more than 2000 items using the OM. An alternative is to use Search API or CAML queries.
More info: http://technet.microsoft.com/en-us/library/cc287790.aspx
A: http://blah.winsmarts.com/2008-4-SharePoint_limits.aspx
for #3: you can index specific columns in a list, but you should still keep the sizes down.
A: The exact answers have already been given, however I do feel I should add this warning:
This might be one of those situations where if you have to ask, you can't afford it.
So if you find yourself approaching the limits posted earlier, think long and hard about what you are trying to do, and make sure you're not doing it wrong.
A: The "2000 limit" expressed above doesn't hold.
Please take a look at this document for more exact answers to your questions.
I personally experimented what the document describes.
A: SharePoint 2013:
What is the maximum number of items that a SharePoint list can contain? 30.000.000.
What is the maximum number of lists that a single SharePoint server can host? I could not find the answer to this question.
When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it? The maximum of 30.000.000 not a hard boundary, but the limit has been found by testing the product. So a performance penalty is to be expected if this limit is exceeded.
Answers found in Software boundaries and limits for SharePoint 2013.
A: Beware, the Performance of SiteDataQuery degrades heavily he more subsites you have. A hundred subsites can take 20 seconds to query.
A: There is documented guidance for Microsoft® Office SharePoint® Server 2007 regarding the maximum size of lists and list containers. For typical customer scenarios in which the standard Office SharePoint Server 2007 browser-based user interface is used, the recommendation is that a single list should not have more than 2,000 items per list container. A container in this case means the root of the list, as well as any folders in the list — a folder is a container because other list items are stored within it. A folder can contain items from the list as well as other folders, and each subfolder can contain more of each, and so on. For example, that means that you could have a list with 1,990 items in the root of the site, 10 folders that each contain 2,000 items, and so on. The maximum number of items supported in a list with recursive folders is 5 million items.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How do I list the symbols in a .so file How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).
I'm using gcc 4.0.2, if that makes a difference.
A: If your .so file is in elf format, you can use readelf program to extract symbol information from the binary. This command will give you the symbol table:
readelf -Ws /usr/lib/libexample.so
You only should extract those that are defined in this .so file, not in the libraries referenced by it. Seventh column should contain a number in this case. You can extract it by using a simple regex:
readelf -Ws /usr/lib/libstdc++.so.6 | grep '^\([[:space:]]\+[^[:space:]]\+\)\{6\}[[:space:]]\+[[:digit:]]\+'
or, as proposed by Caspin,:
readelf -Ws /usr/lib/libstdc++.so.6 | awk '{print $8}';
A: The standard tool for listing symbols is nm, you can use it simply like this:
nm -gD yourLib.so
If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled).
nm -gDC yourLib.so
If your .so file is in elf format, you have two options:
Either objdump (-C is also useful for demangling C++):
$ objdump -TC libz.so
libz.so: file format elf64-x86-64
DYNAMIC SYMBOL TABLE:
0000000000002010 l d .init 0000000000000000 .init
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free
0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location
0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable
Or use readelf:
$ readelf -Ws libz.so
Symbol table '.dynsym' contains 112 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000002010 0 SECTION LOCAL DEFAULT 10
2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)
4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
A: nm -g list the extern variable, which is not necessary exported symbol.
Any non-static file scope variable(in C) are all extern variable.
nm -D will list the symbol in the dynamic table, which you can find it's address by dlsym.
nm --version
GNU nm 2.17.50.0.6-12.el5 20061020
A: objdump -TC /usr/lib/libexample.so
A: For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux
nm -D libNAME.so
and for static library as reported by others
nm -g libNAME.a
A: I kept wondering why -fvisibility=hidden and #pragma GCC visibility did not seem to have any influence, as all the symbols were always visible with nm - until I found this post that pointed me to readelf and objdump, which made me realize that there seem to actually be two symbol tables:
*
*The one you can list with nm
*The one you can list with readelf and objdump
I think the former contains debugging symbols that can be stripped with strip or the -s switch that you can give to the linker or the install command. And even if nm does not list anything anymore, your exported symbols are still exported because they are in the ELF "dynamic symbol table", which is the latter.
A: For C++ .so files, the ultimate nm command is nm --demangle --dynamic --defined-only --extern-only <my.so>
# nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add
0000000000049500 T proton::work_queue::add(proton::internal::v03::work)
0000000000049580 T proton::work_queue::add(proton::void_function0&)
000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)
000000000002b1f0 T proton::container::impl::add_work_queue()
000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)
000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)
source: https://stackoverflow.com/a/43257338
A: If you just want to know if there are symbols present you can use
objdump -h /path/to/object
or to list the debug info
objdump -g /path/to/object
A: For Android .so files, the NDK toolchain comes with the required tools mentioned in the other answers: readelf, objdump and nm.
A: You can use the nm -g tool from the binutils toolchain. However, their source is not always readily available. and I'm not actually even sure that this information can always be retrieved. Perhaps objcopy reveals further information.
/EDIT: The tool's name is of course nm. The flag -g is used to show only exported symbols.
A: Try adding -l to the nm flags in order to get the source of each symbol. If the library is compiled with debugging info (gcc -g) this should be the source file and line number. As Konrad said, the object file / static library is probably unknown at this point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "595"
} |
Q: Best Way to Reuse Code When Using Visual Studio? I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways:
*
*I have tried bringing the projects I need from this code library into my project.
*I have also tried compiling down to a .dll and referencing the .dll from a folder in the root of my current solution.
While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project.
I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions?
A: In short, what you are doing is right, you want to move the common code into a class library (DLL) and then reference that in any projects that require its logic.
Where you are going wrong is that you are not maintaining it. If you need to make little "tweaks", subclass your existing code and extend it, dont change it.. If there are major changes needed, then re-think the design.
A: I have done it both ways that you mentioned. I like the second, but like you said, it is a little tedious for when you make updates to that library.
Another way that I have used, is choosing a central location to keep your libraries. Then add a registry key with a string value to point to that directory. When adding a reference, all your libraries will show up under the .net tab, just like if the libraries were in the GAC. Then you can make a post build command to build the library to that central location.
Here's the registry key, change CompanyName and the directory:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\ComapnyName]
@="C:\\CentralLocation"
A: I like to write all of my generic classes as just that: generics. I keep them as application independent as possible, and try to keep them even type unaware. If I make a fancy Tree class, I'll use generics to create it as Tree<T> so that I can use any type I want with the class. If I need to use the Tree to hold GameCharacter objects, I can instantiate Tree<GameCharacter> but if I'm writing a business application I can use it as Tree<Spreadsheet>.
If you find yourself changing your Reuse Libary to match your projects, try making them less specific and instead deriving from your Library base classes in your actual projects. Put all of the common logic in the library classes, and for the application specific parts, create a derived class and implement their logic in that derived class.
As far as solution organization goes, I keep the Reuse Library as a separate project in a common folder and include the project in any solution that I create, which lets me reference easily into it, but also make any changes from any of my applications' solutions.
A: I don't use Visual Studio or .NET, but it think this problem is common enough amongst ALL programmers so I guess I'll take a crack at it.
We've run into problems just like this when we try to extract common code into a separate library. It might be OK at first, but eventually 1 client is going to need some new functionality and require a change to the library. Invariably this leads to problems with some of the other clients, creating a huge mess. Unless you've got a good way to version your library file, this is a tough problem to solve.
In the end, you might be better off just copying-and-pasting the source files into your new project. Yes, this violates the DRY (Don't Repeat Yourself) principle, but you avoid a lot of problems related to the dependencies a common library creates.
A: What you really need to do is to use some sort of source control software such that:
*
*Any change that you do in one project will reflect across all projects without loss of referential integrity
*You may have the option to keep more than one version of the library you have and reference a specific version instead of pulling hairs figuring out which version is used by which project
Just make sure that you have unit tests in hand to make sure that your previous projects are unaffected or only minorly affected by any changes you make on your library.
Goodluck!
A: @Outlaw
If you need to copy code and make application-specific changes, then that code isn't generic. it should be refactored so that the common functionality stays in the common library, and the application specific functionality should be added to a subclass in that application's codebase.
Using version control with a branch for each app-specific version can help with integration problems - make your changes in the branch, then test them with your other applications before merging them back to trunk. There are several questions on this site about good free online source control hosts if you don't want to set up your own.
A: Some really good re-usable code is in Ayende Rahien's Rhino Tools. Take a peek at not only how he implements various common code, but how it is organized.
A: The idea is good - put your code in a common dll and refer to it. We use this method extensively and it works. Obviously some projects will get out-of-sync eventually so the way we do it is this:
*
*Be least specific, if you can use generic types then do so. For example, if you want a function that handles nulls or nothing values and
returns something, implementing NullConvert(o as object, subst as object) as object is better than NullConvert(o as object, String) as
String. Then you can add other types leaving the signature intact. BUT, if a type is not handled, be specific within the method and raise exceptions for unhandled types - don't leave it to chance that it works. In the example above, examine the type of the return value and check if your implementation handles that type.
*
*Group functions by type in your namespace; MyGeneric.DateFns, MyGeneric.StringFns, MyGeneric.Comms, etc.
*Don't change functionality once a class or method is used and it might not be safe to do so. Mark them as Deprecated and include comments to indicate where a newer / better class has been placed.
*You might consider two or more libraries, for example, Common Methods and Classes in a base library, and domain specific classes and
functions that use common methods (from the base library) in another library (at a higher level). That way, the base library will not need to change all the time.
*
*Consider the use of "Implementations" instead of classes. If you have a function that processes an ArrayList for example, set the
parameter of your method to take iList instead. Then you can use other list types too, as long as they implement iList inside them.
*
*Avoid introducing specifics, for example, an explicit driver (Oracle 8.x). Wrap that up in something else so if it changes, change the
internals of the wrapper object, not the object itself.
*
*Learn how to use reflection. Let's say you need a function to get Distinct values from an array of objects. You may use reflection and
then pass the property name/s you need to get distinct for; GetDistinct(MyList as iList, "Name") as List(of String). Your code may look at
the parameter called 'Name' through reflection (there's a small performance penalty involved).
*
*Learn how to write Extensions (Component Model). For example if you are writing a function to always return a sepcifically formatted
date, turn the function into an extension function. Name wisely, if your company's name is ABC then use ABCDateFormat for example, to distinguish between your and MS functions for example.
There's too much one should do to be listed here. Your's is a step in the right direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using a rotary encoder with AVR Micro controller I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical ALPS encoder, and I'm using Atmega168.
Clarification
I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high.
I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either.
I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes.
A: Adding an analog lowpass filter greatly improves the signal. With the lowpass filter, the code on the AVR was really simple.
_________
| |
| Encoder |
|_________|
| | |
| | |
100n | O | 100n
GND O-||-+ GND +-||-O GND
| |
\ /
3K3 / \ 3K3
\ /
| |
VCC O-/\/-+ +-\/\-O VCC
15K | | 15K
| |
O O
A B
Ah, the wonders of ASCII art :p
Here is the program on the AVR. Connect A and B to input PORTB on the avr:
#include <avr/io.h>
#define PIN_A (PINB&1)
#define PIN_B ((PINB>>1)&1)
int main(void){
uint8_t st0 = 0;
uint8_t st1 = 0;
uint8_t dir = 0;
uint8_t temp = 0;
uint8_t counter = 0;
DDRD = 0xFF;
DDRB = 0;
while(1){
if(dir == 0){
if(PIN_A & (!PIN_B)){
dir = 2;
}else if(PIN_B & (!PIN_A)){
dir = 4;
}else{
dir = 0;
}
}else if(dir == 2){
if(PIN_A & (!PIN_B)){
dir = 2;
}else if((!PIN_A) & (!PIN_B)){
counter--;
dir = 0;
}else{
dir = 0;
}
}else if(dir == 4){
if(PIN_B & (!PIN_A)){
dir = 4;
}else if((!PIN_A) & (!PIN_B)){
counter++;
dir = 0;
}else{
dir = 0;
}
}else if(PIN_B & PIN_A){
dir = 0;
}
PORTD = ~counter;
}
return 0;
}
This code works unless you rotate the encoder really fast. Then it might miss a step or two, but that is not important, as the person using the encoder won't know how many steps they have turned it.
A: I have a webpage about rotary encoders and how to use them, which you might find useful.
Unfortunately without more information I can't troubleshoot your particular problem.
Which microcontroller pins are connected to the encoder, and what is the code you're currently using to decode the pulses?
Ok, you're dealing with a few different issues, the first issue is that this is a mechanical encoder, so you have to deal with switch noise (bounce, chatter). The data sheet indicates that it may take up to 3mS for the parts to stop bouncing and creating false outputs.
You need to create a debounce routine. The simplest of which is to continuously check to see if A goes high. If it does, start a timer and check it again in 3 ms. If it's still high, then you can check B - if it's not high then you ignore the spurious pulse and continue looking for A high. When you check B, you look at it, start a timer for 3 ms, and then look at B again. If it was the same both times, then you can use that value - if it changes within 3 ms then you have to do it again (read B, wait 3 ms, then read it again and see if it matches).
The atmega is fast enough that you shouldn't have to worry about these checks going slowly, unless you're also running a slow clock speed.
Once you deal with the mechanical noise, then you want to look at a proper gray code routine - the algorithm you're following won't work unless you also decrement if A is high when B goes low. Generally people store the last value of the two inputs, and then compare it to the new value of the two inputs and use a small function to increment or decrement based on that. (Check out the heading "high resolution reading" on the website I mentioned above for the table). I combine the two readings into a four bit number and use a simple array to tell me whether I increment or decrement the counter, but there are solutions that are even more advanced, and optimize for code size, speed, or ease of code maintenance.
A: Speed should not be a problem. Mostly all mechanical switches need debounce routines. If you wanna do this with interrupts turn off the interrupt when it triggers, start a timer that will turn it back on after a couple of ms. Will keep your program polling-free >:)
A: What exactly are you having problems with? I assume you've been able to hook the pins of the encoder to your PIC as per the technical specifications linked on the Farnell page you gave, so is the problem with reading the data? Do you not get any data from the encoder? Do you not know how to interpret the data you're getting back?
A: /* into 0 service rutine */
if(CHB)
{
if(flagB)
Count++;
FlagB=0;
}
else
{
if(FlagB)
count--:
FlagB=0:
}
/* into 1 service rutine */
FlagB=1;
/* make this give to you a windows time of 1/4 of T of the encoder resolution
that is in angle term: 360/ (4*resolution)
*/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Setting a form's action in .net 3.5 SP1 causes errors when compiled I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:
<form id="theForm" runat="server" action="post.aspx">
I received this error.
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'.
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this?
A: .NET 3.5 SP1 tries to use the action="" attribute (.NET 3.5 RTM did not). So, when you deploy, your code is attempting to set the HtmlForm.Action property and failing, as the System.Web.dll on the deploy target is RTM and does not have a setter on the property.
A: I don't know the specific solution, but HtmlForm.set_Action() is a function the compiler creates that acts as the setter for a property called Action.
When you do:
public String Action { set { DoStuff(); } }
The set code actually becomes a function called set_Action.
I know it's not the best answer, but I hope it helps you find the source of your problems!
A: I just ran into the same problem.
From what I understood it is indeed caused by the fact the my PC has .NET 3.5 SP1 on it, and the server to which I deployed the project doesn't.
From what I understand, one solution is that the server be updated with .NET 3.5 SP1. As I don't want to do that yet, I just removed the "action" attribute from all the forms in the project, and that solved the problem.
Read more
A: All mentioned above is true...
In fact, when one installs 3.5 SP1, it automatically updates 2.0 and 3.0 with their own SP2.
So, if you are using 2.0 for an application, you'll get the error.
In addition, SP1 on .Net2.0 did not cause the problem.
A: There is another solution to this.
Write a JavaScript that would set the action of the form to the expected URL at Page_Load and register the script at page load.
A: It is enough to install Framework 3.6 sp1 which does work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do you build a ratings implementation? We have need for a "rating" system in a project we are working on, similar to the one in SO. However, in ours there are multiple entities that need to be "tagged" with a vote up (only up, never down, like an increment). Sometimes we will need to show all of the entities in order of what is rated highest, regardless of entity type, basically mixing the result sets, I guess. What data structures / algorithms do you use to implement this so that is flexible and still scalable?
A: Since reddit's ranking algorithm rocks, it makes very much sense to have a look at it, if not copy it:
Given the time the entry was posted A and the time of 7:46:43 a.m. December 8, 2005 B we have ts as their difference in seconds:
ts = A - B
and x as the difference between the number of up votes U and the number of down votes D:
x = U - D
Where
y = 1 if x > 0
y = 0 if x = 0
y = -1 if x < 0
and z as the maximal value of the absolute value of x and 1:
z = |x| if |x| >= 1
z = 1 if |x| < 1
we have the rating as a function ƒ(ts, y, z):
ƒ(ts, y, z) = log10 z + (y • ts)/45000
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Mercurial .hgignore for Visual Studio 2008 projects What is a good setup for .hgignore file when working with Visual Studio 2008?
I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.
I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?
Thanks!
p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.
# regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
A: My Mercurial .hgignore file contents:
syntax: glob
#-- Files
*.bak.*
*.bak
thumbs.db
#-- Directories
App_Data/*
bin/
obj/
_ReSharper.*/
tmp/
#-- Microsoft Visual Studio specific
*.user
*.suo
#-- MonoDevelop specific
*.pidb
*.userprefs
*.usertasks
Keep in mind that I mainly work on WinForms, ASP.NET MVC and Mobile projects using Microsoft Visual Studio and occasionally MonoDevelop. Depending on your toolset and project types, you will probably encounter other files that should be ignored.
I try to keep the latest version on CodePaste.NET at http://codepaste.net/zxov7i
A: some others I use:
output
PrecompiledWeb
_UpgradeReport_Files
#Guidance Automation Toolkit
*.gpState
#patches
*.patch
A: This is specific to a C# project, but I ignore these files/directories:
*
**.csproj.user
*/obj/*
*/bin/*
**.ncb
**.suo
I have no problems running the code in the depot on other machines after I ignore all of these files. The easiest way to find out what you need to keep is to make a copy of the folder and start deleting things you think aren't necessary. Keep trying to build, and as long as you can build successfully keep on deleting. If you delete too much, copy it from the source folder.
In the end you'll have a nice directory full of the only files that have to be committed.
A: Here are a couple pesky ones: Matlab and Excel/Office autosaves.
# use glob syntax
syntax: glob
# Matlab ignore files
*.asv
# Microsoft Office
~$*
If I accidentally add them and then close the real file that was open, Excel and/or Matlab will delete the auto-save and then Mercurial will be stuck wondering where they went. I'm sure there are other programs that do similar things.
A: I feel left out of the conversation. Here's my .hgignore file. It covers C#, C++ and Visual Studio development in general, including COM stuff (type libraries), some final builder files, CodeRush, ReSharper, and Visual Studio project upgrades. It also has some ignores for modern (c.2015) web development.
syntax: glob
* - [Cc]opy
* - [Cc]opy/
* - [Cc]opy (?)/
* - [Cc]opy.*
* - [Cc]opy (?).*
**/.*
**/scss/*.css
*.*scc
*.FileListAbsolute.txt
*.aps
*.bak
*.bin
*.[Cc]ache
*.clw
*.css.map
*.eto
*.exe
*.fb6lck
*.fbl6
*.fbpInf
*.ilk
*.lib
*.log
*.ncb
*.nlb
*.nupkg
*.obj
*.old
*.orig
*.patch
*.pch
*.pdb
*.plg
*.[Pp]ublish.xml
*.rdl.data
*.sbr
*.scc
*.sig
*.sqlsuo
*.suo
*.svclog
*.tlb
*.tlh
*.tli
*.tmp
*.user
*.vshost.*
*.docstates
*DXCore.Solution
*_i.c
*_p.c
__MVC_BACKUP/
_[Rr]e[Ss]harper.*/
_UpgradeReport_Files/
Ankh.Load
Backup*
[Bb]in/
bower_components/
[Bb]uild/
CVS/
[Dd]ebug/
[Ee]xternal/
hgignore[.-]*
ignore[.-]*
lint.db
node_modules/
[Oo]bj/
[Pp]ackages/
PrecompiledWeb/
[Pp]ublished/
[Rr]elease/
svnignore[.-]*
[Tt]humbs.db
UpgradeLog*.*
A: Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file:
# Ignore file for Visual Studio 2008
# use glob syntax
syntax: glob
# Ignore Visual Studio 2008 files
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
*.lib
*.sbr
*.scc
[Bb]in
[Dd]ebug*/
obj/
[Rr]elease*/
_ReSharper*/
[Tt]est[Rr]esult*
[Bb]uild[Ll]og.*
*.[Pp]ublish.xml
A: Here is the content of my .hgignore for C# Visual Studio projects:
syntax: glob
*.user
*.ncb
*.nlb
*.suo
*.aps
*.clw
*.pdb
*\Debug\*
*\Release\*
A few notes:
*
*If you have custom "releases"
besides "Debug" and "Release", you
may need to add them.
*Be careful when you manually edit your
.hgignore. If you make a syntax
error, then hgtortoise will no
longer open the commit dialog.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "166"
} |
Q: duplicating jQuery datepicker The datepicker function only works on the first input box that is created.
I'm trying to duplicate a datepicker by cloning the div that is containing it.
<a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
To initialize the datepicker, according to the jQuery UI documentation I only have to do $('#example').datepicker(); and it does work, but only on the first datepicker that is created.
The code to duplicate the div is the following:
$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
The strangest thing is that on the document.ready I have:
$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
and if I click on the #txt it always works.
A: I'd recommend just using a common class name as well. However, if you're against this for some reason, you could also write a function to create date pickers for all text boxes in your template div (to be called after each duplication). Something like:
function makeDatePickers() {
$("#template input[type=text]").datepicker();
}
A: I had a very similar problem which after hours of testing I found a solution. I was copying a block of HTML code and inserting it after a section that already contained a jQuery date picker calendar. What I failed to realize at first was the jQuery UI calendar modifies the class of the element when executing the .datepicker() function. The result is when you try to copy the code and initiate a new instance of the calendar for that new section it fails because the according to the CSS there already is one. If you attempt to use .datepicker('destroy') this fails to destroy this ghost instance because it doesn't actually exist. I solved the problem by resetting the class of the date picker element in my HTML then adding the datepicker to that element...
Below is the code I was using. Hopefully this saves someone else some time...
$('#addaddress').click(function() {
var count = $('.address_template').size();
var html = $('.address_template').eq(0).html();
$('#addaddress').before('<div class="address_template">' + html + '</div>');
$('.address_template H1').eq(count).html("Previous Address " + count);
$('.address_date').eq(count).attr("class","address_date");
$('.address_date').eq(count).attr("id","movein" + count);
$("#movein" + count).datepicker();
});
A: I use a CSS class instead:
<input type="text" id="BeginDate" class="calendar" />
<input type="text" id="EndDate" class="calendar" />
Then, in your document.ready function:
$('.calendar').datepicker();
Using it that way for multiple calendar fields works for me.
A: The html I am cloning has multiple datepicker inputs.
Using Ryan Stemkoski's answer and Alex King's comment, I came up with this solution:
var clonedObject = this.el.find('.jLo:last-child')
clonedObject.find('input.ui-datepicker').each(function(index, element) {
$(element).removeClass('hasDatepicker');
$(element).datepicker();
});
clonedObject.appendTo('.jLo');
Thanks yall.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Entire Page refreshes even though gridview is in an update panel I have a gridview that is within an updatepanel for a modal popup I have on a page.
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.
Does any one know what I am missing.
Edit: I entered a better solution at the bottom
A: Make sure you have the following set on the UpdatePanel:
ChildrenAsTriggers=false and UpdateMode=Conditional
A: do you have ChildrenAsTriggers="false" on the UpdatePanel?
Are there any javascript errors on the page?
A: I had this problem and came across the following article:
http://bloggingabout.net/blogs/rick/archive/2008/04/02/linkbutton-inside-updatepanel-results-in-full-postback-updatepanel-not-triggered.aspx
My button wasn't dynamically created in the code like in this example, but when I checked the code in the aspx sure enough it was missing an ID property. On adding the ID the postback became asynchronous and started to behave as expected.
So, in summary, check your button has an ID!
A: Are you testing in Firefox or IE? We have a similar issue where the entire page refreshes in Firefox (but not IE). To get around it we use a hidden asp:button with the useSubmitBehavior="false" set.
<asp:Button ID="btnRefresh" runat="server" OnClick="btnRefresh_Click" Style="display: none" UseSubmitBehavior="false" />
A: Several months later this problem was fixed. The project I was working in was a previous v1.1 which was converted with 2.0. However, in the web.config this line remained:
<xhtmlConformance mode="Legacy"/>
When it was commented out all of the bugs that we seemed to have with the ajax control toolkit disappeared
A: Is the Modal Window popped up using the IE Modal window? Or is it a DIV that you are showing?
If it is an IE Modal Pop up you need to ensure you have
<base target="_self" />
To make sure the post back are to the modal page.
If it is a DIV make sure you have your XHTML correct or it might not know what to update.
A: I would leave the onClick and set it as the trigger for the updatePanel.
That's odd that it works in FF and not IE. That is opposite from the behavior we experience.
A: UpdatePanels can be sensitive to malformed HTML. Do a View Source from your browser and run it through something like the W3C validator to look for anything weird (unclosed div or table being the usual suspects)
If you use Firefox, there's a HTML validator Extension/AddOn available that works quite nicely.
A: For reference..
I've also noticed, when using the dreaded <asp:UpdatePanel ... /> and <asp:LinkButton ... />, that as well as UpdateMode="Conditional" on the UpdatePanel the following other changes are required:
*
*ViewStateMode="Enabled" is required on <asp:Content ... /> (I've set it to Disabled in the MasterPage)
*ClientIDMode="Static" had to be removed from <%@ Page ... />
A: To prevent post-backs add return false to the onclick event.
button.attribute.add("onclick","return false;");
Sample:
string PopupURL = Common.GetAppPopupPath() + "Popups/StockChart.aspx?s=" + symbol;
hlLargeChart.Attributes.Add("onclick", String.Format("ShowPopupStdControls(PCStockChartWindow,'{0}');return false;", PopupURL));
A: In my case this works for me:
change in the web.config
<xhtmlConformance mode="Transitional"/>
'default.aspx
asp:GridView ID="GridView1" runat="server" Width="940px"
HorizontalAlign="Center"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false"
AllowPaging="true" PageSize="5"
DataKeyNames="idarea" CssClass="table table-hover table-striped"
OnPageIndexChanging="GridView1_PageIndexChanging"
'default.aspx.vb
Protected Sub GridView1_PageIndexChanging(sender As Object, e As
GridViewPageEventArgs) Handles GridView1.PageIndexChanging
BindGrid()
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub
Thanks for tip.
Luis Palencia
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ValidationRule To Enforce Unique Name I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?
A: First, I'd create a simple DependencyObject class to hold your collection:
class YourCollectionType : DependencyObject {
[PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]
}
Then, on your ValidationRule-derived class, create a property:
YourCollectionType ListToCheck { get; set; }
Then, in the XAML, do this:
<Binding.ValidationRules>
<YourValidationRule>
<YourValidationRule.ListToCheck>
<YourCollectionType BoundList="{Binding Path=TheCollectionYouWantToCheck}" />
</YourValidationRule.ListToCheck>
</YourValidationRule>
</Binding.ValidationRules>
Then in your validation, look at ListToCheck's BoundList property's collection for the item that you're validating against. If it's in there, obviously return a false validation result. If it's not, return true.
A: I would only create a custom dependency object if there were other properties I wanted to bind to the rule. Since in this case all we're doing is attaching a single collection of values to check against, I made my <UniqueValueValidationRule.OtherValues> property a <CollectionContainer>.
From there, to get past the problem of the DataContext not being inherited, <TextBox.Resources> needed to have a <CollectionViewSource> to hold the actual binding and give it a {StaticResource} key, which OtherValues could then use as binding source.
The validation rule itself then need only loop through OtherValues.Collection and perform equality checks.
Observe:
<TextBox>
<TextBox.Resources>
<CollectionViewSource x:Key="otherNames" Source="{Binding OtherNames}"/>
</TextBox.Resources>
<TextBox.Text>
<Binding Path="Name">
<Binding.ValidationRules>
<t:UniqueValueValidationRule>
<t:UniqueValueValidationRule.OtherValues>
<CollectionContainer Collection="{Binding Source={StaticResource otherNames}}"/>
</t:UniqueValueValidationRule.OtherValues>
</t:UniqueValueValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Class design decision I have a little dilemma that maybe you can help me sort out.
I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not.
What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned.
Having said that, my problem has nothing to do with it, it's a generic class design issue.
I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description.
I can think of the following scenarios:
*
*Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer.
*Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it.
*Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation.
I think the best option is the third one...
How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think...
A: I feel the best combination of DRYness and forcing the contract is as follows (in pseudocode):
class Base {
public final constructor(name) {
constructor(name, null)
end
public abstract constructor(name, description);
}
or, alternatively:
class Base {
public abstract constructor(name);
public final constructor(name, description) {
constructor(name)
this.set_description(description)
}
private final set_description(description) {
...
}
}
There's a rule in Java that supports this decision: "never call non-final methods from a constructor."
A: To answer the first part of your post, check out AzMan (Authorization Manager), which, incidentally, is built into windows. It has the capability to specify operations which can be recombined into roles or assigned directly to users.
Check out
To answer the second part of your question, I wouldn't use an Abstract class. Instead just provide the functionality in the constructor and be done with it. It appeasr you want the specified behavior, and you don't want it to change. Why force descendents to provide the implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to tell if an object is modified? I have an object that is mapped to a cookie as a serialized base-64 string. I only want to write out a new cookie if there are changes made to the object stored in the cookie on server-side.
What I want to do is get a hash code when the object is pulled from the cookie/initialized and compare the original hash code to the hash code that exists just before I send the cookie header off to the client to ensure I don't have to re-serialize/send the cookie unless changes were made.
I was going to override the .NET's Object.GetHashCode() method, but I wasn't sure that this is the best way to go about checking if an object is modified.
Are there any other ways I can check if an object is modified, or should I override the GetHashCode() method.
Update I decided to accept @rmbarnes's answer as it had an interesting solution to the problem, and because I decided to use his advice at the end of his post and not check for modification. I'd still be interested to hear any other solutions anyone may have to my scenario however.
A: GetHashCode() should always be in sync with Equals(), and Equals() isn't necessarily guaranteed to check for all of the fields in your object (there's certain situations where you want that to not be the case).
Furthermore, GetHashCode() isn't guaranteed to return unique values for all possible object states. It's conceivable (though unlikely) that two object states could result in the same HashCode (which does, after all, only have an int's worth of possible states; see the Pigeonhole Principle for more details).
If you can ensure that Equals() checks all of the appropriate fields, then you could possibly clone the object to record its state and then check it with Equals() against the new state to see if its changed.
BTW: Your mention of serialization gave me an idea. You could serialize the object, record it, and then when you check for object changing, repeat the process and compare the serialized values. That would let you check for state changes without having to make any code changes to your object. However, this isn't a great solution, because:
*
*It's probably very inefficient
*It's prone to serialization changes in the object; you might get false positives on the object state change.
A: At the end of the object's constructor you could serialize the object to a base 64 string just like the cookie stores it, and store this in a member variable.
When you want to check if the cookie needs recreating, re - serialize the object and compare this new base 64 string against the one stored in a member variable. If it has changed, reset the cookie with the new value.
Watch out for the gotcha - don't include the member variable storing the base 64 serialization in the serialization itself. I presume your language uses something like a sleep() function (is how PHP does it) to serialize itself, so just make sure the member is not included in that function.
This will always work because you are comparing the exact value you'd be saving in the cookie, and wouldn't need to override GetHashCode() which sounds like it could have nasty consequences.
All that said I'd probably just drop the test and always reset the cookie, can't be that much overhead in it when compared to doing the change check, and far less likelyhood of bugs.
A: I personally would say go with the plan you have.. A good hash code is the best way to see if an object is "as-is".. Theres tons of hashing algorithms you can look at, check out the obvious Wikipedia page on hash functions and go from there..
Override GetHashCode and go for it! Just make sure ALL the elements of the information make up part of the hash :)
A: Seems odd to me why you'd want to store the same object both server side and client side - especially if you're comparing them on each trip.
I'd guess that deserializing the cookie and comparing it to the server side object would be equivalent in performance to just serializing the object again.
But, if you wanted to do this, I'd compare the serialized server side object with the cookie's value and update accordingly. Worst case, you did the serialization for naught. Best case, you did a string compare.
The alternative, deserializing and comparing the objects, has a worst case of deserializing, comparing n fields, and then serializing. Best case is deserializing and comparing n fields.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: SQL Server - Does column order matter? In terms of performance and optimizations:
*
*When constructing a table in SQL Server, does it matter what order I put the columns in?
*Does it matter if my primary key is the first column?
*When constructing a multi-field index, does it matter if the columns are adjacent?
*Using ALTER TABLE syntax, is it possible to specify in what position I want to add a column?
*
*If not, how can I move a column to a difference position?
A: In SQL Server 2005, placement of nullable variable length columns has a space impact - placing nullable variable size columns at the end of the definition can result in less space consumption.
SQL Server 2008 adds the "SPARSE" column feature which negates this difference.
See here.
A: I would say the answer to all those questions is NO, altough my experience with MS-SQL goes as far as SQL2000. Might be a different story in SQL2005
A: For the fourth bullet: No you can't specify where you want to add the column. Here is the syntax for ALTER TABLE: https://msdn.microsoft.com/en-us/library/ms190273.aspx
In MySQL they offer an ALTER TABLE ADD ... AFTER ... but this doesn't appear in T-SQL.
If you want to reorder the columns you'll have to rebuild the table.
Edit: For your last last bullet point, you'll have to DROP the table and recreate it to reorder the columns. Some graphical tools that manipulate SQL databases will do this for you and make it look like you're reordering columns, so you might want to look into that.
A: No to the first 3 because the index will hold the data and no the last once also
A: Column order does not matter while creating a table. We can arrange the columns while retrieving the data from the database. Primary key can be set to any column or combination of columns.
A: For the first bullet:
Yes, column order does matter, at least if you are using the deprecated BLOBs image, text, or ntext, and using SQL Server <= 2005.
In those cases, you should have those columns at the 'end' of the table, and there is a performance hit every time you retrieve one.
If you're retrieving the data from such a table using a DAL, this is the perfect place for the Lazy Load pattern.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank When using a Zend_Form, the only way to validate that an input is not left blank is to do
$element->setRequired(true);
If this is not set and the element is blank, it appears to me that validation is not run on the element.
If I do use setRequired(), the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the Zend_Validate_NotEmpty class, but this is a bit hacky.
I would ideally like to be able to use my own class (derived from Zend_Validate_NotEmpty) to perform the not empty check.
A: I did it this way (ZF 1.5):
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Full Name: ')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator($MyNotEmpty);
so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file):
$MyNotEmpty = new Zend_Validate_NotEmpty();
$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);
hope this helps...
A: By default, setRequired(true) tells isValid() to add a NonEmpty validation if one doesn't already exist. Since this validation doesn't exist until isValid() is called, you can't set the message.
The easiest solution is to simply manually add a NonEmpty validation before isValid() is called and set it's message accordingly.
$username = new Zend_Form_Element_Text('username');
$username->setRequired(true)
->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!')));
A: Add a NotEmpty validator, and add your own message:
// In the form class:
$username = $this->createElement('text', 'username');
$username->setRequired(); // Note that this seems to be required!
$username->addValidator('NotEmpty', true, array(
'messages' => array(
'isEmpty' => 'my localized err msg')));
Note that the NotEmpty validator doesn't seem to be triggered unless you've also called setRequired() on the element.
In the controller (or wherever), call $form->setTranslator($yourTranslator) to localize the error message when it's printed to the page.
A: Change the error message.
A: As far as I can see Changing the error message has no way of changing the message of a specific error. Plus the manual makes it look like like this is a function belonging to Zend_Form, but I get method not found when using it on an instance of Zend_Form.
And example of the useage would be really great.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:
public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName))
.List<Customer>();
}
I am calling Session.Flush() at the end of the HttpRequest, and I get a HibernateAdoException. NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the flush, the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing?
Here's the code from the exception:
[SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?]
No parameters are showing as being passed.
A: Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have not changed any fields since you read the entity from the database.
The following sequence explains why this happens:
*
*NHibernate retrieves raw entity's data from DB using ADO.NET
*NHibernate constructs the entity and sets its properties
*If DB field contained NULL the property will be set to the defaul value for its type:
*
*properties of reference types will be set to null
*properties of integer and floating point types will be set to 0
*properties of boolean type will be set to false
*properties of DateTime type will be set to DateTime.MinValue
*etc.
*Now, when transaction is committed, NHibernate compares the value of the property to the original field value it read form DB, and since the field contained NULL but the property contains a non-null value, NHibernate considers the property dirty, and forces an update of the enity.
Not only this hurts performance (you get extra round-trip to DB and extra update every time you retrieve the entity) but it also may cause hard to troubleshoot errors with DateTime columns. Indeed, when DateTime property is initialized to its default value it's set to 1/1/0001. When this value is saved to DB, ADO.NET's SqlClient can't convert it to a valid SqlDateTime value since the smallest possible SqlDateTime is 1/1/1753!!!
The easiest fix is to make the class property use Nullable type, in this case "DateTime?". Alternatively, you could implement a custom type mapper by implementing IUserType with its Equals method properly comparing DbNull.Value with whatever default value of your value type. In our case Equals would need to return true when comparing 1/1/0001 with DbNull.Value. Implementing a full-functional IUserType is not really that hard but it does require knowledge of NHibernate trivia so prepare to do some substantial googling if you choose to go that way.
A: I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping?
A: I also experienced this problem in NH 2.0.1 when trying to hide the inverse ends of many-to-many bags using access="noop" (hint: this doesn't work).
Converting them to access="field" + adding a field on the class fixed the problem. Pretty hard to track them down though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: How to benchmark a SQL Server Query? I'd like to know the standard way to benchmark a SQL Sever Query, preferably I'd like to know about the tools that come with SQL Server rather than 3rd Party tools.
A: set showplan_text on
will show you the execution plan (to see it graphically use CTRL + K (sql 2000) or CTRL + M (sql 2005 +)
set statistics IO on
will show you the reads
set statistics time on
will show you the elapsed time
A: Use SQL Profiler.
For .NET applications, filter that Application name by '.NET%' and you'll omit other extraneous queries.
A: +1 on the execution plan. From here you can see where all the time is being spent in your particular query. Eg. 85% of the time is spent table scanning a particular table, can you put an index on that table to improve it? etc etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do you create optional arguments in php? In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads:
string date ( string $format [, int $timestamp = time() ] )
Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value.
How do you go about creating optional parameters like this when defining a custom function in PHP?
A: Starting with 7.1 there is a type hinting for nullable parameters
function func(?Object $object) {}
It will work for these cases:
func(null); //as nullable parameter
func(new Object()); // as parameter of declared type
But for optional value signature should look like.
function func(Object $object = null) {} // In case of objects
function func(?Object $object = null) {} // or the same with nullable parameter
function func(string $object = '') {} // In case of scalar type - string, with string value as default value
function func(string $object = null) {} // In case of scalar type - string, with null as default value
function func(?string $object = '') {} // or the same with nullable parameter
function func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value
function func(int $object = null) {} // In case of scalar type - integer, with null as default value
function func(?int $object = 0) {} // or the same with nullable parameter
than it can be invoked as
func(); // as optional parameter
func(null); // as nullable parameter
func(new Object()); // as parameter of declared type
A:
The default value of the argument must be a constant expression. It can't be a variable or a function call.
If you need this functionality however:
function foo($foo, $bar = false)
{
if(!$bar)
{
$bar = $foo;
}
}
Assuming $bar isn't expected to be a boolean of course.
A: Much like the manual, use an equals (=) sign in your definition of the parameters:
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
A: Some notes that I also found useful:
*
*Keep your default values on the right side.
function whatever($var1, $var2, $var3="constant", $var4="another")
*The default value of the argument must be a constant expression. It can't be a variable or a function call.
A: Give the optional argument a default value.
function date ($format, $timestamp='') {
}
A: The date function would be defined something like this:
function date($format, $timestamp = null)
{
if ($timestamp === null) {
$timestamp = time();
}
// Format the timestamp according to $format
}
Usually, you would put the default value like this:
function foo($required, $optional = 42)
{
// This function can be passed one or more arguments
}
However, only literals are valid default arguments, which is why I used null as default argument in the first example, not $timestamp = time(), and combined it with a null check. Literals include arrays (array() or []), booleans, numbers, strings, and null.
A: If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).
Syntax:
function <functionName> ([<type> ]...<$paramName>) {}
For example:
function someVariadricFunc(...$arguments) {
foreach ($arguments as $arg) {
// do some stuff with $arg...
}
}
someVariadricFunc(); // an empty array going to be passed
someVariadricFunc('apple'); // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');
As you can see, this token basically turns all parameters to an array, which you can process in any way you like.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "206"
} |
Q: Print out the keys and Data of a Hashtable in C# .NET 1.1 I need debug some old code that uses a Hashtable to store response from various threads.
I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.
How can this be done?
A: I like:
foreach(DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + ":" + entry.Value);
}
A:
public static void PrintKeysAndValues( Hashtable myList ) {
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine( "\t-KEY-\t-VALUE-" );
while ( myEnumerator.MoveNext() )
Console.WriteLine("\t{0}:\t{1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}
from: http://msdn.microsoft.com/en-us/library/system.collections.hashtable(VS.71).aspx
A: foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
A: This should work for pretty much every version of the framework...
foreach (string HashKey in TargetHash.Keys)
{
Console.WriteLine("Key: " + HashKey + " Value: " + TargetHash[HashKey]);
}
The trick is that you can get a list/collection of the keys (or the values) of a given hash to iterate through.
EDIT: Wow, you try to pretty your code a little and next thing ya know there 5 answers... 8^D
A: I also found that this will work too.
System.Collections.IDictionaryEnumerator enumerator = hashTable.GetEnumerator();
while (enumerator.MoveNext())
{
string key = enumerator.Key.ToString();
string value = enumerator.Value.ToString();
Console.WriteLine(("Key = '{0}'; Value = '{0}'", key, value);
}
Thanks for the help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.