text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to test randomness (case in point - Shuffling) First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me.
Assume that you have a algorithm that generates randomness. Now how do you test it?
Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm?
To add some theory to the problem -
A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!.
What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52!
So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more...
How would you black box test a shuffling algorithm for randomness?
A: Here's one simple check that you can perform. It uses generated random numbers to estimate Pi. It's not proof of randomness, but poor RNGs typically don't do well on it (they will return something like 2.5 or 3.8 rather ~3.14).
Ideally this would be just one of many tests that you would run to check randomness.
Something else that you can check is the standard deviation of the output. The expected standard deviation for a uniformly distributed population of values in the range 0..n approaches n/sqrt(12).
/**
* This is a rudimentary check to ensure that the output of a given RNG
* is approximately uniformly distributed. If the RNG output is not
* uniformly distributed, this method will return a poor estimate for the
* value of pi.
* @param rng The RNG to test.
* @param iterations The number of random points to generate for use in the
* calculation. This value needs to be sufficiently large in order to
* produce a reasonably accurate result (assuming the RNG is uniform).
* Less than 10,000 is not particularly useful. 100,000 should be sufficient.
* @return An approximation of pi generated using the provided RNG.
*/
public static double calculateMonteCarloValueForPi(Random rng,
int iterations)
{
// Assumes a quadrant of a circle of radius 1, bounded by a box with
// sides of length 1. The area of the square is therefore 1 square unit
// and the area of the quadrant is (pi * r^2) / 4.
int totalInsideQuadrant = 0;
// Generate the specified number of random points and count how many fall
// within the quadrant and how many do not. We expect the number of points
// in the quadrant (expressed as a fraction of the total number of points)
// to be pi/4. Therefore pi = 4 * ratio.
for (int i = 0; i < iterations; i++)
{
double x = rng.nextDouble();
double y = rng.nextDouble();
if (isInQuadrant(x, y))
{
++totalInsideQuadrant;
}
}
// From these figures we can deduce an approximate value for Pi.
return 4 * ((double) totalInsideQuadrant / iterations);
}
/**
* Uses Pythagoras' theorem to determine whether the specified coordinates
* fall within the area of the quadrant of a circle of radius 1 that is
* centered on the origin.
* @param x The x-coordinate of the point (must be between 0 and 1).
* @param y The y-coordinate of the point (must be between 0 and 1).
* @return True if the point is within the quadrant, false otherwise.
*/
private static boolean isInQuadrant(double x, double y)
{
double distance = Math.sqrt((x * x) + (y * y));
return distance <= 1;
}
A: First, it is impossible to know for sure if a certain finite output is "truly random" since, as you point out, any output is possible.
What can be done, is to take a sequence of outputs and check various measurements of this sequence against what is more likely. You can derive a sort of confidence score that the generating algorithm is doing a good job.
For example, you could check the output of 10 different shuffles. Assign a number 0-51 to each card, and take the average of the card in position 6 across the shuffles. The convergent average is 25.5, so you would be surprised to see a value of 1 here. You could use the central limit theorem to get an estimate of how likely each average is for a given position.
But we shouldn't stop here! Because this algorithm could be fooled by a system that only alternates between two shuffles that are designed to give the exact average of 25.5 at each position. How can we do better?
We expect a uniform distribution (equal likelihood for any given card) at each position, across different shuffles. So among the 10 shuffles, we could try to verify that the choices 'look uniform.' This is basically just a reduced version of the original problem. You could check that the standard deviation looks reasonable, that the min is reasonable, and the max value as well. You could also check that other values, such as the closest two cards (by our assigned numbers), also make sense.
But we also can't just add various measurements like this ad infinitum, since, given enough statistics, any particular shuffle will appear highly unlikely for some reason (e.g. this is one of very few shuffles in which cards X,Y,Z appear in order). So the big question is: which is the right set of measurements to take? Here I have to admit that I don't know the best answer. However, if you have a certain application in mind, you can choose a good set of properties/measurements to test, and work with those -- this seems to be the way cryptographers handle things.
A: The only way to test for randomness is to write a program that attempts to build a predictive model for the data being tested, and then use that model to try to predict future data, and then showing that the uncertainty, or entropy, of its predictions tend towards maximum (i.e. the uniform distribution) over time. Of course, you'll always be uncertain whether or not your model has captured all of the necessary context; given a model, it'll always be possible to build a second model that generates non-random data that looks random to the first. But as long as you accept that the orbit of Pluto has an insignificant influence on the results of the shuffling algorithm, then you should be able to satisfy yourself that its results are acceptably random.
Of course, if you do this, you might as well use your model generatively, to actually create the data you want. And if you do that, then you're back at square one.
A: There's a lot of theory on testing randomness. For a very simple test on a card shuffling algorithm you could do a lot of shuffles and then run a chi squared test that the probability of each card turning up in any position was uniform. But that doesn't test that consecutive cards aren't correlated so you would also want to do tests on that.
Volume 2 of Knuth's Art of Computer Programming gives a number of tests that you could use in sections 3.3.2 (Empirical tests) and 3.3.4 (The Spectral Test) and the theory behind them.
A: Statistics. The de facto standard for testing RNGs is the Diehard suite (originally available at http://stat.fsu.edu/pub/diehard). Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive.
As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see Collections.shuffle).
It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained here).
A: Shuffle alot, and then record the outcomes (if im reading this correctly). I remember seeing comparisons of "random number generators". They just test it over and over, then graph the results.
If it is truly random the graph will be mostly even.
A: I'm not fully following your question. You say
Assume that you have a algorithm that generates randomness. Now how do you test it?
What do you mean? If you're assuming you can generate randomness, there's no need to test it.
Once you have a good random number generator, creating a random permutation is easy (e.g. Call your cards 1-52. Generate 52 random numbers assigning each one to a card in order, and then sort according to your 52 randoms) . You're not going to destroy the randomness of your good RNG by generating your permutation.
The difficult question is whether you can trust your RNG. Here's a sample link to people discussing that issue in a specific context.
A: Testing 52! possibilities is of course impossible. Instead, try your shuffle on smaller numbers of cards, like 3, 5, and 10. Then you can test billions of shuffles and use a histogram and the chi-square statistical test to prove that each permutation is coming up an "even" number of times.
A: No code so far, therefore I copy-paste a testing part from my answer to the original question.
// ...
int main() {
typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
Map freqs;
Deck d;
const size_t ntests = 100000;
// compute frequencies of events: card at position
for (size_t i = 0; i < ntests; ++i) {
d.shuffle();
size_t pos = 0;
for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
++freqs[std::make_pair(pos, *j)];
}
// if Deck.shuffle() is correct then all frequencies must be similar
for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
std::cout << "pos=" << j->first.first << " card=" << j->first.second
<< " freq=" << j->second << std::endl;
}
This code does not test randomness of underlying pseudorandom number generator. Testing PRNG randomness is a whole branch of science.
A: For a quick test, you can always try compressing it. Once it doesn't compress, then you can move onto other tests.
I've tried dieharder but it refuses to work for a shuffle. All tests fail. It is also really stodgy, it wont let you specify the range of values you want or anything like that.
A: Pondering it myself, what I would do is something like:
Setup (Pseudo code)
// A card has a Number 0-51 and a position 0-51
int[][] StatMatrix = new int[52][52]; // Assume all are set to 0 as starting values
ShuffleCards();
ForEach (card in Cards) {
StatMatrix[Card.Position][Card.Number]++;
}
This gives us a matrix 52x52 indicating how many times a card has ended up at a certain position. Repeat this a large number of times (I would start with 1000, but people better at statistics than me may give a better number).
Analyze the matrix
If we have perfect randomness and perform the shuffle an infinite number of times then for each card and for each position the number of times the card ended up in that position is the same as for any other card. Saying the same thing in a different way:
statMatrix[position][card] / numberOfShuffle = 1/52.
So I would calculate how far from that number we are.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Anyone used Dabo for a medium-big project? We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects?
Thanks for your time!
A: I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply.
Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website (http://dabodev.com) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions!
Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs.
Please sign up for our free email support list:
http://leafe.com/mailman/listinfo/dabo-users
...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help.
A: I have no Dabo experience at all but this question is on the top of the list fo such a long time that I decided to give it a shot:
Framework selection
Assumptions:
*
*medium-to-big project: we're talking about a team of more than 20 people working on something for about a year for the first phase. This is usually an expensive and very important effort for the client.
*this project will have significant amount of users (around a hundred) so performance is essential
*it's an ERP project so the application will work with large amounts of information
*you have no prior Dabo experience in your team
Considerations:
*
*I could not open Dabo project site right now. There seems to be some server problem. That alone would make me think twice about using it for a big project.
*It's not a well-known framework. Typing Dabo in Google returns almost no useful results, it does not have a Wikipedia page, all-in-all it's quite obscure. It means that when you will have problems with it (and you will have problems with it) you will have almost no place to go. Your question was unanswered for 8 days on SO, this alone would make me re-consider. If you base your project on an obscure technology you have no previous experience with - it's a huge risk.
*You don't have people who know that framework in your team. It means that you have to learn it to get any results at all and to master it will require quite significant amount of time. You will have to factor that time into your project plan. Do you really need it?
*What does this framework give you that you cannot do yourself? Quite a lot of time my team tried to use some third-party component or tool only to find that building a custom one would be faster than dealing with third-party problems and limitations. There are brilliant tools available to people nowadays and we would be lost without them - but you have to carefully consider if this tool is one of them
*Dabo project version is 0.84. Do you know if they spend time optimising their code for performance at this stage? Did you run any tests to see it will sustain the load you have in your NFRs.
Hope that helps :) Good luck with your project
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: What can cause a reduction in frame rate when upgrading a graphics card? We have a two-screen DirectX application that previously ran at a consistent 60 FPS (the monitors' sync rate) using a NVIDIA 8400GS (256MB). However, when we swapped out the card for one with 512 MB of RAM the frame rate struggles to get above 40 FPS. (It only gets this high because we're using triple-buffering.) The two cards are from the same manufacturer (PNY). All other things are equal, this is a Windows XP Embedded application and we started from a fresh image for each card. The driver version number is 169.21.
The application is all 2D. I.E. just a bunch of textured quads and a whole lot of pre-rendered graphics (hence the need to upgrade the card's memory). We also have compressed animations which the CPU decodes on the fly - this involves a texture lock. The locks take forever but I've also tried having a separate system memory texture for the CPU to update and then updating the rendered texture using the device's UpdateTexture method. No overall difference in performance.
Although I've read through every FAQ I can find on the internet about DirectX performance, this is still the first time I've worked on a DirectX project so any arcane bits of knowledge you have would be useful. :)
One other thing whilst I'm on the subject; when calling Present on the swap chains it seems DirectX waits for the present to complete regardless of the fact that I'm using D3DPRESENT_DONOTWAIT in both present parameters (PresentationInterval) and the flags of the call itself. Because this is a two-screen application this is a problem as the two monitors do not appear to be genlocked, I'm working around it by running the Present calls through a threadpool. What could the underlying cause of this be?
A: Are the cards exactly the same (both GeForce 8400GS), and only the memory size differ? Quite often with different memory sizes come slightly different clock rates (i.e. your card with more memory might use slower memory!).
So the first thing to check would be GPU core & memory clock rates, using something like GPU-Z.
A: It's an easy test to see if the surface lock is the problem, just comment out the texture update and see if the framerate returns to 60hz. Unfortunately, writing to a locked surface and updating the resource kills perfomance, always has. Are you using mipmaps with the textures? I know DX9 added automatic generation of mipmaps, could be taking up a lot of time to generate those. If your constantly locking the same resource each frame, you could also try creating a pool of textures, kinda like triple-buffering except with textures. You would let the render use one texture, and on the next update you pick the next available texture in the pool that's not being used in to render. Unless of course your memory constrained or your only making diffs to the animated texture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Are there any resources for becoming a Cygwin "power user"? I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows.
A: I've found Cygwin to be very useful in the past. FWIW, lately however I've shied away from it in favor of the following:
*
*XAMPP
*Unixutils
I like these tools even better.
A: I'm quite interested in this question myself. I've used the Cygwin Setup guide to get set up, but it doesn't get you all the way. One thing that I learned from it, though, is that it recommends leaving the setup.exe in the directory with Cygwin so that you can quickly add packages, since apt-get apparently doesn't work that well in Cygwin. The article also talks about cyg-get as an alternative.
A: If you've already read the Cygwin User Guide, take a look at Ten Steps To Higher Cygwin Productivity.
Also, if you're using a shell such as bash in Cygwin, and you're familiar with Emacs, consider using Eshell (the Emacs shell) instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Foxpro App and removable drives problem I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (FROM WINDOWS, not fox):
Windows-No disk
Exception Processing Message c0000012 Parameters .....
Any help please
Nelson Marmol
A: Nelson:
"That's how foxpro does it and there is no way around it"?
I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.
You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):
Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.
You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.
SYS(2450 [, 0 | 1 ])
Parameters
0
Search along path and default locations before searching in the application. (Default)
1
Search within the application for the specified procedure or UDF before searching the path and default locations.
One quick workaround could be assign another letter to your USB via the Disk Manager.
A: I agree with @PabloG - it's been over a decade since I worked with FoxPro (Dos & Windows) but even back in FPW2.6 you could determine where your app was running 'from', set absolute or relative search paths and even bundle your resources straight into the "compiled" (heh) exe. All of our resources lived in a specific subfolder within the app folder, the database files in another subfolder also below the app folder. We used relative paths for everything as I recall.
Can you give us a bit more information about the problem?
If you think it would be helpful I could try and dig out some of our FPW2.6 code where we're doing this kind of thing. :-)
A: It's VFP8 and sorry if I did not explained myself corectly. Also I think "there's no way around it" may sounded bad. What I meant is the property "ICON" in the forms. Since we have each component type separated in folders (forms,reports, menus, icons, etc), if you try to make the path relative, next time you edit the file, foxpro will include the fullpath. This problem started recently and we found that our clients started using external usb drives as means for backups.
A: It sounds to me like you are distributing the forms/reports/labels etc to the clients. If you build an EXE, then you shouldn't get the "path" problem as VFP will embed the resource (in this case icon) into the exe and will know how to extract it at runtime.
Peterson
A: No, we are no distributing forms or anything with the app... it's an exe. I forgot to mention that the EXE is compressed and obfuscated with KONXIZE 1.0.
A: Assuming your application can determine the path to the icon file at runtime, then in the load event of the form, you can set the icon with:
THIS.Icon=<path to file>
A: If anybody else runs across this, you can generally type something like this for the Icon property in the Properties window to force it to be evaluated, which will probably prevent the path auto-filling:
="icon.ico"
instead of just icon.ico.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create drop down list options from enum in a DataGridView I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.
Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.
A: I do not know if that would work with a DataGridView column but it works with ComboBoxes:
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
and:
MyEnum value = (MyEnum)comboBox1.SelectedValue;
UPDATE: It works with DataGridView columns too, just remember to set the value type.
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "My Enum Column";
col.DataSource = Enum.GetValues(typeof(MyEnum));
col.ValueType = typeof(MyEnum);
dataGridView1.Columns.Add(col);
A: Or, if you need to do some filtering of the enumerator values, you can loop through Enum.GetValues(typeof(EnumeratorName)) and add the ones you want using:
dataGridViewComboBoxColumn.Items.Add(EnumeratorValue)
As an aside, rather than using a DataTable, you can set the DataSource of the DataGridView to a BindingSource object, with the DataSource of the BindingSource object set to a BindingList<Your Class>, which you populate by passing an IList into the constructor.
Actually, I'd be interested to know from anyone if this is preferable to using a DataTable in situations where you don't already have one (i.e. it is returned from a database call).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: ASP.Net MVC, AJAX, and progressive enhancement I am looking for a reliable technique for adding Ajax to a working ASP.NET MVC application. I want to use jQuery, and understand how to use the AJAX functionality from jQuery.
What I need to know is how I should write my controller so that I can run the site without JavaScript, but at the same time make AJAX calls possible without the need for a separate view, separate controller, or any kind of route hack. My goal is to have a working application enhanced when JavaScript is enabled without the need to duplicate or recreate elements of the app.
A: Typically you would create your site so that it works without JavaScript being enabled. Then you would add the unobtrusive JavaScript needed to enhance your site with Ajax e.g. adding event handlers for links, form submits, etc. to make GET / POST requests and update your UI accordingly.
The only changes you would need in your MVC app would be to handle the Ajax requests and return the data as JSON, XML, etc.
A: in your controller (derived from Controller), you can call Request.IsMvcAjaxRequest() to check if the request is a normal POST or an AJAX request. This will be true if the request was created from a an AjaxForm submit or an AsyncHyperlink.
The Ajax form can be made visible by javascript, along with hiding the standard form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: .Net arrays with lower bound > 0 Although perhaps a bizare thing to want to do, I need to create an Array in .Net with a lower bound > 0. This at first seems to be possible, using:
Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Produces the desired results (an array of objects with a lower bound set to 9). However the created array instance can no longer be passed to other methods expecting Object[] giving me an error saying that:
System.Object[*] can not be cast into a System.Object[]. What is this difference in array types and how can I overcome this?
Edit: test code =
Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Object[] y = (Object[])x;
Which fails with: "Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'."
I would also like to note that this approach DOES work when using multiple dimensions:
Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9});
Object[,] y = (Object[,])x;
Which works fine.
A: The reason why you can't cast from one to the other is that this is evil.
Lets say you create an array of object[5..9] and you pass it to a function F as an object[].
How would the function knows that this is a 5..9 ? F is expecting a general array but it's getting a constrained one. You could say it's possible for it to know, but this is still unexpected and people don't want to make all sort of boundary checks everytime they want to use a simple array.
An array is the simplest structure in programming, making it too complicated makes it unsusable. You probably need another structure.
What you chould do is a class that is a constrained collection that mimics the behaviour you want. That way, all users of that class will know what to expect.
class ConstrainedArray<T> : IEnumerable<T> where T : new()
{
public ConstrainedArray(int min, int max)
{
array = new T[max - min];
}
public T this [int index]
{
get { return array[index - Min]; }
set { array[index - Min] = value; }
}
public int Min {get; private set;}
public int Max {get; private set;}
T[] array;
public IEnumerator<T> GetEnumerator()
{
return array.GetEnumarator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return array.GetEnumarator();
}
}
A: I'm not sure about why that can't be passed as Object[], but wouldn't be easy if you just create a real class to wrap an array and handle your "weird logic" in there?
You'd get the benefits of using a real reference object were you could add "intelligence" to your class.
Edit: How are you casting your Array, could you post some more code? Thanks.
A: Just store your lower bound in a const offset integer, and subtract that value from whatever your source returns as the index.
Also: this is an old VB6 feature. I think there might be an attribute to help support it.
A: The .NET CLR differentiates between two internal array object formats: SZ arrays and MZ arrays. MZ arrays can be multi-dimensional and store their lower bounds in the object.
The reason for this difference is two-fold:
*
*Efficient code generation for single-dimensional arrays requires that there is no lower bound. Having a lower bound is incredibly uncommon. We would not want to sacrifice significant performance in the common case for this rarely used feature.
*Most code expects arrays with zero lower bound. We certainly don't want to pollute all of our code with checking the lower bound or adjusting loop bounds.
These concerns are solved by making a separate CLR type for SZ arrays. This is the type that almost all practically occurring arrays are using.
A: Know it's old question, but to fully explain it.
If type (in this case a single-dimension array with lower bound > 0) can't be created by typed code, simply reflected type instance can't be consumed by typed code then.
What you have noticed is already in documentation:
https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names
Note that from a runtime point of view, MyArray[] != MyArray[*], but
for multidimensional arrays, the two notations are equivalent. That
is, Type.GetType("MyArray [,]") == Type.GetType("MyArray[*,*]")
evaluates to true.
In c#/vb/... you can keep that reflected array in object, pass around as object, and use only reflection to access it's items.
-
Now you ask "why is there LowerBound at all?", well COM object aren't .NET, it could be written in old VB6 that actually had array object that has LowerBound set to 1 (or anything VB6 had such freedom or curse, depends whom you ask). To access first element of such object you would actually need to use 'comObject(1)' instead of 'comObject(0)'. So the reason to check lower bound is when you are performing enumeration of such object to know where to start enumeration, since element functions in COM object expects first element to be of LowerBound value, and not Zero (0), it was reasonable to support same logic on such instances. Imagine your get element value of first element at 0, and use some Com object to pass such element instance with index value of 1 or even with index value of 2001 to a method, code would be very confusing.
To put it simply: it's mostly for legacy support only!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Sending messages to objects while debugging Objective-C in gdb, without symbols I'm trying to send messages to Objective-C objects in gdb.
(gdb) p $esi
$2 = (void *) 0x1268160
(gdb) po $esi
<NSArray: 0x1359c0>
(gdb) po [$esi count]
Target does not respond to this message selector.
I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?
A: If you must override gdb and send a message to an object when it will not let you, you can use performSelector:
(gdb) print (int)[receivedData count]
Target does not respond to this message selector.
(gdb) print (int)[receivedData performSelector:@selector(count) ]
2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]:
unrecognized selector sent to instance 0x105f2e0
If you need to pass an argument use withObject:
(gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ]
A: Is it possible that you need to cast $esi?
p (NSUInteger)[(NSArray *)$esi count]
A: @[John Calsbeek]
Then it complains about missing symbols.
(gdb) p (NSUInteger)[(NSObject*)$esi retainCount]
No symbol table is loaded. Use the "file" command.
(gdb) p [(NSArray *)$esi count]
No symbol "NSArray" in current context.
I tried to load the symbols for Foundation:
(gdb) add-symbol-file /System/Library/Frameworks/Foundation.framework/Foundation
add symbol table from file "/System/Library/Frameworks/Foundation.framework/Foundation"? (y or n) y
Reading symbols from /System/Library/Frameworks/Foundation.framework/Foundation...done.
but still no luck:
(gdb) p [(NSArray *)$esi count]
No symbol "NSArray" in current context.
Anyway, I don't think casting is the solution to this problem, you shouldn't have to know what kind of object it is, to be able to send messages to it.
The weird thing is that I found an NSCFArray I have no problems sending messages to:
(gdb) p $eax
$11 = 367589056
(gdb) po $eax
<NSCFArray 0x15e8f6c0>(
file://localhost/Users/ask/Documents/composing-fractals.pdf
)
(gdb) p (int)[$eax retainCount]
$12 = 1
so I guess there was a problem with the object I was investigating... or something.
Thanks for your help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to interact with Windows Media Player in C# I am looking for a way to interact with a standalone full version of Windows Media Player.
Mostly I need to know the Path of the currently played track.
The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in .Net(C#) without any heavy use of pinvoke, which I am not really comfortable with.
Thanks
Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user
A: Just add a reference to wmp.dll (\windows\system32\wmp.dll)
using WMPLib;
And then you can instantiate a media player
var Player = new WindowsMediaPlayer();
// Load a playlist or file and then get the title
var title = Player.controls.currentItem.name;
See Creating the Windows Media Player Control Programmatically for more information
A: For remoting the Windows Media Player, you can use the IWMPRemoteMediaServices interface to control the stand alone Windows Media Player. And you should be able to read all the informations you want like title or filename from your WMP player object. Unfortunately there is no C# smaple code in the SDK included. You can get the files from here: http://d.hatena.ne.jp/punidama/20080227 Look for the file WmpRemote.zip
Originally it's from here: http://blogs.msdn.com/ericgu/archive/2005/06/22/431783.aspx
Then you have to cast to the WindowsMediaPlayer object:
RemotedWindowsMediaPlayer rm = new RemotedWindowsMediaPlayer();
WMPLib.WindowsMediaPlayer myPlayer = this.GetOcx() as WMPLib.WindowsMediaPlayer;
and there you go..
A: I had this https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player.
Hope that helps.
Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution.
A: The best info I have seen on interacting with Windows Media Player is this article written by Stephen Toub.
He lists a whole load of different ways to play dvr-ms files (doesn't really matter what format they are for this though). The bit that is possibly of interest to you is about using a Media Player ActiveX Control, which you can add to the visual Studio toolbox by right-clicking and adding the Windows Media Player ActiveX COM Control. You can then embed the player into your app, and access various properties of Media Player, like the url:
WMPplayer.URL = stringPathToFile;
This solution is possibly not what you want because it's starting a new instance of Media Player (as far as I know), however it might point you in the right direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Will .NET MVC give me the HTML/CSS/JS separation I need? I'm working with my ASP.NET development team to try and create "better" (i.e. cleaner) HTML when rendering pages. At the moment, .NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some instances, we're struggling to overcome this without having to add a notable chunk to development time estimates.
I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. (This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.)
This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could .NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this?
If .NET MVC isn't going to give me this fine-grained control over separation, any recommendations for .NET coding practices, libraries, etc. which might would be really helpful.
A: The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add.
You can, for the most part, separate HTML / CSS / JS like you would in a different framework.
A: Depending on the view engine you're going to use. yes.
But you can easilly check this by looking at the page-source for stack-overflow. It's not zen-garden but it's pretty clean.
Some more clarification:
The rendering of the pages is done by the view engine. You can use the standard view engine or existing ones like nVelocity or Brail, just like with monorail.
http://www.chadmyers.com/Blog/archive/2007/11/28/testing-scottgu-alternate-view-engines-with-asp.net-mvc-nvelocity.aspx
As the view engine is responsible for creating HTML what comes out depends on your choice. But most view engines are better in this respect than vanilla ASP.Net
A: @Wrestlevania said:
any recommendations for .NET coding
practices, libraries, etc. which might
would be really helpful.
I try to maintain a high level of separation while coding in ASP.Net. I find that if I avoid the asp controls and stick as much as possible with basic html elements, I can avoid any situation where ASP.Net would be inclined to inject extra CSS or JS into my page. Example, use span in place of asp:literal, button in place of asp:button, etc.
The only ASP control I use is the repeater, which is used to create a table. Any functionality I need that would be similar to an asp control, I either implement myself in javascript, or use a framework like jquery.
A: Asp.Net MVC will help you keep html/css/js separate in that it will present fewer features that would prevent you from keeping them separate.
For example Html helpers typically return just that: Html. From that point you are free to choose to keep all style information associated only by class attributes.
Consider also looking into the practices you usually follow with a library like jQuery. It's an excellent example of how to keep the scripted functionality entirely in your js and out of your html by applying the event handling behaviors to the elements on page load based on things like element type, class and id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Can't access variable in C++ DLL from a C app I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put
extern "C" _declspec(dllexport) char* MyNewVariable = 0;
which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including
_declspec(dllimport) char* MyNewVariable;
but that just gives me a linker error:
unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA)
extern "C" _declspec(dllimport) char* MyNewVariable;
as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it:
unresolved external symbol __imp__MyNewVariable
How do I write the declaration so that the C++ DLL variable is accessible from the C app?
The Answer
As identified by botismarius and others (many thanks to all), I needed to link with the DLL's .lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the .lib file.
A: you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the .lib file. And yes, you should also declare the variable as:
extern "C" { declspec(dllimport) char MyNewVariable; }
A: extern "C" is how you remove decoration - it should work to use:
extern "C" declspec(dllimport) char MyNewVariable;
or if you want a header that can be used by C++ or C (with /TC switch)
#ifdef __cplusplus
extern "C" {
#endif
declspec(dllimport) char MyNewVariable;
#ifdef __cplusplus
}
#endif
And of course, link with the import library generated by the dll doing the export.
A: I'm not sure who downmodded botismarius, because he's right. The reason is the .lib generated is the import library that makes it easy to simply declare the external variable/function with __declspec(dllimport) and just use it. The import library simply automates the necessary LoadLibrary() and GetProcAddress() calls. Without it, you need to call these manually.
A: They're both right. The fact that the error message describes __imp_?MyNewVariable@@3PADA means that it's looking for the decorated name, so the extern "C" is necessary. However, linking with the import library is also necessary or you'll just get a different link error.
A: @Graeme: You're right on that, too. I think the "C" compiler that the OP is using is not enforcing C99 standard, but compiling as C++, thus mangling the names. A true C compiler wouldn't understand the "C" part of the extern "C" keyword.
A: In the dll source code you should have this implementation so that the .lib file exports the symbol:
extern "C" _declspec(dllexport) char* MyNewVariable = 0;
The c client should use a header with this declaration so that the client code will import the symbol:
extern "C" _declspec(dllimport) char* MyNewVariable;
This header will cause a compile error if #include-ed in the dll source code, so it is usually put in an export header that is used only for exported functions and only by clients.
If you need to, you can also create a "universal" header that can be included anywhere that looks like this:
#ifdef __cplusplus
extern "C" {
#endif
#ifdef dll_source_file
#define EXPORTED declspec(dllexport)
#else
#define EXPORTED declspec(dllimport)
#endif dll_source_file
#ifdef __cplusplus
}
#endif
EXPORTED char* MyNewVariable;
Then the dll source code looks like this:
#define dll_source_code
#include "universal_header.h"
EXPORTED char* MyNewVariable = 0;
And the client looks like this:
#include "universal_header.h"
...
MyNewVariable = "Hello, world";
If you do this a lot, the monster #ifdef at the top can go in export_magic.h and universal_header.h becomes:
#include "export_magic.h"
EXPORTED char *MyNewVariable;
A: I've never used _declspec(dllimport) when I was programming in Windows. You should be able to simply declare
extern "C" char* MyNewVariable;
and link to the .libb created when DLL was compiled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Is there any difference between type? and Nullable? In C# are the nullable primitive types (i.e. bool?) just aliases for their corresponding Nullable<T> type or is there a difference between the two?
A: I'm surprised nobody went to the source (the C# spec) yet. From §4.1.10 Nullable types:
A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable<T>, and the two forms can be used interchangeably.
So, no, there isn't any difference between the two forms. (Assuming you don't have any other type called Nullable<T> in any of the namespaces you use.)
A: A Nullable<T> is a structure consisting of a T and a bit flag indicating whether or not the T is valid. A Nullable<bool> has three possible values: true, false and null.
Edit: Ah, I missed the fact that the question mark after "bool" was actually part of the type name and not an indicator that you were asking a question :). The answer to your question, then, is "yes, the C# bool? is just an alias for Nullable<bool>".
A: If you look at the IL using Ildasm, you'll find that they both compile down to Nullable<bool>.
A: A bool is a value type, therefore it can't contain a NULL value. If you wrap any value type with Nullable<>, it will give it that ability. Moreover, access methods to the value change by additional properties HasValue and Value.
But to the question: Nullable<bool> and bool? are aliases.
A: There is no difference between bool? b = null and Nullable<bool> b = null. The ? is just C# compiler syntax sugar.
A: No there is no difference. In summary:
System.Boolean -> valid values : true, false
bool -> alias for System.Boolean
Nullable<bool> -> valid values : true, false, null
bool? -> alias for Nullable<bool>
Hope this helps.
A: To access the value of the bool? you need to do the following:
bool? myValue = true;
bool hasValue = false;
if (myValue.HasValue && myValue.Value)
{
hasValue = true;
}
Note you can't just do:
if (myValue)
{
hasValue = true;
}
A: Null primitives are just regular primitives wrapped in Nullable. Any appearances to the contrary are just the compiler and syntactical sugar.
A: No difference. Take a look here: http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
"The syntax T? is shorthand for Nullable, where T is a value type. The two forms are interchangeable."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: Windows Forms Designer upset by a control with a nullable property I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type double? (or Nullable<double>). It's nullable to support the case where the user doesn't enter anything.
The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():
this.numericTextBox1.Value = 1;
Remember 'Value' is of type Nullable<double>. This generates the following warning whenever I try to reopen the form in the Designer:
Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.
As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.
Any suggestions?
A: Or, if you don't want the designer adding any code at all... add this to the Property.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
A: It seems that there is an issue in Visual Studio 2008. You should create custom CodeDomSerializer to work around it:
public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer
{
public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
{
CodeStatementCollection collection = codeObject as CodeStatementCollection;
if (collection != null)
{
foreach (CodeStatement statement in collection)
{
CodeAssignStatement codeAssignment = statement as CodeAssignStatement;
if (codeAssignment != null)
{
CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;
CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;
if (properyRef != null && properyRef.PropertyName == "Value" && primitiveExpression != null && primitiveExpression.Value != null)
{
primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);
break;
}
}
}
}
return base.Deserialize(manager, codeObject);
}
}
Then you should apply it by using the DesignerSerializer attribute on your class.
A: Could it help to setting the DefaultValue attribute on that property to new Nullable(1)?
[DefaultValue(new Nullable<double>(1))]
public double? Value ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Recovering from a slightly out of date subversion repository backup A problem I ran into a while back I never found a good solution for...
Say you have a working copy checked out from subversion at revision 7500, and the disk holding the current repository dies. You've got a backup of the repository at, say, revision 7450. It's easy to restore the repository backup, but any attempt to use the working copy against it gives an error saying that revision 7500 doesn't exist in the repository.
What is the best way to check in one gigantic revision to bring the content of the repository up to match the content of the working copy and get he working copy back to a functional state?
(Ideally I'd like something easier than having to check out a brand new working copy and then copying over all the files manually - I think at the time the working copies were used to configuration manage servers, so it was a real pain to have to check out clean working copies)
A: You could check out a rev.7450 copy somewhere, then export your 7500 copy (to remove the .svn folders). Drag the exported copy (which is the latest copy) over the 7450 copy. All the new files should simply overwrite the older ones, leaving the .svn folders the same.
Subversion will assume you just made a bunch of changes to 7450, and the next checkin will set it as 7451.
A: Do a fresh checkout into a different folder, then use a diff program to create a patch. apply the patch to your new working copy.
A: If you are positive you've got the latest version in your directory, then do this:
*
*Delete the item from the repository
*Delete the SVN references from your copy
*Check your code in as a new copy.
*Check out the code you just checked in
A: You can fill in the missing revision numbers by loading in a dump file with a bunch of empty revisions. There are answers discussing how to do this over at How can I change the revision number of a repository. Load all but one revision this way, then you can just check in all your changes in one last giant revision.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: activerecord as model, is this a good idea? Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a .NET school...) and while I was doing my final year project, i found this definition for a model
The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.
it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well...
so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern?
A: Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity.
If you want to so only simple stuff you can use Transaction Script. This is an architecture you saw in lot's of old ASP and PHP pages where a single script contained the business logic, data-access logic and presentation logic. This falls apart fast when things get more complicated.
The next thing you can do is add some separation between presentation and model. This is activerecord. The model is still tied to the database but you've a bit more flexibility because you can reuse your model/dataccess between views/pages/whatever. It's not as flexible as it could be but depending on your data-access solution it can be flexible enough. Frameworks like CSLA in .Net have a lot of aspects from this patterm (I think Entity Framework looks a bit too much like this too). It can still handle a lot of complexity without becoming unmaintainable.
The next step is separating your data-access layer and your model. This usually requires a good OR mapper or a lot of work. So not everyone wants to go this way. Lot's of methodologies like domain driven design perscribe this approach.
So it's all a matter of context. What do you need and what is the best solution. I even still use transaction-script sometimes for simple single use code.
A: I've said many times that using Active Record (or ORM which is almost the same) as Business Models is not a good idea. Let me explain:
The fact that PHP is Open Source, Free (and all that long story...) provides it with a vast community of developers pouring code into forums, sites like GitHub, Google code and so on. You might see this as a good thing, but sometimes it tends not to be "so good". For instance, suppose you are facing a project and you wish to use a ORM framework for facing your problem written in PHP, well... you'll have a lot of options to choose for:
*
*Doctrine
*Propel
*QCodo
*Torpor
*RedBean
And the list goes on and on. New projects are created regularly. So imagine that you've built a full blown framework and even a source code generator based on that framework. But you didn't placed business classes because, after all, "why writing the same classes again?". Time goes by and a new ORM framework is released and you want to switch to the new ORM, but you'll have to modify almost every client application using direct reference to your data model.
Bottom line, Active Record and ORM are meant to be in the Data Layer of your application, if you mix them with your Presentation Layer, you can experience problems like this example I've just laid.
Hear @Mendelt's wise words: Read Martin Fowler. He's put many books and articles on OO design and published some good material on the subject. Also, you might want to look into Anti-Patterns, more specifically into Vendor Lock In, which is what happens when we make our application dependent on 3rd party tools. Finally, I wrote this blog post speaking about the same issue, so if you want to, check it out.
Hope my answer has been of any use.
A: The great thing about using the Rails ActiveRecord as a model in MVC is that it gives you an automatic ORM (Object Relational Mapper) and easy way to create associations between models. As you have pointed out, MVC can sometimes be lacking.
Therefore, for some complex transaction involving many models, I'd suggest to use a Presenter in between your controller and your models (Rails Presenter Pattern). The Presenter would aggregate your models and transactional logic and would remain easily testable. You definitely want to strive to keep all of your business logic in your models or presenters, and out of your controllers (Skinny Controller, Fat Model).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do you perform a CROSS JOIN with LINQ to SQL? How do you perform a CROSS JOIN with LINQ to SQL?
A: Extension Method:
public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(this IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)
{
return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));
}
And use like:
vals1.CrossJoin(vals2)
A: The same thing with the Linq extension method SelectMany (lambda syntax):
var names = new string[] { "Ana", "Raz", "John" };
var numbers = new int[] { 1, 2, 3 };
var newList=names.SelectMany(
x => numbers,
(y, z) => { return y + z + " test "; });
foreach (var item in newList)
{
Console.WriteLine(item);
}
A: Based on Steve's answer, the simplest expression would be this:
var combo = from Person in people
from Car in cars
select new {Person, Car};
A: A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
};
A: A Tuple is a good type for Cartesian product:
public static IEnumerable<Tuple<T1, T2>> CrossJoin<T1, T2>(IEnumerable<T1> sequence1, IEnumerable<T2> sequence2)
{
return sequence1.SelectMany(t1 => sequence2.Select(t2 => Tuple.Create(t1, t2)));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "136"
} |
Q: Using an external "windows"-keyboard under Mac OS X I use a MacBook, but I've got a usual keyboard attached to it.
The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS.
The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys.
So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this?
(I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models)
Update:
Thanks for the responses, I fixed this.
To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems
The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys, ...). I didn't try it yet, as the commands keys were my biggest gripe.
A: The best method I have is to download the Logitech Control Center for OSX from Logitech. Search throw the Installer package for the LCCKCHR.rsrc. Drop this file into either ~/Library/Keyboard Layouts or /Library/Keyboard Layouts. Logout and log back in and you'll notice a few more options in the International System Preferences under Inputs. Check the keyboard layouts you would like.
Although this keyboard layout is for Logitech keyboards it works for most keybaords (especially international users)
A: You create create your own custom keyboard mapping, which could then be used with the keyboard language menu. So when you plug in your keyboard, just switch to your custom layout. OS X has supported this since 10.2, and Apple has documentation on how to produce your own custom maps.
http://developer.apple.com/technotes/tn2002/tn2056.html
It's not something I've tried myself, just read about it once or twice. Looks like it could potentially do the job. I'd just duplicate a mapping that is as close as you can get to what you want, and then customise it from there.
A: In OS X 10.5 they allow you to have different keyboard setups for different keyboards. This works most of the time. I've had issues with very old keyboards that are plugged in via a PS2 to USB but otherwise it works fine.
A: You could investigate DoubleCommand, it may do what you need.
There's an experimental version that allows for different properties for different keyboards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: What is the proper regular expression for an unescaped backslash before a character? Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q, since the latter is a backslash-escaped backslash followed by a q. Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q. (Well, it would match the \q at the end, not the \\ at the beginning.)
I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.
A: Leon Timmermans got exactly what I was looking for. I would add one small improvement for those who come here later:
/(?<!\\)(?:\\\\)*\\q/
The additional ?: at the beginning of the (\\\\) group makes it not saved into any match-data. I can't imagine a scenario where I'd want the text of that saved.
A: Updated:
My new and improved Perl regex, supporting more than 3 backslashes:
/(?<!\\) # Not preceded by a single backslash
(?>\\\\)* # an even number of backslashes
\\q # Followed by a \q
/x;
or if your regex library doesn't support extended syntax.
/(?<!\\)(?>\\\\)*\\q/
Output of my test program:
q does not match
\q does match
\\q does not match
\\\q does match
\\\\q does not match
\\\\\q does match
Older version
/(?:(?<!\\)|(?<=\\\\))\\q/
A: Now You Have Two Problems.
Just write a simple parser. If the regex ties your head up in knots now, just wait a month.
A: The best solution to this is to do your own string parsing as Regular Expressions don't really support what you are trying to do. (rep @Frank Krueger if you go this way, I'm just repeating his advice)
I did however take a shot at a exclusionary regex. This will match all strings that do not fit your criteria of a "\" followed by a character.
(?:[\\][\\])(?!(([\\](?![\\])[a-zA-Z])))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: What is the best way to convert between char* and System::String in C++/CLI What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?
A: System::String has a constructor that takes a char*:
using namespace system;
const char* charstr = "Hello, world!";
String^ clistr = gcnew String(charstr);
Console::WriteLine(clistr);
Getting a char* back is a bit harder, but not too bad:
IntPtr p = Marshal::StringToHGlobalAnsi(clistr);
char *pNewCharStr = static_cast<char*>(p.ToPointer());
cout << pNewCharStr << endl;
Marshal::FreeHGlobal(p);
A: There's a good overview here (this marshaling support added for VS2008):
http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx
A: What we did is made a C++\CLI object that held the string in unmangaed code and would give out manged copies of the item. The conversion code looks very much like what Stan has on his blog (I can't remember it exactly)(If you use his code make sure you update it to use delete[]) but we made sure that the destructor would handle releasing all the unmanged elements of the object. This is a little overblown but we didn't have leaks when we tied into legacy C++ code modules.
A: I created a few helper methods. I needed to do this to move from an old Qt library to CLI String. If anyone can add onto this and tell me if it seems like I have a memory leak and what I can do to fix it, I would be most appreciative.
void MarshalString ( String ^ s, wstring& os ) {
using namespace Runtime::InteropServices;
const wchar_t* char = (const wchar_t*)(Marshal::StringToHGlobalUni(s)).ToPointer();
os = char;
}
QString SystemStringToQt( System::String^ str)
{
wstring t;
MarshalString(str, t);
QString r = QString::fromUcs2((const ushort*)t.c_str());
return r;
}
A: One additional link to a summary of possible ways:
http://support.microsoft.com/?kbid=311259
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: performing datetime related operations in PHP How do you actually perform datetime operations such as adding date, finding difference, find out how many days excluding weekends in an interval? I personally started to pass some of these operations to my postgresql dbms as typically I would only need to issue one sql statement to obtain an answer, however, to do it in PHP way I would have to write a lot more code that means more chances for errors to occur...
Are there any libraries in PHP that does datetime operation in a way that don't require a lot of code? that beats sql in a situation where 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' that is solved by making this query?
SELECT COUNT(*) AS total_days
FROM (SELECT date '2008-8-26' + generate_series(0,
(date '2008-9-1' - date '2008-8-26')) AS all_days) AS calendar
WHERE EXTRACT(isodow FROM all_days) < 6;
A: While for most datetime operations I would normally convert to Unixtime and perform addition subtraction etc. on the Unixtime integer, you may want to look at the Zend framework Zend_Date class.
This has a lot of the functionality you describe. Although Zend is billed as a "framework" it works exceptionally well as a class library to pick and chose elements from. We routinely include it in projects and then just pull in bits as and when we need them.
A: PEAR::Date looks like it might have some useful functionality.
PEAR::Calendar might also be useful.
A: strtotime() is useful but it does have some odd behaviors that can pop-up from time to time if you are not just using it to convert a formatted date/time string.
things like "+1 month" or "-3 days" can sometimes not give you what you expect it to output.
A: PHP5+'s DateTime object is useful because it is leap time and
daylight savings aware, but it needs some extension to really
solve the problem. I wrote the following to solve a similar problem.
The find_WeekdaysFromThisTo() method is brute-force, but it works reasonably quickly if your time span is less than 2 years.
$tryme = new Extended_DateTime('2007-8-26');
$newer = new Extended_DateTime('2008-9-1');
print 'Weekdays From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_WeekdaysFromThisTo($newer) ."\n";
/* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */
print 'All Days From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_AllDaysFromThisTo($newer) ."\n";
/* Output: All Days From 2007-08-26 To 2008-09-01: 371 */
$timefrom = $tryme->find_TimeFromThisTo($newer);
print 'Between '.$tryme->format('Y-m-d').' and '.$newer->format('Y-m-d').' there are '.
$timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days'].
' days.'."\n";
/* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */
class Extended_DateTime extends DateTime {
public function find_TimeFromThisTo($newer) {
$timefrom = array('years'=>0,'months'=>0,'days'=>0);
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$timefrom['years'] = $this->find_YearsFromThisTo($testnewer);
$mod = '-'.$timefrom['years'].' years';
$testnewer -> modify($mod);
$timefrom['months'] = $this->find_MonthsFromThisTo($testnewer);
$mod = '-'.$timefrom['months'].' months';
$testnewer -> modify($mod);
$timefrom['days'] = $this->find_AllDaysFromThisTo($testnewer);
return $timefrom;
} // end function find_TimeFromThisTo
public function find_YearsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 year');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 year');
}
return $count;
} // end function find_YearsFromThisTo
public function find_MonthsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 month');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 month');
}
return $count;
} // end function find_MonthsFromThisTo
public function find_AllDaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_AllDaysFromThisTo
public function find_WeekdaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
// If the calculated day is not Sunday or Saturday, count this day
if ($testnewer->format('w') != '0' && $testnewer->format('w') != '6')
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_WeekdaysFromThisTo
public function set_Day($newday) {
if (is_int($newday) && $newday > 0 && $newday < 32 && checkdate($this->format('m'),$newday,$this->format('Y')))
$this->setDate($this->format('Y'),$this->format('m'),$newday);
} // end function set_Day
public function set_Month($newmonth) {
if (is_int($newmonth) && $newmonth > 0 && $newmonth < 13)
$this->setDate($this->format('Y'),$newmonth,$this->format('d'));
} // end function set_Month
public function set_Year($newyear) {
if (is_int($newyear) && $newyear > 0)
$this->setDate($newyear,$this->format('m'),$this->format('d'));
} // end function set_Year
} // end class Extended_DateTime
A: For adding a date, you can use the method DateTime::add (Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object), available from php 5.3.0 onwards.
To find the difference between two dates, there's the DateTime::diff method; but there doesn't seem to be a method for counting the working days between two dates.
A: The easiest method is to use a timestamp, representing the number of seconds since January 1, 2008. With a timestamp type, you can do things like...
now = time();
tomorrow = now + 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
Check out the documentation for time(), date() and mktime() on the php web pages. Those are the three methods that I tend to use the most frequently.
A: You can use a combination of strtotime, mktime and date todo the arithmetic
Here is an example which uses a combo todo some arithmetic http://rushi.wordpress.com/2008/04/13/php-print-out-age-of-date-in-words/ I'll reproduce the code here for simplicity
if ($timestamp_diff < (60*60*24*7)) {
echo floor($timestamp_diff/60/60/24)." Days";
} elseif ($timestamp_diff > (60*60*24*7*4)) {
echo floor($timestamp_diff/60/60/24/7)." Weeks";
} else {
$total_months = $months = floor($timestamp_diff/60/60/24/30);
if($months >= 12) {
$months = ($total_months % 12);
$years = ($total_months - $months)/12;
echo $years . " Years ";
}
if($months > 0)
echo $months . " Months";
}
?>
A: @Rushi I don't like strtotime() personally.. i don't know why but i discovered this morning that passing a string like this '2008-09-11 9:5 AM' to strtotime returns a false...
I don't think the code you provided solve the example problem 'Given two dates, how many workdays are there between the two dates? Implement in either SQL, or $pet_lang' and I haven't consider if I have a list of public holiday...
A: If you have a look at http://php.net/date , you will find some examples of using mktime() to perform operations.
A simple example would be to workout what tomorrows date would be. You can do that by simply adding 1, to the day value in mktime() as follows:
$tomorrow = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 1, date("Y")));
So here, you will receive a date in the form of YYYY-MM-DD containing tomorrows date. You can also subtract days by simply replacing '+' with '-'. mktime() makes life a lot easier, and saves you from having to do nested if statements and other such troublesome coding.
A: You can get number of days between two dates like this:
$days = (strtotime("2008-09-10") - strtotime("2008-09-12")) / (60 * 60 * 24);
And you can make function something like that (I don't have php installed in my work computer so i can't guarantee syntax is 100% correct)
function isWorkDay($date)
{
// check if workday and return true if so
}
function numberOfWorkDays($startdate, $enddate)
{
$workdays = 0;
$tmp = strtotime($startdate);
$end = strtotime($enddate);
while($tmp <= $end)
{
if ( isWorkDay( date("Y-m-d",$tmp) ) ) $workdays++;
$tmp += 60*60*24;
}
return $workdays;
}
If you don't like strtotime and you always have date in same format you can use explode function like
list($year, $month, day) = explode("-", $date);
A: I would strongly recommend using PHP 5.2's DateTime objects, rather than using UNIX timestamps, when doing date calculations. When you use the PHP date functions that return UNIX timestamps, you have a very limited range to work with (e.g. nothing before 1970).
A: to get working days/holidays, postgresql CTE ftw -- see http://osssmb.wordpress.com/2009/12/02/business-days-working-days-sql-for-postgres-2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Don't repeat yourself vs Internationalisation A while back I was reading the W3C article on 'Re-using Strings in Scripted Content', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.
To take their example, we might have some code like this...
print "The printer is ";
if (printer.working) {
print "on.\n";
} else {
print "off.\n";
}
print "The stapler is ";
if (stapler.working) {
print "on.\n";
} else {
print "off.\n";
}
My instinct would be to eliminate the repetition roughly as follows...
report-state(printer, "printer");
report-state(stapler, "stapler");
function report-state(name, object) {
print "The "+name+" is ";
if (object.working) {
print "on\n";
} else {
print "off\n";
}
}
...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.
So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?
Part of me wants to argue that internationalisation is one of those extreme programming “you arent gonna need it” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.
A: 100% agree with Mendelt.
It is not only a maintenance problem, but can also be a linguistic one.
In all Latin languages the gender, number, and case of the subject affect other elements.
Example for Romanian
The printer is on: Imprimanta este pornită // feminine
The printer is off: Imprimanta este oprită
The stapler is on: Perforatorul este pornit // masculine
The stapler is off: Perforatorul este oprit
Also see http://www.mihai-nita.net/article.php?artID=20060430a
A: I agree with Mendelt Siebenga when he says you should keep entire sentences or phrases in your language resource files. Differences in grammar will always prevent you from doing single word replacement across languages. This will still lead to less repetitive code than your first example because you only need to check the object type and its state, then print the appropriate message from the language resource.
A: We try not to create message strings by program manipulation because the loc. team can't see them.
The loc. team actually prefer separate but nearly duplicate messages.
However they will accept parameterized messages.
E.g., "The %(appliance)% is %(on_or_off)%."
The parameters can break down but at least it's more obvious to the loc team when it will work and when it won't.
A: I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems.
Just store
The printer is on
The printer is off
The stapler is on
The stapler is off
in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application.
A: I suppose it depends on the level of language quality that you are aiming to achieve.
By trying to minimise repetition of code that deals with these real language strings, you are just exposing yourself to a whole other layer of logic in the syntaxes and structures of different languages. There would be a massive amount of work involved in producing code which still retains the original structure of the language whilst minimising repetition.
You'd have to decide which was a more suitable approach to a particular problem; Code that repeats itself, or code that tries to be a Jack of all Trades and accomodates for countless rules of language (no doubt a maintenance nightmare).
Of course, you can strike a middle-ground and minimise your code repitition but give up satisfactory grammatical eloquence. Take the example of Ultima Online - when it was localised, a string that previously read "A pile of 329 gold coins" became something like "A pile of gold coins: 329". Not great, but a fairly reasonable solution that lends itself easily to localisation.
A: I would suggest using a CMS rather than hardcoding in your textual values to cover localisation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Can you query different databases on the same server using 1 NHibernate Session? Does a new SessionFactory and Session object have to be created for each database? I have a data store for my application data, and a separate data store for my employee security, which is used to validate users. Do I have to create a new SessionFactory ans Session object for calls to the 2 different databases?
A: ok so this doesn't answer your question directly but it might offer an insight as to why you should create multiple session objects for each datastore.
This article explains how you can implement a thread safe lazy singleton for each type of Session you need so that you only have one session per datastore but it's shared across the entire application. So at most you're only ever going to have 2 session objects.
To directly answer your question however, you will need 1 session object per database.
A: General case
The general case answer is no, you need at least different sessions for the general case.
You may use a single session factory by using the OpenSession overload taking an opened connection as argument, allowing you to switch database for the session requiring it.
This has some drawbacks, like lack of connection auto-releasing after transactions, disabling of second level cache, ... Better have two session factories in my opinion, rather than supplying your own connection on session opening.
Database specific cases
Depending on the database server you use, you may be able to use a single connection string for accessing both with NHibernate. If you can use a single connection string, then you can use a single session factory and use the same session for accessing your entities split between two databases.
Simplest case
Using SQL Server, you may have your two databases on the same SQL Server. In such case, you can use a single connection string and adjust the catalog attribute on your <class> mappings for telling in which database the table is to be found. (schema can be used too, by appending a dot. It is available in NHibernate since longer, so with an old version you may only have schema.)
Of course, the connection credentials must be valid for accessing both databases.
Other cases
Still using SQL Server, if the second database is on another server, you may use a linked server. You would adjust again the catalog attribute on classes requiring it for specifying the appropriate linkedServerName.DbName.
Maybe other databases could have similar solutions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Double Quotes in Oracle Column Aliases Ok, this is bit of an obscure question, but hopefully someone can help me out with it.
The system I'm working on builds a dynamic SQL string for execution inside a stored procedure, and part of that dynamic SQL defining column aliases, which themselves are actually values retrieved from another table of user generated data.
So, for example, the string might look something like;
SELECT table1.Col1 AS "This is an alias" FROM table1
This works fine. However, the value that is used for the alias can potentially contain a double quote character, which breaks the outer quotes. I thought that I could maybe escape double quotes inside the alias somehow, but I've had no luck figuring out how to do so. Backslash doesn't work, and using two double quotes in a row results in this error;
SQL Error: ORA-03001: unimplemented feature
03001. 00000 - "unimplemented feature"
*Cause: This feature is not implemented.
Has anyone had any experience with this issue before?
Cheers for any insight anyone has.
p.s. the quotes are needed around the aliases because they can contain spaces.
A: Can you just put another character instead of double quotes and replace that with double quotes in the code?
Something like this:
SELECT table1.Col1 AS "This is |not| an alias" FROM table1
Then just replace | with ".
I know it's a hack, but I can't think of any better solution... And what you are doing there is a hack anyway. The "nice" way would be to select the values and the column names separately and associate them in your code. That would make things much cleaner.
A: use the Oracle quote operator:
select q'#someone's quote#' from dual;
the '#' can be replaced by any character
A: When I run this:
select 'test"columnname"' from dual
Oracle returns this (notice the Oracle-generated column name):
'TESTCOLUMNNAME'
--------------------------------
test"columnname
The fact that Oracle's column name doesn't include my double-quote tells me that Oracle probably cannot represent that.
Best bet as far as I can see is to strip double-quotes from your data prior to using column names. Sadly, that will also require that you do the same filtering when you select those columns, but I don't see another way.
A: a possibly fruitful area of investigation would be to look into the quote method.
my $quotedString = $dbh->quote( $string );
A: Try this, two single quotes actually look like one double quote in output:
select 1 as "University ''John Smith''" from dual;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to escape XML content with XSL to safely output it as JSON? How to escape XML content with XSL to safely output it as JSON?
A: Sorry, I have myself found the answer on Google (literaly):
http://code.google.com/p/xml2json-xslt/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Does IE7 have a "developer mode" or plugin like Firefox/Chrome/Safari?
Possible Duplicate:
Debugging JavaScript in IE7
Firefox has Web Developer plugin and Firebug for troubleshooting html/css/javascript issues. Google Chrome and Safari have a very similar console and right-click options for "Inspect Element".
Does IE7 have anything similar for troubleshooting layout/html/css issues?
A: I have also used Debug Bar.
A: Check out the IE Developer toolboar.
A: Yes - The Internet Explorer Developer Toolbar
Download details: Internet Explorer Developer Toolbar
A: Web Development Helper
Web Development Helper is a free browser extension for Internet Explorer that provides a set of tools and utilities for the Web developer, esp. Ajax and ASP.NET developers. The tool provides features such as a DOM inspector, an HTTP tracing tool, and script diagnostics and immediate window.
Web Development Helper works against IE6+, and requires the .NET Framework 2.0 or greater to be installed on the machine.
Once installed, the tool can be activated using the Tools | Web Development Helper command. You can also customize your browser's toolbar to add a button for this command to facilitate frequest use. Clicking on the menu command or browser button brings up the tool's console window and set of commands.
Page Features:
DOM inspector allows viewing all elements, selected elements, or elements matching an ID or CSS class, their attributes and styles.
Capturing a screen shot of the current page.
Viewing page information such as metadata, tags, and linked resources. .......
A: unfortunately it seems microsoft have discontinued it, the page for the toolbar now just says 'We are sorry, the page you requested cannot be found.'
I reckon because its built into 8 they have removed it for download, and cant be bothered with helping out us devs who are forced to make our projects work in their more archaic browsers :'(
Also before anyone says it, IE8 compatability mode != IE7
A: You can also use Firebug Lite, wich works on IE, Opera and Safari.
It's a Javascript implementation that you can load with a simple bookmarklet.
As SO doesn't allow Javascript, here is the bookmarklet source code (just copy paste to your browser location bar (always make sure it's safe before executing random javascript (In any case check the first link)))
javascript:var%20firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);
Firebug Lite supports all basic commands of Firebug.
A: There's a toolbar you can get but it still doesn't match up to Firefox, especially for javascript debugging.
IE8 will be a huge improvement for development.
A: The following is specifically for IE7, other versions are probably similar.
Here is the new link to the developmment tools from microsoft.(as of 4-26-2011) IE Development Tools
Once installed, you will need to enable the toolbar.
To Enable, click on Tools | Manage Add-Ons | Enable or Disable Add-ons, to enable the addon.
To add the icon to the IE Toolbar, right click on the IE menu | Customize Command Bar | Add or Remove Commands. Add the "< (arrow) >" icon.
Hope that helps.
A: You can also use IE watch, which is like firebug, but you need to buy it. It is a 30 days trail version.
A: Actually, the best add-on for developers to IE would be Fiddler. It has a number of features that the other browsers possess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: How do you clear the SQL Server transaction log? I'm not a SQL expert, and I'm reminded of the fact every time I need to do something beyond the basics. I have a test database that is not large in size, but the transaction log definitely is. How do I clear out the transaction log?
A: This technique that John recommends is not recommended as there is no guarantee that the database will attach without the log file. Change the database from full to simple, force a checkpoint and wait a few minutes. The SQL Server will clear the log, which you can then shrink using DBCC SHRINKFILE.
A: Most answers here so far are assuming you do not actually need the Transaction Log file, however if your database is using the FULL recovery model, and you want to keep your backups in case you need to restore the database, then do not truncate or delete the log file the way many of these answers suggest.
Eliminating the log file (through truncating it, discarding it, erasing it, etc) will break your backup chain, and will prevent you from restoring to any point in time since your last full, differential, or transaction log backup, until the next full or differential backup is made.
From the Microsoft article onBACKUP
We recommend that you never use NO_LOG or TRUNCATE_ONLY to manually
truncate the transaction log, because this breaks the log chain. Until
the next full or differential database backup, the database is not
protected from media failure. Use manual log truncation in only very
special circumstances, and create backups of the data immediately.
To avoid that, backup your log file to disk before shrinking it. The syntax would look something like this:
BACKUP LOG MyDatabaseName
TO DISK='C:\DatabaseBackups\MyDatabaseName_backup_2013_01_31_095212_8797154.trn'
DBCC SHRINKFILE (N'MyDatabaseName_Log', 200)
A: The SQL Server transaction log needs to be properly maintained in order to prevent its unwanted growth. This means running transaction log backups often enough. By not doing that, you risk the transaction log to become full and start to grow.
Besides the answers for this question I recommend reading and understanding the transaction log common myths. These readings may help understanding the transaction log and deciding what techniques to use to "clear" it:
From 10 most important SQL Server transaction log myths:
Myth: My SQL Server is too busy. I don’t want to make SQL Server transaction log backups
One of the biggest performance intensive operations in SQL Server is an auto-grow event of the online transaction log file. By not making transaction log backups often enough, the online transaction log will become full and will have to grow. The default growth size is 10%. The busier the database is, the quicker the online transaction log will grow if transaction log backups are not created
Creating a SQL Server transaction log backup doesn’t block the online transaction log, but an auto-growth event does. It can block all activity in the online transaction log
From Transaction log myths:
Myth: Regular log shrinking is a good maintenance practice
FALSE. Log growth is very expensive because the new chunk must be zeroed-out. All write activity stops on that database until zeroing is finished, and if your disk write is slow or autogrowth size is big, that pause can be huge and users will notice. That’s one reason why you want to avoid growth. If you shrink the log, it will grow again and you are just wasting disk operation on needless shrink-and-grow-again game
A: Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take.
First, take a full backup
Never make any changes to your database without ensuring you can restore it should something go wrong.
If you care about point-in-time recovery
(And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.)
Presumably your database is in FULL recovery mode. If not, then make sure it is:
ALTER DATABASE testdb SET RECOVERY FULL;
Even if you are taking regular full backups, the log file will grow and grow until you perform a log backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful).
DECLARE @path NVARCHAR(255) = N'\\backup_share\log\testdb_'
+ CONVERT(CHAR(8), GETDATE(), 112) + '_'
+ REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','')
+ '.trn';
BACKUP LOG foo TO DISK = @path WITH INIT, COMPRESSION;
Note that \\backup_share\ should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database and its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible.
Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does not mean running SHRINKFILE over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it.
Note that you may need to back up the log twice before a shrink is possible (thanks Robert).
So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way:
USE [master];
GO
ALTER DATABASE Test1
MODIFY FILE
(NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);
GO
Note that if the log file is currently > 200 MB, you may need to run this first:
USE yourdb;
GO
DBCC SHRINKFILE(yourdb_log, 200);
GO
If you don't care about point-in-time recovery
If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in SIMPLE recovery mode.
ALTER DATABASE testdb SET RECOVERY SIMPLE;
Putting the database in SIMPLE recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of all transactions (like FULL recovery does until you back up the log). CHECKPOINT events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between CHECKPOINTs.
Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following:
USE yourdb;
GO
CHECKPOINT;
GO
CHECKPOINT; -- run twice to ensure file wrap-around
GO
DBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs
GO
Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters.
Some things you don't want to do
*
*Back up the log with TRUNCATE_ONLY option and then SHRINKFILE. For one, this TRUNCATE_ONLY option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in FULL recovery model, this will destroy your log chain and require a new, full backup.
*Detach the database, delete the log file, and re-attach. I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc.
*Use the "shrink database" option. DBCC SHRINKDATABASE and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using DBCC SHRINKFILE or ALTER DATABASE ... MODIFY FILE (examples above).
*Shrink the log file to 1 MB. This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using ALTER DATABASE), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully?
*Create a second log file. This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. Paul Randal also explains why multiple log files can bite you later.
Be proactive
Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations.
The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and asked for changes to no avail) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve).
Further reading
Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space.
A blog post I wrote in 2009, when I saw a few "here's how to shrink the log file" posts spring up.
A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should not have been published.
A blog post by Paul Randal explaining why t-log maintenance is important and why you shouldn't shrink your data files, either.
Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately.
A: Below is a script to shrink the transaction log, but I’d definitely recommend backing up the transaction log before shrinking it.
If you just shrink the file you are going to lose a ton of data that may come as a life saver in case of disaster. The transaction log contains a lot of useful data that can be read using a third-party transaction log reader (it can be read manually but with extreme effort though).
The transaction log is also a must when it comes to point in time recovery, so don’t just throw it away, but make sure you back it up beforehand.
Here are several posts where people used data stored in the transaction log to accomplish recovery:
*
*How to view transaction logs in SQL Server 2008
*Read the log file (*.LDF) in SQL Server 2008
USE DATABASE_NAME;
GO
ALTER DATABASE DATABASE_NAME
SET RECOVERY SIMPLE;
GO
--First parameter is log file name and second is size in MB
DBCC SHRINKFILE (DATABASE_NAME_Log, 1);
ALTER DATABASE DATABASE_NAME
SET RECOVERY FULL;
GO
You may get an error that looks like this when the executing commands above
“Cannot shrink log file (log file name) because the logical
log file located at the end of the file is in use“
This means that TLOG is in use. In this case try executing this several times in a row or find a way to reduce database activities.
A: Use the DBCC ShrinkFile ({logicalLogName}, TRUNCATEONLY) command. If this is a test database and you are trying to save/reclaim space, this will help.
Remember though that TX logs do have a sort of minimum/steady state size that they will grow up to. Depending upon your recovery model you may not be able to shrink the log - if in FULL and you aren't issuing TX log backups the log can't be shrunk - it will grow forever. If you don't need TX log backups, switch your recovery model to Simple.
And remember, never ever under any circumstances delete the log (LDF) file! You will pretty much have instant database corruption. Cooked! Done! Lost data! If left "unrepaired" the main MDF file could become corrupt permanently.
Never ever delete the transaction log - you will lose data! Part of your data is in the TX Log (regardless of recovery model)... if you detach and "rename" the TX log file that effectively deletes part of your database.
For those that have deleted the TX Log you may want to run a few checkdb commands and fix the corruption before you lose more data.
Check out Paul Randal's blog posts on this very topic, bad advice.
Also in general do not use shrinkfile on the MDF files as it can severely fragment your data. Check out his Bad Advice section for more info ("Why you should not shrink your data files")
Check out Paul's website - he covers these very questions. Last month he walked through many of these issues in his Myth A Day series.
A: To Truncate the log file:
*
*Backup the database
*Detach the database, either by using Enterprise Manager or by executing : Sp_DetachDB [DBName]
*Delete the transaction log file. (or rename the file, just in case)
*Re-attach the database again using: Sp_AttachDB [DBName]
*When the database is attached, a new transaction log file is created.
To Shrink the log file:
*
*Backup log [DBName] with No_Log
*Shrink the database by either:
Using Enterprise manager :-
Right click on the database, All tasks, Shrink database, Files, Select log file, OK.
Using T-SQL :-
Dbcc Shrinkfile ([Log_Logical_Name])
You can find the logical name of the log file by running sp_helpdb or by looking in the properties of the database in Enterprise Manager.
A: First check the database recovery model. By default, SQL Server Express Edition creates a database for the simple recovery
model (if I am not mistaken).
Backup log DatabaseName With Truncate_Only:
DBCC ShrinkFile(yourLogical_LogFileName, 50)
SP_helpfile will give you the logical log file name.
Refer to:
Recover from a full transaction log in a SQL Server database
If your database is in Full Recovery Model and if you are not taking TL backup, then change it to SIMPLE.
A: It happened with me where the database log file was of 28 GBs.
What can you do to reduce this?
Actually, log files are those file data which the SQL server keeps when an transaction has taken place. For a transaction to process SQL server allocates pages for the same. But after the completion of the transaction, these are not released suddenly hoping that there may be a transaction coming like the same one. This holds up the space.
Step 1:
First Run this command in the database query explored
checkpoint
Step 2:
Right click on the database
Task> Back up
Select back up type as Transaction Log
Add a destination address and file name to keep the backup data (.bak)
Repeat this step again and at this time give another file name
Step 3:
Now go to the database
Right-click on the database
Tasks> Shrinks> Files
Choose File type as Log
Shrink action as release unused space
Step 4:
Check your log file
normally in SQL 2014 this can be found at
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQL2014EXPRESS\MSSQL\DATA
In my case, its reduced from 28 GB to 1 MB
A: Here is a simple and very inelegant & potentially dangerous way.
*
*Backup DB
*Detach DB
*Rename Log file
*Attach DB
*New log file will be recreated
*Delete Renamed Log file.
I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from full to simple. This will prevent log bloat.
A: If you do not use the transaction logs for restores (i.e. You only ever do full backups), you can set Recovery Mode to "Simple", and the transaction log will very shortly shrink and never fill up again.
If you are using SQL 7 or 2000, you can enable "truncate log on checkpoint" in the database options tab. This has the same effect.
This is not recomended in production environments obviously, since you will not be able to restore to a point in time.
A: To my experience on most SQL Servers there is no backup of the transaction log.
Full backups or differential backups are common practice, but transaction log backups are really seldom.
So the transaction log file grows forever (until the disk is full).
In this case the recovery model should be set to "simple".
Don't forget to modify the system databases "model" and "tempdb", too.
A backup of the database "tempdb" makes no sense, so the recovery model of this db should always be "simple".
A: -- DON'T FORGET TO BACKUP THE DB :D (Check [here][1])
USE AdventureWorks2008R2;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks2008R2
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks2008R2_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks2008R2
SET RECOVERY FULL;
GO
From: DBCC SHRINKFILE (Transact-SQL)
You may want to backup first.
A: *
*Take a backup of the MDB file.
*Stop SQL services
*Rename the log file
*Start the service
(The system will create a new log file.)
Delete or move the renamed log file.
A: Database → right click Properties → file → add another log file with a different name and set the path the same as the old log file with a different file name.
The database automatically picks up the newly created log file.
A: DISCLAIMER: Please read comments below this answer carefully before attempting it, and be sure to check the accepted answer. As I said nearly 5 years ago:
if anyone has any comments to add for situations when this is NOT an
adequate or optimal solution then please comment below
Turns out there were :-)
Original Answer:
*
*Right click on the database name.
*Select Tasks → Shrink → Database
*Then click OK!
I usually open the Windows Explorer directory containing the database files, so I can immediately see the effect.
I was actually quite surprised this worked! Normally I've used DBCC before, but I just tried that and it didn't shrink anything, so I tried the GUI (2005) and it worked great - freeing up 17 GB in 10 seconds
In Full recovery mode this might not work, so you have to either back up the log first, or change to Simple recovery, then shrink the file. [thanks @onupdatecascade for this]
--
PS: I appreciate what some have commented regarding the dangers of this, but in my environment I didn't have any issues doing this myself especially since I always do a full backup first. So please take into consideration what your environment is, and how this affects your backup strategy and job security before continuing. All I was doing was pointing people to a feature provided by Microsoft!
A: Try this:
USE DatabaseName
GO
DBCC SHRINKFILE( TransactionLogName, 1)
BACKUP LOG DatabaseName WITH TRUNCATE_ONLY
DBCC SHRINKFILE( TransactionLogName, 1)
GO
A: Slightly updated answer, for MSSQL 2017, and using the SQL server management studio.
I went mostly from these instructions https://www.sqlshack.com/sql-server-transaction-log-backup-truncate-and-shrink-operations/
I had a recent db backup, so I backed up the transaction log. Then I backed it up again for good measure.
Finally I shrank the log file, and went from 20G to 7MB, much more in line with the size of my data.
I don't think the transaction logs had ever been backed up since this was installed 2 years ago.. so putting that task on the housekeeping calendar.
A: *
*Backup DB
*Detach DB
*Rename Log file
*Attach DB (while attaching remove renamed .ldf (log file).Select it and remove by pressing Remove button)
*New log file will be recreated
*Delete Renamed Log file.
This will work but it is suggested to take backup of your database first.
A: Some of the other answers did not work for me: It was not possible to create the checkpoint while the db was online, because the transaction log was full (how ironic). However, after setting the database to emergency mode, I was able to shrink the log file:
alter database <database_name> set emergency;
use <database_name>;
checkpoint;
checkpoint;
alter database <database_name> set online;
dbcc shrinkfile(<database_name>_log, 200);
A: DB Transaction Log Shrink to min size:
*
*Backup: Transaction log
*Shrink files: Transaction log
*Backup: Transaction log
*Shrink files: Transaction log
I made tests on several number of DBs: this sequence works.
It usually shrinks to 2MB.
OR by a script:
DECLARE @DB_Name nvarchar(255);
DECLARE @DB_LogFileName nvarchar(255);
SET @DB_Name = '<Database Name>'; --Input Variable
SET @DB_LogFileName = '<LogFileEntryName>'; --Input Variable
EXEC
(
'USE ['+@DB_Name+']; '+
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2) ' +
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2)'
)
GO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "660"
} |
Q: How can I get a fixed-position menu like slashdot's comment filtration menu Slashdot has a little widget that allows you to tweak your comment threshold to filter out down-modded comments. It will be in one place if you scroll to the top of the page, and as you scroll down, at some point, where its original home is about to scroll off the page, it will switch to fixed position, and stay on your screen. (To see an example, click here.)
My question is, how can I accomplish the same effect of having a menu be in one place when scrolled up, and switch to fixed position as the user scrolls down? I know this will involve a combination of CSS and javascript. I'm not necessarily looking for a full example of working code, but what steps will my code need to go through?
A: Okay, I figured it out. I will post it here in case it help anyone else. This solution uses prototype, and an internal library that gives me the registerEvent, getElementX and getElementY functions, which do what you would think.
var MenuManager = Class.create({
initialize: function initialize(menuElt) {
this.menu = $(menuElt);
this.homePosn = { x: getElementX(this.menu), y: getElementY(this.menu) };
registerEvent(document, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.menu.style.position = 'fixed';
this.menu.style.top = 0;
this.menu.style.left = this.homePosn.x;
} else {
this.menu.style.position = 'absolute';
this.menu.style.top = null;
this.menu.style.left = null;
}
}
});
Just call the constructor with the id of your menu, and the class will take it from there.
A: Thanks for the effort of sharing this code.
I made some small changes to make it work with the current release of Prototype.
var TableHeaderManager = Class.create({
initialize: function initialize(headerElt) {
this.tableHeader = $(headerElt);
this.homePosn = { x: this.tableHeader.cumulativeOffset()[0], y: this.tableHeader.cumulativeOffset()[1] };
Event.observe(window, 'scroll', this.handleScroll.bind(this));
this.handleScroll();
},
handleScroll: function handleScroll() {
this.scrollOffset = document.viewport.getScrollOffsets().top;
if (this.scrollOffset > this.homePosn.y) {
this.tableHeader.style.position = 'fixed';
this.tableHeader.style.top = 0;
this.tableHeader.style.left = this.homePosn.x;
} else {
this.tableHeader.style.position = 'absolute';
this.tableHeader.style.top = null;
this.tableHeader.style.left = null;
}
}
});
A: For a demo but not based on the code above checkout:
fixed-floating-elements
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to convert from PRTime to .NET datetime I want to convert a number that is in PRTime format (a 64-bit integer representing the number of microseconds since midnight (00:00:00) 1 January 1970 Coordinated Universal Time (UTC)) to a DateTime.
Note that this is slightly different than the usual "number of milliseconds since 1/1/1970".
A: Dim prTimeInMillis As UInt64
prTimeInMillis = prTime/1000
Dim prDateTime As New DateTime(1970, 1, 1)
prDateTime = prDateTime.AddMilliseconds(prTimeInMillis)
A: DateTime has a constructor that takes Ticks (which are 100 nanoseconds).
So take your prTime, multiply it by 10 and add it to the number of ticks representing the Epoch time and you have your conversion.
private static DateTime epoch = new DateTime(1970, 1, 1);
private static DateTime ConvertPrTime(long time)
{
return new DateTime(epoch.Ticks + (time*10), DateTimeKind.Utc);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loader lock error I am building on C++ dll, by writing code in C#.
I get an error, saying
LoaderLock was detected Message:
Attempting managed execution inside OS
Loader lock. Do not attempt to run
managed code inside a DllMain or image
initialization function since doing so
can cause the application to hang.
I tried seraching what this error exactly means, but I am drawing pointless articles, mostly saying that it's just a warning, and I should switch that off in Visual Studio.
The other solutions seem to be due to ITunes, or this problem occurring when programming with DirectX. My problem is connected to neither.
Can anybody explain, what this actually means?
A: you need to go to menu Debug -> Exceptions, open the Managed Debugging Assistants, find LoaderLock and uncheck
A: kindly remind those VS2017 users that you need to disable "exception helper" instead of "exception assistant"(before VS2017) to prevent from loader lock error, which setting path is Debug->Exception. Just ran int to this problem and wasted 2 hours searching for solutions...
A: Press ctr d+e Then Expend Managed Debugging Assistants Node. Then Unchecked the LoaderLock.
Hope this will help you.
A: The general idea of loader lock:
The system runs the code in DllMain inside a lock (as in - synchronization lock). Therefore, running non-trivial code inside DllMain is "asking for a deadlock", as described here.
The question is, why are you trying to run code inside DllMain? Is it crucial that this code run inside the context of DllMain or can you spawn a new thread and run the code in it, and not wait for the code to finish execution inside DllMain?
I believe that the problem with manged code specifically, is that running managed code might involves loading the CLR and suchlike and there's no knowing what could happen there that would result in a deadlock... I would not heed the advice of "disable this warning" if I were you because most chances are you'll find your applications hangs unexpectedly under some scenarios.
A: I recently got this error while creating an instance of an COM-Object written in native code:
m_ComObject = Activator.CreateInstance(Type.GetTypeFromProgID("Fancy.McDancy"));
This led to the described error. A "LoaderLock was detected"-Exception was thrown.
I overcame this error by creating the object-instance in an extra thread:
ThreadStart threadRef = new ThreadStart(delegate { m_ComObject = Activator.CreateInstance(Type.GetTypeFromProgID("Fancy.McDancy")); });
Thread myThread = new Thread(threadRef);
myThread.Start();
myThread.Join(); // for synchronization
A: I'm building a C++ CLR DLL (MSVS2015) that has to make calls into an unmanaged DLL and define unmanaged code. I use #pragma managed and #pragma unmanaged to control what mode it is in for a given area of the code.
In my case I simply put #pragma unmanaged in front of my DllMain() and this solved the problem.
It seemed to be thinking I wanted a managed version of DllMain().
A: UPDATE FOR .NET 4.0 AND MORE RECENT FRAMEWORKS
This is an old question asked at the time of .Net 2.0, when support for mixed mode DLLs had serious initialization problems, prone to random deadlocks. As of .Net 4.0, the initialization of mixed mode DLLs has changed. Now there are two separate stages of initialization:
*
*Native initialization, called at the DLL's entry point, which includes native C++ run-time setup and execution of your DllMain method.
*Managed initialization, executed automatically by system loader.
Since step #2 is performed outside of the Loader Lock, there is no deadlocks. The details are described at Initialization of Mixed Assemblies.
To ensure your mixed mode assembly can be loaded from a native executable, the only thing you need to check is that DllMain method is declared as native code. #pragma unmanaged could help here:
#pragma unmanaged
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
... // your implementation here
}
It is also important that any code that DllMain might call directly or indirectly is also unmanaged. It makes sense to limit the type of functionality used by DllMain so you trace all code reachable from DllMain and ensure it is all compiled with #pragma unmanaged.
Compiler helps a little by giving you warining C4747 if it detects that DllMain is not declared as unmanaged:
1> Generating Code...
1>E:\src\mixedmodedll\dllmain.cpp : warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock, including the DLL entrypoint and calls reached from the DLL entrypoint
However compiler won't generate any warnings if DllMain indirectly calls some other managed function, so you need to ensure that never happens, otherwise your application could deadlock randomly.
A: The setting path in my visual studio 2017 instance is Debug -> Windows -> Exception Settings . The exception settings "window" showed up in the bottom tab group (as opposed to a separate window), took me a while to notice it. Search for "loader".
A: This problem occurs because of the way in which the debugger in Visual Studio runs managed applications that use Microsoft Foundation Classes version 8.0 in one or more DLL files.
Have a thorough reading at: http://msdn.microsoft.com/en-us/library/aa290048(vs.71).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "101"
} |
Q: How do I detect if a Windows server is available after a reboot? I want to automate a Windows 2000+ server reboot process using Task Scheduler or similar tool to remotely reboot a server and wait for it to come back up. I can issue shutdown or psshutdown to remotely reboot, but I want something better than sleep to wait for it to come back. I need to verify it is back online within n minutes or throw an error.
By 'back online', I would like to verify more than just that it can be pinged, but perhaps its RFC service is responding or some other determinate vital sign.
I'd prefer an NT script approach, but I'm not ruling out writing a custom tool to do this.
Any ideas?
A: After working on this for a while, I came up with the following VBScript. Feel free to comment/improve.
'
' Remotely reboot a server and
' wait for server to come back up.
'
' Usage: cscript /nologo /E:VBScript RebootWait.vbs <Server Name>
'
' Shawn Poulson, 2008.09.11
'
'
' Get server name from command line
'
If WScript.Arguments.Count <> 1 Then
ShowUsage()
WScript.Quit(1)
End If
ServerName = WScript.Arguments(0)
'
' Verify server is currently up
'
WScript.StdOut.WriteLine Now & ": Verify server '" & ServerName & "' is currently up..."
If Not IsAvailable(ServerName) Then
WScript.StdOut.WriteLine "Error: Server is down. Reboot aborted!"
WScript.Quit(1)
End If
WScript.StdOut.WriteLine Now & ": Server is up."
'
' Reboot server
'
WScript.StdOut.WriteLine Now & ": Rebooting server '" & ServerName & "'..."
RebootStatus = RebootServer(ServerName)
If RebootStatus < 0 Then
WScript.StdOut.WriteLine "Error: Reboot returned error " & RebootStatus
WScript.Quit(1)
End If
WScript.StdOut.WriteLine Now & ": Reboot command was successful"
'
' Wait for server to come down
'
WScript.StdOut.Write Now & ": Waiting for server '" & ServerName & "' to go down..."
WaitCount = 0
Do While IsAvailable(ServerName)
WaitCount = WaitCount + 1
If WaitCount > 60 Then ' 5 min timeout
WScript.StdOut.WriteLine "Error: Timeout waiting for server to come down!"
WScript.Quit(1)
End If
WScript.StdOut.Write(".")
WScript.Sleep(5000)
Loop
WScript.StdOut.WriteLine "Success!"
WScript.StdOut.WriteLine Now & ": Server is down."
'
' Wait for server to come back up
'
WScript.StdOut.Write Now & ": Waiting for server '" & ServerName & "' to come back up..."
WaitCount = 0
Do While Not IsAvailable(ServerName)
WaitCount = WaitCount + 1
If WaitCount > 240 Then ' 20 min timeout
WScript.StdOut.WriteLine "Error: Timeout waiting for server to come back up!"
WScript.Quit(1)
End If
WScript.StdOut.Write(".")
WScript.Sleep(5000)
Loop
WScript.StdOut.WriteLine "Success!"
WScript.StdOut.WriteLine Now & ": Server is back up after reboot."
'
' Success!
'
WScript.Quit(0)
Sub ShowUsage()
WScript.Echo "Usage: " & WScript.ScriptName & " <Server name>"
End Sub
' Returns:
' 1 = Successfully issued reboot command
' -2 = Could not reach server
' -3 = Reboot command failed
Function RebootServer(ServerName)
Dim OpSystem
On Error Resume Next
For Each OpSystem in GetObject("winmgmts:{(Shutdown)}!\\" & ServerName & "\root\CIMV2").ExecQuery("select * from Win32_OperatingSystem where Primary=true")
On Error GoTo 0
If IsObject(OpSystem) Then
' Invoke forced reboot
If OpSystem.Win32Shutdown(6, 0) = 0 Then
' Success
RebootServer = 1
Else
' Command failed
RebootServer = -3
End If
Else
RebootServer = -2
End If
Next
End Function
' Return True if available
Function IsAvailable(ServerName)
' Use Windows RPC service state as vital sign
IsAvailable = (GetServiceState(ServerName, "RpcSs") = "Running")
End Function
' Return one of:
' Stopped, Start Pending, Stop Pending,
' Running, Continue Pending, Pause Pending,
' Paused, Unknown
Function GetServiceState(ServerName, ServiceName)
Dim Service
On Error Resume Next
Set Service = GetObject("winmgmts:\\" & ServerName & "\root\CIMV2:Win32_Service='" & ServiceName & "'")
On Error GoTo 0
If IsObject(Service) Then GetServiceState = Service.State
End Function
A: Your remote restart script could start the server, wait n minutes, then query your RFC service. You could also have a local script on the server do the same thing.
A: You could use psservice to query the status of the RFC or Print Spooler services. The Spooler is usually one of the last services to start. You could use syntax like:
psservice \\someothermachine query spooler
That will return something like this once the service is running.
SERVICE_NAME: Spooler
DISPLAY_NAME: Print Spooler
Manages all local and network print queues and controls all printing jobs. If this service is stop
ped, printing on the local machine will be unavailable. If this service is disabled, any services
that explicitly depend on it will fail to start.
GROUP : SpoolerGroup
TYPE : 110 WIN32_OWN_PROCESS INTERACTIVE_PROCESS
STATE : 4 RUNNING
(STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
If the other machine is not ready, you'll get something like
Unable to connect to \\someothermachine:
The RPC server is unavailable.
A: With VBScript (WSH) you could check it with the .state property. This script shows that property being used in a different application but should help illustrate the idea:
http://www.robvanderwoude.com/vbstech_proc_service.html
A: You can poll some core service to see if it has started:
sc "\\server_name" query EventSystem
A: Use nmap to get a list of open services on the machine and parse the results to make sure what you need is active. It's also useful to make sure that things you don't need are not active.
A: The key here is I need to script this. Is there a cleaner way to extract the service status from psservice/sc query? I'm able to pipe it to findstr "RUNNING", but there's got to be a better way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What's the Best Way to Shuffle an NSMutableArray? If you have an NSMutableArray, how do you shuffle the elements randomly?
(I have my own answer for this, which is posted below, but I'm new to Cocoa and I'm interested to know if there is a better way.)
Update: As noted by @Mukesh, as of iOS 10+ and macOS 10.12+, there is an -[NSMutableArray shuffledArray] method that can be used to shuffle. See https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc for details. (But note that this creates a new array, rather than shuffling the elements in place.)
A: You don't need the swapObjectAtIndex method. exchangeObjectAtIndex:withObjectAtIndex: already exists.
A: This is the simplest and fastest way to shuffle NSArrays or NSMutableArrays
(object puzzles is a NSMutableArray, it contains puzzle objects. I've added to
puzzle object variable index which indicates initial position in array)
int randomSort(id obj1, id obj2, void *context ) {
// returns random number -1 0 1
return (random()%3 - 1);
}
- (void)shuffle {
// call custom sort function
[puzzles sortUsingFunction:randomSort context:nil];
// show in log how is our array sorted
int i = 0;
for (Puzzle * puzzle in puzzles) {
NSLog(@" #%d has index %d", i, puzzle.index);
i++;
}
}
log output:
#0 has index #6
#1 has index #3
#2 has index #9
#3 has index #15
#4 has index #8
#5 has index #0
#6 has index #1
#7 has index #4
#8 has index #7
#9 has index #12
#10 has index #14
#11 has index #16
#12 has index #17
#13 has index #10
#14 has index #11
#15 has index #13
#16 has index #5
#17 has index #2
you may as well compare obj1 with obj2 and decide what you want to return
possible values are:
*
*NSOrderedAscending = -1
*NSOrderedSame = 0
*NSOrderedDescending = 1
A: Since I can't yet comment, I thought I'd contribute a full response. I modified Kristopher Johnson's implementation for my project in a number of ways (really trying to make it as concise as possible), one of them being arc4random_uniform() because it avoids modulo bias.
// NSMutableArray+Shuffling.h
#import <Foundation/Foundation.h>
/** This category enhances NSMutableArray by providing methods to randomly
* shuffle the elements using the Fisher-Yates algorithm.
*/
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
// NSMutableArray+Shuffling.m
#import "NSMutableArray+Shuffling.h"
@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
NSUInteger count = [self count];
for (uint i = 0; i < count - 1; ++i)
{
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = arc4random_uniform(nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
@end
A: I solved this by adding a category to NSMutableArray.
Edit: Removed unnecessary method thanks to answer by Ladd.
Edit: Changed (arc4random() % nElements) to arc4random_uniform(nElements) thanks to answer by Gregory Goltsov and comments by miho and blahdiblah
Edit: Loop improvement, thanks to comment by Ron
Edit: Added check that array is not empty, thanks to comment by Mahesh Agrawal
// NSMutableArray_Shuffling.h
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif
// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end
// NSMutableArray_Shuffling.m
#import "NSMutableArray_Shuffling.h"
@implementation NSMutableArray (Shuffling)
- (void)shuffle
{
NSUInteger count = [self count];
if (count <= 1) return;
for (NSUInteger i = 0; i < count - 1; ++i) {
NSInteger remainingCount = count - i;
NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
[self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}
}
@end
A: From iOS 10, you can use NSArray shuffled() from GameplayKit. Here is an helper for Array in Swift 3:
import GameplayKit
extension Array {
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func shuffled() -> [Element] {
return (self as NSArray).shuffled() as! [Element]
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
mutating func shuffle() {
replaceSubrange(0..<count, with: shuffled())
}
}
A: There is a nice popular library, that has this method as it's part, called SSToolKit in GitHub.
File NSMutableArray+SSToolkitAdditions.h contains shuffle method. You can use it also. Among this, there seem to be tons of useful things.
The main page of this library is here.
If you use this, your code will be like this:
#import <SSCategories.h>
NSMutableArray *tableData = [NSMutableArray arrayWithArray:[temp shuffledArray]];
This library also has a Pod (see CocoaPods)
A: If you import GameplayKit, there is a shuffled API:
https://developer.apple.com/reference/foundation/nsarray/1640855-shuffled
let shuffledArray = array.shuffled()
A: A slightly improved and concise solution (compared to the top answers).
The algorithm is the same and is described in literature as "Fisher-Yates shuffle".
In Objective-C:
@implementation NSMutableArray (Shuffle)
// Fisher-Yates shuffle
- (void)shuffle
{
for (NSUInteger i = self.count; i > 1; i--)
[self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
}
@end
In Swift 3.2 and 4.x:
extension Array {
/// Fisher-Yates shuffle
mutating func shuffle() {
for i in stride(from: count - 1, to: 0, by: -1) {
swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))
}
}
}
In Swift 3.0 and 3.1:
extension Array {
/// Fisher-Yates shuffle
mutating func shuffle() {
for i in stride(from: count - 1, to: 0, by: -1) {
let j = Int(arc4random_uniform(UInt32(i + 1)))
(self[i], self[j]) = (self[j], self[i])
}
}
}
Note: A more concise solution in Swift is possible from iOS10 using GameplayKit.
Note: An algorithm for unstable shuffling (with all positions forced to change if count > 1) is also available
A: If elements have repeats.
e.g. array: A A A B B or B B A A A
only solution is: A B A B A
sequenceSelected is an NSMutableArray which stores elements of class obj, which are pointers to some sequence.
- (void)shuffleSequenceSelected {
[sequenceSelected shuffle];
[self shuffleSequenceSelectedLoop];
}
- (void)shuffleSequenceSelectedLoop {
NSUInteger count = sequenceSelected.count;
for (NSUInteger i = 1; i < count-1; i++) {
// Select a random element between i and end of array to swap with.
NSInteger nElements = count - i;
NSInteger n;
if (i < count-2) { // i is between second and second last element
obj *A = [sequenceSelected objectAtIndex:i-1];
obj *B = [sequenceSelected objectAtIndex:i];
if (A == B) { // shuffle if current & previous same
do {
n = arc4random_uniform(nElements) + i;
B = [sequenceSelected objectAtIndex:n];
} while (A == B);
[sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:n];
}
} else if (i == count-2) { // second last value to be shuffled with last value
obj *A = [sequenceSelected objectAtIndex:i-1];// previous value
obj *B = [sequenceSelected objectAtIndex:i]; // second last value
obj *C = [sequenceSelected lastObject]; // last value
if (A == B && B == C) {
//reshufle
sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];
[self shuffleSequenceSelectedLoop];
return;
}
if (A == B) {
if (B != C) {
[sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:count-1];
} else {
// reshuffle
sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];
[self shuffleSequenceSelectedLoop];
return;
}
}
}
}
}
A: Edit: This is not correct. For reference purposes, I did not delete this post. See comments on the reason why this approach is not correct.
Simple code here:
- (NSArray *)shuffledArray:(NSArray *)array
{
return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if (arc4random() % 2) {
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}];
}
A: NSUInteger randomIndex = arc4random() % [theArray count];
A: Kristopher Johnson's answer is pretty nice, but it's not totally random.
Given an array of 2 elements, this function returns always the inversed array, because you are generating the range of your random over the rest of the indexes. A more accurate shuffle() function would be like
- (void)shuffle
{
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
NSInteger exchangeIndex = arc4random_uniform(count);
if (i != exchangeIndex) {
[self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "192"
} |
Q: How do I access performance counters from C# in Windows XP Embedded? I have an application running under Windows XP, and I'm accessing the Processor and Memory performance counters. When I try to run the same code and access them on XP Embedded, the counters don't seem to be present. They are present in the image - I can see them all in perfmon. What's the missing piece here?
A: Have you added all the WMI components? As far as I know, you need all the WMI components to access the counters!
The Performance Counter Windows Management Instrumentation (WMI) Provider component provides a bridge between the performance registry interface and the WMI interface. This component allows WMI clients to access performance counters through WMI scripts, and allows management applications built using WMI to access performance counters. Without this component, applications must directly use the registry interface or the performance data helper interface to access performance counters.
Thank you TimK for the link (http://msdn.microsoft.com/en-us/library/aa939695.aspx)
A: It looks like this is what I was missing: http://msdn.microsoft.com/en-us/library/aa939695.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Arithmetic underflow or overflow exception during debugging This is the day of weird behavior.
We have a Win32 project made with Delphi 2007, which hosts the .NET runtime and calls into .NET to show new forms, as part of a transition period.
Recently we've begun experiencing exceptions at seemingly random locations and points of our code: Arithmetic overflow or underflow.
The stack trace of one of these looks like this:
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at Gatsoft.Gat.UI.Windows.Forms.Remanaging.RemanageForm.DelphiOpenInNewMode(String employeeCode, String departmentCode, DateTime date) in C:\Dev\VS.NET\Gatsoft\Gatsoft.Gat.UI.Windows\Forms\Remanaging\RemanageForm.Delphi.cs:line 67
In the Visual Studio solution, one of the outmost class libraries (ie. pulls in all the references it can), has set a specific debug program, targetted for the Delphi project output. This allows us to debug .NET code from Visual Studio, even though the main bulk of the program is written in Delphi.
The problem only occurs when run from the debugger, not if we just run the exe file directly (either through explorer, shortcuts, or even Ctrl+F5 inside Visual Studio).
There's apparently no spyware on the machine (as hinted by this).
Any other things we can check?
Edit: It looks like the .NET debugger is enabling this SNaN flags, and the Delphi debugger does not. We'll have to investigate this further, but for now I'll accept @Lorenzo Boccaccia's answer.
Apparently Solved
Ok, it looks like we've finally nailed this problem. The problem started occuring without having the debugger attached as well, for our testers, so we had to prioritize the problem way up.
Finally we found one common issue with the machines that had the problem, they are Dell Lattitude D620 laptops with an NVIDIA Quadro NVS 110M, with an old driver from a system image used to provision the laptops, from back in 2006.
I found one post on the web, though I lost the url when I rebooted to update the display driver, that had a .NET service crashing, mostly when the machine was busy doing something on the screen. One way to reproduce his problem was to open a command prompt to C:\ and doing a DIR /S to just force a massive amount of screen updates, which would trigger the crash.
He too had a NVIDIA video card.
The problem on my machine occured roughly every 2-4 startups of our program, but after updating the video driver I've had 123 successfull startups without any problems. (BTW I can recommend AutoHotKey for such things).
So it looks like we've found the culprit, an old/buggy NVIDIA driver.
Updated this question so that perhaps someone in the future can save some time.
Now, if you'll excuse me, I'm going to go cry in a corner.
Jinxed!
I must've jinxed it. No sooner had I posted the above update than a colleague laptop failed, after updating the video driver.
Still, I'm positive it's a problem outside of our application now, so it just remains to figure out which specific things to update.
Further updates: Ok, my machine is now apparently fixed, not so with my colleagues machine. So far we've updated the BIOS, Chipset drivers, and currently SP3 for XP is on its way in.
A burn-in test will be done tonight, where the app will be left overnight starting up, as the problem cropped up either during startup, or at the first time some WinForms .NET code was executed. This app is mainly a Delphi Win32 app, but it hosts the .NET runtime, and the problem seems to be related to .NET code. When we "boot" the .NET runtime, the problem can appear, or when we fire the first .NET window from Win32 then it can also appear.
Statistically I'm ready to release this code now. Over the night the application has been started 3051 times without errors, whereas before I updated the video driver it crashed every 2-4 times.
Prodded and found(!/?)
This bug-fixing ordeal feels like going to the doctor, where the following conversation ensues:
Doc: Does this hurt?
Me: No...
Doc: What about now?
I've prodded and poked the application and finally I think I've found something we did that introduced this problem.
In our app we host the .NET runtime, from a Delphi 2007 Win32 application, and in our glue-code we have the following line (now):
rc := CorBindToRuntimeEx('v2.0.50727', 'wks',
STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN or STARTUP_CONCURRENT_GC,
@clsid, @iid, UnkRuntimeEngine);
The two constants in the middle there was originally just a 0, meaning pick the defaults. This change was introduced a few months ago and the problem has been slowly creeping in on us after this. The change was introduced in order to encourage ANTS profiler to load our Win32 application + hosted .NET runtime in order to do performance profiling and the changes we introduced back then made that work. Additionally, the problem with arithmetic overflow/underflow has slowly been getting worse so I bet the problem didn't appear for a while after the change so it wasn't attributed to any of the changes we did.
Also, since we only (originally) saw the problem when running through the debugger, we thought something was wrong with Visual Studio and/or Delphi.
Anyway, statistically now, with a browser on one screen doing repeated scrolling up and down triggered by a javascript (apparently needed in order to trigger the bug), then I have been able to successfully start the application 726 times with a 0 in the call, and it crashes 5 out of 17 times with the two constants there.
Doc: Does this hurt?
And let's not get into who made that change in the first place. I'm sure the culprit wants to be left anonymous... cough
A: Do the errors occur still occur if you attach the debugger after starting the application?
A: a debug version of a linked dll could be compiled with signaling nan support, see http://blogs.msdn.com/oldnewthing/archive/2008/07/02/8679191.aspx for an example of this problem.
that heisenbug was caused by uninitialized variables, here there could be a linked dll enabling the snan feature of the cpu and forgetting to disable it upon returning
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Copying a directory that is version controlled I am curious whether it is OK to copy a directory that is under version control and start working on both copies.
I know it can be different from one VCS to another, but I intentionally don't specify any VCS since I am curious about different cases.
I was talking to a coworker recently about doing it in SVN. I think it should be OK, but I am still not 100% sure, since I don't know what exactly SVN is storing in the working copy.
However, if we talk about the DVCS world, things might be even more unclear, since every working copy is a repository by itself. Being faced with doing this in bzr now, I decided to ask the question.
Later edit:
Some people asked why I would want to do that. Here is the whole story:
In the case of SVN it was because being out of the office, the connection to the SVN server was really slow, so me and my coworker decided to check out the sources only once and make a local copy. That's what we did and it worked OK, but I am still wondering whether it is guaranteed to work, or it just happened.
In the bzr case, I am planning to move the "main" repo to another server. So I was thinking to just copy it there and start considering that the main repo. I guess the safest is to make a clone though.
A: In Subversion, every .svn folder has whatever is necessary for the containing folder. And since all local paths are stored as relative, you are safe while copying whole or partial trees outside the original checkout tree. They will continue to function in their new homes.
I frequently copy subtrees from my trunk outside, switch the new copies to other branches/tags and do whatever is necessary on the "cloned" local copies. This way, if, for any reason, I need to go back and do something in the trunk, I have an undisturbed trunk copy in the original location.
Copying source-controlled directories into other source-controlled trees, on the other hand, is unsafe. If you will be overwriting any .svn folders, you'll most probably be corrupting your target copies.
A: I do this occasionally in SVN and I haven't run into any problems. I believe that in SVN all that is stored is the original state of the directory and a pointer to the repository directory it came from.
So basically it works as you would think it should.
*
*If File1 in Copy1 changes and File2 in Copy2 changes both can commit
*If File1 in Copy1 changes and File1 in Copy2 changes whoever commits second will have an error and will have to update/merge first.
For those curious as to why I had to copy, I have had problems with checkouts over our network being very slow when first checking out one of our larger projects. By contrast, simply copying from another computer seemed to provide me with all the same benefits.
A: In svn, it's no problem. You can just working with the copy as if you had made a second checkout.
I'd recommend just checking out a second time, though. If you want a copy without the .svn files, svn export will create one.
A: For bzr, if you just copy the .bzr directory to another location, it'll work. It doesn't store any information about the path it's in or the host it's on, so you can copy it wherever and expect it to work out OK.
A: I would suggest not, as you're circumventing the source control mechanism.
But perhaps you can explain 'why'?
A: You could also just check out two working copies (at least with SVN) to say work/copy1 and work/copy2 and work on the two versions in parallel.
I wonder though what it is you are trying to achieve, since copying may not be the best solution to your problem.
A: It will depend on the VCS. I know in CVS that it stores (hidden) directories inside every version-controlled directory. These files are, of course, then copied with any copy of that directory.
It's so frequently the case that you do NOT want to copy those hidden files that the rsync tool comes with an option (-C) to ignore these files the same way CVS does.
A: I've had a few headaches with SVN when I've reorganized the folder layout from within Visual Studio. A folder moved within a solution will literally move the folder in the filesystem, including the hidden .svn folder. This causes commit problems because the .svn data is associated to the old path and I haven't found a way to reassociate to its new path. SVN clean up runs OK but fixes nothing. SVN switch doesn't allow you to change it after the folder was moved. I've only been able to fix this by deleting all .svn folders within the moved folder and its subfolders, then re-add the folder.
The problem I have with this fix is that you lose your version trail on those files because SVN sees it as brand new. Also, it doesn't store the file contents as efficiently by storing the diff from the previous version.
Per the SVN documentation, it is recommended to allow the svn client to do all your folder move/create/delete to keep everything in sync for the next commit. This isn't always acceptable from Visual Studio. Fortunately, most problem cases are caught during commit-time, particularly if you use TortoiseSVN.
A: For SVN, this will generally work as others have already stated.
If you are copying between machines, you probably will run into trouble though. For example, if you are accessing your SVN repo using file:// repository URL, things will most likely break. Same applies to http:// or svn:// URLs where server access might be different.
To stay safe, I'd just to a checkout at the new location. If you have a lot of uncomitted changes in one that you want to have in the new working directory (generally a bad idea), you could then use rsync to copy your source across without bringing in the .svn directories.
A: Seems to me like GIT might also serve your needs, as you mention being disconnected or over a crappy connection. GIT also has very nice SVN support so the two are complementary and you'll end up with a nice versioned file system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I specify in HTML or CSS the absolute minimum width of a table cell Summary
What's the best way to ensure a table cell cannot be less than a certain minimum width.
Example
I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.
Browser compatibility
I possible I would like to find a solution that works in
*
*IE 6-8
*FF 2-3
*Safari
In order of preference.
A: Another hack is the old 1x1 transparent pixel trick. Insert an 1x1 transparent gif image and set its width in the image tag to the width you want. This will force the cell to be at least as wide as the image.
A: This CSS should suffice:
td { min-width: 100px; }
However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).
Edit: As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.
However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act like a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).
A: I know this is an old question but i thought I'd share something that wasn't mentioned (Although pretty simple in concept..) you can just put a <div> inside the table (in one of the <td>'s or something) and set the <div> to min-width. the table will stop at the <div>'s width. Just thought I'd throw that out there in case somebody comes across this on google. Also, I'm not so sure about how min-width is handled in I.E6. but that has already been covered in another answer.
A: I had some success with:
min-width: 193px;
width:auto !important;
_width: 193px; /* IE6 hack */
Based on a combination of Vatos' response and a min-height article here: http://www.dustindiaz.com/min-height-fast-hack/
A: what about this css property
min-width: 100px
but it doesn't really work in IE6 if not mistaken
if you don't want to do it in the css way, I suppose you can add this attribute
nowrap="nowrap"
in your table data tag
A: This is a cross-browser way for setting minimum width and/or mimimum height:
{
width (or height): auto !important;
width (or height): 200px;
min-width (or min-height): 200px;
}
IE 6 doesn't understand !important
IE 6 sees width/height:200px (overwriting auto)
Other browsers understand the min- and the !important
I am not 100% familiar with the behaviour of widths in TD elements, but this all works nicely on eg DIV tags
BTW:
Based on a combination of Vatos' response and a min-height article here: http://www.dustindiaz.com/min-height-fast-hack/
This is not working because of the order of the first 2 lines, they need to be in the right order (think about the above) ;)
A: IE6 handles width as min-width:
td {
min-width: 100px;
_width: 100px;/* IE6 hack */
}
If you want IE6 to handle width like normal browsers, give it an overflow:visible; (not the case here)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: Custom Counter Creation Through Web Application I have a .NET 3.5 web application for which I have implemented a class called CalculationsCounterManager (code below). This class has some shared/static members that manage the creation and incrementing of two custom performance counters that monitor data calls to a SQL Server database. Execution of these data calls drives the creation of the counters if the don't exist. Of course, everything works fine through the unit tests that are executed through the nUnit GUI for this class. The counters are created and incremented fine.
However, when the same code executes through the ASPNET worker process, the following error message occurs: "Requested registry access is not allowed.". This error happens on line 44 in the CalculationsCounterManager class when a read is done to check if the counter category already exists.
Does anyone know a way to provide enough priveledges to the worker process account in order to allow it to create the counters in a production environment without opening the server up to security problems?
Namespace eA.Analytics.DataLayer.PerformanceMetrics
''' <summary>
''' Manages performance counters for the calculatioins data layer assembly
''' </summary>
''' <remarks>GAJ 09/10/08 - Initial coding and testing</remarks>
Public Class CalculationCounterManager
Private Shared _AvgRetrieval As PerformanceCounter
Private Shared _TotalRequests As PerformanceCounter
Private Shared _ManagerInitialized As Boolean
Private Shared _SW As Stopwatch
''' <summary>
''' Creates/recreates the perf. counters if they don't exist
''' </summary>
''' <param name="recreate"></param>
''' <remarks></remarks>
Public Shared Sub SetupCalculationsCounters(ByVal recreate As Boolean)
If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Or recreate = True Then
Dim AvgCalcsProductRetrieval As New CounterCreationData(CounterSettings.AvgProductRetrievalTimeCounterName, _
CounterSettings.AvgProductRetrievalTimeCounterHelp, _
CounterSettings.AvgProductRetrievalTimeCounterType)
Dim TotalCalcsProductRetrievalRequests As New CounterCreationData(CounterSettings.TotalRequestsCounterName, _
CounterSettings.AvgProductRetrievalTimeCounterHelp, _
CounterSettings.TotalRequestsCounterType)
Dim CounterData As New CounterCreationDataCollection()
' Add counters to the collection.
CounterData.Add(AvgCalcsProductRetrieval)
CounterData.Add(TotalCalcsProductRetrievalRequests)
If recreate = True Then
If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then
PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName)
End If
End If
If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = False Then
PerformanceCounterCategory.Create(CollectionSettings.CalculationMetricsCollectionName, CollectionSettings.CalculationMetricsDescription, _
PerformanceCounterCategoryType.SingleInstance, CounterData)
End If
End If
_AvgRetrieval = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.AvgProductRetrievalTimeCounterName, False)
_TotalRequests = New PerformanceCounter(CollectionSettings.CalculationMetricsCollectionName, CounterSettings.TotalRequestsCounterName, False)
_ManagerInitialized = True
End Sub
Public Shared ReadOnly Property CategoryName() As String
Get
Return CollectionSettings.CalculationMetricsCollectionName
End Get
End Property
''' <summary>
''' Determines if the performance counters have been initialized
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Shared ReadOnly Property ManagerInitializaed() As Boolean
Get
Return _ManagerInitialized
End Get
End Property
Public Shared ReadOnly Property AvgRetrieval() As PerformanceCounter
Get
Return _AvgRetrieval
End Get
End Property
Public Shared ReadOnly Property TotalRequests() As PerformanceCounter
Get
Return _TotalRequests
End Get
End Property
''' <summary>
''' Initializes the Average Retrieval Time counter by starting a stopwatch
''' </summary>
''' <remarks></remarks>
Public Shared Sub BeginIncrementAvgRetrieval()
If _SW Is Nothing Then
_SW = New Stopwatch
End If
_SW.Start()
End Sub
''' <summary>
''' Increments the Average Retrieval Time counter by stopping the stopwatch and changing the
''' raw value of the perf counter.
''' </summary>
''' <remarks></remarks>
Public Shared Sub EndIncrementAvgRetrieval(ByVal resetStopwatch As Boolean, ByVal outputToTrace As Boolean)
_SW.Stop()
_AvgRetrieval.RawValue = CLng(_SW.ElapsedMilliseconds)
If outPutToTrace = True Then
Trace.WriteLine(_AvgRetrieval.NextValue.ToString)
End If
If resetStopwatch = True Then
_SW.Reset()
End If
End Sub
''' <summary>
''' Increments the total requests counter
''' </summary>
''' <remarks></remarks>
Public Shared Sub IncrementTotalRequests()
_TotalRequests.IncrementBy(1)
End Sub
Public Shared Sub DeleteAll()
If PerformanceCounterCategory.Exists(CollectionSettings.CalculationMetricsCollectionName) = True Then
PerformanceCounterCategory.Delete(CollectionSettings.CalculationMetricsCollectionName)
End If
End Sub
End Class
End Namespace
A: Yes, it’s not possible. You can’t add privileges to the worker process without opening the server up to potential security / DOS problems in a production environment. An installer (like a MSI) usually runs with elevated permissions, and installs / uninstalls the performance counter categories and counters as well as other locked down objects.
For example, Windows Installer XML (WiX) has support for Performance Counters...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you profile your code? I hope not everyone is using Rational Purify.
So what do you do when you want to measure:
*
*time taken by a function
*peak memory usage
*code coverage
At the moment, we do it manually [using log statements with timestamps and another script to parse the log and output to excel. phew...)
What would you recommend? Pointing to tools or any techniques would be appreciated!
EDIT: Sorry, I didn't specify the environment first, Its plain C on a proprietary mobile platform
A: I've done this a lot. If you have an IDE, or an ICE, there is a technique that takes some manual effort, but works without fail.
Warning: modern programmers hate this, and I'm going to get downvoted. They love their tools. But it really works, and you don't always have the nice tools.
I assume in your case the code is something like DSP or video that runs on a timer and has to be fast. Suppose what you run on each timer tick is subroutine A. Write some test code to run subroutine A in a simple loop, say 1000 times, or long enough to make you wait at least several seconds.
While it's running, randomly halt it with a pause key and sample the call stack (not just the program counter) and record it. (That's the manual part.) Do this some number of times, like 10. Once is not enough.
Now look for commonalities between the stack samples. Look for any instruction or call instruction that appears on at least 2 samples. There will be many of these, but some of them will be in code that you could optimize.
Do so, and you will get a nice speedup, guaranteed. The 1000 iterations will take less time.
The reason you don't need a lot of samples is you're not looking for small things. Like if you see a particular call instruction on 5 out of 10 samples, it is responsible for roughly 50% of the total execution time. More samples would tell you more precisely what the percentage is, if you really want to know. If you're like me, all you want to know is where it is, so you can fix it, and move on to the next one.
Do this until you can't find anything more to optimize, and you will be at or near your top speed.
A: You probably want different tools for performance profiling and code coverage.
For profiling I prefer Shark on MacOSX. It is free from Apple and very good. If your app is vanilla C you should be able to use it, if you can get hold of a Mac.
For profiling on Windows you can use LTProf. Cheap, but not great:
http://successfulsoftware.net/2007/12/18/optimising-your-application/
(I think Microsoft are really shooting themself in the foot by not providing a decent profiler with the cheaper versions of Visual Studio.)
For coverage I prefer Coverage Validator on Windows:
http://successfulsoftware.net/2008/03/10/coverage-validator/
It updates the coverage in real time.
A: For complex applications I am a great fan of Intel's Vtune. It is a slightly different mindset to a traditional profiler that instruments the code. It works by sampling the processor to see where instruction pointer is 1,000 times a second. It has the huge advantage of not requiring any changes to your binaries, which as often as not would change the timing of what you are trying to measure.
Unfortunately it is no good for .net or java since there isn't a way for the Vtune to map instruction pointer to symbol like there is with traditional code.
It also allows you to measure all sorts of other processor/hardware centric metrics, like clocks per instruction, cache hits/misses, TLB hits/misses, etc which let you identify why certain sections of code may be taking longer to run than you would expect just by inspecting the code.
A: If you're doing an 'on the metal' embedded 'C' system (I'm not quite sure what 'mobile' implied in your posting), then you usually have some kind of timer ISR, in which it's fairly easy to sample the code address at which the interrupt occurred (by digging back in the stack or looking at link registers or whatever). Then it's trivial to build a histogram of addresses at some combination of granularity/range-of-interest.
It's usually then not too hard to concoct some combination of code/script/Excel sheets which merges your histogram counts with addresses from your linker symbol/list file to give you profile information.
If you're very RAM limited, it can be a bit of a pain to collect enough data for this to be both simple and useful, but you would need to tell us a more about your platform.
A: nProf - Free, does that for .NET.
Gets the job done, at least enough to see the 80/20. (20% of the code, taking 80% of the time)
A: Windows (.NET and Native Exes): AQTime is a great tool for the money. Standalone or as a Visual Studio plugin.
Java: I'm a fan of JProfiler. Again, can run standalone or as an Eclipse (or various other IDEs) plugin.
I believe both have trial versions.
A: The Google Perftools are extremely useful in this regard.
A: I use devpartner with MSVC 6 and XP
A: How are any tools going to work if your platform is a proprietary OS? I think you're doing the best you can right now
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Is there a way to parser a SQL query to pull out the column names and table names? I have 150+ SQL queries in separate text files that I need to analyze (just the actual SQL code, not the data results) in order to identify all column names and table names used. Preferably with the number of times each column and table makes an appearance. Writing a brand new SQL parsing program is trickier than is seems, with nested SELECT statements and the like.
There has to be a program, or code out there that does this (or something close to this), but I have not found it.
A: How about using the Execution Plan report in MS SQLServer? You can save this to an xml file which can then be parsed.
A: You may want to looking to something like this:
JSqlParser
which uses JavaCC to parse and return the query string as an object graph. I've never used it, so I can't vouch for its quality.
A: If you're application needs to do it, and has access to a database that has the tables etc, you could run something like:
SELECT TOP 0 * FROM MY_TABLE
Using ADO.NET. This would give you a DataTable instance for which you could query the columns and their attributes.
A: I actually ended up using a tool called
SQL Pretty Printer. You can purchase a desktop version, but I just used the free online application. Just copy the query into the text box, set the Output to "List DB Object" and click the Format SQL button.
It work great using around 150 different (and complex) SQL queries.
A: Please go with antlr... Write a grammar n follow the steps..which is given in antlr site..eventually you will get AST(abstract syntax tree). For the given query... we can traverse through this and bring all table ,column which is present in the query..
A: In DB2 you can append your query with something such as the following, but 1 is the minimum you can specify; it will throw an error if you try to specify 0:
FETCH FIRST 1 ROW ONLY
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Is a Flex debugger included in the sdk? I have been writing Flex applications for a few months now and luckily have not needed a full debugger as of yet, so far I have just used a few Alert boxes...
Is there an available debugger that is included in the free Flex SDK? I am not using FlexBuilder (I have been using Emacs and compiling with ant).
If not, how do you debug Flex applications without FlexBuilder? (note: I have no intentions of using flexbuilder)
A: A debugger called fdb is included in the Flex SDK. Here's some documentation on how to use it:
*
*Adobe DevCenter: Debugging Client-Side Code in Flex Applications
*Flex 3 Help: Using the Command-Line Debugger
A: I had the same problem when programming with ActionScript and having to test it on a browser. Try this. It involves using Firefox (which I believe you do) and FireBug to receive the debug messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to see if a subfile of a directory has changed In Windows, is there an easy way to tell if a folder has a subfile that has changed?
I verified, and the last modified date on the folder does not get updated when a subfile changes.
Is there a registry entry I can set that will modify this behavior?
If it matters, I am using an NTFS volume.
I would ultimately like to have this ability from a C++ program.
Scanning an entire directory recursively will not work for me because the folder is much too large.
Update: I really need a way to do this without a process running while the change occurs. So installing a file system watcher is not optimal for me.
Update2: The archive bit will also not work because it has the same problem as the last modification date. The file's archive bit will be set, but the folders will not.
A: This article should help. Basically, you create one or more notification object such as:
HANDLE dwChangeHandles[2];
dwChangeHandles[0] = FindFirstChangeNotification(
lpDir, // directory to watch
FALSE, // do not watch subtree
FILE_NOTIFY_CHANGE_FILE_NAME); // watch file name changes
if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
{
printf("\n ERROR: FindFirstChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
// Watch the subtree for directory creation and deletion.
dwChangeHandles[1] = FindFirstChangeNotification(
lpDrive, // directory to watch
TRUE, // watch the subtree
FILE_NOTIFY_CHANGE_DIR_NAME); // watch dir name changes
if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
{
printf("\n ERROR: FindFirstChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
and then you wait for a notification:
while (TRUE)
{
// Wait for notification.
printf("\nWaiting for notification...\n");
DWORD dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles,
FALSE, INFINITE);
switch (dwWaitStatus)
{
case WAIT_OBJECT_0:
// A file was created, renamed, or deleted in the directory.
// Restart the notification.
if ( FindNextChangeNotification(dwChangeHandles[0]) == FALSE )
{
printf("\n ERROR: FindNextChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
break;
case WAIT_OBJECT_0 + 1:
// Restart the notification.
if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE )
{
printf("\n ERROR: FindNextChangeNotification function failed.\n");
ExitProcess(GetLastError());
}
break;
case WAIT_TIMEOUT:
// A time-out occurred. This would happen if some value other
// than INFINITE is used in the Wait call and no changes occur.
// In a single-threaded environment, you might not want an
// INFINITE wait.
printf("\nNo changes in the time-out period.\n");
break;
default:
printf("\n ERROR: Unhandled dwWaitStatus.\n");
ExitProcess(GetLastError());
break;
}
}
}
A: This is perhaps overkill, but the IFS kit from MS or the FDDK from OSR might be an alternative. Create your own filesystem filter driver with simple monitoring of all changes to the filesystem.
A: ReadDirectoryChangesW
Some excellent sample code in this CodeProject article
A: If you can't run a process when the change occurs, then there's not much you can do except scan the filesystem, and check the modification date/time. This requires you to store each file's last date/time, though, and compare.
You can speed this up by using the archive bit (though it may mess up your backup software, so proceed carefully).
An archive bit is a file attribute
present in many computer file systems,
notably FAT, FAT32, and NTFS. The
purpose of an archive bit is to track
incremental changes to files for the
purpose of backup, also called
archiving.
As the archive bit is a binary bit, it
is either 1 or 0, or in this case more
frequently called set (1) and clear
(0). The operating system sets the
archive bit any time a file is
created, moved, renamed, or otherwise
modified in any way. The archive bit
therefore represents one of two
states: "changed" and "not changed"
since the last backup.
Archive bits are not affected by
simply reading a file. When a file is
copied, the original file's archive
bit is unaffected, however the copy's
archive bit will be set at the time
the copy is made.
So the process would be:
*
*Clear the archive bit on all the files
*Let the file system change over time
*Scan all the files - any with the archive bit set have changed
This will eliminate the need for your program to keep state, and since you're only going over the directory entries (where the bit is stored) and they are clustered, it should be very, very fast.
If you can run a process during the changes, however, then you'll want to look at the FileSystemWatcher class. Here's an example of how you might use it.
It also exists in .NET (for future searchers of this type of problem)
Perhaps you can leave a process running on the machine watching for changes and creating a file for you to read later.
-Adam
A: Perhaps you can use the NTFS 5 Change Journal with DeviceIoControl as explained here
A: If you are not opposed to using .NET the FileSystemWatcher class will handle this for you fairly easily.
A: Nothing easy - if you have a running app you can use the Win32 file change notification apis (FindFirstChangeNotification) as suggested with the other answers. warning: circa 2000 trend micro real-time virus scanner would group the changes together making it necessary to use really large buffers when requesting the file system change lists.
If you don't have a running app, you can turn on ntfs journaling and scan the journal for changes http://msdn.microsoft.com/en-us/library/aa363798(VS.85).aspx but this can be slower than scanning the whole directory when the # of changes is larger than the # of files.
A: From the double post someone mentioned: WMI Event Sink
Still looking for a better answer though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I get rid of Windows Update reboot prompt? I want Windows Update to automatically download and install updates on my Vista machine, however I don't want to be bothered by the system tray reboot prompts (which can, at best, only be postponed by 4 hours).
I have performed the registry hack described here to prevent Windows forcibly rebooting my machine, which is a good start. However, is there any way to get rid of the reboot prompts altogether, or decrease their frequency?
A: Just turn off the Automatic Update service. It will restart the next time you reboot so you'll still get the updates done.
A: Running this in a command window will stop it until the next reboot.
sc stop wuauserv
A: I recommend disabling the auto update.
As a developer the last thing you need is to have random updates done to your workstation, especially while you are working. I set aside a time every month to go through the process manually. I avoid doing it if I am in the middle of testing something really important or up against an immediate deadline.
A: Not sure if it is the same for vista, but worth a try.
On Windows XP, you can modify a group policy setting to change how frequently it re-prompts you. (start -> run type gpedit.msc)
Look under Computer Configuration/Administrative Templates/Windows Components/Windows Update
The setting you want is called Re-Prompt for restart with scheduled installations.
The default is 10 minutes.
You can also try modifying the No auto-restart for scheduled Automatic Updates installations setting found in the same location.
A: To clarify what ehogue said:
Start->Control Panel->Administrative Tools->Services->Automatic Updates->Right-click->Stop.
A: In Windows XP, after windows has been updated, I use the following trick: run this command
pssuspend wuauclt
pssuspend is a free sys-internals tool.
This way, you will not be prompted about restart.
A: I will risk some down-votes here by saying: this seems a little bit schizophrenic, though a lot of people ask for it.
If you want Windows to download and install the updates, but not complete the install process by rebooting - what's the point? Why not simply turn of AutoUpdates in the first place? if you don't even want the OS to tell you it would like to reboot, then how can you know that you need to, y'know, reboot?
Patches which call for a reboot are not fully active until that reboot is complete; thus your system remains vulnerable to the unpatched behaviour. If you are a human who goes to the bathroom or eats meals, I just do not understand the mentality of wanting to patch but then postpone the reboot for days, weeks, months. Better to stay unpatched!
A: just open taskmanager and right-click on "wuauclt.exe" en clcik stop or delete or something that should keep that program from running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: How do I ensure that RMI uses only a specific set of ports? In our application, we are using RMI for client-server communication in very different ways:
*
*Pushing data from the server to the client to be displayed.
*Sending control information from the client to the server.
*Callbacks from those control messages code paths that reach back from the server to the client (sidebar note - this is a side-effect of some legacy code and is not our long-term intent).
What we would like to do is ensure that all of our RMI-related code will use only a known specified inventory of ports. This includes the registry port (commonly expected to be 1099), the server port and any ports resulting from the callbacks.
Here is what we already know:
*
*LocateRegistry.getRegistry(1099) or Locate.createRegistry(1099) will ensure that the registry is listening in on 1099.
*Using the UnicastRemoteObject constructor / exportObject static method with a port argument will specify the server port.
These points are also covered in this Sun forum post.
What we don't know is: how do we ensure that the client connections back to the server resulting from the callbacks will only connect on a specified port rather than defaulting to an anonymous port?
EDIT: Added a longish answer summarizing my findings and how we solved the problem. Hopefully, this will help anyone else with similar issues.
SECOND EDIT: It turns out that in my application, there seems to be a race condition in my creation and modification of socket factories. I had wanted to allow the user to override my default settings in a Beanshell script. Sadly, it appears that my script is being run significantly after the first socket is created by the factory. As a result, I'm getting a mix of ports from the set of defaults and the user settings. More work will be required that's out of the scope of this question but I thought I would point it out as a point of interest for others who might have to tread these waters at some point....
A: You can do this with a custom RMI Socket Factory.
The socket factories create the sockets for RMI to use at both the client and server end so if you write your own you've got full control over the ports used. The client factories are created on the server, Serialized and then sent down to the client which is pretty neat.
Here's a guide at Sun telling you how to do it.
A: You don't need socket factories for this, or even multiple ports. If you're starting the Registry from your server JVM you can use port 1099 for everything, and indeed that is what will happen by default. If you're not starting the registry at all, as in a client callback object, you can provide port 1099 when exporting it.
The part of your question about 'the client connections back to the server resulting from callbacks' doesn't make sense. They are no different from the original client connections to the server, and they will use the same server port(s).
A: Summary of the long answer below: to solve the problem that I had (restricting server and callback ports at either end of the RMI connection), I needed to create two pairs of client and server socket factories.
Longer answer ensues:
Our solution to the callback problem had essentially three parts. The first was the object wrapping which needed the ability to specify that it was being used for a client to server connection vs. being used for a server to client callback. Using an extension of UnicastRemoteObject gave us the ability to specify the client and server socket factories that we wanted to use. However, the best place to lock down the socket factories is in the constructor of the remote object.
public class RemoteObjectWrapped extends UnicastRemoteObject {
// ....
private RemoteObjectWrapped(final boolean callback) throws RemoteException {
super((callback ? RemoteConnectionParameters.getCallbackPort() : RemoteConnectionParameters.getServerSidePort()),
(callback ? CALLBACK_CLIENT_SOCKET_FACTORY : CLIENT_SOCKET_FACTORY),
(callback ? CALLBACK_SERVER_SOCKET_FACTORY : SERVER_SOCKET_FACTORY));
}
// ....
}
So, the first argument specifies the part on which the object is expecting requests, whereas the second and third specify the socket factories that will be used at either end of the connection driving this remote object.
Since we wanted to restrict the ports used by the connection, we needed to extend the RMI socket factories and lock down the ports. Here are some sketches of our server and client factories:
public class SpecifiedServerSocketFactory implements RMIServerSocketFactory {
/** Always use this port when specified. */
private int serverPort;
/**
* @param ignoredPort This port is ignored.
* @return a {@link ServerSocket} if we managed to create one on the correct port.
* @throws java.io.IOException
*/
@Override
public ServerSocket createServerSocket(final int ignoredPort) throws IOException {
try {
final ServerSocket serverSocket = new ServerSocket(this.serverPort);
return serverSocket;
} catch (IOException ioe) {
throw new IOException("Failed to open server socket on port " + serverPort, ioe);
}
}
// ....
}
Note that the server socket factory above ensures that only the port that you previously specified will ever be used by this factory. The client socket factory has to be paired with the appropriate socket factory (or you'll never connect).
public class SpecifiedClientSocketFactory implements RMIClientSocketFactory, Serializable {
/** Serialization hint */
public static final long serialVersionUID = 1L;
/** This is the remote port to which we will always connect. */
private int remotePort;
/** Storing the host just for reference. */
private String remoteHost = "HOST NOT YET SET";
// ....
/**
* @param host The host to which we are trying to connect
* @param ignoredPort This port is ignored.
* @return A new Socket if we managed to create one to the host.
* @throws java.io.IOException
*/
@Override
public Socket createSocket(final String host, final int ignoredPort) throws IOException {
try {
final Socket socket = new Socket(host, remotePort);
this.remoteHost = host;
return socket;
} catch (IOException ioe) {
throw new IOException("Failed to open a socket back to host " + host + " on port " + remotePort, ioe);
}
}
// ....
}
So, the only thing remaining to force your two way connection to stay on the same set of ports is some logic to recognize that you are calling back to the client-side. In that situation, just make sure that your factory method for the remote object calls the RemoteObjectWrapper constructor up top with the callback parameter set to true.
A: I've been having various problems implementing an RMI Server/Client architecture, with Client Callbacks. My scenario is that both Server and Client are behind Firewall/NAT. In the end I got a fully working implementation. Here are the main things that I did:
Server Side , Local IP: 192.168.1.10. Public (Internet) IP 80.80.80.10
On the Firewall/Router/Local Server PC open port 6620.
On the Firewall/Router/Local Server PC open port 1099.
On the Router/NAT redirect incoming connections on port 6620 to 192.168.1.10:6620
On the Router/NAT redirect incoming connections on port 1099 to 192.168.1.10:1099
In the actual program:
System.getProperties().put("java.rmi.server.hostname", IP 80.80.80.10);
MyService rmiserver = new MyService();
MyService stub = (MyService) UnicastRemoteObject.exportObject(rmiserver, 6620);
LocateRegistry.createRegistry(1099);
Registry registry = LocateRegistry.getRegistry();
registry.rebind("FAManagerService", stub);
Client Side, Local IP: 10.0.1.123 Public (Internet) IP 70.70.70.20
On the Firewall/Router/Local Server PC open port 1999.
On the Router/NAT redirect incoming connections on port 1999 to 10.0.1.123:1999
In the actual program:
System.getProperties().put("java.rmi.server.hostname", 70.70.70.20);
UnicastRemoteObject.exportObject(this, 1999);
MyService server = (MyService) Naming.lookup("rmi://" + serverIP + "/MyService ");
Hope this helps.
Iraklis
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Random weighted choice Consider the class below that represents a Broker:
public class Broker
{
public string Name = string.Empty;
public int Weight = 0;
public Broker(string n, int w)
{
this.Name = n;
this.Weight = w;
}
}
I'd like to randomly select a Broker from an array, taking into account their weights.
What do you think of the code below?
class Program
{
private static Random _rnd = new Random();
public static Broker GetBroker(List<Broker> brokers, int totalWeight)
{
// totalWeight is the sum of all brokers' weight
int randomNumber = _rnd.Next(0, totalWeight);
Broker selectedBroker = null;
foreach (Broker broker in brokers)
{
if (randomNumber <= broker.Weight)
{
selectedBroker = broker;
break;
}
randomNumber = randomNumber - broker.Weight;
}
return selectedBroker;
}
static void Main(string[] args)
{
List<Broker> brokers = new List<Broker>();
brokers.Add(new Broker("A", 10));
brokers.Add(new Broker("B", 20));
brokers.Add(new Broker("C", 20));
brokers.Add(new Broker("D", 10));
// total the weigth
int totalWeight = 0;
foreach (Broker broker in brokers)
{
totalWeight += broker.Weight;
}
while (true)
{
Dictionary<string, int> result = new Dictionary<string, int>();
Broker selectedBroker = null;
for (int i = 0; i < 1000; i++)
{
selectedBroker = GetBroker(brokers, totalWeight);
if (selectedBroker != null)
{
if (result.ContainsKey(selectedBroker.Name))
{
result[selectedBroker.Name] = result[selectedBroker.Name] + 1;
}
else
{
result.Add(selectedBroker.Name, 1);
}
}
}
Console.WriteLine("A\t\t" + result["A"]);
Console.WriteLine("B\t\t" + result["B"]);
Console.WriteLine("C\t\t" + result["C"]);
Console.WriteLine("D\t\t" + result["D"]);
result.Clear();
Console.WriteLine();
Console.ReadLine();
}
}
}
I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.
Is there a more accurate algorithm?
Thanks!
A: Since this is the top result on Google:
I've created a C# library for randomly selected weighted items.
*
*It implements both the tree-selection and walker alias method algorithms, to give the best performance for all use-cases.
*It is unit-tested and optimized.
*It has LINQ support.
*It's free and open-source, licensed under the MIT license.
Some example code:
IWeightedRandomizer<string> randomizer = new DynamicWeightedRandomizer<string>();
randomizer["Joe"] = 1;
randomizer["Ryan"] = 2;
randomizer["Jason"] = 2;
string name1 = randomizer.RandomWithReplacement();
//name1 has a 20% chance of being "Joe", 40% of "Ryan", 40% of "Jason"
string name2 = randomizer.RandomWithRemoval();
//Same as above, except whichever one was chosen has been removed from the list.
A: Your algorithm is nearly correct. However, the test should be < instead of <=:
if (randomNumber < broker.Weight)
This is because 0 is inclusive in the random number while totalWeight is exclusive. In other words, a broker with weight 0 would still have a small chance of being selected – not at all what you want. This accounts for broker A having more hits than broker D.
Other than that, your algorithm is fine and in fact the canonical way of solving this problem.
A: An alternative method favours speed when selecting the broker over memory usage. Basically we create the list containing the same number of references to a broker instance as the specified weight.
List<Broker> brokers = new List<Broker>();
for (int i=0; i<10; i++)
brokers.Add(new Broker("A", 10));
for (int i=0; i<20; i++)
brokers.Add(new Broker("B", 20));
for (int i=0; i<20; i++)
brokers.Add(new Broker("C", 20));
for (int i=0; i<10; i++)
brokers.Add(new Broker("D", 10));
Then, to select a randomly weighted instance is an O(1) operation:
int randomNumber = _rnd.Next(0, brokers.length);
selectedBroker = brokers[randomNumber];
A: How about something a little more generic, that can be used for any data type?
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public static class IEnumerableExtensions {
public static T RandomElementByWeight<T>(this IEnumerable<T> sequence, Func<T, float> weightSelector) {
float totalWeight = sequence.Sum(weightSelector);
// The weight we are after...
float itemWeightIndex = (float)new Random().NextDouble() * totalWeight;
float currentWeightIndex = 0;
foreach(var item in from weightedItem in sequence select new { Value = weightedItem, Weight = weightSelector(weightedItem) }) {
currentWeightIndex += item.Weight;
// If we've hit or passed the weight we are after for this item then it's the one we want....
if(currentWeightIndex >= itemWeightIndex)
return item.Value;
}
return default(T);
}
}
Simply call by
Dictionary<string, float> foo = new Dictionary<string, float>();
foo.Add("Item 25% 1", 0.5f);
foo.Add("Item 25% 2", 0.5f);
foo.Add("Item 50%", 1f);
for(int i = 0; i < 10; i++)
Console.WriteLine(this, "Item Chosen {0}", foo.RandomElementByWeight(e => e.Value));
A: A little bit too late but here's C#7 example. It's pretty small and gives correct distribution.
public static class RandomTools
{
public static T PickRandomItemWeighted<T>(IList<(T Item, int Weight)> items)
{
if ((items?.Count ?? 0) == 0)
{
return default;
}
int offset = 0;
(T Item, int RangeTo)[] rangedItems = items
.OrderBy(item => item.Weight)
.Select(entry => (entry.Item, RangeTo: offset += entry.Weight))
.ToArray();
int randomNumber = new Random().Next(items.Sum(item => item.Weight)) + 1;
return rangedItems.First(item => randomNumber <= item.RangeTo).Item;
}
}
A: June 2022: One more implementation (in c#) for the pile:
https://github.com/cdanek/KaimiraWeightedList
O(1) gets (!), O(n) memory, O(n) add/removes/edits, robust (nearly all IList methods are implemented) and extremely easy to use (one C# file, one line of code to construct, one line of code to add items, one line of code to get an item):
WeightedList<string> myList = new();
myList.Add("Hello", 1);
myList.Add("World", 2);
Console.WriteLine(myList.Next()); // Hello 33%, World 66%
Uses walker-vose alias method.
A: class Program
{
static void Main(string[] args)
{
var books = new List<Book> {
new Book{Isbn=1,Name="A",Popularity=1},
new Book{Isbn=2,Name="B",Popularity=100},
new Book{Isbn=3,Name="C",Popularity=1000},
new Book{Isbn=4,Name="D",Popularity=10000},
new Book{Isbn=5,Name="E",Popularity=100000}};
Book randomlySelectedBook = books.WeightedRandomization(b => b.Popularity);
}
}
public static class EnumerableExtensions
{
private static readonly Random rand = new Random();
public static T WeightedRandomization<T>(this IEnumerable<T> source, Func<T, int> weightSelector)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (weightSelector == null)
{
throw new ArgumentNullException(nameof(weightSelector));
}
int count = source.Count();
if (count == 0)
{
throw new InvalidOperationException("Sequence contains no elements");
}
int totalWeight = source.Sum(weightSelector);
int choice = rand.Next(totalWeight);
int sum = 0;
foreach (var obj in source)
{
sum += weightSelector(obj);
if (choice < sum)
{
return obj;
}
}
return source.First();
}
}
public class Book
{
public int Isbn { get; set; }
public string Name { get; set; }
public int Popularity { get; set; }
}
A: If you want more speed you can either consider weighted reservoir sampling where you don't have to find the total weight ahead of time (but you sample more often from the random number generator). The code might look something like
Broker selected = null;
int s = 0;
foreach(Broker broker in brokers) {
s += broker.Weight;
if (broker.Weight <= _rnd.Next(0,s)) {
selected = broker;
}
}
This requires going once through the list brokers. However if the list of brokers is fixed or doesn't change that often you can keep an array of cumulative sums, i.e. A[i] is the sum of weights of all brokers 0,..,i-1. Then A[n] is the total weight and if you pick a number between 1 and A[n-1], say x you find the broker j s.t. A[j-1] <= x < A[j]. For convenience you let A[0] = 0. You can find this broker number j in log(n) steps using binary search, I'll leave the code as an easy exercise. If your data changes frequently this might not be a good way to go since every time some weight changes you might need to update a large portion of the array.
A: I've come up with a generic version of this solution:
public static class WeightedEx
{
/// <summary>
/// Select an item from the given sequence according to their respective weights.
/// </summary>
/// <typeparam name="TItem">Type of item item in the given sequence.</typeparam>
/// <param name="a_source">Given sequence of weighted items.</param>
/// <returns>Randomly picked item.</returns>
public static TItem PickWeighted<TItem>(this IEnumerable<TItem> a_source)
where TItem : IWeighted
{
if (!a_source.Any())
return default(TItem);
var source= a_source.OrderBy(i => i.Weight);
double dTotalWeight = source.Sum(i => i.Weight);
Random rand = new Random();
while (true)
{
double dRandom = rand.NextDouble() * dTotalWeight;
foreach (var item in source)
{
if (dRandom < item.Weight)
return item;
dRandom -= item.Weight;
}
}
}
}
/// <summary>
/// IWeighted: Implementation of an item that is weighted.
/// </summary>
public interface IWeighted
{
double Weight { get; }
}
A: Just to share my own implementation. Hope you'll find it useful.
// Author: Giovanni Costagliola <[email protected]>
using System;
using System.Collections.Generic;
using System.Linq;
namespace Utils
{
/// <summary>
/// Represent a Weighted Item.
/// </summary>
public interface IWeighted
{
/// <summary>
/// A positive weight. It's up to the implementer ensure this requirement
/// </summary>
int Weight { get; }
}
/// <summary>
/// Pick up an element reflecting its weight.
/// </summary>
/// <typeparam name="T"></typeparam>
public class RandomWeightedPicker<T> where T:IWeighted
{
private readonly IEnumerable<T> items;
private readonly int totalWeight;
private Random random = new Random();
/// <summary>
/// Initiliaze the structure. O(1) or O(n) depending by the options, default O(n).
/// </summary>
/// <param name="items">The items</param>
/// <param name="checkWeights">If <c>true</c> will check that the weights are positive. O(N)</param>
/// <param name="shallowCopy">If <c>true</c> will copy the original collection structure (not the items). Keep in mind that items lifecycle is impacted.</param>
public RandomWeightedPicker(IEnumerable<T> items, bool checkWeights = true, bool shallowCopy = true)
{
if (items == null) throw new ArgumentNullException("items");
if (!items.Any()) throw new ArgumentException("items cannot be empty");
if (shallowCopy)
this.items = new List<T>(items);
else
this.items = items;
if (checkWeights && this.items.Any(i => i.Weight <= 0))
{
throw new ArgumentException("There exists some items with a non positive weight");
}
totalWeight = this.items.Sum(i => i.Weight);
}
/// <summary>
/// Pick a random item based on its chance. O(n)
/// </summary>
/// <param name="defaultValue">The value returned in case the element has not been found</param>
/// <returns></returns>
public T PickAnItem()
{
int rnd = random.Next(totalWeight);
return items.First(i => (rnd -= i.Weight) < 0);
}
/// <summary>
/// Resets the internal random generator. O(1)
/// </summary>
/// <param name="seed"></param>
public void ResetRandomGenerator(int? seed)
{
random = seed.HasValue ? new Random(seed.Value) : new Random();
}
}
}
Gist: https://gist.github.com/MrBogomips/ae6f6c9af8032392e4b93aaa393df447
A: The implementation in the original question seems a little odd to me;
The total weight of the list is 60 so the random number is 0-59.
It always checks the random number against the weight and then decrements it.
It looks to me that it would favour things in the list based on their order.
Here's a generic implementation I'm using - the crux is in the Random property:
using System;
using System.Collections.Generic;
using System.Linq;
public class WeightedList<T>
{
private readonly Dictionary<T,int> _items = new Dictionary<T,int>();
// Doesn't allow items with zero weight; to remove an item, set its weight to zero
public void SetWeight(T item, int weight)
{
if (_items.ContainsKey(item))
{
if (weight != _items[item])
{
if (weight > 0)
{
_items[item] = weight;
}
else
{
_items.Remove(item);
}
_totalWeight = null; // Will recalculate the total weight later
}
}
else if (weight > 0)
{
_items.Add(item, weight);
_totalWeight = null; // Will recalculate the total weight later
}
}
public int GetWeight(T item)
{
return _items.ContainsKey(item) ? _items[item] : 0;
}
private int? _totalWeight;
public int totalWeight
{
get
{
if (!_totalWeight.HasValue) _totalWeight = _items.Sum(x => x.Value);
return _totalWeight.Value;
}
}
public T Random
{
get
{
var temp = 0;
var random = new Random().Next(totalWeight);
foreach (var item in _items)
{
temp += item.Value;
if (random < temp) return item.Key;
}
throw new Exception($"unable to determine random {typeof(T)} at {random} in {totalWeight}");
}
}
}
A: Another option is this
private static Random _Rng = new Random();
public static Broker GetBroker(List<Broker> brokers){
List<Broker> weightedBrokerList = new List<Broker>();
foreach(Broker broker in brokers) {
for(int i=0;i<broker.Weight;i++) {
weightedBrokerList.Add(broker);
}
}
return weightedBrokerList[_Rng.Next(weightedBrokerList.Count)];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Best way to get a list of differences between 2 of the same objects I would like to generate a list of differences between 2 instances of the the same object. Object in question:
public class Step
{
[DataMember]
public StepInstanceInfo InstanceInfo { get; set; }
[DataMember]
public Collection<string> AdHocRules { get; set; }
[DataMember]
public Collection<StepDoc> StepDocs
{...}
[DataMember]
public Collection<StepUsers> StepUsers
{...}
}
What I would like to do is find an intelligent way to return an object that lists the differences between the two instances (for example, let me know that 2 specific StepDocs were added, 1 specific StepUser was removed, and one rule was changed from "Go" to "Stop"). I have been looking into using a MD5 hash, but I can't find any good examples of traversing an object like this and returning a manifest of the specific differences (not just indicating that they are different).
Additional Background: the reason that I need to do this is the API that I am supporting allows clients to SaveStep(Step step)...this works great for persisting the Step object to the db using entities and repositories. I need to raise specific events (like this user was added, etc) from this SaveStep method, though, in order to alert another system (workflow engine) that a specific element in the step has changed.
Thank you.
A: You'll need a separate object, like StepDiff with collections for removed and added items. The easiest way to do something like this is to copy the collections from each of the old and new objects, so that StepDiff has collectionOldStepDocs and collectionNewStepDocs.
Grab the shorter collection and iterate through it and see if each StepDoc exists in the other collection. If so, delete the StepDoc reference from both collections. Then when you're finished iterating, collectionOldStepDocs contains stepDocs that were deleted and collectionNewStepDocs contains the stepDocs that were added.
From there you should be able to build your manifest in whatever way necessary.
A: Implementing the IComparable interface in your object may provide you with the functionality you need. This will provide you a custom way to determine differences between objects without resorting to checksums which really won't help you track what the differences are in usable terms. Otherwise, there's no way to determine equality between two user objects in .NET that I know of. There are some decent examples of the usage of this interface in the help file for Visual Studio, or here. You might be able to glean some directives from the examples on clean ways to compare the properties and store the values in some usable manner for tracking purposes (perhaps a collection, or dictionary object?).
Hope this helps,
Greg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Right Click does not make a selection. What is the easiest way to solve this globally? Is there a way to globally make right click also select the element that you right click on?
From what I understand this has been a bug in Swing for a long time likely to never be fixed because at this point applications depend on it.
Any advice on doing this on a global scale? Perhaps on the L&F?
A: Using the Glass Pane will do the trick.
Here's a tutorial on how to use the glass pane to get the right click button and redispatch it to the right component.
As the glass pane is not a solution in this case, I suggest you take a look at the Toolkit class. Specificaly the addAWTEventListener method. You can add a global event listener with it. To add a mouse event listener:
Toolkit.getDefaultToolkit().
addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK);
Cheers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Objective-C for Windows What would be the best way to write Objective-C on the Windows platform?
Cygwin and gcc? Is there a way I can somehow integrate this into Visual Studio?
Along those lines - are there any suggestions as to how to link in and use the Windows SDK for something like this. Its a different beast but I know I can write assembly and link in the Windows DLLs giving me accessibility to those calls but I don't know how to do this without googling and getting piecemeal directions.
Is anyone aware of a good online or book resource to do or explain these kinds of things?
A: You can use Objective C inside the Windows environment. If you follow these steps, it should be working just fine:
*
*Visit the GNUstep website and download GNUstep MSYS Subsystem (MSYS for GNUstep), GNUstep Core (Libraries for GNUstep), and GNUstep Devel
*After downloading these files, install in that order, or you will have problems with configuration
*Navigate to C:\GNUstep\GNUstep\System\Library\Headers\Foundation1 and ensure that Foundation.h exists
*Open up a command prompt and run gcc -v to check that GNUstep MSYS is correctly installed (if you get a file not found error, ensure that the bin folder of GNUstep MSYS is in your PATH)
*Use this simple "Hello World" program to test GNUstep's functionality:
#include <Foundation/Foundation.h>
int main(void)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Hello World!.");
[pool drain];
return;
}
*Go back to the command prompt and cd to where you saved the "Hello World" program and then compile it:2
gcc -o helloworld.exe <HELLOWORLD>.m -I /GNUstep/GNUstep/System/Library/Headers -L /GNUstep/GNUstep/System/Library/Libraries -std=c99 -lobjc -lgnustep-base -fconstant-string-class=NSConstantString
*Finally, from the command prompt, type helloworld to run it
All the best, and have fun with Objective-C!
NOTES:
*
*I used the default install path - adjust your command line accordingly
*Ensure the folder path of yours is similar to mine, otherwise you will get an error
A: I have mixed feelings about the Cocotron project. I'm glad they are releasing source code and sharing but I don't feel that they are doing things the easiest way.
Examples.
Apple has released the source code to the objective-c runtime, which includes properties and garbage collection. The Cocotron project however has their own implementation of the objective-c runtime. Why bother to duplicate the effort? There is even a Visual Studio Project file that can be used to build an objc.dll file. Or if you're really lazy, you can just copy the DLL file from an installation of Safari on Windows.
They also did not bother to leverage CoreFoundation, which is also open sourced by Apple. I posted a question about this but did not receive an answer.
I think the current best solution is to take source code from multiple sources (Apple, CocoTron, GnuStep) and merge it together to what you need. You'll have to read a lot of source but it will be worth the end result.
A: I'm aware this is a very old post, but I have found a solution which has only become available more recently AND enables nearly all Objective-C 2.0 features on the Windows platform.
With the advent of gcc 4.6, support for Objective-C 2.0 language features (blocks, dot syntax, synthesised properties, etc) was added to the Objective-C compiler (see the release notes for full details). Their runtime has also been updated to work almost identically to Apple's own Objective-C 2.0 runtime. In short this means that (almost) any program that will legitimately compile with Clang on a Mac will also compile with gcc 4.6 without modification.
As a side-note, one feature that is not available is dictionary/array/etc literals as they are all hard-coded into Clang to use Apple's NSDictionary, NSArray, NSNumber, etc classes.
However, if you are happy to live without Apple's extensive frameworks, you can.
As noted in other answers, GNUStep and the Cocotron provide modified versions of Apple's class libraries, or you can write your own (my preferred option).
MinGW is one way to get GCC 4.6 on the Windows platform, and can be downloaded from The MinGW website. Make sure when you install it you include the installation of C, C++, Objective-C and Objective-C++. While optional, I would also suggest installing the MSYS environment.
Once installed, Objective-C 2.0 source can be compiled with:
gcc MyFile.m -lobjc -std=c99 -fobjc-exceptions -fconstant-string-class=clsname (etc, additional flags, see documentation)
MinGW also includes support for compiling native GUI Windows applications with the -mwindows flag. For example:
g++ -mwindows MyFile.cpp
I have not attempted it yet, but I imagine if you wrap your Objective-C classes in Objective-C++ at the highest possible layer, you should be able to successfully intertwine native Windows GUI C++ and Objective-C all in the one Windows Application.
A: Check out WinObjC:
https://github.com/Microsoft/WinObjC
It's an official, open-source project by Microsoft that integrates with Visual Studio + Windows.
A: If you just want to experiment, there's an Objective-C compiler for .NET (Windows) here: qckapp
A: You can get an objective c compiler that will work with Windows and play nice with Visual Studio 2008\2010 here.
open-c flite
Just download the latest source. You don't need to build all of CF-Lite there is a solution called objc.sln. You will need to fix a few of the include paths but then it will build just fine. There is even a test project included so you can see some objective-c .m files being compiled and working in visual studio. One sad thing is it only works with Win32 not x64. There is some assembly code that would need to be written for x64 for it to support that.
A: A recent attempt to port Objective C 2.0 to Windows is the Subjective project.
From the Readme:
Subjective is an attempt to bring Objective C 2.0 with ARC support to
Windows.
This project is a fork of objc4-532.2, the Objective C runtime that
ships with OS X 10.8.5. The port can be cross-compiled on OS X using
llvm-clang combined with the MinGW linker.
There are certain limitations many of which are a matter of extra
work, while others, such as exceptions and blocks, depend on more
serious work in 3rd party projects. The limitations are:
• 32-bit only - 64-bit is underway
• Static linking only - dynamic linking is underway
• No closures/blocks - until libdispatch supports them on Windows
• No exceptions - until clang supports them on Windows
• No old style GC - until someone cares...
• Internals: no vtables, no gdb support, just plain malloc, no
preoptimizations - some of these things will be available under the
64-bit build.
• Currently a patched clang compiler is required; the patch adds
-fobjc-runtime=subj flag
The project is available on Github, and there is also a thread on the Cocotron Group outlining some of the progress and issues encountered.
A: Get GNUStep here
Get MINGW here
Install MINGW
Install GNUStep
Then Test
A: Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.
Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.
I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.
For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.
A: Also:
The Cocotron is an open source project which aims to implement a cross-platform Objective-C API similar to that described by Apple Inc.'s Cocoa documentation. This includes the AppKit, Foundation, Objective-C runtime and support APIs such as CoreGraphics and CoreFoundation.
http://www.cocotron.org/
A: WinObjC? Windows Bridge for iOS (previously known as ‘Project Islandwood’).
Windows Bridge for iOS (also referred to as WinObjC) is a Microsoft open source project that provides an Objective-C development environment for Visual Studio/Windows. In addition, WinObjC provides support for iOS API compatibility. While the final release will happen later this fall (allowing the bridge to take advantage of new tooling capabilities that will ship with the upcoming Visual Studio 2015 Update),
The bridge is available to the open-source community now in its current state. Between now and the fall. The iOS bridge as an open-source project under the MIT license. Given the ambition of the project, making it easy for iOS developers to build and run apps on Windows.
Salmaan Ahmed has an in-depth post on the Windows Bridge for iOS http://blogs.windows.com/buildingapps/2015/08/06/windows-bridge-for-ios-lets-open-this-up/ discussing the compiler, runtime, IDE integration, and what the bridge is and isn’t. Best of all, the source code for the iOS bridge is live on GitHub right now.
The iOS bridge supports both Windows 8.1 and Windows 10 apps built for x86 and x64 processor architectures, and soon we will add compiler optimizations and support for ARM, which adds mobile support.
A: If you are comfortable with Visual Studio environment,
Small project: jGRASP with gcc
Large project: Cocotron
I heard there are emulators, but I could find only Apple II Emulator http://virtualapple.org/. It looks like limited to games.
A: First of all, forget about GNUStep tools. Neither ProjectManager nor ProjectCenter can be called an IDE. With all due respect, it looks like guys from GNUStep project are stuck in the late 80-s (which is when NeXTSTEP first appeared).
Vim
ctags support Objective-C since r771 (be sure to pick the pre-release 5.9 version and add --langmap=ObjectiveC:.m.h to the command line, see here), so you'll have decent code completion/tag navigation.
Here's a short howto on adding Objective-C support to Vim tagbar plugin.
Emacs
The same applies to etags shipped with modern Emacsen, so you can start with Emacs Objective C Mode. YASnippet will provide useful templates:
and if you want something more intelligent than the basic tags-based code completion, take a look at this question.
Eclipse
CDT supports Makefile-based projects:
-- so technically you can build your Objective-C projects out of the box (on Windows, you'll need the Cygwin or MinGW toolchain). The only problem is the code editor which will report plenty of errors against what it thinks is a pure C code (on-the-fly code checking can be turned off, but still...). If you want proper syntax highlighting, you can add Eclim to your Eclipse and enjoy all the good features of both Eclipse and Vim (see above).
Another promising Eclipse plugin is Colorer, but it doesn't support Objective-C as of yet. Feel free to file a feature request though.
SlickEdit
SlickEdit, among other features of a great IDE, does support Objective-C. While it is fairly complex to learn (not as complex as Emacs though), I believe this is your best option provided you don't mind purchasing it (the price is quite affordable).
Additionally, it has an Eclipse plugin which can be used as an alternative to the stand-alone editor.
KDevelop
Rumor has it there exists a KDevelop patch (15 year old, but who cares?). I personally don't think KDevelop is feature-superior compared to Emacsen, so I wouldn't bother trying it.
The above also applies to Objective-C development on Linux, since all of the tools mentioned are more or less portable.
A: As of 2021, the GNUstep Windows MSVC Toolchain allows to integrate Objective-C code in any Windows app, including Visual Studio projects using LLVM/Clang. This includes support for Automatic Reference Counting (ARC) and Objective-C 2.0 features such as blocks.
The project includes the Foundation, CoreFoundation, and libdispatch libraries from GNUstep. It does currently not include any UI framework such as AppKit or UIKit, but it can be used to e.g. write a Windows-specific UI with cross-platform business logic written in Objective-C.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "231"
} |
Q: User does not have permission to run DBCC DBREINDEX I get the following error message in SQL Server 2005:
User '<username>' does not have permission to run DBCC DBREINDEX for object '<table>'.
Which minimum role do I have to give to user in order to run the command?
A: You will need to be a member of the db_ddladmin or the db_owner role AFAIK
A:
Caller must own the table, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.
DBCC DBREINDEX (Transact-SQL) @ MSDN
A: ALTER AUTHORIZATION ON Tablename TO [domain\username]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Best way to query disk space on remote server I am trying to nail down free space on a remote server by querying all the drives and then looping until I find the drive I am seeking.
Is there a better way to do this?
Dim oConn As New ConnectionOptions
Dim sNameSpace As String = "\\mnb-content2\root\cimv2"
Dim oMS As New ManagementScope(sNameSpace, oConn)
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3")
Dim oSearcher As ManagementObjectSearcher = New ManagementObjectSearcher(oMS, oQuery)
Dim oReturnCollection As ManagementObjectCollection = oSearcher.Get()
Dim oReturn As ManagementObject
For Each oReturn In oReturnCollection
'Disk name
Console.WriteLine("Name : " + oReturn("Name").ToString())
'Free Space in bytes
Dim sFreespace As String = oReturn("FreeSpace").ToString()
If Left(oReturn("Name").ToString(), 1) = "Y" Then
Console.WriteLine(sFreespace)
End If
Next
A: Why not just make your WMI query only pull back where name='Y'?
So:
Dim oQuery As System.Management.ObjectQuery = New System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3 AND name='Y'")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Architecture for modeling A common solution to building a model of a system which consists of many items of different types is to create a modular system, where each module is responsible for particular type. For example, there will be module for wombats WombatModule:IModule, where IModule interface has methods like GetCount() (to find number of wombats) and Update() (to update all wombats' state).
More object-oriented approach would be to have class for every item type and create an instance for every item. That will make class Wombat:IItem with methods like Update() (to update this one wombat).
From code perspective difference is negligible, but run-time is significantly different. Module-oriented solution is certainly faster: less object creation, easier to optimize operations common for all wombats.
Problems come when number of types and modules grow. Either you lose most of performance advantage because each module only supports several items, or modules' complexity grows to accomodate for slightly different items of one general type - say, fat and slim wombats. Or both.
At least once I've seen it degrade into poor state when all WombatModule does is keep a collection of hidden Wombat objects and run their methods in loop.
When performance is less of a problem than long-term development, can you identify any architectural reasons to use modules instead of per-item objects? May be there's another possibility I'm missing?
A: I work for an embedded software company and our code base is quite large. The code base was designed with modules that perform specific functions and maintain some objects - also some objects exist as just independent objects. The largest problem we see with our approach is distinguishing the boundaries of modules. Our modules have tended to grow unnecessarily complicated over time and slowly grow to perform functions that were originally outside of it's boundaries. I would say the best direction to take would be to design modularly and implement very specific objects and to make a dedicated effort to not let modules grow larger than you intend.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Automated processing of an Email in Java Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to.
What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.
Any information of even where to start would be helpful.\
Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).
A: Edit: since I first wrote this answer, Wiser has moved and now claims to only be a unit testing tool, so take the answer below with a pinch of salt...
Svrist's answer is good, but if you want to avoid his middle step (the mailserver that writes the mail to disk for later pickup by the Java system) you can use Wiser.
Wiser lets you start an in-Java mailserver:
Wiser wiser = new Wiser();
wiser.setPort(2500);
wiser.start();
Then you can just poll it periodically for mail:
for (WiserMessage message : wiser.getMessages())
{
String envelopeSender = message.getEnvelopeSender();
String envelopeReceiver = message.getEnvelopeReceiver();
MimeMessage mess = message.getMimeMessage();
// mail processing goes here
}
A: Email -> mailserver ->[something] -> file-on-disk.
File on disk is pretty easy to parse, use JavaMail.
The [something] could be:
*
*listener for smtp connections (overkill)!
*Pop3/imap client
*Maildir/Mailbox
A: I've done quite a bit lately with Java agents on Domino servers. The Domino 8.5 server supports Java 6 and its embedded so it won't take someone with a bit of Domino development experience long to put together an agent that runs when new mail arrives. In LotusScript its even easier but that needs more specialised skills which you'd probably need to get a contractor in to provide.
The limitation your likely to encounter concerns the extracted file, you can easily place it on the Domino server's file structure but you may be limited by the OS security from placing it on a different server.
A: Use a mail in database (your Domino administrator can set that up for you but it's in the help file as well).
In that database, you can create an agent that runs periodically to process all new documents. That agent will use the EmbeddedObjects property of the NotesRichTextItem class and the ExtractFile method of the NotesEmbeddedObject class to get a handle on the file attachment and extract it to the location you specify.
For example, this script goes through all the file attachments, object links, and embedded objects in the Body item of a document. Each time it finds a file attachment, it detaches the file to the SAMPLES directory on the C drive and removes the attachment from the document
Dim doc As NotesDocument
Dim rtitem As Variant
'...set value of doc...
Set rtitem = doc.GetFirstItem( "Body" )
If ( rtitem.Type = RICHTEXT ) Then
Forall o In rtitem.EmbeddedObjects
If ( o.Type = EMBED_ATTACHMENT ) Then
Call o.ExtractFile( "c:\samples\" & o.Source )
Call o.Remove
Call doc.Save( False, True )
End If
End Forall
End If
A: Lotus Notes/Domino stores mail in a Notes database. There are APIs available for getting documents (emails), reading field values (From, Subject), and detaching files.
APIs include
-LotusScript (VB variant, available within the Notes database)
-Java (from within or external to the database)
-C API (external)
-Same API available through COM server
You can create a "scheduled agent" within the database (using LotusScript or Java) that can locate documents created since it last ran, locate the attachments, and extract them. The agent will need to be signed with an ID that has the appropriate permissions on the server, including those required to write to the file system and initiate any other processes.
External to the database, you can use any API except LotusScript to log-in to the server/mail database, and follow a similar process, e.g. extracting the files locally on a client or separate server. C API and COM require a notes client install, but Java applications can be set up to run via CORBA/DIIOP without a full install.
Consult the Domino Designer help (or IBM's website for C API) for more information.
As to a "generic way" to do this, if you are accessing data in Notes and needing to extract attachments, I believe these APIs are your best option. If you envision porting the application to another mail system, consider decoupling the API routines via an "interface" so you only need to add a new implementation of that interface to support a new mail system.
A: You can access Notes Documents relatively easily using DIIOP, would be a lot easier than going down the C Api road...
A: Try POP3Client in the Net Commons package; it'll let your Java program check for new mail for a particular account at whatever interval you want (every few minutes? hourly?), and get/delete messages as desired.
A: SMTP/POP3 can be enabled on the Domino server. Worked with this before and gotten Squirrel Mail running with it. SMTP is a bit resource intensive, but well worth the effort because then you don't have to descend into LotusLand to get things working. Just write a small Java CLI program that will check a specific email box (POP3 or SMTP), and parse through the messages, pulling the attachments and placing them where needed.
Plenty of documentation and examples here:
http://java.sun.com/products/javamail/
The techniques that you develop taking this approach will be more widely applicable in your future career than anything Lotus/Domino specific.
A: No matter what you do, you'll need an understanding of the Lotus Notes data structures. The good news is that a fully automated solution can be built in Notes very easily.
Your best bet is to have it built within Notes, and it can be set up to run automatically whenever new mail is received. Gary's answer is dead on, but without any experience, it would probably be hard to figure out how to implement it yourself. On the other hand, it really shouldn't take any competent Notes programmer more than an hour or two to set it up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Display blanks instead of 0 or 0.0 in a BIRT report When using an aggregate control in some reports you would prefer to see a blank field instead of 0. There does not appear to be a way to do this automatically. Does anyone have a way that this can be done. Note, you want to maintain the '0' value for the field in cases when you export, but you want to show a blank when rendering to PDF or HTML.
A: There are a number of ways to solve this. The two primary are to use either visibility rules or highlights to create conditional formatting. The visibility is particularly attractive since it is easy to only apply the format rules to particular types of output (e.g. HTML).
For this particular case, there are two problems with these approaches. First, I want a general solutions where I don't have to specify the text color. In other words, when the condition is true (value of 0) then I want my text color to match the background color. In that way if someone changes the backgroundColor for the control, the code still works.
The other issue is that in this case I am using dynamic column binding which does not support value lookup.
The solution that I created was to add a JavaScript function called hideMe as shown below.
function hideText (dataControl){
if (dataControl.getValue() == 0) {
var color = dataControl.getStyle().getBackgroundColor();
var parentItem = dataControl.getParent();
do {
if (color == null && parentItem != null) {
color = parentItem.getStyle().getBackgroundColor();
parentItem = parentItem.getParent();
} else {
break;
}
} while (color == null);
dataControl.getStyle().color = color;
}
}
Once this function has been added to the report (in my case an included javascript file) I just call it from the OnCreate method of the control.
hideText(this);
This can also be done using Java Event Handlers but this method seems to be easier.
A: Just an FYI, after working with this for a while longer, I have found that it is just easier to use Visibility rules. The one big advantage is that you can easily configure different visibility for different output formats. So for PDF it may be best to use blanks, but for Excel you may want the 0 values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to call the AllocateAndInitializeSid function from C#? Can somebody give me a complete and working example of calling the AllocateAndInitializeSid function from C# code?
I found this:
BOOL WINAPI AllocateAndInitializeSid(
__in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
__in BYTE nSubAuthorityCount,
__in DWORD dwSubAuthority0,
__in DWORD dwSubAuthority1,
__in DWORD dwSubAuthority2,
__in DWORD dwSubAuthority3,
__in DWORD dwSubAuthority4,
__in DWORD dwSubAuthority5,
__in DWORD dwSubAuthority6,
__in DWORD dwSubAuthority7,
__out PSID *pSid
);
and I don't know how to construct the signature of this method - what should I do with PSID_IDENTIFIER_AUTHORITY and PSID types? How should I pass them - using ref or out?
A: Using P/Invoke Interop Assistant:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SidIdentifierAuthority {
/// BYTE[6]
[System.Runtime.InteropServices.MarshalAsAttribute(
System.Runtime.InteropServices.UnmanagedType.ByValArray,
SizeConst = 6,
ArraySubType =
System.Runtime.InteropServices.UnmanagedType.I1)]
public byte[] Value;
}
public partial class NativeMethods {
/// Return Type: BOOL->int
///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY->_SID_IDENTIFIER_AUTHORITY*
///nSubAuthorityCount: BYTE->unsigned char
///nSubAuthority0: DWORD->unsigned int
///nSubAuthority1: DWORD->unsigned int
///nSubAuthority2: DWORD->unsigned int
///nSubAuthority3: DWORD->unsigned int
///nSubAuthority4: DWORD->unsigned int
///nSubAuthority5: DWORD->unsigned int
///nSubAuthority6: DWORD->unsigned int
///nSubAuthority7: DWORD->unsigned int
///pSid: PSID*
[System.Runtime.InteropServices.DllImportAttribute("advapi32.dll", EntryPoint = "AllocateAndInitializeSid")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool AllocateAndInitializeSid(
[System.Runtime.InteropServices.InAttribute()]
ref SidIdentifierAuthority pIdentifierAuthority,
byte nSubAuthorityCount,
uint nSubAuthority0,
uint nSubAuthority1,
uint nSubAuthority2,
uint nSubAuthority3,
uint nSubAuthority4,
uint nSubAuthority5,
uint nSubAuthority6,
uint nSubAuthority7,
out System.IntPtr pSid);
}
A: If you are targeting .NET 2.0 or later, the class System.Security.Principal.SecurityIdentifier wraps a SID and allows you to avoid the error-prone Win32 APIs.
Not exactly an answer to your question, but who knows it may be useful.
A: For Platform Invoke www.pinvoke.net is your new best friend!
http://www.pinvoke.net/default.aspx/advapi32/AllocateAndInitializeSid.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is DocumentBuilder.parse() thread safe? Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel?
The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is?
The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.
A: You can also check this code to make further optimization https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java
A: Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
private static final ThreadLocal<DocumentBuilder> builderLocal =
new ThreadLocal<DocumentBuilder>() {
@Override protected DocumentBuilder initialValue() {
try {
return
DocumentBuilderFactory
.newInstance(
"xx.MyDocumentBuilderFactory",
getClass().getClassLoader()
).newDocumentBuilder();
} catch (ParserConfigurationException exc) {
throw new IllegalArgumentException(exc);
}
}
};
(Disclaimer: Not so much as attempted to compile the code.)
A: There's a reset() method on DocumentBuilder which restores it to the state when it was first created. If you're going the ThreadLocal route, don't forget to call this or you're hosed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: File system info - how to query it? Is there a way to access file system info via some type of Windows API? If not what other methods are available to a user mode developer?
A: Not very clean, but you can use DeviceIoControl()
Open volume as a file, pass resulting handle to DeviceIoControl() together with control code. Check MSDN for control codes, there is something like "read journal record".
A: In another post, someone recommended this : Keeping an Eye on Your NTFS Drives: the Windows 2000 Change Journal Explained.
It explains how to use the NTFS Filesystem with C++ through Windows 2000.
The implementation might have changed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Keyboard Shortcut in Access 2003 Is there a keyboard shortcut in Access 2003 that will run a query while in design or sql mode?
A: Sendkeys is always a mistake because almost nothing in Access not doable via code.
The correct code is:
DoCmd.RunCommand acCmdRun
How you run that code is up to you, but it's definitely preferable to SendKeys.
A: It's not built-in. I would try a macro - AutoKeys? You should be able to make almost any keyboard short you want that way.
A: I used a combination of the answers writing a little function that is called from the AutoKeys macro like so:
Public Function RunMyQuery() As Boolean
SendKeys "%Q" & "R"
RunMyQuery = True
End Function
Thanks!
A: This function isn't built in, but you can set it up so you can press the F5 function key to run the query.
*
*Create a new macro.
*Use the menu, View > Macro Names to add the "Macro Names" column to the grid if it's not already showing.
*Type this in the "Macro Names" column: {F5}
*In the "Action" column, scroll down and select "RunCommand."
*The bottom half of the window pane is "Action Arguments." For "Command," scroll down and select "Run."
*Save the macro as AutoKeys.
*Close the macro.
*Open a saved query in design view or sql view.
*Press the function key, F5, to run the query.
A: Ctrl+, and Ctrl+. will let MS Access cycle left and right through the query views Design, Datasheet, SQL, PivotTable, PivotChart.
Otherwise, you can right click on the "Run" exclamation mark and select customize, then with that customize window open, you can right click on the "Run" exclamation mark again, select "Image and Text" to show the word Run. As long as the word is shown, you can use Alt+Shift+R to activate that button based on the underlined capital R. If you right click on the "Run" exclamation mark again and select properties, you can change the capital R to a lowercase r so that the SHIFT key isn't needed and the shortcut simply becomes Alt+R.
A: Keyboard shortcut to run a query:
Press (don't hold down) Alt then tap v then tap s
Keyboard shortcut to return to query view:
Press Alt then tap v then tap q
A: Does Alt Q Alt R (ie menu item selection) not suit?
A: Not sure what resemblance this bears to the same issue in Windows 2007 but FWIW, I fixed it there by doing the following:
*
*Right click the Run button
*Select "Customize Quick Access Toolbar"
*In the dialog that appears, select "Query Tools | Design Tab" from the drop-down list on the left. The options in the list box on the left will change to reflect the selection.
*In the list box on the left, select "Run" and click "Add >>". "Run" should be added to the list on the right.
*Click Okay.
Now you can run your SQL using Alt+4.
A: Though not a keyboard shortcut, it is also possible to add the button to the quick Access toolbar for easy access regardless what tab you are own, or when the ribbon is minimized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Starting a new job focused on brownfield application refactoring & Agile I am starting a new job on Monday. The company has a home grown enterprise case management application written in ASP.NET/VB.NET. They are attempting to implement an Agile development process. They have gone so far as to get two people Scrum Master certified and hire an Agile coach. They are currently focused on 6-9 months of refactoring.
My question is what are some good approaches/tooling given this environment for becoming familiar with the code base and being productive as soon as I hit the ground? Any suggestion?
A: Great question!
I would say the first thing to do is get the daily scrums going. Your part in the scrum will be learning the code. It will provide you a way to ask questions and get a feel for who can help you learn the code.
Once you have that guy (or guys) picked out start pair programming with them. Let them drive but ask questions. You will be surprised how much you can pick up that way. Given their bend on Agile, that should be an easy sell. :)
Once you have that established, be sure to swap partners every so often so you get a feel for the enitre code base. Just sticking woth one guy who is doing one part won't give you a big picture but jumping between people will get you a better big picture view of the code.
Just my 2 cents. :) Good luck and have fun!!
A: Congratulations on the new job!
Relax and keep your cool. Read something on here.
I guess, the process itself will make sure you are productive as long as you apply common sense :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Differences Between DataSet Merges Is there a difference (performance, overhead) between these two ways of merging data sets?
MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
and
MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
Which do you recommend?
A: Those two lines do different things.
The first one creates a new set, and then merges a second set into it.
The second one sets the ds reference to point to the second set, so:
MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")
//anotherDataSet does not contain the new table
MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");
//anotherDataSet now contains the new table
Ok, let's assume that what you meant was:
MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );
//vs
MyClass o2 = new MyClass( /* some data */ );
Then the latter is better, as the former creates an empty object before populating it.
However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.
A: Your second example does not create a new dataset. It's just a second reference to an existing dataset.
A: While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and not construct an intermediate, empty object as in your case. Two reasons:
*
*Performance. This should be obvious: Object creation costs time so creating less objects is better.
*Much more important however, it better states your intent. You do generally not intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I tell a multi-core / multi-CPU machine to process function calls in a loop in parallel? I am currently designing an application that has one module which will load large amounts of data from a database and reduce it to a much smaller set by various calculations depending on the circumstances.
Many of the more intensive operations behave deterministically and would lend themselves to parallel processing.
Provided I have a loop that iterates over a large number of data chunks arriving from the db and for each one call a deterministic function without side effects, how would I make it so that the program does not wait for the function to return but rather sets the next calls going, so they could be processed in parallel? A naive approach to demonstrate the principle would do me for now.
I have read Google's MapReduce paper and while I could use the overall principle in a number of places, I won't, for now, target large clusters, rather it's going to be a single multi-core or multi-CPU machine for version 1.0. So currently, I'm not sure if I can actually use the library or would have to roll a dumbed-down basic version myself.
I am at an early stage of the design process and so far I am targeting C-something (for the speed critical bits) and Python (for the productivity critical bits) as my languages. If there are compelling reasons, I might switch, but so far I am contented with my choice.
Please note that I'm aware of the fact that it might take longer to retrieve the next chunk from the database than to process the current one and the whole process would then be I/O-bound. I would, however, assume for now that it isn't and in practice use a db cluster or memory caching or something else to be not I/O-bound at this point.
A: Well, if .net is an option, they have put a lot of effort into Parallel Computing.
A: You can implement the algorithm from Google's MapReduce without having physically separate machines. Just consider each of those "machines" to be "threads." Threads are automatically distributed on multi-core machines.
A: If you still plan on using Python, you might want to have a look at Processing. It uses processes rather than threads for parallel computing (due to the Python GIL) and provides classes for distributing "work items" onto several processes. Using the pool class, you can write code like the following:
import processing
def worker(i):
return i*i
num_workers = 2
pool = processing.Pool(num_workers)
result = pool.imap(worker, range(100000))
This is a parallel version of itertools.imap, which distributes calls over to processes. You can also use the apply_async methods of the pool and store lazy result objects in a list:
results = []
for i in range(10000):
results.append(pool.apply_async(worker, i))
For further reference, see the documentation of the Pool class.
Gotchas:
*
*processing uses fork(), so you have to be careful on Win32
*objects transferred between processes need to be pickleable
*if the workers are relatively fast, you can tweak chunksize, i.e.
the number of work items send to a worker process in one batch
*processing.Pool uses a background thread
A: If you're working with a compiler that will support it, I would suggest taking a look at http://www.openmp.org for a way of annotating your code in such a way that
certain loops will be parallelized.
It does a lot more as well, and you might find it very helpful.
Their web page reports that gcc4.2 will support openmp, for example.
A: I might be missing something here, but this this seems fairly straight forward using pthreads.
Set up a small threadpool with N threads in it and have one thread to control them all.
The master thread simply sits in a loop doing something like:
*
*Get data chunk from DB
*Find next free thread If no thread is free then wait
*Hand over chunk to worker thread
*Go back and get next chunk from DB
In the meantime the worker threads they sit and do:
*
*Mark myself as free
*Wait for the mast thread to give me a chunk of data
*Process the chunk of data
*Mark myself as free again
The method by which you implement this can be as simple as two mutex controlled arrays. One has the worked threads in it (the threadpool) and the other indicated if each corresponding thread is free or busy.
Tweak N to your liking ...
A: The same thread pool is used in java. But the threads in threadpools are serialisable and sent to other computers and deserialised to run.
A: I have developed a MapReduce library for multi-threaded/multi-core use on a single server. Everything is taken care of by the library, and the user just has to implement Map and Reduce. It is positioned as a Boost library, but not yet accepted as a formal lib. Check out http://www.craighenderson.co.uk/mapreduce
A: You may be interested in examining the code of libdispatch, which is the open source implementation of Apple's Grand Central Dispatch.
A: Intel's TBB or boost::mpi might be of interest to you also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How do I make dynamic content with dynamic navigation? I'm creating an ASP.NET web site where all pages hang off a database-driven tree-hierarchy. Pages typically present HTML content. But, some will execute programming.
Examples:
*
*a "contact us" form
*a report generator
How should I represent/reference the programming within the database? Should I have a varchar value of a Web User Control (.ascx) name? Or a Web Form (.aspx) name? Something else? Or should it just be an integer or other such ID in a dictionary within my application?
Can I make an ASP.NET Site Map Provider with this structure?
See more information here: Which is the best database schema for my navigation?
A: You might consider inserting placeholders like <my:contact-us-form/> in the database on specific pages; that way the database can describe all the static text content instead of completely replacing that database-driven content with an .ascx control.
A: Our development team has had success with defining the name of a Web User Control in the database. Upon page load it checks too see what controls to dynamically load from the database.
We use Web User Controls instead of Web Forms in order to ensure we can use the control on any page.
You can also dynamically build a site map using ASP.Net's provider. CodeProject has a good example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do you set focus to the HTML5 canvas element? I'm using the HTML5 <canvas> element in Firefox 2.0.0.16 and in Safari 3.1.2, both on my iMac. (I've tried this in Firefox 3.0 on Windows as well, also to no avail.) The tag looks like this:
<td>
<canvas id="display"
width="500px"
height="500px">
</canvas>
</td>
I have a button to "activate" some functionality that interacts with the canvas. That button's onclick() event calls a function. In that function I have the following line:
document.getElementById("display").focus();
This does not work. Firebug reports no error. But the focus still remains where it was. I can click on the canvas or tab towards the canvas and focus will be lost from the other elements, but apparently never be gained on by the canvas (The canvas's onfocus() event never fires).
I find this odd. Is it that the canvas simply cannot get focus, or am I missing something here? Any insight would be appreciated.
Thank you.
A: Give the canvas a tab index:
<canvas id="display"
width="500px"
height="500px"
tabindex="1">
</canvas>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Do I need to leave gaps in a standard server rack? We have a 42U rack which is getting a load of new 1U and 2U servers real soon. One of the guys here reckons that you need to leave a gap between the servers (of 1U) to aid cooling.
Question is, do you? When looking around the datacenter, no-one else seems to be, and it also diminishes how much we can fit in. We're using Dell 1850 and 2950 hardware.
A: You don't need to leave a gap between systems for gear designed to be rack-mountable. If you were building the systems yourself you'd need to select components carefully: some CPU+motherboards run too hot even if they can physically fit inside a 1U case.
Dell gear will be fine.
You do need to keep the space between and behind the racks clear of clutter. Most servers today channel their airflow front to back, if you don't leave enough open air behind the rack it will get very hot back there and reduce the cooling capacity.
On a typical 48 port switch the front panel is covered with RJ-45 connectors and the back by redundant power connections, PoE power tray hookups, stacking ports and uplinks. Many 1U network switches route their airflow side-to-side, because they can't get enough air through the maze of connectors front-to-back. So you also need to make sure the channels beside the rack are relatively open, to let the switches get enough airflow.
In a crowded server rack, tidiness is important.
A: I agree with Unkwntech that gaps are not normally required, but I think there are two things to watch out for:
1) Equipment that is not as deep as the rest may have trouble ventilating if mounted below deeper equipment (see below). This is of course less of a concern in a well ventilated server room.
TOP OF RACK
===============
===============
===============
===============
===============
======== (Shallow equipment, trapped hot air)
2) When mounting equipment in a cabinet, you usually need to leave a few inches clear at the top to allow proper ventilation.
A: Generally, no. That's kind of the whole point a of 1U server: if it needed extra space (even for cooling) they'd give it a bigger chassis and call it 2U. In some designs, where the airflow is controlled and only the rack is supposed to be cooled, the gap is even counter-productive, as it allows for the warm air from the back to flow and mix with the cool air in the front, reducing cooling efficiency. Even when you have gaps for logical groupings, you're supposed to plug them with blank panels to the control the airflow.
Unfortunately, in practice some whitebox vendors occasionally push too hard for that 1U designation, and you'll find that if you stack too many too close together without the occasional gap for airflow you have issues. This isn't a problem with good quality servers and an adequate cooling design, but the bottom end of the market might surprise you.
A: Simply NO, the servers and switches, and KVMs, and PSUs are all designed to be on the rack stacked on top of eachother. I'm basing this on a few years building, COs and Data centers for AT&T.
A: The last two places I worked have large datacenters and they stack all their servers and appliances with no gaps. The servers have plenty of cooling with their internal fans. It is also recommended to run the rack on a raised floor with perforated tiles in the front of the rack and A/C air return above the rear of the racks for circulation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Converting scripts from ksh to bash I have some ksh scripts which I'd like to convert to run with bash instead.
Are there any useful on-line resources for this?
I'm really looking for a list of differences between the two shells and any gotchas I might encounter, although all information is welcome :-)
A: Have you tried looking at this page? It has a useful matrix of features and links to elsewhere.
Also this link, search for:
C2) How does bash differ from the Korn shell
A: Here's a comparison from HP on the differences between shells:
*
*https://web.archive.org/web/20100829200456/http://docs.hp.com/en/B2355-90046/ch15s03.html
Here's a great set of UNIX shell tutorials from Richard's Shell Scripting Universe:
*
*http://www.injunea.demon.co.uk/index.htm
The second is by far one of the most useful scripting resources I have found, and it really helps you learn how to write scripts with portability in mind.
Good luck with your conversions.
2022 EDIT: HP retired the comparison page, so I updated the link to an archived version in the wayback machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: The difference between the connections strings in SQLCLR I was reviewing some code that a consultant checked in and notice they were using SQLCLR. I don't have any experience with it so thought I would research what it was about. I noticed that they used
Dim cn As New SqlConnection("server=LOCALHOST;integrated security=yes;database=" & sDb)
instead of
DIM conn As New SqlConnection("context connection=true")
I'm wondering what the difference since it's localhost on the first?
A: The context connection uses the user's already established connection to the server. So you inherit things like their database context, connection options, etc.
Using localhost will connect to the server using a normal shared memory connection. This can be useful if you don't want to use the user's connection (i.e. if you want to connect to a different database, or with different options, etc).
In most cases you should use the context connection, since it doesn't create a separate connection to the server.
Also, be warned that using a separate connection means you are not part of the user's transaction and are subject to normal locking semantics.
A: Consider a big office phone systems:
My office has an internal phone system. But every phone also has an external phone number (virtual numbers that utilize one of a group of real TELCO lines). I can call another office by dialing their phone extension directly and the call will route through our internal phone system (one hop). Alternatively I could dial that phone's public number and the call routes out from the building's system to the TELCO switching office, then back through the building's system then to the office extension (3 hops).
The first SQL connection behaves as any standard SQL connection would when connecting to the server specified in the connection string. A new connection is created using the standard native SQL connectivity. This behaves like dialing the full public phone number of another office phone. Sure, you are connecting to the local machine, but the connection is routed differently.
The context connection has the new SqlConnection instance using the existing connection that is executing the SQLCLR object. It's using the existing/local context. This is like dialing my office mate's extension directly. Local context and more efficient.
Although I'm not positive, I believe that when using the context connection, the calls to the SQLCLR objects also then participate in the context's transaction. Someone please correct me if I'm wrong.
Peter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I start threads in plain C? I have used fork() in C to start another process. How do I start a new thread?
A: pthreads is a good start, look here
A: Threads are not part of the C standard, so the only way to use threads is to use some library (eg: POSIX threads in Unix/Linux, _beginthread/_beginthreadex if you want to use the C-runtime from that thread or just CreateThread Win32 API)
A: Since you mentioned fork() I assume you're on a Unix-like system, in which case POSIX threads (usually referred to as pthreads) are what you want to use.
Specifically, pthread_create() is the function you need to create a new thread. Its arguments are:
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *
(*start_routine)(void *), void * arg);
The first argument is the returned pointer to the thread id. The second argument is the thread arguments, which can be NULL unless you want to start the thread with a specific priority. The third argument is the function executed by the thread. The fourth argument is the single argument passed to the thread function when it is executed.
A: Check out the pthread (POSIX thread) library.
A: AFAIK, ANSI C doesn't define threading, but there are various libraries available.
If you are running on Windows, link to msvcrt and use _beginthread or _beginthreadex.
If you are running on other platforms, check out the pthreads library (I'm sure there are others as well).
A: C11 threads + C11 atomic_int
Added to glibc 2.28. Tested in Ubuntu 18.10 amd64 (comes with glic 2.28) and Ubuntu 18.04 (comes with glibc 2.27) by compiling glibc 2.28 from source: Multiple glibc libraries on a single host
Example adapted from: https://en.cppreference.com/w/c/language/atomic
main.c
#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>
atomic_int atomic_counter;
int non_atomic_counter;
int mythread(void* thr_data) {
(void)thr_data;
for(int n = 0; n < 1000; ++n) {
++non_atomic_counter;
++atomic_counter;
// for this example, relaxed memory order is sufficient, e.g.
// atomic_fetch_add_explicit(&atomic_counter, 1, memory_order_relaxed);
}
return 0;
}
int main(void) {
thrd_t thr[10];
for(int n = 0; n < 10; ++n)
thrd_create(&thr[n], mythread, NULL);
for(int n = 0; n < 10; ++n)
thrd_join(thr[n], NULL);
printf("atomic %d\n", atomic_counter);
printf("non-atomic %d\n", non_atomic_counter);
}
GitHub upstream.
Compile and run:
gcc -ggdb3 -std=c11 -Wall -Wextra -pedantic -o main.out main.c -pthread
./main.out
Possible output:
atomic 10000
non-atomic 4341
The non-atomic counter is very likely to be smaller than the atomic one due to racy access across threads to the non-atomic variable.
See also: How to do an atomic increment and fetch in C?
Disassembly analysis
Disassemble with:
gdb -batch -ex "disassemble/rs mythread" main.out
contains:
17 ++non_atomic_counter;
0x00000000004007e8 <+8>: 83 05 65 08 20 00 01 addl $0x1,0x200865(%rip) # 0x601054 <non_atomic_counter>
18 __atomic_fetch_add(&atomic_counter, 1, __ATOMIC_SEQ_CST);
0x00000000004007ef <+15>: f0 83 05 61 08 20 00 01 lock addl $0x1,0x200861(%rip) # 0x601058 <atomic_counter>
so we see that the atomic increment is done at the instruction level with the f0 lock prefix.
With aarch64-linux-gnu-gcc 8.2.0, we get instead:
11 ++non_atomic_counter;
0x0000000000000a28 <+24>: 60 00 40 b9 ldr w0, [x3]
0x0000000000000a2c <+28>: 00 04 00 11 add w0, w0, #0x1
0x0000000000000a30 <+32>: 60 00 00 b9 str w0, [x3]
12 ++atomic_counter;
0x0000000000000a34 <+36>: 40 fc 5f 88 ldaxr w0, [x2]
0x0000000000000a38 <+40>: 00 04 00 11 add w0, w0, #0x1
0x0000000000000a3c <+44>: 40 fc 04 88 stlxr w4, w0, [x2]
0x0000000000000a40 <+48>: a4 ff ff 35 cbnz w4, 0xa34 <mythread+36>
so the atomic version actually has a cbnz loop that runs until the stlxr store succeed. Note that ARMv8.1 can do all of that with a single LDADD instruction.
This is analogous to what we get with C++ std::atomic: What exactly is std::atomic?
Benchmark
TODO. Crate a benchmark to show that atomic is slower.
POSIX threads
main.c
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <stdlib.h>
#include <pthread.h>
enum CONSTANTS {
NUM_THREADS = 1000,
NUM_ITERS = 1000
};
int global = 0;
int fail = 0;
pthread_mutex_t main_thread_mutex = PTHREAD_MUTEX_INITIALIZER;
void* main_thread(void *arg) {
int i;
for (i = 0; i < NUM_ITERS; ++i) {
if (!fail)
pthread_mutex_lock(&main_thread_mutex);
global++;
if (!fail)
pthread_mutex_unlock(&main_thread_mutex);
}
return NULL;
}
int main(int argc, char **argv) {
pthread_t threads[NUM_THREADS];
int i;
fail = argc > 1;
for (i = 0; i < NUM_THREADS; ++i)
pthread_create(&threads[i], NULL, main_thread, NULL);
for (i = 0; i < NUM_THREADS; ++i)
pthread_join(threads[i], NULL);
assert(global == NUM_THREADS * NUM_ITERS);
return EXIT_SUCCESS;
}
Compile and run:
gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread
./main.out
./main.out 1
The first run works fine, the second fails due to missing synchronization.
There don't seem to be POSIX standardized atomic operations: UNIX Portable Atomic Operations
Tested on Ubuntu 18.04. GitHub upstream.
GCC __atomic_* built-ins
For those that don't have C11, you can achieve atomic increments with the __atomic_* GCC extensions.
main.c
#define _XOPEN_SOURCE 700
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
enum Constants {
NUM_THREADS = 1000,
};
int atomic_counter;
int non_atomic_counter;
void* mythread(void *arg) {
(void)arg;
for (int n = 0; n < 1000; ++n) {
++non_atomic_counter;
__atomic_fetch_add(&atomic_counter, 1, __ATOMIC_SEQ_CST);
}
return NULL;
}
int main(void) {
int i;
pthread_t threads[NUM_THREADS];
for (i = 0; i < NUM_THREADS; ++i)
pthread_create(&threads[i], NULL, mythread, NULL);
for (i = 0; i < NUM_THREADS; ++i)
pthread_join(threads[i], NULL);
printf("atomic %d\n", atomic_counter);
printf("non-atomic %d\n", non_atomic_counter);
}
Compile and run:
gcc -ggdb3 -O3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c -pthread
./main.out
Output and generated assembly: the same as the "C11 threads" example.
Tested in Ubuntu 16.04 amd64, GCC 6.4.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "60"
} |
Q: BOM not expected in CF but sent by IIS/SharePoint I'm trying to consume a SharePoint webservice from ColdFusion via cfinvoke ('cause I don't want to deal with (read: parse) the SOAP response itself).
The SOAP response includes a byte-order-mark character (BOM), which produces the following exception in CF:
"Cannot perform web service invocation GetList.
The fault returned when invoking the web service operation is:
'AxisFault
faultCode: {http://www.w3.org/2003/05/soap-envelope}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Content is not allowed in prolog."
The standard for UTF-8 encoding optionally includes the BOM character (http://unicode.org/faq/utf_bom.html#29). Microsoft almost universally includes the BOM character with UTF-8 encoded streams . From what I can tell there’s no way to change that in IIS. The XML parser that JRun (ColdFusion) uses by default doesn’t handle the BOM character for UTF-8 encoded XML streams. So, it appears that the way to fix this is to change the XML parser used by JRun (http://www.bpurcell.org/blog/index.cfm?mode=entry&entry=942).
Adobe says that it doesn't handle the BOM character (see comments from anoynomous and halL on May 2nd and 5th).
http://livedocs.adobe.com/coldfusion/8/htmldocs/Tags_g-h_09.html#comments
A: I'm going to say that the answer to your question (is it possible?) is no. I don't know that definitively, but the poster who commented just above halL (in the comments on this page) gave a work-around for the problem -- so I assume it is possible to deal with when parsing manually.
You say that you're using CFInvoke because you don't want to deal with the soap response yourself. It looks like you don't have any choice.
A: As Adam Tuttle said already, the workaround is on the page that you linked to
<!--- Remove BOM from the start of the string, if it exists --->
<cfif Left(responseText, 1) EQ chr(65279)>
<cfset responseText = mid(xmlText, 2, len(responseText))>
</cfif>
A: It sounds like ColdFusion is using Apache Axis under the covers.
This doesn't apply exactly to your solution, but I've had to deal with this issue once before when consuming a .NET web service with Apache Axis/Java. The only solution I was able to find (since the owner of the web service was unwilling to change anything on his end) was to write a Handler class that Axis would plug into the pipeline which would delete the BOM from the message if it existed.
So perhaps it's possible to configure Axis through ColdFusion? If so you can add additional Handlers to the message handling flow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: round() doesn't seem to be rounding properly The documentation for the round() function states that you pass it a number, and the positions past the decimal to round. Thus it should do this:
n = 5.59
round(n, 1) # 5.6
But, in actuality, good old floating point weirdness creeps in and you get:
5.5999999999999996
For the purposes of UI, I need to display 5.6. I poked around the Internet and found some documentation that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. See here also.
Short of creating my own round library, is there any way around this?
A: Take a look at the Decimal module
Decimal “is based on a floating-point
model which was designed with people
in mind, and necessarily has a
paramount guiding principle –
computers must provide an arithmetic
that works in the same way as the
arithmetic that people learn at
school.” – excerpt from the decimal
arithmetic specification.
and
Decimal numbers can be represented
exactly. In contrast, numbers like 1.1
and 2.2 do not have an exact
representations in binary floating
point. End users typically would not
expect 1.1 + 2.2 to display as
3.3000000000000003 as it does with binary floating point.
Decimal provides the kind of operations that make it easy to write apps that require floating point operations and also need to present those results in a human readable format, e.g., accounting.
A: Floating point math is vulnerable to slight, but annoying, precision inaccuracies. If you can work with integer or fixed point, you will be guaranteed precision.
A: It's a big problem indeed. Try out this code:
print "%.2f" % (round((2*4.4+3*5.6+3*4.4)/8,2),)
It displays 4.85. Then you do:
print "Media = %.1f" % (round((2*4.4+3*5.6+3*4.4)/8,1),)
and it shows 4.8. Do you calculations by hand the exact answer is 4.85, but if you try:
print "Media = %.20f" % (round((2*4.4+3*5.6+3*4.4)/8,20),)
you can see the truth: the float point is stored as the nearest finite sum of fractions whose denominators are powers of two.
A: printf the sucker.
print '%.1f' % 5.59 # returns 5.6
A: I would avoid relying on round() at all in this case. Consider
print(round(61.295, 2))
print(round(1.295, 2))
will output
61.3
1.29
which is not a desired output if you need solid rounding to the nearest integer. To bypass this behavior go with math.ceil() (or math.floor() if you want to round down):
from math import ceil
decimal_count = 2
print(ceil(61.295 * 10 ** decimal_count) / 10 ** decimal_count)
print(ceil(1.295 * 10 ** decimal_count) / 10 ** decimal_count)
outputs
61.3
1.3
Hope that helps.
A: If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:
from decimal import Decimal, ROUND_UP
Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)
This will return a Decimal Number which is 16.20.
A: You can use the string format operator %, similar to sprintf.
mystring = "%.2f" % 5.5999
A: I am doing:
int(round( x , 0))
In this case, we first round properly at the unit level, then we convert to integer to avoid printing a float.
so
>>> int(round(5.59,0))
6
I think this answer works better than formating the string, and it also makes more sens to me to use the round function.
A: round(5.59, 1) is working fine. The problem is that 5.6 cannot be represented exactly in binary floating point.
>>> 5.6
5.5999999999999996
>>>
As Vinko says, you can use string formatting to do rounding for display.
Python has a module for decimal arithmetic if you need that.
A: Works Perfect
format(5.59, '.1f') # to display
float(format(5.59, '.1f')) #to round
A: Another potential option is:
def hard_round(number, decimal_places=0):
"""
Function:
- Rounds a float value to a specified number of decimal places
- Fixes issues with floating point binary approximation rounding in python
Requires:
- `number`:
- Type: int|float
- What: The number to round
Optional:
- `decimal_places`:
- Type: int
- What: The number of decimal places to round to
- Default: 0
Example:
```
hard_round(5.6,1)
```
"""
return int(number*(10**decimal_places)+0.5)/(10**decimal_places)
A: You get '5.6' if you do str(round(n, 1)) instead of just round(n, 1).
A: You can switch the data type to an integer:
>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5)
56
And then display the number by inserting the locale's decimal separator.
However, Jimmy's answer is better.
A: I can't help the way it's stored, but at least formatting works correctly:
'%.1f' % round(n, 1) # Gives you '5.6'
A: Formatting works correctly even without having to round:
"%.1f" % n
A: Code:
x1 = 5.63
x2 = 5.65
print(float('%.2f' % round(x1,1))) # gives you '5.6'
print(float('%.2f' % round(x2,1))) # gives you '5.7'
Output:
5.6
5.7
A: The problem is only when last digit is 5. Eg. 0.045 is internally stored as 0.044999999999999... You could simply increment last digit to 6 and round off. This will give you the desired results.
import re
def custom_round(num, precision=0):
# Get the type of given number
type_num = type(num)
# If the given type is not a valid number type, raise TypeError
if type_num not in [int, float, Decimal]:
raise TypeError("type {} doesn't define __round__ method".format(type_num.__name__))
# If passed number is int, there is no rounding off.
if type_num == int:
return num
# Convert number to string.
str_num = str(num).lower()
# We will remove negative context from the number and add it back in the end
negative_number = False
if num < 0:
negative_number = True
str_num = str_num[1:]
# If number is in format 1e-12 or 2e+13, we have to convert it to
# to a string in standard decimal notation.
if 'e-' in str_num:
# For 1.23e-7, e_power = 7
e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])
# For 1.23e-7, number = 123
number = ''.join(str_num.split('e-')[0].split('.'))
zeros = ''
# Number of zeros = e_power - 1 = 6
for i in range(e_power - 1):
zeros = zeros + '0'
# Scientific notation 1.23e-7 in regular decimal = 0.000000123
str_num = '0.' + zeros + number
if 'e+' in str_num:
# For 1.23e+7, e_power = 7
e_power = int(re.findall('e\+[0-9]+', str_num)[0][2:])
# For 1.23e+7, number_characteristic = 1
# characteristic is number left of decimal point.
number_characteristic = str_num.split('e+')[0].split('.')[0]
# For 1.23e+7, number_mantissa = 23
# mantissa is number right of decimal point.
number_mantissa = str_num.split('e+')[0].split('.')[1]
# For 1.23e+7, number = 123
number = number_characteristic + number_mantissa
zeros = ''
# Eg: for this condition = 1.23e+7
if e_power >= len(number_mantissa):
# Number of zeros = e_power - mantissa length = 5
for i in range(e_power - len(number_mantissa)):
zeros = zeros + '0'
# Scientific notation 1.23e+7 in regular decimal = 12300000.0
str_num = number + zeros + '.0'
# Eg: for this condition = 1.23e+1
if e_power < len(number_mantissa):
# In this case, we only need to shift the decimal e_power digits to the right
# So we just copy the digits from mantissa to characteristic and then remove
# them from mantissa.
for i in range(e_power):
number_characteristic = number_characteristic + number_mantissa[i]
number_mantissa = number_mantissa[i:]
# Scientific notation 1.23e+1 in regular decimal = 12.3
str_num = number_characteristic + '.' + number_mantissa
# characteristic is number left of decimal point.
characteristic_part = str_num.split('.')[0]
# mantissa is number right of decimal point.
mantissa_part = str_num.split('.')[1]
# If number is supposed to be rounded to whole number,
# check first decimal digit. If more than 5, return
# characteristic + 1 else return characteristic
if precision == 0:
if mantissa_part and int(mantissa_part[0]) >= 5:
return type_num(int(characteristic_part) + 1)
return type_num(characteristic_part)
# Get the precision of the given number.
num_precision = len(mantissa_part)
# Rounding off is done only if number precision is
# greater than requested precision
if num_precision <= precision:
return num
# Replace the last '5' with 6 so that rounding off returns desired results
if str_num[-1] == '5':
str_num = re.sub('5$', '6', str_num)
result = round(type_num(str_num), precision)
# If the number was negative, add negative context back
if negative_number:
result = result * -1
return result
A: Here's where I see round failing. What if you wanted to round these 2 numbers to one decimal place?
23.45
23.55
My education was that from rounding these you should get:
23.4
23.6
the "rule" being that you should round up if the preceding number was odd, not round up if the preceding number were even.
The round function in python simply truncates the 5.
A: Here is an easy way to round a float number to any number of decimal places, and it still works in 2021!
float_number = 12.234325335563
rounded = round(float_number, 3) # 3 is the number of decimal places to be returned.You can pass any number in place of 3 depending on how many decimal places you want to return.
print(rounded)
And this will print;
12.234
A: What about:
round(n,1)+epsilon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "141"
} |
Q: How can I make an exact copy of a xml node's children with XSLT? My problem is that my XML document contains snippets of XHTML within it and while passing it through an XSLT I would like it to render those snippets without mangling them.
I've tried wrapping the snippet in a CDATA but it doesn't work since less than and greater than are translated to < and > as opposed to being echoed directly.
What's the XSL required for doing this?
A: <xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
This is referred to as the "identity transformation" in the XSLT specification.
A: I ran in that problem and the copy-of is certainly the easiest to use. The identity works, but that's 5 lines of code and you'd need to call such a template, not just define it as is in your XSLT document (otherwise you probably won't get what you expected in your output.)
My main problem actually was to copy the content of a tag, and not the tag itself. It's actually very easy to resolve but it took me a little time to figure it out (maybe because QtXmlPatterns crashes quite a bit!)
So, the following copies the tag named here and all of its children:
<xsl:copy-of select="this/tag/here"/>
But most often you do not want to do that because <here> is actually the container, in other words, it should not appear in the output. In that case you can simply do this:
<xsl:copy-of select="this/tag/here/*"/>
This copies all the children found in the tag named <here>.
A: Assuming your xhtml is in an element YYY
http://www.dpawson.co.uk/xsl/sect2/N1930.html explains options
A: xsl:copy-of
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Looking for an HQL builder (Hibernate Query Language) I'm looking for a builder for HQL in Java. I want to get rid of things like:
StringBuilder builder = new StringBuilder()
.append("select stock from ")
.append( Stock.class.getName() )
.append( " as stock where stock.id = ")
.append( id );
I'd rather have something like:
HqlBuilder builder = new HqlBuilder()
.select( "stock" )
.from( Stock.class.getName() ).as( "stock" )
.where( "stock.id" ).equals( id );
I googled a bit, and I couldn't find one.
I wrote a quick & dumb HqlBuilder that suits my needs for now, but I'd love to find one that has more users and tests than me alone.
Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:
select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id
ie. select all stocks whose property someValue points to any bonus from the Bonus table.
Thanks!
A: For a type-safe approach to your problem, consider Querydsl.
The example query becomes
HQLQuery query = new HibernateQuery(session);
List<Stock> s = query.from(stock, bonus)
.where(stock.someValue.eq(bonus.id))
.list(stock);
Querydsl uses APT for code generation like JPA2 and supports JPA/Hibernate, JDO, SQL and Java collections.
I am the maintainer of Querydsl, so this answer is biased.
A: Doesn't the Criteria API do it for you? It looks almost exactly like what you're asking for.
A: @Sébastien Rocca-Serra
Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a DetachedCriteria for the bonus table, then use the IN operator for someValue.
DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class);
List stocks = session.createCriteria(Stock.class)
.add(Property.forName("someValue").in(bonuses)).list();
This is equivalent to
select stock
from com.something.Stock as stock
where stock.someValue in (select bonus.id from com.something.Bonus as bonus)
The only downside would be if you have references to different tables in someValue and your ID's are not unique across all tables. But your query would suffer from the same flaw.
A: For another type-safe query dsl, I recommend http://www.torpedoquery.org. The library is still young but it provides type safety by directly using your entity's classes. This means early compiler errors when the query no longer applies before of refactoring or redesign.
I also provided you with an example. I think from your posts that you where trying to do a subquery restriction, so I based the exemple on that:
import static org.torpedoquery.jpa.Torpedo.*;
Bonus bonus = from(Bonus.class);
Query subQuery = select(bonus.getId());
Stock stock = from(Stock.class);
where(stock.getSomeValue()).in(subQuery);
List<Stock> stocks = select(stock).list(entityManager);
A: It looks like you want to use the Criteria query API built into Hibernate. To do your above query it would look like this:
List<Stock> stocks = session.createCriteria(Stock.class)
.add(Property.forName("id").eq(id))
.list();
If you don't have access to the Hibernate Session yet, you can used 'DetachedCriteria' like so:
DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)
.add(Property.forName("id").eq(id));
If you wanted to get all Stock that have a Bonus with a specific ID you could do the following:
DetachedCriteria criteria = DetachedCriteria.forClass(Stock.class)
.createCriteria("Stock")
.add(Property.forName("id").eq(id)));
For more infromation check out Criteria Queries from the Hibernate docs
A: @Sébastien Rocca-Serra
select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.bonus.id = bonus.id
That's just a join. Hibernate does it automatically, if and only if you've got the mapping between Stock and Bonus setup and if bonus is a property of Stock. Criteria.list() will return Stock objects and you just call stock.getBonus().
Note, if you want to do anything like
select stock
from com.something.Stock as stock
where stock.bonus.value > 1000000
You need to use Criteria.createAlias(). It'd be something like
session.createCriteria(Stock.class).createAlias("bonus", "b")
.add(Restrictions.gt("b.value", 1000000)).list()
A: Criteria API does not provide all functionality avaiable in HQL. For example, you cannot do more than one join over the same column.
Why don't you use NAMED QUERIES? The look much more clean:
Person person = session.getNamedQuery("Person.findByName")
.setString(0, "Marcio")
.list();
A: I wrote a GPL'd solution for OMERO which you could easily build suited to your situation.
*
*Source: QueryBuilder.java
*Test: QueryBuilderMockTest
Usage:
QueryBuilder qb = new QueryBuilder();
qb.select("img");
qb.from("Image", "img");
qb.join("img.pixels", "pix", true, false);
// Can't join anymore after this
qb.where(); // First
qb.append("(");
qb.and("pt.details.creationTime > :time");
qb.param("time", new Date());
qb.append(")");
qb.and("img.id in (:ids)");
qb.paramList("ids", new HashSet());
qb.order("img.id", true);
qb.order("this.details.creationEvent.time", false);
It functions as a state machine "select->from->join->where->order", etc. and keeps up with optional parameters. There were several queries which the Criteria API could not perform (see HHH-879), so in the end it was simpler to write this small class to wrap StringBuilder. (Note: there is a ticket HHH-2407 describing a Hibernate branch which should unify the two. After that, it would probably make sense to re-visit the Criteria API)
A: Take a look at the search package available from the hibernate-generic-dao project. This is a pretty decent HQL Builder implementation.
A: I know this thread is pretty old, but I also was looking for a HqlBuilder And I found this "screensaver" project
It is NOT a Windows screensaver, it's a
"Lab Information Management System (LIMS) for high-throughput screening (HTS) facilities that perform small molecule and RNAi screens."
It contains an HQLBuilder that is looking quite good.
Here is a sample list of available methods:
...
HqlBuilder select(String alias);
HqlBuilder select(String alias, String property);
HqlBuilder from(Class<?> entityClass, String alias);
HqlBuilder fromFetch(String joinAlias, String joinRelationship, String alias);
HqlBuilder where(String alias, String property, Operator operator, Object value);
HqlBuilder where(String alias, Operator operator, Object value);
HqlBuilder where(String alias1, Operator operator, String alias2);
HqlBuilder whereIn(String alias, String property, Set<?> values);
HqlBuilder whereIn(String alias, Set<?> values);
HqlBuilder where(Clause clause);
HqlBuilder orderBy(String alias, String property);
HqlBuilder orderBy(String alias, SortDirection sortDirection);
HqlBuilder orderBy(String alias, String property, SortDirection sortDirection);
String toHql();
...
A: Now are also available the standard JPA Type Safe query and an less standard but also good Object Query
Examples:
JPA Type Safe
EntityManager em = ...
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Stock> c = qb.createQuery(Stock.class);
Root<Stock> = c.from(Stock.class);
Predicate condition = qb.eq(p.get(Stock_.id), id);
c.where(condition);
TypedQuery<Stock> q = em.createQuery(c);
List<Stock> result = q.getResultList();
Object Query
EntityManager em = ...
ObjectQuery<Stock> query = new GenericObjectQuery<Stock>(Stock.class);
Stock toSearch = query.target();
query.eq(toSearch.getId(),id);
List<Stock> res = (List<Stock>)JPAObjectQuery.execute(query, em);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I make a UIDatePicker display specific dates? My application has a need to let the user choose a date from a list of dates conforming to a certain pattern. For instance, they may need to choose a monday from a list Monday's for a month. Is there a way to get a UIDatePicker to limit date choices to a certain subset or should I just use a UIPickerView?
A: You cannot limit which dates are selectable in a UIDatePicker. You could change the date when the value changed event is sent, but since the user cannot tell which dates are "good" and which are not, it's a bad UI choice to do so.
Use a UIPickerView of your own making instead.
A: UIDatePicker has minimumDate and maximumDate properties for this purpose. No need to use UIPickerView just for this reason.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it possible to display a modal window in SCSF application at the center of the screen In SCSF application I would like to display a view as a modal window at the center of the screen. Is it possible to do that?
WindowSmartPartInfo doesn't have any option for setting screen postion.
Thanks.
A: Assuming you're talking about Winforms, not WPF since the WPF layer for CAB does expose this option. In winforms there is no option in the WindowSmartPartInfo to do this. However, you could extend it and extend WindowWorkspace to use your new SmartPartInfo (override the OnApplySmartPartInfo method).
Before you do this, you might want to check the contrib and community sites to see if anyone has already done it. I think I've seen one somewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is an example of the Liskov Substitution Principle? I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?
A: This principle was introduced by Barbara Liskov in 1987 and extends the Open-Closed Principle by focusing on the behavior of a superclass and its subtypes.
Its importance becomes obvious when we consider the consequences of violating it. Consider an application that uses the following class.
public class Rectangle
{
private double width;
private double height;
public double Width
{
get
{
return width;
}
set
{
width = value;
}
}
public double Height
{
get
{
return height;
}
set
{
height = value;
}
}
}
Imagine that one day, the client demands the ability to manipulate squares in addition to rectangles. Since a square is a rectangle, the square class should be derived from the Rectangle class.
public class Square : Rectangle
{
}
However, by doing that we will encounter two problems:
A square does not need both height and width variables inherited from the rectangle and this could create a significant waste in memory if we have to create hundreds of thousands of square objects.
The width and height setter properties inherited from the rectangle are inappropriate for a square since the width and height of a square are identical.
In order to set both height and width to the same value, we can create two new properties as follows:
public class Square : Rectangle
{
public double SetWidth
{
set
{
base.Width = value;
base.Height = value;
}
}
public double SetHeight
{
set
{
base.Height = value;
base.Width = value;
}
}
}
Now, when someone will set the width of a square object, its height will change accordingly and vice-versa.
Square s = new Square();
s.SetWidth(1); // Sets width and height to 1.
s.SetHeight(2); // sets width and height to 2.
Let's move forward and consider this other function:
public void A(Rectangle r)
{
r.SetWidth(32); // calls Rectangle.SetWidth
}
If we pass a reference to a square object into this function, we would violate the LSP because the function does not work for derivatives of its arguments. The properties width and height aren't polymorphic because they aren't declared virtual in rectangle (the square object will be corrupted because the height won't be changed).
However, by declaring the setter properties to be virtual we will face another violation, the OCP. In fact, the creation of a derived class square is causing changes to the base class rectangle.
A: Robert Martin has an excellent paper on the Liskov Substitution Principle. It discusses subtle and not-so-subtle ways in which the principle may be violated.
Some relevant parts of the paper (note that the second example is heavily condensed):
A Simple Example of a Violation of LSP
One of the most glaring violations of this principle is the use of C++
Run-Time Type Information (RTTI) to select a function based upon the
type of an object. i.e.:
void DrawShape(const Shape& s)
{
if (typeid(s) == typeid(Square))
DrawSquare(static_cast<Square&>(s));
else if (typeid(s) == typeid(Circle))
DrawCircle(static_cast<Circle&>(s));
}
Clearly the DrawShape function is badly formed. It must know about
every possible derivative of the Shape class, and it must be changed
whenever new derivatives of Shape are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.
Square and Rectangle, a More Subtle Violation.
However, there are other, far more subtle, ways of violating the LSP.
Consider an application which uses the Rectangle class as described
below:
class Rectangle
{
public:
void SetWidth(double w) {itsWidth=w;}
void SetHeight(double h) {itsHeight=w;}
double GetHeight() const {return itsHeight;}
double GetWidth() const {return itsWidth;}
private:
double itsWidth;
double itsHeight;
};
[...] Imagine that one day the users demand the ability to manipulate
squares in addition to rectangles. [...]
Clearly, a square is a rectangle for all normal intents and purposes.
Since the ISA relationship holds, it is logical to model the Square
class as being derived from Rectangle. [...]
Square will inherit the SetWidth and SetHeight functions. These
functions are utterly inappropriate for a Square, since the width and
height of a square are identical. This should be a significant clue
that there is a problem with the design. However, there is a way to
sidestep the problem. We could override SetWidth and SetHeight [...]
But consider the following function:
void f(Rectangle& r)
{
r.SetWidth(32); // calls Rectangle::SetWidth
}
If we pass a reference to a Square object into this function, the
Square object will be corrupted because the height won’t be changed.
This is a clear violation of LSP. The function does not work for
derivatives of its arguments.
[...]
A: Some addendum: I wonder why didn't anybody write about the Invariant , preconditions and post conditions of the base class that must be obeyed by the derived classes.
For a derived class D to be completely sustitutable by the Base class B, class D must obey certain conditions:
*
*In-variants of base class must be preserved by the derived class
*Pre-conditions of the base class must not be strengthened by the derived class
*Post-conditions of the base class must not be weakened by the derived class.
So the derived must be aware of the above three conditions imposed by the base class. Hence, the rules of subtyping are pre-decided. Which means, 'IS A' relationship shall be obeyed only when certain rules are obeyed by the subtype. These rules, in the form of invariants, precoditions and postcondition, should be decided by a formal 'design contract'.
Further discussions on this available at my blog: Liskov Substitution principle
A: It states that if C is a subtype of E then E can be replaced with objects of type C without changing or breaking the behavior of the program. In simple words, derived classes should be substitutable for their parent classes. For example, if a Farmer’s son is Farmer then he can work in place of his father but if a Farmer’s son is a cricketer then he can’t work in place of his father.
Violation Example:
public class Plane{
public void startEngine(){}
}
public class FighterJet extends Plane{}
public class PaperPlane extends Plane{}
In the given example FighterPlane and PaperPlane classes both extending the Plane class which contain startEngine() method. So it's clear that FighterPlane can start engine but PaperPlane can’t so it’s breaking LSP.
PaperPlane class although extending Plane class and should be substitutable in place of it but is not an eligible entity that Plane’s instance could be replaced by, because a paper plane can’t start the engine as it doesn’t have one. So the good example would be,
Respected Example:
public class Plane{
}
public class RealPlane{
public void startEngine(){}
}
public class FighterJet extends RealPlane{}
public class PaperPlane extends Plane{}
A: The Liskov Substitution Principle (LSP, lsp) is a concept in Object Oriented Programming that states:
Functions that use pointers or
references to base classes must be
able to use objects of derived classes
without knowing it.
At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.
The most effective way I have seen to illustrate this point was in Head First OOA&D. They present a scenario where you are a developer on a project to build a framework for strategy games.
They present a class that represents a board that looks like this:
All of the methods take X and Y coordinates as parameters to locate the tile position in the two-dimensional array of Tiles. This will allow a game developer to manage units in the board during the course of the game.
The book goes on to change the requirements to say that the game frame work must also support 3D game boards to accommodate games that have flight. So a ThreeDBoard class is introduced that extends Board.
At first glance this seems like a good decision. Board provides both the Height and Width properties and ThreeDBoard provides the Z axis.
Where it breaks down is when you look at all the other members inherited from Board. The methods for AddUnit, GetTile, GetUnits and so on, all take both X and Y parameters in the Board class but the ThreeDBoard needs a Z parameter as well.
So you must implement those methods again with a Z parameter. The Z parameter has no context to the Board class and the inherited methods from the Board class lose their meaning. A unit of code attempting to use the ThreeDBoard class as its base class Board would be very out of luck.
Maybe we should find another approach. Instead of extending Board, ThreeDBoard should be composed of Board objects. One Board object per unit of the Z axis.
This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP.
A: A square is a rectangle where the width equals the height. If the square sets two different sizes for the width and height it violates the square invariant. This is worked around by introducing side effects. But if the rectangle had a setSize(height, width) with precondition 0 < height and 0 < width. The derived subtype method requires height == width; a stronger precondition (and that violates lsp). This shows that though square is a rectangle it is not a valid subtype because the precondition is strengthened. The work around (in general a bad thing) cause a side effect and this weakens the post condition (which violates lsp). setWidth on the base has post condition 0 < width. The derived weakens it with height == width.
Therefore a resizable square is not a resizable rectangle.
A: The big picture :
*
*What is Liskov Substitution Principle about ? It's about what is (and what is not) a subtype of a given type.
*Why is it so important ? Because there is a difference between a subtype and a subclass.
Example
Unlike the other answers, I won't start with a Liskov Substitution Principle (LSP) violation, but with a LSP compliance. I use Java but it would be almost the same in every OOP language.
Circle and ColoredCircle
Geometrical examples seem pretty popular here.
class Circle {
private int radius;
public Circle(int radius) {
if (radius < 0) {
throw new RuntimeException("Radius should be >= 0");
}
this.radius = radius;
}
public int getRadius() {
return this.radius;
}
}
The radius is not allowed to be negative. Here's a suclass:
class ColoredCircle extends Circle {
private Color color; // defined elsewhere
public ColoredCircle(int radius, Color color) {
super(radius);
this.color = color;
}
public Color getColor() {
return this.color;
}
}
This subclass is a subtype of Circle, according to the LSP.
The LSP states that:
If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T. (Barbara Liskov, "Data Abstraction and Hierarchy", SIGPLAN Notices, 23,5 (May, 1988))
Here, for each ColoredCircle instance o1, consider the Circle instance having the same radius o2. For every program using Circle objects, if you replace o2 by o1, the behavior of any program using Circle will remain the same after the substitution. (Note that this is theoretical : you will exhaust the memory faster using ColoredCircle instances than using Circle instances, but that's not relevant here.)
How do we find the o2 depending on o1 ? We just strip the color attribute and keep the radius attribute. I call the transformation o1 -> o2 a projection from the CircleColor space on the Circle space.
Counter Example
Let's create another example to illustrate the violation of the LSP.
Circle and Square
Imagine this subclass of the previous Circle class:
class Square extends Circle {
private int sideSize;
public Square(int sideSize) {
super(0);
this.sideSize = sideSize;
}
@Override
public int getRadius() {
return -1; // I'm a square, I don't care
}
public int getSideSize() {
return this.sideSize;
}
}
The violation of the LSP
Now, look at this program :
public class Liskov {
public static void program(Circle c) {
System.out.println("The radius is "+c.getRadius());
}
We test the program with a Circle object and with a Square object.
public static void main(String [] args){
Liskov.program(new Circle(2)); // prints "The radius is 2"
Liskov.program(new Square(2)); // prints "The radius is -1"
}
}
What happened ? Intuitively, although Square is a subclass of Circle, Square is not a subtype of Circle because no regular Circle instance would ever have a radius of -1.
Formally, this is a violation of Liskov Substitution Principle.
We have a program defined in terms of Circle and there is no Circle object that can replace new Square(2) (or any Square instance by the way) in this program and leave the behavior unchanged: remember that radius of any Circle is always positive.
Subclass and subtype
Now we know why a subclass is not always subtype. When a subclass is not a subtype, i.e. when there is a LSP violation, the behavior of some programs (at least one) won't always be the expected behavior. This is very frustrating and is usually interpreted as a bug.
In an ideal world, the compiler or interpreter would be able to check is a given subclass is a real subtype, but we are not in an ideal world.
Static typing
If there is some static typing, you are bound by the superclass signature at compile time. Square.getRadius() can't return a String or a List.
If there is no static typing, you'll get an error at runtime if the type of one argument is wrong (unless the typing is weak) or the number of arguments is inconsistent (unless the language is very permissive).
Note about the static typing: there is a mechanism of covariance of the return type (a method of S can return a subclass of the return type of the same method of T) and contravariance of the parameters types (a method of S can accept a superclass of a parameter of the same parameter of the same method of T). That is a specific case of precondition and postcondition explained below.
Design by contract
There's more. Some languages (I think of Eiffel) provide a mechanism to enforce the compliance with the LSP.
Let alone the determination the projection o2 of the initial object o1, we can expect the same behavior of any program if o1 is substituted for o2 if, for any argument x and any method f:
*
*if o2.f(x) is a valid call, then o1.f(x) should also be a valid call (1).
*the result (return value, display on console, etc.) of o1.f(x) should be equal to the result of o2.f(x), or at least equally valid (2).
*o1.f(x) should let o1 in an internal state and o2.f(x) should let o2 in an internal state so that next function calls will ensure that (1), (2) and (3) will still be valid (3).
(Note that (3) is given for free if the function f is pure. That's why we like to have immutable objects.)
These conditions are about the semantics (what to expect) of the class, not only the syntax of the class. Also, these conditions are very strong. But they can be approximated by assertions in design by contract programming. These assertions are a way to ensure that the semantic of the type is upheld. Breaking the contract leads to runtime errors.
*
*The precondition defines what is a valid call. When subclassing a class, the precondition may only be weakened (S.f accepts more than T.f) (a).
*The postcondition defines what is a valid result. When subclassing a class, the postcondition may only be strengthened (S.f provides more than T.f) (b).
*The invariant defines what is a valid internal state. When subclassing a class, the invariant must remain the same (c).
We see that, roughly, (a) ensures (1) and (b) ensures (2), but (c) is weaker than (3). Moreover, assertions are sometimes difficult to express.
Think of a class Counter having a unique method Counter.counter() that returns the next integer. How do you write a postcondition for that ? Think of a class Random having a method Random.gaussian() that returns a float between 0.0 and 1.0 . How do you write a postcondition to check that the distribution is gaussian ? It may be possible, but the cost would be so high that we would rely on test rather than on postconditions.
Conclusion
Unfortunately, a subclass is not always a subtype. This can lead to an unexpected behavior -- a bug.
OOP languages provide mechanism to avoid this situation. At syntactic level first. At semantical level too, depending on the programming language: a part of the semantics can be encoded in the text of the program using assertions. But it's up to you to ensure that a subclass is a subtype.
Remember when you began to learn OOP ? "If the relation is IS-A, then use inheritance". That's true the other way: if you use inheritance, be sure that the relation is IS-A.
The LSP defines, at a higher level than assertions, what is a subtype. Assertions are a valuable tool to ensure that the LSP is upheld.
A:
Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S
Let's do a simple example in Java:
Bad example
public class Bird{
public void fly(){}
}
public class Duck extends Bird{}
The duck can fly because it is a bird, but what about this:
public class Ostrich extends Bird{}
Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.
Good example
public class Bird{}
public class FlyingBirds extends Bird{
public void fly(){}
}
public class Duck extends FlyingBirds{}
public class Ostrich extends Bird{}
A: There is a checklist to determine whether or not you are violating Liskov.
*
*If you violate one of the following items -> you violate Liskov.
*If you don't violate any -> can't conclude anything.
Check list:
*
*No new exceptions should be thrown in derived class: If your base class threw ArgumentNullException then your sub classes were only allowed to throw exceptions of type ArgumentNullException or any exceptions derived from ArgumentNullException. Throwing IndexOutOfRangeException is a violation of Liskov.
*Pre-conditions cannot be strengthened: Assume your base class works with a member int. Now your sub-type requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.
*Post-conditions cannot be weakened: Assume your base class required all connections to the database should be closed before the method returned. In your sub-class you overrode that method and left the connection open for further reuse. You have weakened the post-conditions of that method.
*Invariants must be preserved: The most difficult and painful constraint to fulfill. Invariants are sometimes hidden in the base class and the only way to reveal them is to read the code of the base class. Basically you have to be sure when you override a method anything unchangeable must remain unchanged after your overridden method is executed. The best thing I can think of is to enforce these invariant constraints in the base class but that would not be easy.
*History Constraint: When overriding a method you are not allowed to modify an unmodifiable property in the base class. Take a look at these code and you can see Name is defined to be unmodifiable (private set) but SubType introduces new method that allows modifying it (through reflection):
public class SuperType
{
public string Name { get; private set; }
public SuperType(string name, int age)
{
Name = name;
Age = age;
}
}
public class SubType : SuperType
{
public void ChangeName(string newName)
{
var propertyType = base.GetType().GetProperty("Name").SetValue(this, newName);
}
}
There are 2 others items: Contravariance of method arguments and Covariance of return types. But it is not possible in C# (I'm a C# developer) so I don't care about them.
A: I see rectangles and squares in every answer, and how to violate the LSP.
I'd like to show how the LSP can be conformed to with a real-world example :
<?php
interface Database
{
public function selectQuery(string $sql): array;
}
class SQLiteDatabase implements Database
{
public function selectQuery(string $sql): array
{
// sqlite specific code
return $result;
}
}
class MySQLDatabase implements Database
{
public function selectQuery(string $sql): array
{
// mysql specific code
return $result;
}
}
This design conforms to the LSP because the behaviour remains unchanged regardless of the implementation we choose to use.
And yes, you can violate LSP in this configuration doing one simple change like so :
<?php
interface Database
{
public function selectQuery(string $sql): array;
}
class SQLiteDatabase implements Database
{
public function selectQuery(string $sql): array
{
// sqlite specific code
return $result;
}
}
class MySQLDatabase implements Database
{
public function selectQuery(string $sql): array
{
// mysql specific code
return ['result' => $result]; // This violates LSP !
}
}
Now the subtypes cannot be used the same way since they don't produce the same result anymore.
A: LSP is necessary where some code thinks it is calling the methods of a type T, and may unknowingly call the methods of a type S, where S extends T (i.e. S inherits, derives from, or is a subtype of, the supertype T).
For example, this occurs where a function with an input parameter of type T, is called (i.e. invoked) with an argument value of type S. Or, where an identifier of type T, is assigned a value of type S.
val id : T = new S() // id thinks it's a T, but is a S
LSP requires the expectations (i.e. invariants) for methods of type T (e.g. Rectangle), not be violated when the methods of type S (e.g. Square) are called instead.
val rect : Rectangle = new Square(5) // thinks it's a Rectangle, but is a Square
val rect2 : Rectangle = rect.setWidth(10) // height is 10, LSP violation
Even a type with immutable fields still has invariants, e.g. the immutable Rectangle setters expect dimensions to be independently modified, but the immutable Square setters violate this expectation.
class Rectangle( val width : Int, val height : Int )
{
def setWidth( w : Int ) = new Rectangle(w, height)
def setHeight( h : Int ) = new Rectangle(width, h)
}
class Square( val side : Int ) extends Rectangle(side, side)
{
override def setWidth( s : Int ) = new Square(s)
override def setHeight( s : Int ) = new Square(s)
}
LSP requires that each method of the subtype S must have contravariant input parameter(s) and a covariant output.
Contravariant means the variance is contrary to the direction of the inheritance, i.e. the type Si, of each input parameter of each method of the subtype S, must be the same or a supertype of the type Ti of the corresponding input parameter of the corresponding method of the supertype T.
Covariance means the variance is in the same direction of the inheritance, i.e. the type So, of the output of each method of the subtype S, must be the same or a subtype of the type To of the corresponding output of the corresponding method of the supertype T.
This is because if the caller thinks it has a type T, thinks it is calling a method of T, then it supplies argument(s) of type Ti and assigns the output to the type To. When it is actually calling the corresponding method of S, then each Ti input argument is assigned to a Si input parameter, and the So output is assigned to the type To. Thus if Si were not contravariant w.r.t. to Ti, then a subtype Xi—which would not be a subtype of Si—could be assigned to Ti.
Additionally, for languages (e.g. Scala or Ceylon) which have definition-site variance annotations on type polymorphism parameters (i.e. generics), the co- or contra- direction of the variance annotation for each type parameter of the type T must be opposite or same direction respectively to every input parameter or output (of every method of T) that has the type of the type parameter.
Additionally, for each input parameter or output that has a function type, the variance direction required is reversed. This rule is applied recursively.
Subtyping is appropriate where the invariants can be enumerated.
There is much ongoing research on how to model invariants, so that they are enforced by the compiler.
Typestate (see page 3) declares and enforces state invariants orthogonal to type. Alternatively, invariants can be enforced by converting assertions to types. For example, to assert that a file is open before closing it, then File.open() could return an OpenFile type, which contains a close() method that is not available in File. A tic-tac-toe API can be another example of employing typing to enforce invariants at compile-time. The type system may even be Turing-complete, e.g. Scala. Dependently-typed languages and theorem provers formalize the models of higher-order typing.
Because of the need for semantics to abstract over extension, I expect that employing typing to model invariants, i.e. unified higher-order denotational semantics, is superior to the Typestate. ‘Extension’ means the unbounded, permuted composition of uncoordinated, modular development. Because it seems to me to be the antithesis of unification and thus degrees-of-freedom, to have two mutually-dependent models (e.g. types and Typestate) for expressing the shared semantics, which can't be unified with each other for extensible composition. For example, Expression Problem-like extension was unified in the subtyping, function overloading, and parametric typing domains.
My theoretical position is that for knowledge to exist (see section “Centralization is blind and unfit”), there will never be a general model that can enforce 100% coverage of all possible invariants in a Turing-complete computer language. For knowledge to exist, unexpected possibilities much exist, i.e. disorder and entropy must always be increasing. This is the entropic force. To prove all possible computations of a potential extension, is to compute a priori all possible extension.
This is why the Halting Theorem exists, i.e. it is undecidable whether every possible program in a Turing-complete programming language terminates. It can be proven that some specific program terminates (one which all possibilities have been defined and computed). But it is impossible to prove that all possible extension of that program terminates, unless the possibilities for extension of that program is not Turing complete (e.g. via dependent-typing). Since the fundamental requirement for Turing-completeness is unbounded recursion, it is intuitive to understand how Gödel's incompleteness theorems and Russell's paradox apply to extension.
An interpretation of these theorems incorporates them in a generalized conceptual understanding of the entropic force:
*
*Gödel's incompleteness theorems: any formal theory, in which all arithmetic truths can be proved, is inconsistent.
*Russell's paradox: every membership rule for a set that can contain a set, either enumerates the specific type of each member or contains itself. Thus sets either cannot be extended or they are unbounded recursion. For example, the set of everything that is not a teapot, includes itself, which includes itself, which includes itself, etc…. Thus a rule is inconsistent if it (may contain a set and) does not enumerate the specific types (i.e. allows all unspecified types) and does not allow unbounded extension. This is the set of sets that are not members of themselves. This inability to be both consistent and completely enumerated over all possible extension, is Gödel's incompleteness theorems.
*Liskov Substition Principle: generally it is an undecidable problem whether any set is the subset of another, i.e. inheritance is generally undecidable.
*Linsky Referencing: it is undecidable what the computation of something is, when it is described or perceived, i.e. perception (reality) has no absolute point of reference.
*Coase's theorem: there is no external reference point, thus any barrier to unbounded external possibilities will fail.
*Second law of thermodynamics: the entire universe (a closed system, i.e. everything) trends to maximum disorder, i.e. maximum independent possibilities.
A: Would implementing ThreeDBoard in terms of an array of Board be that useful?
Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.
In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).
A: The clearest explanation for LSP I found so far has been "The Liskov Substitution Principle says that the object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class" from here. The article gives code example for violating LSP and fixing it.
A: Long story short, let's leave rectangles rectangles and squares squares, practical example when extending a parent class, you have to either PRESERVE the exact parent API or to EXTEND IT.
Let's say you have a base ItemsRepository.
class ItemsRepository
{
/**
* @return int Returns number of deleted rows
*/
public function delete()
{
// perform a delete query
$numberOfDeletedRows = 10;
return $numberOfDeletedRows;
}
}
And a sub class extending it:
class BadlyExtendedItemsRepository extends ItemsRepository
{
/**
* @return void Was suppose to return an INT like parent, but did not, breaks LSP
*/
public function delete()
{
// perform a delete query
$numberOfDeletedRows = 10;
// we broke the behaviour of the parent class
return;
}
}
Then you could have a Client working with the Base ItemsRepository API and relying on it.
/**
* Class ItemsService is a client for public ItemsRepository "API" (the public delete method).
*
* Technically, I am able to pass into a constructor a sub-class of the ItemsRepository
* but if the sub-class won't abide the base class API, the client will get broken.
*/
class ItemsService
{
/**
* @var ItemsRepository
*/
private $itemsRepository;
/**
* @param ItemsRepository $itemsRepository
*/
public function __construct(ItemsRepository $itemsRepository)
{
$this->itemsRepository = $itemsRepository;
}
/**
* !!! Notice how this is suppose to return an int. My clients expect it based on the
* ItemsRepository API in the constructor !!!
*
* @return int
*/
public function delete()
{
return $this->itemsRepository->delete();
}
}
The LSP is broken when substituting parent class with a sub class breaks the API's contract.
class ItemsController
{
/**
* Valid delete action when using the base class.
*/
public function validDeleteAction()
{
$itemsService = new ItemsService(new ItemsRepository());
$numberOfDeletedItems = $itemsService->delete();
// $numberOfDeletedItems is an INT :)
}
/**
* Invalid delete action when using a subclass.
*/
public function brokenDeleteAction()
{
$itemsService = new ItemsService(new BadlyExtendedItemsRepository());
$numberOfDeletedItems = $itemsService->delete();
// $numberOfDeletedItems is a NULL :(
}
}
You can learn more about writing maintainable software in my course: https://www.udemy.com/enterprise-php/
A: Let's say we use a rectangle in our code
r = new Rectangle();
// ...
r.setDimensions(1,2);
r.fill(colors.red());
canvas.draw(r);
In our geometry class we learned that a square is a special type of rectangle because its width is the same length as its height. Let's make a Square class as well based on this info:
class Square extends Rectangle {
setDimensions(width, height){
assert(width == height);
super.setDimensions(width, height);
}
}
If we replace the Rectangle with Square in our first code, then it will break:
r = new Square();
// ...
r.setDimensions(1,2); // assertion width == height failed
r.fill(colors.red());
canvas.draw(r);
This is because the Square has a new precondition we did not have in the Rectangle class: width == height. According to LSP the Rectangle instances should be substitutable with Rectangle subclass instances. This is because these instances pass the type check for Rectangle instances and so they will cause unexpected errors in your code.
This was an example for the "preconditions cannot be strengthened in a subtype" part in the wiki article. So to sum up, violating LSP will probably cause errors in your code at some point.
A: LSP says that ''Objects should be replaceable by their subtypes''.
On the other hand, this principle points to
Child classes should never break the parent class`s type definitions.
and the following example helps to have a better understanding of LSP.
Without LSP:
public interface CustomerLayout{
public void render();
}
public FreeCustomer implements CustomerLayout {
...
@Override
public void render(){
//code
}
}
public PremiumCustomer implements CustomerLayout{
...
@Override
public void render(){
if(!hasSeenAd)
return; //it isn`t rendered in this case
//code
}
}
public void renderView(CustomerLayout layout){
layout.render();
}
Fixing by LSP:
public interface CustomerLayout{
public void render();
}
public FreeCustomer implements CustomerLayout {
...
@Override
public void render(){
//code
}
}
public PremiumCustomer implements CustomerLayout{
...
@Override
public void render(){
if(!hasSeenAd)
showAd();//it has a specific behavior based on its requirement
//code
}
}
public void renderView(CustomerLayout layout){
layout.render();
}
A: Let’s illustrate in Java:
class TrasportationDevice
{
String name;
String getName() { ... }
void setName(String n) { ... }
double speed;
double getSpeed() { ... }
void setSpeed(double d) { ... }
Engine engine;
Engine getEngine() { ... }
void setEngine(Engine e) { ... }
void startEngine() { ... }
}
class Car extends TransportationDevice
{
@Override
void startEngine() { ... }
}
There is no problem here, right? A car is definitely a transportation device, and here we can see that it overrides the startEngine() method of its superclass.
Let’s add another transportation device:
class Bicycle extends TransportationDevice
{
@Override
void startEngine() /*problem!*/
}
Everything isn’t going as planned now! Yes, a bicycle is a transportation device, however, it does not have an engine and hence, the method startEngine() cannot be implemented.
These are the kinds of problems that violation of Liskov Substitution
Principle leads to, and they can most usually be recognized by a
method that does nothing, or even can’t be implemented.
The solution to these problems is a correct inheritance hierarchy, and in our case we would solve the problem by differentiating classes of transportation devices with and without engines. Even though a bicycle is a transportation device, it doesn’t have an engine. In this example our definition of transportation device is wrong. It should not have an engine.
We can refactor our TransportationDevice class as follows:
class TrasportationDevice
{
String name;
String getName() { ... }
void setName(String n) { ... }
double speed;
double getSpeed() { ... }
void setSpeed(double d) { ... }
}
Now we can extend TransportationDevice for non-motorized devices.
class DevicesWithoutEngines extends TransportationDevice
{
void startMoving() { ... }
}
And extend TransportationDevice for motorized devices. Here is is more appropriate to add the Engine object.
class DevicesWithEngines extends TransportationDevice
{
Engine engine;
Engine getEngine() { ... }
void setEngine(Engine e) { ... }
void startEngine() { ... }
}
Thus our Car class becomes more specialized, while adhering to the Liskov Substitution Principle.
class Car extends DevicesWithEngines
{
@Override
void startEngine() { ... }
}
And our Bicycle class is also in compliance with the Liskov Substitution Principle.
class Bicycle extends DevicesWithoutEngines
{
@Override
void startMoving() { ... }
}
A: The LSP is a rule about the contract of the clases: if a base class satisfies a contract, then by the LSP derived classes must also satisfy that contract.
In Pseudo-python
class Base:
def Foo(self, arg):
# *... do stuff*
class Derived(Base):
def Foo(self, arg):
# *... do stuff*
satisfies LSP if every time you call Foo on a Derived object, it gives exactly the same results as calling Foo on a Base object, as long as arg is the same.
A: I guess everyone kind of covered what LSP is technically: You basically want to be able to abstract away from subtype details and use supertypes safely.
So Liskov has 3 underlying rules:
*
*Signature Rule : There should be a valid implementation of every operation of the supertype in the subtype syntactically. Something a compiler will be able to check for you. There is a little rule about throwing fewer exceptions and being at least as accessible as the supertype methods.
*Methods Rule: The implementation of those operations is semantically sound.
*
*Weaker Preconditions : The subtype functions should take at least what the supertype took as input, if not more.
*Stronger Postconditions: They should produce a subset of the output the supertype methods produced.
*Properties Rule : This goes beyond individual function calls.
*
*Invariants : Things that are always true must remain true. Eg. a Set's size is never negative.
*Evolutionary Properties : Usually something to do with immutability or the kind of states the object can be in. Or maybe the object only grows and never shrinks so the subtype methods shouldn't make it.
All these properties need to be preserved and the extra subtype functionality shouldn't violate supertype properties.
If these three things are taken care of , you have abstracted away from the underlying stuff and you are writing loosely coupled code.
Source: Program Development in Java - Barbara Liskov
A: An important example of the use of LSP is in software testing.
If I have a class A that is an LSP-compliant subclass of B, then I can reuse the test suite of B to test A.
To fully test subclass A, I probably need to add a few more test cases, but at the minimum I can reuse all of superclass B's test cases.
A way to realize is this by building what McGregor calls a "Parallel hierarchy for testing": My ATest class will inherit from BTest. Some form of injection is then needed to ensure the test case works with objects of type A rather than of type B (a simple template method pattern will do).
Note that reusing the super-test suite for all subclass implementations is in fact a way to test that these subclass implementations are LSP-compliant. Thus, one can also argue that one should run the superclass test suite in the context of any subclass.
See also the answer to the Stackoverflow question "Can I implement a series of reusable tests to test an interface's implementation?"
A:
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
When I first read about LSP, I assumed that this was meant in a very strict sense, essentially equating it to interface implementation and type-safe casting. Which would mean that LSP is either ensured or not by the language itself. For example, in this strict sense, ThreeDBoard is certainly substitutable for Board, as far as the compiler is concerned.
After reading up more on the concept though I found that LSP is generally interpreted more broadly than that.
In short, what it means for client code to "know" that the object behind the pointer is of a derived type rather than the pointer type is not restricted to type-safety. Adherence to LSP is also testable through probing the objects actual behavior. That is, examining the impact of an object's state and method arguments on the results of the method calls, or the types of exceptions thrown from the object.
Going back to the example again, in theory the Board methods can be made to work just fine on ThreeDBoard. In practice however, it will be very difficult to prevent differences in behavior that client may not handle properly, without hobbling the functionality that ThreeDBoard is intended to add.
With this knowledge in hand, evaluating LSP adherence can be a great tool in determining when composition is the more appropriate mechanism for extending existing functionality, rather than inheritance.
A: I encourage you to read the article: Violating Liskov Substitution Principle (LSP).
You can find there an explanation what is the Liskov Substitution Principle, general clues helping you to guess if you have already violated it and an example of approach that will help you to make your class hierarchy be more safe.
A: LISKOV SUBSTITUTION PRINCIPLE (From Mark Seemann book) states that we should be able to replace one implementation of an interface with another without breaking either client or implementation.It’s this principle that enables to address requirements that occur in the future, even if we can’t foresee them today.
If we unplug the computer from the wall (Implementation), neither the wall outlet (Interface) nor the computer (Client) breaks down (in fact, if it’s a laptop computer, it can even run on its batteries for a period of time). With software, however, a client often expects a service to be available. If the service was removed, we get a NullReferenceException. To deal with this type of situation, we can create an implementation of an interface that does “nothing.” This is a design pattern known as Null Object,[4] and it corresponds roughly to unplugging the computer from the wall. Because we’re using loose coupling, we can replace a real implementation with something that does nothing without causing trouble.
A: Likov's Substitution Principle states that if a program module is using a Base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.
Intent - Derived types must be completely substitute able for their base types.
Example - Co-variant return types in java.
A: Here is an excerpt from this post that clarifies things nicely:
[..] in order to comprehend some principles, it’s important to realize when it’s been violated. This is what I will do now.
What does the violation of this principle mean? It implies that an object doesn’t fulfill the contract imposed by an abstraction expressed with an interface. In other words, it means that you identified your abstractions wrong.
Consider the following example:
interface Account
{
/**
* Withdraw $money amount from this account.
*
* @param Money $money
* @return mixed
*/
public function withdraw(Money $money);
}
class DefaultAccount implements Account
{
private $balance;
public function withdraw(Money $money)
{
if (!$this->enoughMoney($money)) {
return;
}
$this->balance->subtract($money);
}
}
Is this a violation of LSP? Yes. This is because the account’s contract tells us that an account would be withdrawn, but this is not always the case. So, what should I do in order to fix it? I just modify the contract:
interface Account
{
/**
* Withdraw $money amount from this account if its balance is enough.
* Otherwise do nothing.
*
* @param Money $money
* @return mixed
*/
public function withdraw(Money $money);
}
Voilà, now the contract is satisfied.
This subtle violation often imposes a client with the ability to tell the difference between concrete objects employed. For example, given the first Account’s contract, it could look like the following:
class Client
{
public function go(Account $account, Money $money)
{
if ($account instanceof DefaultAccount && !$account->hasEnoughMoney($money)) {
return;
}
$account->withdraw($money);
}
}
And, this automatically violates the open-closed principle [that is, for money withdrawal requirement. Because you never know what happens if an object violating the contract doesn't have enough money. Probably it just returns nothing, probably an exception will be thrown. So you have to check if it hasEnoughMoney() -- which is not part of an interface. So this forced concrete-class-dependent check is an OCP violation].
This point also addresses a misconception that I encounter quite often about LSP violation. It says the “if a parent’s behavior changed in a child, then, it violates LSP.” However, it doesn’t — as long as a child doesn’t violate its parent’s contract.
A: Liskov Substitution Principle
[SOLID]
Inheritance Subtyping
Wiki Liskov substitution principle (LSP)
Preconditions cannot be strengthened in a subtype.
Postconditions cannot be weakened in a subtype.
Invariants of the supertype must be preserved in a subtype.
*
*Subtype should not require(Preconditions) from caller more than supertype
*Subtype should not expose(Postconditions) for caller less than supertype
*Precondition + Postcondition = function (method) types[Swift Function type. Swift function vs method]
//Swift function
func foo(parameter: Class1) -> Class2
//function type
(Class1) -> Class2
//Precondition
Class1
//Postcondition
Class2
Example
//C3 -> C2 -> C1
class C1 {}
class C2: C1 {}
class C3: C2 {}
*
*Preconditions(e.g. function parameter type) can be the same or weaker(strives for -> C1)
*Postconditions(e.g. function returned type) can be the same or stronger(strives for -> C3)
*Invariant variable[About] of super type should stay invariant
Swift
class A {
func foo(a: C2) -> C2 {
return C2()
}
}
class B: A {
override func foo(a: C1) -> C3 {
return C3()
}
}
Java
class A {
public C2 foo(C2 a) {
return new C2();
}
}
class B extends A {
@Override
public C3 foo(C2 a) { //You are available pass only C2 as parameter
return new C3();
}
}
Behavioral subtyping
Wiki Liskov substitution principle (LSP)
Contravariance of method parameter types in the subtype. Covariance of method return types in the subtype.
New exceptions cannot be thrown by the methods in the subtype, except if they are subtypes of exceptions thrown by the methods of the supertype.
[Variance, Covariance, Contravariance, Invariance]
A: LSP concerns invariants.
The classic example is given by the following pseudo-code declaration (implementations omitted):
class Rectangle {
int getHeight()
void setHeight(int value) {
postcondition: width didn’t change
}
int getWidth()
void setWidth(int value) {
postcondition: height didn’t change
}
}
class Square extends Rectangle { }
Now we have a problem although the interface matches. The reason is that we have violated invariants stemming from the mathematical definition of squares and rectangles. The way getters and setters work, a Rectangle should satisfy the following invariant:
void invariant(Rectangle r) {
r.setHeight(200)
r.setWidth(100)
assert(r.getHeight() == 200 and r.getWidth() == 100)
}
However, this invariant (as well as the explicit postconditions) must be violated by a correct implementation of Square, therefore it is not a valid substitute of Rectangle.
A: The Liskov Substitution Principle
*
*The overridden method shouldn’t remain empty
*The overridden method shouldn’t throw an error
*Base class or interface behavior should not go for modification (rework) as because of derived class behaviors.
A: The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.
For example, if we have a Cat and a Dog class derived from an Animal class, any functions using the Animal class should be able to use Cat or Dog and behave normally.
A: A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.
In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square derive from Rectangle, then a Square should be usable anywhere you expect a Rectangle. This makes for some strange behavior.
Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to a Square, then SetWidth and SetHeight doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square inherit from Rectangle is a bad one.
Y'all should check out the other priceless SOLID Principles Explained With Motivational Posters.
A: This formulation of the LSP is way too strong:
If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.
Which basically means that S is another, completely encapsulated implementation of the exact same thing as T. And I could be bold and decide that performance is part of the behavior of P...
So, basically, any use of late-binding violates the LSP. It's the whole point of OO to to obtain a different behavior when we substitute an object of one kind for one of another kind!
The formulation cited by wikipedia is better since the property depends on the context and does not necessarily include the whole behavior of the program.
A: In a very simple sentence, we can say:
The child class must not violate its base class characteristics. It must be capable with it. We can say it's same as subtyping.
A:
Liskov's Substitution Principle(LSP)
All the time we design a program module and we create some class
hierarchies. Then we extend some classes creating some derived
classes.
We must make sure that the new derived classes just extend without
replacing the functionality of old classes. Otherwise, the new classes
can produce undesired effects when they are used in existing program
modules.
Liskov's Substitution Principle states that if a program module is
using a Base class, then the reference to the Base class can be
replaced with a Derived class without affecting the functionality of
the program module.
Example:
Below is the classic example for which the Liskov's Substitution Principle is violated. In the example, 2 classes are used: Rectangle and Square. Let's assume that the Rectangle object is used somewhere in the application. We extend the application and add the Square class. The square class is returned by a factory pattern, based on some conditions and we don't know the exact what type of object will be returned. But we know it's a Rectangle. We get the rectangle object, set the width to 5 and height to 10 and get the area. For a rectangle with width 5 and height 10, the area should be 50. Instead, the result will be 100
// Violation of Likov's Substitution Principle
class Rectangle {
protected int m_width;
protected int m_height;
public void setWidth(int width) {
m_width = width;
}
public void setHeight(int height) {
m_height = height;
}
public int getWidth() {
return m_width;
}
public int getHeight() {
return m_height;
}
public int getArea() {
return m_width * m_height;
}
}
class Square extends Rectangle {
public void setWidth(int width) {
m_width = width;
m_height = width;
}
public void setHeight(int height) {
m_width = height;
m_height = height;
}
}
class LspTest {
private static Rectangle getNewRectangle() {
// it can be an object returned by some factory ...
return new Square();
}
public static void main(String args[]) {
Rectangle r = LspTest.getNewRectangle();
r.setWidth(5);
r.setHeight(10);
// user knows that r it's a rectangle.
// It assumes that he's able to set the width and height as for the base
// class
System.out.println(r.getArea());
// now he's surprised to see that the area is 100 instead of 50.
}
}
Conclusion:
This principle is just an extension of the Open Close Principle and it
means that we must make sure that new derived classes are extending
the base classes without changing their behavior.
See also: Open Close Principle
Some similar concepts for better structure: Convention over configuration
A: Let me try, consider an interface:
interface Planet{
}
This is implemented by class:
class Earth implements Planet {
public $radius;
public function construct($radius) {
$this->radius = $radius;
}
}
You will use Earth as:
$planet = new Earth(6371);
$calc = new SurfaceAreaCalculator($planet);
$calc->output();
Now consider one more class which extends Earth:
class LiveablePlanet extends Earth{
public function color(){
}
}
Now according to LSP, you should be able to use LiveablePlanet in place of Earth and it should not break your system. Like:
$planet = new LiveablePlanet(6371); // Earlier we were using Earth here
$calc = new SurfaceAreaCalculator($planet);
$calc->output();
Examples taken from here
A:
Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
Actually, the accepted answer is not a counterexample for the Liskov principle. A square naturally is a specific rectangle, so it makes perfect sense that inherits from the class rectangle. You simply need to implement it in this way:
@Override
public void setHeight(double height) {
this.height = height;
this.width = height; // since it's a square
}
@Override
public void setWidth(double width) {
setHeight(width);
}
So, having provided a good example, this, however, is a counterexample:
class Family:
-- getChildrenCount()
class FamilyWithKids extends Family:
-- getChildrenCount() { return childrenCount; } // always > 0
class DeadFamilyWithKids extends FamilyWithKids:
-- getChildrenCount() { return 0; }
-- getChildrenCountWhenAlive() { return childrenCountWhenAlive; }
In this implementation, DeadFamilyWithKids cannot inherit from FamilyWithKids since getChildrenCount() returns 0, while from FamilyWithKids it should always return something greater 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1194"
} |
Q: Calling a Web Service from Seam A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?
I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like.
(Any sample web service can be chosen as an example.)
A: There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses HttpClient from Apache Commons:
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient");
client.executeMethod(method);
A: import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Uses YAHOO!'s RESTful web service with XML.
*/
public class YahooSearch {
private static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
public static void main(final String[] args) {
if (1 != args.length) {
System.err.println("You need to pass a search term!");
} else {
final String term = Reference.encode(args[0]);
final String uri = BASE_URI + "?appid=restbook&query=" + term;
final Response response = new Client(Protocol.HTTP).get(uri);
final DomRepresentation document = response.getEntityAsDom();
document.setNamespaceAware(true);
document.putNamespace("y", "urn:yahoo:srch");
final String expr = "/y:ResultSet/y:Result/y:Title/text()";
for (final Node node : document.getNodes(expr)) {
System.out.println(node.getTextContent());
}
}
}
}
This code uses Restlet to make a request to Yahoo's RESTful search service. Obviously, the details of the web service you are using will dictate what your client for it looks like.
A: final Response response = new Client(Protocol.HTTP).get(uri);
So, if I understand this correctly, the above line is where the actual call to the web service is being made, with the response being converted to an appropriate format and manipulated after this line.
Assuming I were not using Restlet, how would this line differ?
(Of course, the actual processing code would be significantly different as well, so that's a given.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Interface vs Base class When should I use an interface and when should I use a base class?
Should it always be an interface if I don't want to actually define a base implementation of the methods?
If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
A: Interfaces should be small. Really small. If you're really breaking down your objects, then your interfaces will probably only contain a few very specific methods and properties.
Abstract classes are shortcuts. Are there things that all derivatives of PetBase share that you can code once and be done with? If yes, then it's time for an abstract class.
Abstract classes are also limiting. While they give you a great shortcut to producing child objects, any given object can only implement one abstract class. Many times, I find this a limitation of Abstract classes, and this is why I use lots of interfaces.
Abstract classes may contain several interfaces. Your PetBase abstract class may implement IPet (pets have owners) and IDigestion (pets eat, or at least they should). However, PetBase will probably not implement IMammal, since not all pets are mammals and not all mammals are pets. You may add a MammalPetBase that extends PetBase and add IMammal. FishBase could have PetBase and add IFish. IFish would have ISwim and IUnderwaterBreather as interfaces.
Yes, my example is extensively over-complicated for the simple example, but that's part of the great thing about how interfaces and abstract classes work together.
A: Interfaces
*
*Most languages allow you to implement multiple interfaces
*Modifying an interface is a breaking change. All implementations need to be recompiled/modified.
*All members are public. Implementations have to implement all members.
*Interfaces help in Decoupling. You can use mock frameworks to mock out anything behind an interface
*Interfaces normally indicate a kind of behavior
*Interface implementations are decoupled / isolated from each other
Base classes
*
*Allows you to add some default implementation that you get for free by derivation (From C# 8.0 by interface you can have default implementation)
*Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea.
*Changing the base class is relatively easy. Derivations do not need to do anything special
*Base classes can declare protected and public functions that can be accessed by derivations
*Abstract Base classes can't be mocked easily like interfaces
*Base classes normally indicate type hierarchy (IS A)
*Class derivations may come to depend on some base behavior (have intricate knowledge of parent implementation). Things can be messy if you make a change to the base implementation for one guy and break the others.
A: In general, you should favor interfaces over abstract classes. One reason to use an abstract class is if you have common implementation among concrete classes. Of course, you should still declare an interface (IPet) and have an abstract class (PetBase) implement that interface.Using small, distinct interfaces, you can use multiples to further improve flexibility. Interfaces allow the maximum amount of flexibility and portability of types across boundaries. When passing references across boundaries, always pass the interface and not the concrete type. This allows the receiving end to determine concrete implementation and provides maximum flexibility. This is absolutely true when programming in a TDD/BDD fashion.
The Gang of Four stated in their book "Because inheritance exposes a subclass to details of its parent's implementation, it's often said that 'inheritance breaks encapsulation". I believe this to be true.
A: The case for Base Classes over Interfaces was explained well in the Submain .NET Coding Guidelines:
Base Classes vs. Interfaces
An interface type is a partial
description of a value, potentially
supported by many object types. Use
base classes instead of interfaces
whenever possible. From a versioning
perspective, classes are more flexible
than interfaces. With a class, you can
ship Version 1.0 and then in Version
2.0 add a new method to the class. As long as the method is not abstract,
any existing derived classes continue
to function unchanged.
Because interfaces do not support
implementation inheritance, the
pattern that applies to classes does
not apply to interfaces. Adding a
method to an interface is equivalent
to adding an abstract method to a base
class; any class that implements the
interface will break because the class
does not implement the new method.
Interfaces are appropriate in the
following situations:
*
*Several unrelated classes want to support the protocol.
*These classes already have established base classes (for
example,
some are user interface (UI) controls,
and some are XML Web services).
*Aggregation is not appropriate or practicable. In all other
situations,
class inheritance is a better model.
A:
Let's take your example of a Dog and a Cat class, and let's illustrate using C#:
Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:
public abstract class Mammal
This base class will probably have default methods such as:
*
*Feed
*Mate
All of which are behavior that have more or less the same implementation between either species. To define this you will have:
public class Dog : Mammal
public class Cat : Mammal
Now let's suppose there are other mammals, which we will usually see in a zoo:
public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal
This will still be valid because at the core of the functionality Feed() and Mate() will still be the same.
However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:
public interface IPettable
{
IList<Trick> Tricks{get; set;}
void Bathe();
void Train(Trick t);
}
The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.
Your Dog and Cat definitions should now look like:
public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable
Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need into a class without the need for inheritance.
Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
A: This is pretty .NET specific, but the Framework Design Guidelines book argues that in general classes give more flexibility in an evolving framework. Once an interface is shipped, you don't get the chance to change it without breaking code that used that interface. With a class however, you can modify it and not break code that links to it. As long you make the right modifications, which includes adding new functionality, you will be able to extend and evolve your code.
Krzysztof Cwalina says on page 81:
Over the course of the three versions of the .NET Framework, I have talked about this guideline with quite a few developers on our team. Many of them, including those who initially disagreed with the guidelines, have said that they regret having shipped some API as an interface. I have not heard of even one case in which somebody regretted that they shipped a class.
That being said there certainly is a place for interfaces. As a general guideline always provide an abstract base class implementation of an interface if for nothing else as an example of a way to implement the interface. In the best case that base class will save a lot of work.
A: One important difference is that you can only inherit one base class, but you can implement many interfaces. So you only want to use a base class if you are absolutely certain that you won't need to also inherit a different base class. Additionally, if you find your interface is getting large then you should start looking to break it up into a few logical pieces that define independent functionality, since there's no rule that your class can't implement them all (or that you can define a different interface that just inherits them all to group them).
A: When I first started learning about object-oriented programming, I made the easy and probably common mistake of using inheritance to share common behavior - even where that behavior was not essential to the nature of the object.
To further build on an example much used in this particular question, there are lots of things that are petable - girlfriends, cars, fuzzy blankets... - so I might have had a Petable class that provided this common behavior, and various classes inheriting from it.
However, being petable is not part of the nature of any of these objects. There are vastly more important concepts that are essential to their nature - the girlfriend is a person, the car is a land vehicle, the cat is a mammal...
Behaviors should be assigned first to interfaces (including the default interface of the class), and promoted to a base class only if they are (a) common to a large group of classes that are subsets of a larger class - in the same sense that "cat" and "person" are subsets of "mammal".
The catch is, after you understand object-oriented design sufficiently better than I did at first, you'll normally do this automatically without even thinking about it. So the bare truth of the statement "code to an interface, not an abstract class" becomes so obvious you have a hard time believing anyone would bother to say it - and start trying to read other meanings into it.
Another thing I'd add is that if a class is purely abstract - with no non-abstract, non-inherited members or methods exposed to child, parent, or client - then why is it a class? It could be replaced, in some cases by an interface and in other cases by Null.
A: Prefer interfaces over abstract classes
Rationale,
the main points to consider [two already mentioned here] are :
*
*Interfaces are more flexible, because a class can implement multiple
interfaces. Since Java does not have multiple inheritance, using
abstract classes prevents your users from using any other class
hierarchy. In general, prefer interfaces when there are no default
implementations or state. Java collections offer good examples of
this (Map, Set, etc.).
*Abstract classes have the advantage of allowing better forward
compatibility. Once clients use an interface, you cannot change it;
if they use an abstract class, you can still add behavior without
breaking existing code. If compatibility is a concern, consider using
abstract classes.
*Even if you do have default implementations or internal state,
consider offering an interface and an abstract implementation of it.
This will assist clients, but still allow them greater freedom if
desired [1].
Of course, the subject has been discussed at length
elsewhere [2,3].
[1] It adds more code, of course, but if brevity is your primary concern, you probably should have avoided Java in the first place!
[2] Joshua Bloch, Effective Java, items 16-18.
[3] http://www.codeproject.com/KB/ar...
A: Previous comments about using abstract classes for common implementation is definitely on the mark. One benefit I haven't seen mentioned yet is that the use of interfaces makes it much easier to implement mock objects for the purpose of unit testing. Defining IPet and PetBase as Jason Cohen described enables you to mock different data conditions easily, without the overhead of a physical database (until you decide it's time to test the real thing).
A: Don't use a base class unless you know what it means, and that it applies in this case. If it applies, use it, otherwise, use interfaces. But note the answer about small interfaces.
Public Inheritance is overused in OOD and expresses a lot more than most developers realize or are willing to live up to. See the Liskov Substitutablity Principle
In short, if A "is a" B then A requires no more than B and delivers no less than B, for every method it exposes.
A: Conceptually, an interface is used to formally and semi-formally define a set of methods that an object will provide. Formally means a set of method names and signatures, and semi-formally means human readable documentation associated with those methods.
Interfaces are only descriptions of an API (after all, API stands for application programming interface), they can't contain any implementation, and it's not possible to use or run an interface. They only make explicit the contract of how you should interact with an object.
Classes provide an implementation, and they can declare that they implement zero, one or more Interfaces. If a class is intended to be inherited, the convention is to prefix the class name with "Base".
There is a distinction between a base class and an abstract base classes (ABC). ABCs mix interface and implementation together. Abstract outside of computer programming means "summary", that is "abstract == interface". An abstract base class can then describe both an interface, as well as an empty, partial or complete implementation that is intended to be inherited.
Opinions on when to use interfaces versus abstract base classes versus just classes is going to vary wildly based on both what you are developing, and which language you are developing in. Interfaces are often associated only with statically typed languages such as Java or C#, but dynamically typed languages can also have interfaces and abstract base classes. In Python for example, the distinction is made clear between a Class, which declares that it implements an interface, and an object, which is an instance of a class, and is said to provide that interface. It's possible in a dynamic language that two objects that are both instances of the same class, can declare that they provide completely different interfaces. In Python this is only possible for object attributes, while methods are shared state between all objects of a class. However, in Ruby, objects can have per-instance methods, so it's possible that the interface between two objects of the same class can vary as much as the programmer desires (however, Ruby doesn't have any explicit way of declaring Interfaces).
In dynamic languages the interface to an object is often implicitly assumed, either by introspecting an object and asking it what methods it provides (look before you leap) or preferably by simply attempting to use the desired interface on an object and catching exceptions if the object doesn't provide that interface (easier to ask forgiveness than permission). This can lead to "false positives" where two interfaces have the same method name, but are semantically different. However, the trade-off is that your code is more flexible since you don't need to over specify up-front to anticipate all possible uses of your code.
A: Another option to keep in mind is using the "has-a" relationship, aka "is implemented in terms of" or "composition." Sometimes this is a cleaner, more flexible way to structure things than using "is-a" inheritance.
It may not make as much sense logically to say that Dog and Cat both "have" a Pet, but it avoids common multiple inheritance pitfalls:
public class Pet
{
void Bathe();
void Train(Trick t);
}
public class Dog
{
private Pet pet;
public void Bathe() { pet.Bathe(); }
public void Train(Trick t) { pet.Train(t); }
}
public class Cat
{
private Pet pet;
public void Bathe() { pet.Bathe(); }
public void Train(Trick t) { pet.Train(t); }
}
Yes, this example shows that there is a lot of code duplication and lack of elegance involved in doing things this way. But one should also appreciate that this helps to keep Dog and Cat decoupled from the Pet class (in that Dog and Cat do not have access to the private members of Pet), and it leaves room for Dog and Cat to inherit from something else--possibly the Mammal class.
Composition is preferable when no private access is required and you don't need to refer to Dog and Cat using generic Pet references/pointers. Interfaces give you that generic reference capability and can help cut down on the verbosity of your code, but they can also obfuscate things when they are poorly organized. Inheritance is useful when you need private member access, and in using it you are committing yourself to highly coupling your Dog and Cat classes to your Pet class, which is a steep cost to pay.
Between inheritance, composition, and interfaces there is no one way that is always right, and it helps to consider how all three options can be used in harmony. Of the three, inheritance is typically the option that should be used the least often.
A: It depends on your requirements. If IPet is simple enough, I would prefer to implement that. Otherwise, if PetBase implements a ton of functionality you don't want to duplicate, then have at it.
The downside to implementing a base class is the requirement to override (or new) existing methods. This makes them virtual methods which means you have to be careful about how you use the object instance.
Lastly, the single inheritance of .NET kills me. A naive example: Say you're making a user control, so you inherit UserControl. But, now you're locked out of also inheriting PetBase. This forces you to reorganize, such as to make a PetBase class member, instead.
A: I usually don't implement either until I need one. I favor interfaces over abstract classes because that gives a little more flexibility. If there's common behavior in some of the inheriting classes I move that up and make an abstract base class. I don't see the need for both, since they essentially server the same purpose, and having both is a bad code smell (imho) that the solution has been over-engineered.
A: Regarding C#, in some senses interfaces and abstract classes can be interchangeable. However, the differences are: i) interfaces cannot implement code; ii) because of this, interfaces cannot call further up the stack to subclass; and iii) only can abstract class may be inherited on a class, whereas multiple interfaces may be implemented on a class.
A: By def, interface provides a layer to communicate with other code. All the public properties and methods of a class are by default implementing implicit interface. We can also define an interface as a role, when ever any class needs to play that role, it has to implement it giving it different forms of implementation depending on the class implementing it. Hence when you talk about interface, you are talking about polymorphism and when you are talking about base class, you are talking about inheritance. Two concepts of oops !!!
A: I've found that a pattern of Interface > Abstract > Concrete works in the following use-case:
1. You have a general interface (eg IPet)
2. You have a implementation that is less general (eg Mammal)
3. You have many concrete members (eg Cat, Dog, Ape)
The abstract class defines default shared attributes of the concrete classes, yet enforces the interface. For example:
public interface IPet{
public boolean hasHair();
public boolean walksUprights();
public boolean hasNipples();
}
Now, since all mammals have hair and nipples (AFAIK, I'm not a zoologist), we can roll this into the abstract base class
public abstract class Mammal() implements IPet{
@override
public walksUpright(){
throw new NotSupportedException("Walks Upright not implemented");
}
@override
public hasNipples(){return true}
@override
public hasHair(){return true}
And then the concrete classes merely define that they walk upright.
public class Ape extends Mammal(){
@override
public walksUpright(return true)
}
public class Catextends Mammal(){
@override
public walksUpright(return false)
}
This design is nice when there are lots of concrete classes, and you don't want to maintain boilerplate just to program to an interface. If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.
In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.
A: Juan,
I like to think of interfaces as a way to characterize a class. A particular dog breed class, say a YorkshireTerrier, may be a descended of the parent dog class, but it is also implements IFurry, IStubby, and IYippieDog. So the class defines what the class is but the interface tells us things about it.
The advantage of this is it allows me to, for example, gather all the IYippieDog's and throw them into my Ocean collection. So now I can reach across a particular set of objects and find ones that meet the criteria I am looking at without inspecting the class too closely.
I find that interfaces really should define a sub-set of the public behavior of a class. If it defines all the public behavior for all the classes that implement then it usually does not need to exist. They do not tell me anything useful.
This thought though goes counter to the idea that every class should have an interface and you should code to the interface. That's fine, but you end up with a lot of one to one interfaces to classes and it makes things confusing. I understand that the idea is it does not really cost anything to do and now you can swap things in and out with ease. However, I find that I rarely do that. Most of the time I am just modifying the existing class in place and have the exact same issues I always did if the public interface of that class needs changing, except I now have to change it in two places.
So if you think like me you would definitely say that Cat and Dog are IPettable. It is a characterization that matches them both.
The other piece of this though is should they have the same base class? The question is do they need to be broadly treated as the same thing. Certainly they are both Animals, but does that fit how we are going to use them together.
Say I want to gather all Animal classes and put them in my Ark container.
Or do they need to be Mammals? Perhaps we need some kind of cross animal milking factory?
Do they even need to be linked together at all? Is it enough to just know they are both IPettable?
I often feel the desire to derive a whole class hierarchy when I really just need one class. I do it in anticipation someday I might need it and usually I never do. Even when I do, I usually find I have to do a lot to fix it. That’s because the first class I am creating is not the Dog, I am not that lucky, it is instead the Platypus. Now my entire class hierarchy is based on the bizarre case and I have a lot of wasted code.
You might also find at some point that not all Cats are IPettable (like that hairless one). Now you can move that Interface to all the derivative classes that fit. You will find that a much less breaking change that all of a sudden Cats are no longer derived from PettableBase.
A: Here is the basic and simple definiton of interface and base class:
*
*Base class = object inheritance.
*Interface = functional inheritance.
cheers
A: Well, Josh Bloch said himself in Effective Java 2d:
Prefer interfaces over abstract classes
Some main points:
*
*Existing classes can be easily retrofitted to implement a new
interface. All you have to do is add
the required methods if they don’t yet
exist and add an implements clause to
the class declaration.
*Interfaces are ideal for defining mixins. Loosely speaking, a
mixin is a type that a class can
implement in addition to its “primary
type” to declare that it provides
some optional behavior. For example,
Comparable is a mixin interface that
allows a class to declare that its
instances are ordered with respect to
other mutually comparable objects.
*Interfaces allow the construction of nonhierarchical type
frameworks. Type hierarchies are
great for organizing some things, but
other things don’t fall neatly into a
rigid hierarchy.
*Interfaces enable safe, powerful functionality enhancements via the
wrap- per class idiom. If you use
abstract classes to define types, you
leave the programmer who wants to add
functionality with no alternative but
to use inheritance.
Moreover, you can combine the virtues
of interfaces and abstract classes by
providing an abstract skeletal
implementation class to go with each
nontrivial interface that you export.
On the other hand, interfaces are very hard to evolve. If you add a method to an interface it'll break all of it's implementations.
PS.: Buy the book. It's a lot more detailed.
A: It is explained well in this Java World article.
Personally, I tend to use interfaces to define interfaces - i.e. parts of the system design that specify how something should be accessed.
It's not uncommon that I will have a class implementing one or more interfaces.
Abstract classes I use as a basis for something else.
The following is an extract from the above mentioned article JavaWorld.com article, author Tony Sintes, 04/20/01
Interface vs. abstract class
Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.
Many developers forget that a class that defines an abstract method can call that method as well. Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
Class vs. interface
Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
A: Interfaces and base classes represent two different forms of relationships.
Inheritance (base classes) represent an "is-a" relationship. E.g. a dog or a cat "is-a" pet. This relationship always represents the (single) purpose of the class (in conjunction with the "single responsibility principle").
Interfaces, on the other hand, represent additional features of a class. I'd call it an "is" relationship, like in "Foo is disposable", hence the IDisposable interface in C#.
A: I recommend using composition instead of inheritence whenever possible. Use interfaces but use member objects for base implementation. That way, you can define a factory that constructs your objects to behave in a certain way. If you want to change the behavior then you make a new factory method (or abstract factory) that creates different types of sub-objects.
In some cases, you may find that your primary objects don't need interfaces at all, if all of the mutable behavior is defined in helper objects.
So instead of IPet or PetBase, you might end up with a Pet which has an IFurBehavior parameter. The IFurBehavior parameter is set by the CreateDog() method of the PetFactory. It is this parameter which is called for the shed() method.
If you do this you'll find your code is much more flexible and most of your simple objects deal with very basic system-wide behaviors.
I recommend this pattern even in multiple-inheritence languages.
A: Modern style is to define IPet and PetBase.
The advantage of the interface is that other code can use it without any ties whatsoever to other executable code. Completely "clean." Also interfaces can be mixed.
But base classes are useful for simple implementations and common utilities. So provide an abstract base class as well to save time and code.
A: Also keep in mind not to get swept away in OO (see blog) and always model objects based on behavior required, if you were designing an app where the only behavior you required was a generic name and species for an animal then you would only need one class Animal with a property for the name, instead of millions of classes for every possible animal in the world.
A: I have a rough rule-of-thumb
Functionality: likely to be different in all parts: Interface.
Data, and functionality, parts will be mostly the same, parts different: abstract class.
Data, and functionality, actually working, if extended only with slight changes: ordinary (concrete) class
Data and functionality, no changes planned: ordinary (concrete) class with final modifier.
Data, and maybe functionality: read-only: enum members.
This is very rough and ready and not at all strictly defined, but there is a spectrum from interfaces where everything is intended to be changed to enums where everything is fixed a bit like a read-only file.
A: Source: http://jasonroell.com/2014/12/09/interfaces-vs-abstract-classes-what-should-you-use/
C# is a wonderful language that has matured and evolved over the last 14 years. This is great for us developers because a mature language provides us with a plethora of language features that are at our disposal.
However, with much power becomes much responsibility. Some of these features can be misused, or sometimes it is hard to understand why you would choose to use one feature over another. Over the years, a feature that I have seen many developers struggle with is when to choose to use an interface or to choose to use an abstract class. Both have there advantages and disadvantages and the correct time and place to use each. But how to we decide???
Both provide for reuse of common functionality between types. The most obvious difference right away is that interfaces provide no implementation for their functionality whereas abstract classes allow you to implement some “base” or “default” behavior and then have the ability to “override” this default behavior with the classes derived types if necessary.
This is all well and good and provides for great reuse of code and adheres to the DRY (Don’t Repeat Yourself) principle of software development. Abstract classes are great to use when you have an “is a” relationship.
For example: A golden retriever “is a” type of dog. So is a poodle. They both can bark, as all dogs can. However, you might want to state that the poodle park is significantly different than the “default” dog bark. Therefor, it could make sense for you to implement something as follows:
public abstract class Dog
{
public virtual void Bark()
{
Console.WriteLine("Base Class implementation of Bark");
}
}
public class GoldenRetriever : Dog
{
// the Bark method is inherited from the Dog class
}
public class Poodle : Dog
{
// here we are overriding the base functionality of Bark with our new implementation
// specific to the Poodle class
public override void Bark()
{
Console.WriteLine("Poodle's implementation of Bark");
}
}
// Add a list of dogs to a collection and call the bark method.
void Main()
{
var poodle = new Poodle();
var goldenRetriever = new GoldenRetriever();
var dogs = new List<Dog>();
dogs.Add(poodle);
dogs.Add(goldenRetriever);
foreach (var dog in dogs)
{
dog.Bark();
}
}
// Output will be:
// Poodle's implementation of Bark
// Base Class implementation of Bark
//
As you can see, this would be a great way to keep your code DRY and allow for the base class implementation be called when any of the types can just rely on the default Bark instead of a special case implementation. The classes like GoldenRetriever, Boxer, Lab could all could inherit the “default” (bass class) Bark at no charge just because they implement the Dog abstract class.
But I’m sure you already knew that.
You are here because you want to understand why you might want to choose an interface over an abstract class or vice versa. Well one reason you may want to choose an interface over an abstract class is when you don’t have or want to prevent a default implementation. This is usually because the types that are implementing the interface not related in an “is a” relationship. Actually, they don’t have to be related at all except for the fact that each type “is able” or has “the ablity” to do something or have something.
Now what the heck does that mean? Well, for example: A human is not a duck…and a duck is not a human. Pretty obvious. However, both a duck and a human have “the ability” to swim (given that the human passed his swimming lessons in 1st grade :) ). Also, since a duck is not a human or vice versa, this is not an “is a” realationship, but instead an “is able” relationship and we can use an interface to illustrate that:
// Create ISwimable interface
public interface ISwimable
{
public void Swim();
}
// Have Human implement ISwimable Interface
public class Human : ISwimable
public void Swim()
{
//Human's implementation of Swim
Console.WriteLine("I'm a human swimming!");
}
// Have Duck implement ISwimable interface
public class Duck: ISwimable
{
public void Swim()
{
// Duck's implementation of Swim
Console.WriteLine("Quack! Quack! I'm a Duck swimming!")
}
}
//Now they can both be used in places where you just need an object that has the ability "to swim"
public void ShowHowYouSwim(ISwimable somethingThatCanSwim)
{
somethingThatCanSwim.Swim();
}
public void Main()
{
var human = new Human();
var duck = new Duck();
var listOfThingsThatCanSwim = new List<ISwimable>();
listOfThingsThatCanSwim.Add(duck);
listOfThingsThatCanSwim.Add(human);
foreach (var something in listOfThingsThatCanSwim)
{
ShowHowYouSwim(something);
}
}
// So at runtime the correct implementation of something.Swim() will be called
// Output:
// Quack! Quack! I'm a Duck swimming!
// I'm a human swimming!
Using interfaces like the code above will allow you to pass an object into a method that “is able” to do something. The code doesn’t care how it does it…All it knows is that it can call the Swim method on that object and that object will know which behavior take at run-time based on its type.
Once again, this helps your code stay DRY so that you would not have to write multiple methods that are calling the object to preform the same core function (ShowHowHumanSwims(human), ShowHowDuckSwims(duck), etc.)
Using an interface here allows the calling methods to not have to worry about what type is which or how the behavior is implemented. It just knows that given the interface, each object will have to have implemented the Swim method so it is safe to call it in its own code and allow the behavior of the Swim method be handled within its own class.
Summary:
So my main rule of thumb is use an abstract class when you want to implement a “default” functionality for a class hierarchy or/and the classes or types you are working with share a “is a” relationship (ex. poodle “is a” type of dog).
On the other hand use an interface when you do not have an “is a” relationship but have types that share “the ability” to do something or have something (ex. Duck “is not” a human. However, duck and human share “the ability” to swim).
Another difference to note between abstract classes and interfaces is that a class can implement one to many interfaces but a class can only inherit from ONE abstract class (or any class for that matter). Yes, you can nest classes and have an inheritance hierarchy (which many programs do and should have) but you cannot inherit two classes in one derived class definition (this rule applies to C#. In some other languages you are able to do this, usually only because of the lack of interfaces in these languages).
Also remember when using interfaces to adhere to the Interface Segregation Principle (ISP). ISP states that no client should be forced to depend on methods it does not use. For this reason interfaces should be focused on specific tasks and are usually very small (ex. IDisposable, IComparable ).
Another tip is if you are developing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
Hope this clears things up for some people!
Also if you can think of any better examples or want to point something out, please do so in the comments below!
A: An inheritor of a base class should have an "is a" relationship. Interface represents An "implements a" relationship.
So only use a base class when your inheritors will maintain the is a relationship.
A: Use Interfaces to enforce a contract ACROSS families of unrelated classes. For example, you might have common access methods for classes that represent collections, but contain radically different data i.e. one class might represent a result set from a query, while the other might represent the images in a gallery. Also, you can implement multiple interfaces, thus allowing you to blend (and signify) the capabilities of the class.
Use Inheritance when the classes bear a common relationship and therefore have a similair structural and behavioural signature, i.e. Car, Motorbike, Truck and SUV are all types of road vehicle that might contain a number of wheels, a top speed
A: Make a list of the things your objects must be, have, or do and the things your objects can (or might) be, have, or do. Must indicates your base types and can indicates your interfaces.
E.g., your PetBase must Breathe, and your IPet might DoTricks.
Analysis of your problem domain will help you define the precise hierarchy structure.
A:
When should I use an interface and when should I use a base class?
You should use interface if
*
*You have pure abstract methods and don't have non-abstract methods
*You don't have default implementation of non abstract methods (except for Java 8 language, where interface methods provides default implementation)
*If you are using Java 8, now interface will provide default implementation for some non-abstract methods. This will make interface more usable compared to abstract classes.
Have a look at this SE question for more details.
Should it always be an interface if I don't want to actually define a base implementation of the methods?
Yes. It's better and cleaner. Even if you have a base class with some abstract methods, let's base class extends abstract methods through interface. You can change interface in future without changing the base class.
Example in java:
abstract class PetBase implements IPet {
// Add all abstract methods in IPet interface and keep base class clean.
Base class will contain only non abstract methods and static methods.
}
If I have a Dog and Cat class. Why would I want to implement IPet instead of PetBase? I can understand having interfaces for ISheds or IBarks (IMakesNoise?), because those can be placed on a pet by pet basis, but I don't understand which to use for a generic Pet.
I prefer to have base class implement the interface.
abstract class PetBase implements IPet {
// Add all abstract methods in IPet
}
/*If ISheds,IBarks is common for Pets, your PetBase can implement ISheds,IBarks.
Respective implementations of PetBase can change the behaviour in their concrete classes*/
abstract class PetBase implements IPet,ISheds,IBarks {
// Add all abstract methods in respective interfaces
}
Advantages:
*
*If I want to add one more abstract method in existing interfaces, I simple change interface without touching the abstract base class. If I want to change the contract, I will change interface & implementation classes without touching base class.
*You can provide immutability to base class through interface. Have a look at this article
Refer to this related SE question for more details:
How should I have explained the difference between an Interface and an Abstract class?
A: In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.
The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.
A: Use your own judgement and be smart. Don't always do what others (like me) are saying. You will hear "prefer interfaces to abstract classes" but it really depends. It depends what the class is.
In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.
On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.
Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.
A: Interfaces have the distinct advantage of being somewhat "hot swappable" for classes. Changing a class from one parent to another will often result in a great deal of work, but Interfaces can often be removed and changed without a great deal of effect on the implementation class. This is especially useful in cases where you have several narrow sets of behaviour that you "may" want a class to implement.
This works especially well in my field: game programming. Base classes can get bloated with tons of behaviours that "may" be needed by inherited objects. With interfaces different behaviours can be added or removed to objects easily and readily. For example, if I create an interface for "IDamageEffects" for objects that I want to reflect damage, then I can easily apply that to various game objects, and easily change my mind later. Say I design an initial class that I want to use for "static" decorative objects and I initially decide they are non-destructible. Later on, I may decide it would be more fun if they could blow up so I alter the class to implement the "IDamageEffects" interface. This is much easier to do than switching base classes or creating a new object hierarchy.
A: There are other advantages to inheritance as well - such as the ability for a variable to be able to hold an object of either the parent class or the inherited class (without having to declare it as something generic, like "Object").
For example, in .NET WinForms, most UI components derive from System.Windows.Forms.Control, so a variable declared as that could "hold" just about any UI element - be it a button, a ListView, or what have you. Now, granted, you won't have access to all the properties or methods of the item, but you'll have all the basic stuff - and that can be useful.
A: You should use a base class if there really isn't any reason for other developers to desire using their own base class in addition to your type's members and you foresee versioning issues (see http://haacked.com/archive/2008/02/21/versioning-issues-with-abstract-base-classes-and-interfaces.aspx).
If inheriting developers have any reason to use their own base class to implement your type's interface and you don't see the interface changing, then go with an interface. In this case, you can still throw in a default base class that implements the interface for sake of convenience.
A: Thanks for answering by Jon Limjap but I want to add some explanation for concept of Interface and Abstract Base Classes
Interface Types vs. Abstract Base Classes
Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.
The interface type might seem very similar to an abstract base class. Recall
that when a class is marked as abstract, it may define any number of abstract members to provide a
polymorphic interface to all derived types. However, even when a class does define a set of abstract
members, it is also free to define any number of constructors, field data, nonabstract members (with
implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.
The polymorphic interface established by an abstract parent class suffers from one major limitation
in that only derived types support the members defined by the abstract parent. However, in larger
software systems, it is very common to develop multiple class hierarchies that have no common parent
beyond System.Object. Given that abstract members in an abstract base class apply only to derived
types, we have no way to configure types in different hierarchies to support the same polymorphic
interface. By way of example, assume you have defined the following abstract class:
public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
public abstract object Clone();
}
Given this definition, only members that extend CloneableType are able to support the Clone()
method. If you create a new set of classes that do not extend this base class, you can’t gain this
polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.
Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:
// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}
As you would guess, interface types come to the rescue. After an interface has been defined, it can
be implemented by any class or structure, in any hierarchy, within any namespace or any assembly
(written in any .NET programming language). As you can see, interfaces are highly polymorphic.
Consider the standard .NET interface named ICloneable, defined in the System namespace. This
interface defines a single method named Clone():
public interface ICloneable
{
object Clone();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "831"
} |
Q: UI Thread Safety Any suggestions on the best way to ensure thread safety when changing the properties on Form controls? I have been using Me. Invoke in the past, and I was wondering if you have pros/cons, comments, suggestions, etc.
A: Invoke is the proper way to do it if you're pushing stuff at the form from another thread.
But you might consider whether the form might be better pulling data itself, perhaps from a timer, and perhaps less frequently than a background process might push individual updates.
A: I do control. Invoke on the target control rather than the entire form, but that's just me. I claim no advanced knowledge of win forms, I just have to use it every now and then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Proving SQL query equivalency How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.
As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.
A: This sounds to me like a an NP complete problem. I'm not sure there is a sure fire way to prove this kind of thing
A: This is pretty easy to do.
Lets assume your queries are named a and b
a
minus
b
should give you an empty set. If it does not. then the queries return different sets, and the result set shows you the rows that are different.
then do
b
minus
a
that should give you an empty set. If it does, then the queries do return the same sets.
if it is not empty, then the queries are different in some respect, and the result set shows you the rows that are different.
A: The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data.
For Oracle one of the better if not best approaches (very efficient) is here (Ctrl+F Comparing the Contents of Two Tables):
http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html
Which boils down to:
select c1,c2,c3,
count(src1) CNT1,
count(src2) CNT2
from (select a.*,
1 src1,
to_number(null) src2
from a
union all
select b.*,
to_number(null) src1,
2 src2
from b
)
group by c1,c2,c3
having count(src1) <> count(src2);
A: 1) Real equivalency proof with Cosette:
Cosette checks (with a proof) if 2 SQL query's are equivalent and counter examples when not equivalent. It's the only way to be absolutely sure, well almost ;) You can even throw in 2 query's on their website and check (formal) equivalence right away.
Link to Cosette:
https://cosette.cs.washington.edu/
Link to article that gives a good explanation of how Cosette works: https://medium.com/@uwdb/introducing-cosette-527898504bd6
2) Or if you're just looking for a quick practical fix:
Try this stackoverflow answer: [sql - check if two select's are equal]
Which comes down to:
(select * from query1 MINUS select * from query2)
UNION ALL
(select * from query2 MINUS select * from query1)
This query gives you all rows that are returned by only one of the queries.
A: The DBMS vendors have been working on this for a very, very long time. As Rik said, it's probably an intractable problem, but I don't think any formal analysis on the NP-completeness of the problem space has been done.
However, your best bet is to leverage your DBMS as much as possible. All DBMS systems translate SQL into some sort of query plan. You can use this query plan, which is an abstracted version of the query, as a good starting point (the DBMS will do LOTS of optimization, flattening queries into more workable models).
NOTE: modern DBMS use a "cost-based" analyzer which is non-deterministic across statistics updates, so the query planner, over time, may change the query plan for identical queries.
In Oracle (depending on your version), you can tell the optimizer to switch from the cost based analyzer to the deterministic rule based analyzer (this will simplify plan analysis) with a SQL hint, e.g.
SELECT /*+RULE*/ FROM yourtable
The rule-based optimizer has been deprecated since 8i but it still hangs around even thru 10g (I don't know 'bout 11). However, the rule-based analyzer is much less sophisticated: the error rate potentially is much higher.
For further reading of a more generic nature, IBM has been fairly prolific with their query-optimization patents. This one here on a method for converting SQL to an "abstract plan" is a good starting point:
http://www.patentstorm.us/patents/7333981.html
A: Perhaps you could draw (by hand) out your query and the results using Venn Diagrams, and see if they produce the same diagram. Venn diagrams are good for representing sets of data, and SQL queries work on sets of data. Drawing out a Venn Diagram might help you to visualize if 2 queries are functionally equivalent.
A: This will do the trick. If this query returns zero rows the two queries are returning the same results. As a bonus, it runs as a single query, so you don't have to worry about setting the isolation level so that the data doesn't change between two queries.
select * from ((<query 1> MINUS <query 2>) UNION ALL (<query 2> MINUS <query 1>))
Here's a handy shell script to do this:
#!/bin/sh
CONNSTR=$1
echo query 1, no semicolon, eof to end:; Q1=`cat`
echo query 2, no semicolon, eof to end:; Q2=`cat`
T="(($Q1 MINUS $Q2) UNION ALL ($Q2 MINUS $Q1));"
echo select 'count(*)' from $T | sqlplus -S -L $CONNSTR
A: CAREFUL! Functional "equivalence" is often based on the data, and you may "prove" equivalence of 2 queries by comparing results for many cases and still be wrong once the data changes in a certain way.
For example:
SQL> create table test_tabA
(
col1 number
)
Table created.
SQL> create table test_tabB
(
col1 number
)
Table created.
SQL> -- insert 1 row
SQL> insert into test_tabA values (1)
1 row created.
SQL> commit
Commit complete.
SQL> -- Not exists query:
SQL> select * from test_tabA a
where not exists
(select 'x' from test_tabB b
where b.col1 = a.col1)
COL1
----------
1
1 row selected.
SQL> -- Not IN query:
SQL> select * from test_tabA a
where col1 not in
(select col1
from test_tabB b)
COL1
----------
1
1 row selected.
-- THEY MUST BE THE SAME!!! (or maybe not...)
SQL> -- insert a NULL to test_tabB
SQL> insert into test_tabB values (null)
1 row created.
SQL> commit
Commit complete.
SQL> -- Not exists query:
SQL> select * from test_tabA a
where not exists
(select 'x' from test_tabB b
where b.col1 = a.col1)
COL1
----------
1
1 row selected.
SQL> -- Not IN query:
SQL> select * from test_tabA a
where col1 not in
(select col1
from test_tabB b)
**no rows selected.**
A: You don't.
If you need a high level of confidence that a performance change, for example, hasn't changed the output of a query then test the hell out it.
If you need a really high level of confidence .. then errrm, test it even more.
Massive level's of testing aren't that hard to cobble together for a SQL query. Write a proc which will iterate around a large/complete set of possible paramenters, and call each query with each set of params, and write the outputs to respective tables. Compare the two tables and there you have it.
It's not exactly scientific, which I guess was the OP's question, but I'm not aware of a formal method to prove equivalency.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: ASP.Net AJAX JavaScript Serialization Error Ran into an “Out of Stack Space” error trying to serialize an ASP.Net AJAX Array object.
Here is the scenario with simplified code:
*
*Default.aspx
*MainScript.js
function getObject(){
return new Array();
}
function function1(obj){
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
function function2(){
var obj=getObject();
var s=Sys.Serialization.JavaScriptSerializer.serialize(obj);
alert(s);
}
*Content.aspx
*ContentScript.js
function serializeObject(){
var obj=window.top.getObject();
window.top.function1(obj); // <– This works fine
obj=new Array();
window.top.function1(obj); // <– this causes an Out of Stack Space error
}
The code for the sample pages and JavaScript is here.
Posting the code for the aspx pages here posed a problem. So please check the above link to see the code for the aspx pages.
A web page (default.aspx) with an IFrame on that hosts a content page (content.aspx).
Clicking the “Serialize Object” button calls the JavaScript function serializeObject(). The serialization works fine for Array objects created in the top window (outside the frame). However if the array object is created in the IFrame, serialization bombs with an out of stack space error. I stepped through ASP.Net AJAX JS files and what I discovered is, the process goes into an endless loop trying to figure out the type of the array object. Endless call to Number.IsInstanceOf and pretty soon you get an out of stack error.
Any ideas?
A: This problem happens because Sys.Serialization.JavaScriptSerializer can't serialize objects from others frames, but only those objects which where instantiated in the current window (which calls serialize() method). The only workaround which is known for me it's making clone of the object from other frame before calling serialize() method.
Example of the clone() methode you can find here (comments in Russian):
link text
A: I converted your example to a set of static html files, and dowloaded the standalone Microsoft Ajax Library 3.5 to test with. It didn't have issue on either Firefox 3 or IE 7, but I did notice the first alert box displayed [] (an array) and the second {} (an object).
Then, I converted your new Array() code to:
var obj = [];
obj.push(1);
and after that, I got [1] and {"0", 1} is the alert boxes. I don't think the bug is with JavaScriptSerializer, but something to do with passing objects across frames.
A: I have no way of testing your code right now, but it looks like a bug in JavaScriptSerializer.serialize to me. My guess is that it tries to do some kind of type checking on the array via the CLR and that it doesn't handle an empty array properly.
Have you tried to add an item of a serializable type to the array in your code? If so, what happens?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Opening a file stored in a database in .NET I'm storing a Word document in a SQL Server 2005 database in a varbinary(max) column. Is there a way to open this document from a VB.NET Windows Forms application without serialising to a file first (i.e. directly from the byte array I've read from the database)?
A: Depends on what's reading it. If it's Word, you'll probably have to serialize to a file, but if it's a function or library that can take an IO.Stream then you could wrap a new MemoryStream around the byte array and pass that.
A: Not really. You need to treat it like an e-mail attachment, where the file is generally copied to a temp folder that is cleaned out periodically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C#: Create a virtual drive in Computer Is there any way to create a virtual drive in "(My) Computer" and manipulate it, somewhat like JungleDisk does it?
It probably does something like:
override OnRead(object sender, Event e) {
ShowFilesFromAmazon();
}
Are there any API:s for this? Maybe to write to an XML-file or a database, instead of a real drive.
The Dokan Library seems to be the answer that mostly corresponds with my question, even though System.IO.IsolatedStorage seems to be the most standardized and most Microsoft-environment adapted.
A: You can use the Dokan library to create a virtual drive. There is a .Net wrapper for interfacing with C#.
A: Yes, use the classes in System.IO.IsolatedStorage
A: The contents of My Computer can include Shell Namespace Extensions. These COM objects run inside the main Explorer process, as do many other shell extensions. Using C# for such extensions is a bad idea, since your extension cannot control which CLR version Explorer.exe can use. And Microsoft allows only one CLR per process.
A: Depending on what type of virtual drive you wish to build, here are some new OS API recently introduced in Windows, macOS and iOS.
Some of the below API is available as managed .NET code on Windows but many are a native Windows / macOS / iOS API. Even though, I was able to consume many of the below API in .NET and Xamarin applications and build entire Virtual Drive in C# for Windows, macOS and iOS.
For Remote Cloud Storage
On Windows. Windows 10 provides Cloud Sync Engine API for creating virtual drives that publish data from a remote location. It is also known under the “Cloud Filter API” name or “Windows Cloud Provider”. Here are its major features:
*
*On-demand folders listing. Folder listing is made only when the first requested by the client application to the file system is made. File content is not downloaded, but all file properties including file size are available on the client via regular files API.
*On-demand file content loading. File content can be downloaded in several modes (progressive, streaming mode, allow background download, etc) and made available to OS when application makes first file content reading request.
*Offline files support. Files can be edited in the offline mode, pinned/unpinned and synched to/from the server.
*Windows shell integration. Windows File Manager shows file status (modified, in-sync, conflict) and file download progress.
*Metadata and properties support. Custom columns can be displayed in Windows File Manager as well as some binary metadata can be associated with each file and folder.
On macOS and iOS. MacOS Big Sur and iOS 11+ provides similar API called File Provider API. Its features are similar to what Windows API provides:
*
*On-demand folders listing.
*On-demand files content loading.
*Offline files support.
*File Manager Integration. In macOS Finder and iOS Files application you can can show file status (in the cloud, local).
I am not sure currently if files/folders and can show custom columns in macOS Finder and store any metadata.
For High-Speed Local Storage
On Windows. Windows provides ProjFS API. Its main difference from the Cloud Sync Engine API and macOS/iOS File Provider API is that it hides the fact that it is a remote storage. It does not provide any indication of the file status, download progress, ets. The documentation says it is intended for “projecting” hierarchical data in the form of file system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Batch renaming of files with international chars on Windows XP I have a whole bunch of files with filenames using our lovely Swedish letters å å and ö.
For various reasons I now need to convert these to an [a-zA-Z] range. Just removing anything outside this range is fairly easy. The thing that's causing me trouble is that I'd like to replace å with a, ö with o and so on.
This is charset troubles at their worst.
I have a set of test files:
files\Copy of New Text Documen åäö t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase åäöÅÄÖéÉ.txt
I'm basing my script on this line, piping it's results into various commands
for %%X in (files\*.txt) do (echo %%X)
The wierd thing is that if I print the results of this (the plain for-loop that is) into a file I get this output:
files\Copy of New Text Documen †„” t.txt
files\fofo.txt
files\New Text Document.txt
files\worstcase †„”Ž™‚.txt
So something wierd is happening to my filenames before they even reach the other tools (I've been trying to do this using a sed port for Windows from something called GnuWin32 but no luck so far) and doing the replace on these characters doesn't help either.
How would you solve this problem? I'm open to any type of tools, commandline or otherwise…
EDIT: This is a one time problem, so I'm looking for a quick 'n ugly fix
A: You might have more luck in cmd.exe if you opened it in UNICODE mode. Use "cmd /U".
Others have proposed using a real programming language. That's fine, especially if you have a language you are very comfortable with. My friend on the C# team says that C# 3.0 (with Linq) is well-suited to whipping up quick, small programs like this. He has stopped writing batch files most of the time.
Personally, I would choose PowerShell. This problem can be solved right on the command line, and in a single line. I'll
EDIT: it's not one line, but it's not a lot of code, either. Also, it looks like StackOverflow doesn't like the syntax "$_.Name", and renders the _ as _.
$mapping = @{
"å" = "a"
"ä" = "a"
"ö" = "o"
}
Get-ChildItem -Recurse . *.txt | Foreach-Object {
$newname = $_.Name
foreach ($l in $mapping.Keys) {
$newname = $newname.Replace( $l, $mapping[$l] )
$newname = $newname.Replace( $l.ToUpper(), $mapping[$l].ToUpper() )
}
Rename-Item -WhatIf $_.FullName $newname # remove the -WhatIf when you're ready to do it for real.
}
A: You can use this code (Python)
Rename international files
# -*- coding: cp1252 -*-
import os, shutil
base_dir = "g:\\awk\\" # Base Directory (includes subdirectories)
char_table_1 = "áéíóúñ"
char_table_2 = "aeioun"
adirs = os.walk (base_dir)
for adir in adirs:
dir = adir[0] + "\\" # Directory
# print "\nDir : " + dir
for file in adir[2]: # List of files
if os.access(dir + file, os.R_OK):
file2 = file
for i in range (0, len(char_table_1)):
file2 = file2.replace (char_table_1[i], char_table_2[i])
if file2 <> file:
# Different, rename
print dir + file, " => ", file2
shutil.move (dir + file, dir + file2)
###
You have to change your encoding and your char tables (I tested this script with Spanish files and works fine). You can comment the "move" line to check if it's working ok, and remove the comment later to do the renaming.
A: I would write this in C++, C#, or Java -- environments where I know for certain that you can get the Unicode characters out of a path properly. It's always uncertain with command-line tools, especially out of Cygwin.
Then the code is a simple find/replace or regex/replace. If you can name a language it would be easy to write the code.
A: I'd write a vbscript (WSH) to scan the directories, then send the filenames to a function that breaks up the filenames into their individual letters, then does a SELECT CASE on the Swedish ones and replaces them with the ones you want. Or, instead of doing that the function could just drop it thru a bunch of REPLACE() functions, reassigning the output to the input string. At the end it then renames the file with the new value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I script a password change for a SQL server login? Just what the title says, I need to change the password for an existing sql server login and I want to do it via sql script.
A: alter login mylogin with password = 'mylogin'
A: If the user already has the ALTER ANY LOGIN permission (i.e. the user can change any password for any user) then this works:
alter login mylogin with password = 'mylogin'
Otherwise, if you don't want to make every user in your system a superuser, add a parameter of the old password for the same command:
alter login mylogin with password = 'mylogin' old_password='oldpassword'
A: ALTER LOGIN
http://msdn.microsoft.com/en-us/library/ms189828.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Crystal Reports 2008 InprocServer + TempDir = "Operation not yet implemented" I have a .NET web app that uses CR 2008 for reports. The server it's deployed on is saddled with McAfee, and we want to tell CR to use a temp directory other than the Windows temp dir.
Google found me the following registry key:
SOFTWARE\Business Objects\Suite 12.0\Report Application Server\InprocServer\TempDir.
Adding this key does result in CR creating a bunch of temp files in the directory I specified. However, at the end of the report run I get an "Operation not yet implemented" exception.
I'm trying to return a PDF to the browser via ExportToHttpRequest(), which works just fine if I don't change the In-process server's tempdir.
Has anyone run into this before? I've already given the local ASPNET account full control of the new tempdir.
Thanks.
A: The other temp directory than C:/windows/temp should be located in your web site's virtual directory. Just add that temp folder in your web site's directory and when you make its virtual path to host it on IIS , it automatically gets included. If you want to make it at some other place like at D:/CrystalTEmp, you need to add this folder in your Inetmgr, just right click this directory and enable its web sharing. And yes you need to give Network service full rights over this temp folder.
If your placing your web site directory in inetpub/wwwroot, then you dont need to give rights to network service.
A: I have used CR for more years than I ever wanted to, but never had to specify a different temp folder. Do you have any specific reason for that? I don't know if IIS process can "simply" access that.
What is the "other" temp dir or better yet, "where is it" in the HDD?
A: We have tried this to no avail as well under IIS5. Ran into the same exact problem after trying to set the TempDir registry key. PDF export started failing although all other report exports (apparently) work.
However, at a client site running IIS6, this redirection of temp files to a dedicated directory works fine. By default, on their site, Crystal Reports uses the directory
C:\Program Files\Business Objects\BusinessObjects Enterprise 11.5\Data
as its temp storage location, and gives the ASP.NET account adequate privileges to create and remove files there. So perhaps there is some hardwired logic that mandates that the files be created within the CR installation directory hierarchy. In other words, this all worked as expected by default after CR installation under IIS6.
For release 12, obviously the directory would be slightly different.
A: “Operation not yet implemented”
change "Font" type from
- right click on text area.
- format setting.
- change font
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Yes/No dialog in Java ME I'm looking for a simple solution for a yes/no dialog to use in a Java ME midlet. I'd like to use it like this but other ways are okey.
if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
A: You need an Alert:
An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next Displayable. An alert can contain a text string and an image. The intended use of Alert is to inform the user about errors and other exceptional conditions.
With 2 commands ("Yes"/"No" in your case):
If there are two or more Commands present on the Alert, it is automatically turned into a modal Alert, and the timeout value is always FOREVER. The Alert remains on the display until a Command is invoked.
These are built-in classes supported in MIDP 1.0 and higher. Also your code snippet will never work. Such an API would need to block the calling thread awaiting for the user to select and answer. This goes exactly in the opposite direction of the UI interaction model of MIDP, which is based in callbacks and delegation. You need to provide your own class, implementing CommandListener, and prepare your code for asynchronous execution.
Here is an (untested!) example class based on Alert:
public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
To use it (again, untested and on top of my head):
MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
This code will make the prompt the current displayed form in your app, but it won't block your thread like in the example you posted. You need to continue running and wait for a commandAction invocation.
A: I dont have programed in Java ME, but i found in it's reference for optional packages the
Advanced Graphics and User Interface API, and it's used like the Java SE API to create these dialogs with the JOptionPane Class
int JOptionPane.showConfirmDialog(java.awt.Component parentComponent, java.lang.Object >message, java.lang.String title, int optionType)
Return could be
JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: secure way to authenticate administrator in ASP.NET site using OpenID with DotNetOpenID Encouraged by SO, I'm trying to write an ASP.NET site that uses OpenID for user authentication. It's a regular WinForms site (not MVC.NET), using the DotNetOpenId library for authentication.
Is it safe for me to permit/deny administrative functions on the site by simply comparing the current session's "ClaimedID" (as returned in the OpenIdLogin_LoggedIn event, as member DotNetOpenId.RelyingParty,OpenIdEventArgs.Response.ClaimedIdentifier) to a known administrator's OpenID (i.e. mine)?
If so, is it safe for this ID to be visible (e.g. in open source code), or should it be "hidden" in a configuration file or a database row? (I know it's better design to make it configurable, my question is just about safety.)
A: My solution is to follow the same idea of the Roles table. After you've authenticated the user, look up that user's roles. If the user has role "Administrator" in the UserRoles table, then they can do whatever the Administrator can do.
I don't broadcast open ID's in my app. They're stored in the table. On every action result, I'm hitting the Users table, since I have also modified mine to store various user state information. With the exception of the home page, there is going to be some user information that I need from that table. I'm using LINQ, so I include the .LoadWith() to load the User with his list of roles when it serializes.
A: Jarrett makes some good comments about using database tables.
Just to answer another one of your questions, no, it's not a confidentiality thing to put your OpenID in your code generally. If setting up roles seems overkill for your site, a simple equality check against your ClaimedIdentifier is just perfect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Highlight parents in xml string Say I have:
<ul>
<li id="x">
<a href="x">x</a>
</li>
<li id="y">
<a href="y">y</a>
<ul>
<li id="z">
<a href="z">z</a>
</li>
</ul>
</li>
</ul>
I want to add a class value to all the list items that are the parents of z. So, I want to modify y but not x.
Obviously, I can parse this into some kind of associative array and then recurse backwards. Any ideas how I can do it with just text processing (string replacing, regular expression, etc)?
Thanks!
A: I would use XSLT. You can specify to search for nodes that are ancestors of z .
A: xpath has an ancestor-axis which includes all ancestors of the current context node.
//*[@id="z"]/ancestor::li
* any element
[@id="z"] that has an attribute id with the value z (since the attribute is id there can(/should be) only be one such element)
/ancestor::li all li elements that are ancestors of that
see also: https://www.w3schools.com/xml/xpath_axes.asp
A: Example of the whole XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:variable name="ancestors" select="descendant::li[@id = 'z']/ancestor::li"/>
<xsl:template match="li">
<xsl:copy>
<!-- test if current li is in the $ancestors node-list -->
<xsl:if test="count($ancestors | .) = count($ancestors)">
<xsl:attribute name="class">ancestor</xsl:attribute>
</xsl:if>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
A: I suggest you parse it into a DOM and recurse backwards like you were thinking. Regular expressions don't work very well for nested structures with arbitrary nesting levels.
A:
Will add the attribute only to elements with a descendent element of 'z'.
A: Thanks for the input. I figured it was impossible without parsing (or using xsl, etc)... Oh well.
A: This is a good fit for jQuery if that's available to you.
$("#z").parent().parent().addClass("foo");
A: In addition to John Sheehan's anwser:
With JQuery I'd rather use
$('#z').parents('li').addClass('myClass');
than relying on the actual structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How is floating point stored? When does it matter? In follow up to this question, it appears that some numbers cannot be represented by floating point at all, and instead are approximated.
How are floating point numbers stored?
Is there a common standard for the different sizes?
What kind of gotchas do I need to watch out for if I use floating point?
Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?
A: As to the second part of your question, unless performance and efficiency are important for your project, then I suggest you transfer the floating point data as a string over TCP/IP. This lets you avoid issues such as byte alignment and will ease debugging.
A: The standard is IEEE 754.
Of course, there are other means to store numbers when IEE754 isn't good enough. Libraries like Java's BigDecimal are available for most platforms and map well to SQL's number type. Symbols can be used for irrational numbers, and ratios that can't be accurately represented in binary or decimal floating point can be stored as a ratio.
A: Basically what you need to worry about in floating point numbers is that there is a limited number of digits of precision. This can cause problems when testing for equality, or if your program actually needs more digits of precision than what that data type give you.
In C++, a good rule of thumb is to think that a float gives you 7 digits of precision, while a double gives you 15. Also, if you are interested in knowing how to test for equality, you can look at this question thread.
A:
In follow up to this question, it
appears that some numbers cannot be
represented by floating point at all,
and instead are approximated.
Correct.
How are floating point numbers stored?
Is there a common standard for the different sizes?
As the other posters already mentioned, almost exclusively IEEE754 and its successor
IEEE754R. Googling it gives you thousand explanations together with bit patterns and their explanation.
If you still have problems to get it, there are two still common FP formats: IBM and DEC-VAX. For some esoteric machines and compilers (BlitzBasic, TurboPascal) there are some
odd formats.
What kind of gotchas do I need to watch out for if I use floating point?
Are they cross-language compatible (ie, what conversions do I need to deal with to
send a floating point number from a python program to a C program over TCP/IP)?
Practically none, they are cross-language compatible.
Very rare occuring quirks:
*
*IEEE754 defines sNaNs (signalling NaNs) and qNaNs (quiet NaNs). The former ones cause a trap which forces the processor to call a handler routine if loaded. The latter ones don't do this. Because language designers hated the possibility that sNaNs interrupt their workflow and supporting them enforce support for handler routines, sNaNs are almost always silently converted into qNaNs.
So don't rely on a 1:1 raw conversion. But again: This is very rare and occurs only if NaNs
are present.
*You can have problems with endianness (the bytes are in the wrong order) if files between different computers are shared. It is easily detectable because you are getting NaNs for numbers.
A: As mentioned, the Wikipedia article on IEEE 754 does a good job of showing how floating point numbers are stored on most systems.
Now, here are some common gotchas:
*
*The biggest is that you almost never want to compare two floating point numbers for equality (or inequality). You'll want to use greater than/less than comparisons instead.
*The more operations you do on a floating point number, the more significant rounding errors can become.
*Precision is limited by the size of the fraction, so you may not be able to correctly add numbers that are separated by several orders of magnitude. (For example, you won't be able to add 1E-30 to 1E30.)
A: This article entitled "IEEE Standard 754 Floating Point Numbers" may be helpful. To be honest I'm not completely sure I'm understanding your question so I'm not sure that this is going to be helpful but I hope it will be.
A: Yes there is the IEEE Standard for Binary Floating-Point Arithmetic (IEEE 754)
The number is split into three parts, sign, exponent and fraction, when stored in binary.
A: If you're really worried about floating point rounding errors, most languages offer data types that don't have floating point errors. SQL Server has the Decimal and Money data types. .Net has the Decimal data type. They aren't infinite precision like BigDecimal in Java, but they are precise down to the number of decimal points they are defined for. So you don't have to worry about a dollar value you type in as $4.58 getting saved as a floating point value of 4.579999999999997
A: What I remember is a 32 bit floating point is stored using 24 bits for a actual number, and the remain 8 bits are used as a power of 10, determining where the decimal point is.
I'm a bit rusty on the subject tho...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: Race Condition Analysers for .NET I've seen there are some race condition analysis tools for C++, C and Java. Anyone know of any static analysis tools that do the same for .NET?
A: I haven't ever used this tool, but it looks like TypeMock has a tool called Racer that can handle this. Roy Osherove blogged about it here. Another post with a better preview is here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Right Align Numeric Data in SQL Server We all know T-SQL's string manipulation capabilities sometimes leaves much to be desired...
I have a numeric field that needs to be output in T-SQL as a right-aligned text column. Example:
Value
----------
143.55
3532.13
1.75
How would you go about that? A good solution ought to be clear and compact, but remember there is such a thing as "too clever".
I agree this is the wrong place to do this, but sometimes we're stuck by forces outside our control.
Thank you.
A: The STR function has an optional length argument as well as a number-of-decimals one.
SELECT STR(123.45, 6, 1)
------
123.5
(1 row(s) affected)
A: If you MUST do this in SQL you can use the folowing code (This code assumes that you have no numerics that are bigger than 40 chars):
SELECT REPLICATE(' ', 40 - LEN(CAST(numColumn as varchar(40)))) +
CAST(numColumn AS varchar(40)) FROM YourTable
A: The easiest way is to pad left:
CREATE FUNCTION PadLeft(@PadString nvarchar(100), @PadLength int)
RETURNS nvarchar(200)
AS
begin
return replicate(' ',@padlength-len(@PadString)) + @PadString
end
go
print dbo.PadLeft('123.456', 20)
print dbo.PadLeft('1.23', 20)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Is it possible to programmatically push files to a wireless SD card? Is it possible to programmatically push files to a wireless SD card - like a www.eye.fi card?
I use a Mac and thought I could do this using some AppleScript - but have not found a way...
Derek
A: The eye-fi card relies on image files being written to a specific directory in the card before they'll transfer them. Beyond that it works exactly like a memory card.
Write a file to it as if you're writing a regular memory card, and as long as it's a jpg image file of reasonable size, and in an appropriate directory (something under \DCIM\ probably) and they should transfer.
If you're having trouble, double check that it works with your camera, and find out where your camera puts the images on the card, and duplicate that. You might even try naming them similar names to the types of images your camera produces.
-Adam
A: It looks like you can treat it just like an external hard drive (plug the memory card in and figure out where the mount point is).
A: I think he wants to send files to it while its in another device, not plug it in and use it to transmit files like an antena directly connected to the machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: EasyMock: How do I create a mock of a genericized class without a warning? The code
private SomeClass<Integer> someClass;
someClass = EasyMock.createMock(SomeClass.class);
gives me a warning "Type safety: The expression of type SomeClass needs unchecked conversion to conform to SomeClass<Integer>".
A: AFAIK, you can't avoid the unchecked warning when a class name literal is involved, and the SuppressWarnings annotation is the only way to handle this.
Note that it is good form to narrow the scope of the SuppressWarnings annotation as much as possible. You can apply this annotation to a single local variable assignment:
public void testSomething() {
@SuppressWarnings("unchecked")
Foo<Integer> foo = EasyMock.createMock(Foo.class);
// Rest of test method may still expose other warnings
}
or use a helper method:
@SuppressWarnings("unchecked")
private static <T> Foo<T> createFooMock() {
return (Foo<T>)EasyMock.createMock(Foo.class);
}
public void testSomething() {
Foo<String> foo = createFooMock();
// Rest of test method may still expose other warnings
}
A: The two obvious routes are to suppress the warning or mock a subclass.
private static class SomeClass_Integer extends SomeClass<Integer>();
private SomeClass<Integer> someClass;
...
someClass = EasyMock.createMock(SomeClass_Integer.class);
(Disclaimer: Not even attempted to compile this code, nor have I used EasyMock.)
A: You can annotate the test method with @SuppressWarnings("unchecked"). I agree this is some what of a hack but in my opinion it's acceptable on test code.
@Test
@SuppressWarnings("unchecked")
public void someTest() {
SomeClass<Integer> someClass = EasyMock.createMock(SomeClass.class);
}
A: I worked around this problem by introducing a subclass, e.g.
private abstract class MySpecialString implements MySpecial<String>{};
Then create a mock of that abstract class:
MySpecial<String> myMock = createControl().createMock(MySpecialString.class);
A: I know this goes against the question, but why not create a List rather than a Mock List?
It's less code and easier to work with, for instance if you want to add items to the list.
MyItem myItem = createMock(myItem.class);
List<MyItem> myItemList = new ArrayList<MyItem>();
myItemList.add(myItem);
Instead of
MyItem myItem = createMock(myItem.class);
@SuppressWarnings("unchecked")
List<MyItem> myItemList = createMock(ArrayList.class);
expect(myItemList.get(0)).andReturn(myItem);
replay(myItemList);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Trouble with scrolling a UIScrollBar component within a class I'm trying to attach an instance of UIScrollbar component to a dynamic text field inside of an instance of a class that is being made after some XML is loaded. The scroll bar component is getting properly attached, as the size of the slider varies depending on the amount of content in the text field, however, it won't scroll.
Here's the code:
function xmlLoaded(evt:Event):void
{
//do some stuff
for(var i:int = 0; i < numProfiles; i++)
{
var thisProfile:profile = new profile();
thisProfile.alpha = 0;
thisProfile.x = 0;
thisProfile.y = 0;
thisProfile.name = "profile" + i;
profilecontainer.addChild(thisProfile);
thisProfile.profiletextholder.profilename.htmlText = profiles[i].attribute("name");
thisProfile.profiletextholder.profiletext.htmlText = profiles[i].profiletext;
//add scroll bar
var vScrollBar:UIScrollBar = new UIScrollBar();
vScrollBar.direction = ScrollBarDirection.VERTICAL;
vScrollBar.move(thisProfile.profiletextholder.profiletext.x + thisProfile.profiletextholder.profiletext.width, thisProfile.profiletextholder.profiletext.y);
vScrollBar.height = thisProfile.profiletextholder.profiletext.height;
vScrollBar.scrollTarget = thisProfile.profiletextholder.profiletext;
vScrollBar.name = "scrollbar";
vScrollBar.update();
vScrollBar.visible = (thisProfile.profiletextholder.profiletext.maxScrollV > 1);
thisProfile.profiletextholder.addChild(vScrollBar);
//do some more stuff
}
}
I've also tried it with a UIScrollBar component within the movieclip/class itself, and it still doesn't work. Any ideas?
A: You might try adding the scrollbar once your textfield is initialized from a separate function similar to this:
private function assignScrollBar(tf:TextField, sb:UIScrollBar):void {
trace("assigning scrollbar");
sb.move(tf.x + tf.width, tf.y);
sb.setSize(15, tf.height);
sb.direction = ScrollBarDirection.VERTICAL;
sb.scrollTarget = tf;
addChild(sb);
sb.update();
}
That is how I currently doing it.
A: Have you tried putting the UI scrollbar onto the stage, binding it to the textfield at design time, and then calling update() during the loaded event?
I have had some interesting experiences in the past with dynamically creating UIScrollbars at runtime.
A: In your first example have you tried putting the
vScrollBar.update();
statement after the
addChild(vScollbar);
?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Keyword for the outer class from an anonymous inner class In the following snippet:
public class a {
public void otherMethod(){}
public void doStuff(String str, InnerClass b){}
public void method(a){
doStuff("asd",
new InnerClass(){
public void innerMethod(){
otherMethod();
}
}
);
}
}
Is there a keyword to refer to the outer class from the inner class? Basically what I want to do is outer.otherMethod(), or something of the like, but can't seem to find anything.
A: OuterClassName.this.outerClassMethod();
A: In general you use OuterClassName.this to refer to the enclosing instance of the outer class.
In your example that would be a.this.otherMethod()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "215"
} |
Q: What is the best way to send large batches of emails in ASP.NET? I'm currently looping through a datareader and calling the System.Net.Mail.SmtpClient's Send() method. The problem with this is that it's slow. Each email takes about 5-10 seconds to send (it's possible this is just an issue with my host). I had to override the executionTimeout default in my web.config file (it defaults to 90 seconds) like this:
<httpRuntime executionTimeout="3000" />
One caveat: I'm on a shared host, so I don't think it is possible for me to send using the PickupDirectoryFromIis option (at least, it gave me errors when I turned it on).
A: You could send the mail asynchronous. That way the timeout should not interrupt your sending.
This article should help you get started with that: Sending Emails Asynchronously in C#.
There is another approach here: http://www.vikramlakhotia.com/Sending_Email_asynchronously_in_AspNet_20.aspx
And off course there are several commercial clients available, but the only one that i have tried and can recommend is http://www.aspnetemail.com/
A: Definitely spawn it off on a background worker process so they go out asynchronously.
BTW, 5-10 seconds per e-mail seems way slow to me. On my server it takes just fractions of a second per e-mail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Which is the best database schema for my navigation? I'm creating a web site where all pages hang off a database-driven tree-hierarchy.
All but one node has a parent node. Nodes may have role-based read permissions. Some nodes may have special rules (such as: don't display within navigation menus).
Nodes may represent links to other nodes (like a shortcut in Windows). Nodes typically represent pages.
Pages present either HTML content or execute programming. Some pages may be roots of subtrees (alternate masterpages and stylesheets).
Please help me setup my nodes database in Microsoft SQL Server for use by Linq to SQL.
I've got three ideas:
*
*Many lightweight tables with almost
zero nullalbe fields.
*Heavyweight Node table with lots of
nullalbe fields.
*Best (or worst) of both: Lots of
nullalbe foreign keys to many
lightweight tables.
Which do you feel best represents the data? Which will be easiest to use with Linq to SQL?
How can I keep my data integrity rules within the database? How do I best enforce them within my programming?
*
*Nodes must be either (but not both)
links or pages.
*Pages must be either (but not both) html or code.
*Links may not be roots, html, nor code.
Can I make an ASP.NET Site Map Provider with such a structure? Should I?
Update: I've asked a more general question:
What’s the best way to handle one-to-one relationships in SQL?
Related question:
How do I enforce data integrity rules in my database?
A: My initial impression after reading your post is that I would be very averse to let any one technology (in this case linq) heavily influence the database schema design to the extent you seem to be suggesting.
I think your schema should be pretty much the same, regardless of what technology you then chose to build your business/presentation layers.
I hope I haven't misunderstood you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to access a PCMCIA modem's serial number? A Sprint cellular modem plugs into a laptop - often the PCMCIA slot. To connect, the user opens a program called the Connection Manager. This program has a menu option to display the serial number and phone number of the modem that's currently inserted.
Does that imply that the serial/phone number of the modem could be available to other programs running on the system? (Note: let's assume this is Windows XP.)
Specifically, could a company's VPN software be configured to pass along information about which modem is being used to connect?
Finally, is there existing VPN software that already does this, or would it have to be custom-programmed?
A: Sometimes you can get the modem's serial number using the AT command set. To see this in action, go to your control panel and open up Phone and Modem Options. Select the Modems tab, select the modem you're interested in, and choose Properties.
In the modem window, select the Diagnostics tab, and press the Query Modem button.
This opens the serial port and sends a series of AT commands to gather various settings and information. You can open the serial port in your program (or a terminal program), send the AT command, and get the same information back.
You may need to check your specific modem's AT command set to find where the serial number is stored, or use a serial port spy program to see how Sprint's program does it.
I'm not aware of any VPNs that use this information, and I can think of several ways to spoof it, since communications between the modem and the computer are not cryptographically secure.
-Adam
A: Open hyperterminal or make a serial port connection programatically and use Hayes AT language to talk to it. Most software also has it listed in the device properties and/or diagnostics.
AT+GSN
press enter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS to make an empty cell's border appear? What CSS should I use to make a cell's border appear even if the cell is empty?
IE 7 specifically.
A: I just found the following. It's standards compliant but it doesn't work in IE. sigh.
empty-cells: show
A: I happened across this question and haven't seen any answers that really addressed the issue.
The problem results because IE7 does not see any internal content for the cell; in programming terms the cell is resulting as a null and like most things, you cannot border a null or perform any action on it. The browser needs an element/object that has a layout, in order to apply a border/layout.
Even empty <div></div> or <span></span> do not contain content, thus there is nothing to render, resulting in that null case again.
However, you can trick the browser into thinking the cell has content, by giving the empty div/span layout properties. The easiest way is to apply the CSS style zoom:1.
<table>
<tr><td>Foo</td>
<td><span style="zoom:1;"></span></td></tr>
</table>
This workaround is better than using a , since it doesn't unnecessarily mess up screen readers, and isn't misrepresenting the value of the cell. In newer browser you can use the empty-cell:<show|hide> alternative.
Note: in lieu of Tomalak's comment, it should be understood that hasLayout has nothing to do with null, it was merely a comparison of how the browser interacts and renders hasLayout similarly to how a database or programming language interacts with nulls. It is a strech, but I thought it might be easier to understand for those programmers turned web designers.
A: If I recall, the cell dosn't exist in some IE's unless it's filled with something...
If you can put a (non-breaking space) to fill the void, that will usually work. Or do you require a pure CSS solution?
Apparently, IE8 shows the cells by default, and you have to hide it with empty-cells:hide But it doesn't work at all in IE7 (which hides by default).
A: Ideally, you shouldn't have any empty cells in a table. Either you have a table of data, and there's no data in that specific cell (which you should indicate with "-", or "n/a/", or something equally appropriate, or - if you must - , as suggested), or you have a cell that needs to span a column or row, or you're trying to achieve some layout with a table that you should be using CSS for.
Can we have a bit more detail?
A: This question's old, but still a top result in Google, so I'll add what I've found:
Simply adding border-collapse: collapse to the table style fixed this problem for me in IE7 (and didn't affect the way they're displayed in FF, Chrome, etc).
Best to avoid the extraneous code of adding an or other spacing element when you can fix with CSS.
A: Another way of making sure there is data in all cells:
$(document).ready(function() {
$("td:empty").html(" ");
});
A: If you set the border-collapse property to collapse, IE7 will show empty cells. It also collapses the borders though so this might not be 100% what you want
td {
border: 1px solid red;
}
table {
border-collapse: collapse;
}
<html> <head> <title>Border-collapse Test</title> <style type="text/css"> td {
border: 1px solid red;
}
table {
border-collapse: collapse;
}
<table>
<tr>
<td></td>
<td>test</td>
<td>test</td>
</tr>
<tr>
<td>test</td>
<td></td>
<td>test</td>
</tr>
<tr>
<td>test</td>
<td></td>
<td>test</td>
</tr>
<tr>
<td>test</td>
<td></td>
<td />
</tr>
</table>
A: The question asked for a CSS solution, but on the off-chance an HTML solution will do, here is one:
Try adding these two attributes to the table element: frame="box" rules="all"
like this:
<table border="1" cellspacing="0" frame="box" rules="all">
A: I guess this can't be done with CSS;
You need to put a in every empty cell for the border to show in IE...
A: empty-cell only fixed Firefox (YES I really did have this issue in Firefox) IE 7 & 8 were still problematic..
This worked for me in both Firefox 3.6.x, IE 7 & 8, Chrome, and Safari:
==============================
table {
*border-collapse: collapse;}
.sampleTD {
empty-cells: show;}
==============================
Had to use the * to make sure the table style was only applied to the IE browser.
A: Try this if you can't use non-breakable space:
var tn = document.createTextNode('\ ');
yourContainer.appendChild(ta);
A: I create a div style that has the same font color as the background of your cell and write anything (usually a "-" "n/a" or "empty") to give the cell content. It shows up if you highlight the page, but when viewed normally looks how you want.
A: I use a mix of html and css to create cross browser table grids:
html
<table cellspacing="1" style="background-color:#000;" border="0">
css
td{background-color:#fff;}
I haven't seen any issues with any browsers so far.
A: "IE" isn't a useful term in this context anymore now that IE8 is out.
IE7 always does "empty-cells:show" (or so I'm told ... Vista).
IE8 in any of its "Quirks" or "IE7 Standards" modes always does "empty-cells:hide".
IE8 in "Standards" mode defaults to "empty-cells:show" and supports the attribute via CSS.
As far as I know, every other browser has correctly supported this for several years (I know it was added in Firefox 2).
A: I'm taking this from another website but:
.sampletable {
border-collapse: collapse;}
.sampleTD {
empty-cells: show;}
Use for the CSS for the table and TD element respectively.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "73"
} |
Q: How can I find what search terms (if any) brought a user to my site? I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.
A: You can use the "referer" part of the request that the user sent to figure out what he searched for. Example from Google:
http://www.google.no/search?q=stack%20overflow
So you must search the string (in ASP(.NET) this can be found be looking in Request.Referer) for "q=" and then URLDecode the contents.
Also, you should take a look at this article that talks more about referrers and also other methods to track your visitors:
http://www.15seconds.com/issue/021119.htm
A: This is some code to backup the idea of using a querystring method and if that's not available using the UrlReferrer property of the Request object. This can then be stashed in a session object (or somewhere else if that works better for you) so that you can track the source between pages. (Page_Load doesn't seem to be formatted correctly inside the code sample here)
public void Page_Load(Object Sender, EventArgs E) {
if (null == Session["source"] || Session["source"].ToString().Equals(string.Empty)) {
if (Request.QueryString["src"] != null) {
Session["source"] = Server.UrlDecode(Request.QueryString["src"].ToString());
} else {
if (Request.UrlReferrer != null) {
Session["source"] = Request.UrlReferrer.ToString();
} else {
Session["source"] = string.Empty;
}
}
}}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Getting Information From Master File Table on Windows I need to get some information that is contained in the MFT on a Windows machine, and I'm hoping that there is some super-secret API for getting this information. I need to be able to get to this information programmatically, and because of legal concerns I might not be able to use the tools provided by the company formally known as sysinternals.
My other option (which I really don't want to have to do) is to get the start sector of the MFT with DeviceIoControl, and manually parse through the information.
Anyway, in particular, what I really need to get out of the Master File Table is the logical sectors used to hold the data that is associated with a file.
A: There is a documented API for getting info on file positions on disk since Windows 2000. Look for DeviceIoControl function with FSCTL_GET_RETRIEVAL_POINTERS control code on MSDN:
http://msdn.microsoft.com/en-us/library/aa364572(VS.85).aspx
The API has been provided for writing custom disk defragmenters and consists of several other control codes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Best way to reduce sequences in an array of strings Please, now that I've re-written the question, and before it suffers from further fast-gun answers or premature closure by eager editors let me point out that this is not a duplicate of this question. I know how to remove duplicates from an array.
This question is about removing sequences from an array, not duplicates in the strict sense.
Consider this sequence of elements in an array;
[0] a
[1] a
[2] b
[3] c
[4] c
[5] a
[6] c
[7] d
[8] c
[9] d
In this example I want to obtain the following...
[0] a
[1] b
[2] c
[3] a
[4] c
[5] d
Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.
Further, notice that when two lines repeat they should be reduced to one set (of two lines).
[0] c
[1] d
[2] c
[3] d
...reduces to...
[0] c
[1] d
I'm coding in C# but algorithms in any language appreciated.
A: EDIT: made some changes and new suggestions
What about a sliding window...
REMOVE LENGTH 2: (no other length has other matches)
//the lower case letters are the matches
ABCBAbabaBBCbcbcbVbvBCbcbcAB
__ABCBABABABBCBCBCBVBVBCBCBCAB
REMOVE LENGTH 1 (duplicate characters):
//* denote that a string was removed to prevent continual contraction
//of the string, unless this is what you want.
ABCBA*BbC*V*BC*AB
_ABCBA*BBC*V*BC*AB
RESULT:
ABCBA*B*C*V*BC*AB == ABCBABCVBCAB
This is of course starting with length=2, increase it to L/2 and iterate down.
I'm also thinking of two other approaches:
*
*digraph - Set a stateful digraph with the data and iterate over it with the string, if a cycle is found you'll have a duplication. I'm not sure how easy it is check check for these cycles... possibly some dynamic programming, so it could be equivlent to method 2 below. I'm going to have to think about this one as well longer.
*distance matrix - using a levenstein distance matrix you might be able to detect duplication from diagonal movement (off the diagonal) with cost 0. This could indicate duplication of data. I will have to think about this more.
A: Here's C# app i wrote that solves this problem.
takes
aabccacdcd
outputs
abcacd
Probably looks pretty messy, took me a bit to get my head around the dynamic pattern length bit.
class Program
{
private static List<string> values;
private const int MAX_PATTERN_LENGTH = 4;
static void Main(string[] args)
{
values = new List<string>();
values.AddRange(new string[] { "a", "b", "c", "c", "a", "c", "d", "c", "d" });
for (int i = MAX_PATTERN_LENGTH; i > 0; i--)
{
RemoveDuplicatesOfLength(i);
}
foreach (string s in values)
{
Console.WriteLine(s);
}
}
private static void RemoveDuplicatesOfLength(int dupeLength)
{
for (int i = 0; i < values.Count; i++)
{
if (i + dupeLength > values.Count)
break;
if (i + dupeLength + dupeLength > values.Count)
break;
var patternA = values.GetRange(i, dupeLength);
var patternB = values.GetRange(i + dupeLength, dupeLength);
bool isPattern = ComparePatterns(patternA, patternB);
if (isPattern)
{
values.RemoveRange(i, dupeLength);
}
}
}
private static bool ComparePatterns(List<string> pattern, List<string> candidate)
{
for (int i = 0; i < pattern.Count; i++)
{
if (pattern[i] != candidate[i])
return false;
}
return true;
}
}
fixed the initial values to match the questions values
A: I would dump them all into your favorite Set implementation.
EDIT: Now that I understand the question, your original solution looks like the best way to do this. Just loop through the array once, keeping an array of flags to mark which elements to keep, plus a counter to keep track to the size of the new array. Then loop through again to copy all the keepers to a new array.
A: I agree that if you can just dump the strings into a Set, then that might be the easiest solution.
If you don't have access to a Set implementation for some reason, I would just sort the strings alphabetically and then go through once and remove the duplicates. How to sort them and remove duplicates from the list will depend on what language and environment you are running your code.
EDIT: Oh, ick.... I see based on your clarification that you expect that patterns might occur even over separate lines. My approach won't solve your problem. Sorry. Here is a question for you. If I had the following file.
a
a
b
c
c
a
a
b
c
c
Would you expect it to simplify to
a
b
c
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Where should cross-platform apps keep their data? I'm building an application that is targeting Windows, Mac and Linux soon. I was wondering where should I keep application data such as settings, etc.
Application's installation folder is the easiest choice, but I think that might be a problem with new Vista security model. Besides, users might want different settings.
Is it C:\Documents and Settings\username\MyApp good for both Vista and XP?
Is it /home/username/.MyApp good for Linux and Macs?
Any ideas and/or links to best practices much appreciated.
Thanks!
Juan
A: In regards to best practices, Jeff posted an article on polluting user space that you might find useful: Don't Pollute User Space
A: As a general point, I'd recommend abstracting the implementation of your settings into a 'Settings Provider' and provide different providers for each platform. That way, you can implement the storage of the settings in the manner that best suits the target platforms (for example, a file on Linux or the Windows Registry).
Don't simply adopt the 'lowest common denominator'. Where you have content that must be explicity stored in files, have your settings provider expose the platform-specific location for those files.
A: I'm not :)
I'm using USERPROFILE in Windows and HOME in Mac/Linux. But even so, I need to know that those are the right places.
Thanks!
A: In windows you need to go another level deep than just the user profile. Use the Application Data folder.
A: On Windows I use APPDATA,and on Linux I use HOME.
A: For Linux/BSD/Solaris:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
A: Each platform has its own API for finding the user's home folder, or documents folder, or preferences folder.
*
*Windows: SHGetFolderPath() or SHGetKnownFolderPath()
*Mac OS X and iPhone OS: NSSearchPathForDirectoriesInDomains()
*Unix: $HOME environment variable
Don't hardcode specific paths or just tack a prefix and suffix on the user's name. Also, try to follow whatever conventions there are for the platform for naming the files.
A: Never, ever store user data in the application folder. It's just a bad idea.
Most operating systems have a $HOME (or %HOME%) environment variable. That would be the first place to look.
If you want to cleanly support multiple operating systems, though, you're going to have to have some OS-specific code for each that figures out exactly where things need to go. (~/Library for Mac OS, ~/.config for GNOME-based systems, %HOME%/Application Data for Windows, etc.).
A: What language are you planning to use? Java, for example, has a dedicated Preference API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.