text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Best way to set the permissions for a specific user on a specific folder on a remote machine? We have a deployment system at my office where we can automatically deploy a given build of our code to a specified dev environment (dev01, dev02, etc.).
These dev environments are generalized virtual machines, so our system has to configure them automatically. We have a new system requirement with our next version; we need to give certain user accounts read/write access to certain folders (specifically, giving the ASPNET user read/write to a logging folder).
I'm pretty sure we could do this with WMI or scripts (we use Sysinternals PSTools in a few places for deployment), but I'm not sure what is the best way to do it. The deployment system is written in C# 2.0, the dev environment is a VM with Windows XP. The VM is on the same domain as the deployment system and I have administrator access.
Edit: There's not really a right answer for this, so I'm hesitant to mark an answer as accepted.
A: Another option would be to investigate using a Powershell script There are a lot powershell community snap ins to support VMs and active directory.
Active Directory Script Rescources
Powershell Script Library
Microsoft Script Resources
VMWARE VI Toolkit (for Windows)
A: If you can run scripts, it might be as simple as runing the CACLS command on the VM. Perhaps just have your deployment script read in a config and run the appropriate CACLs commands.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Mapping collections with LINQ I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?
A: var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}
A: I don't think that you can using pure LINQ. However, if you're doing this sort of thing a lot in your code you may be able to make this work with reflection.
A: Why do you want to add the extra property? Or, put a different way, what do you intend to do with the property once you have it in your new IEnumerable source?
If you need it for data binding, I have a helper class that might help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Good ways to improve jQuery selector performance? I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this:
Is $("div.myclass") faster than $(".myclass")
I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance?
A: In order to fully comprehend what is faster, you have to understand how the CSS parser works.
The selector you pass in gets split into recognizable parts using RegExp and then processed piece by piece.
Some selectors like ID and TagName, use browser's native implementation which is faster. While others like class and attributes are programmed in separately and therefore are much slower, requiring looping through selected elements and checking each and every class name.
So yes to answer your question:
$('tag.class') is faster than just $('.class'). Why?
With the first case, jQuery uses the native browser implementation to filter the selection down to just the elements you need. Only then it launches the slower .class implementation filtering down to what you asked for.
In the second case, jQuery uses it's method to filter each and every element by grabbing class.
This spreads further than jQuery as all javascript libraries are based on this. The only other option is using xPath but it is currently not very well supported among all browsers.
A: As Reid stated above jQuery is working from the bottom up. Although
that means $('#foo bar div') is a
lot slower than $('bar div #foo')
That's not the point. If you had #foo you wouldn't put anything before it in the selector anyway since IDs have to be unique.
The point is:
*
*if you are subselecting anything from an element with an ID then select the later first and then use .find, .children etc.: $('#foo').find('div')
*your leftmost (first) part of the selector can be less efficient scaling to the rightmost (last) part which should be the most efficient - meaning if you don't have an ID make sure you are looking for $('div.common[slow*=Search] input.rare') rather than $('div.rare input.common[name*=slowSearch]') - since this isn't always applicable make sure to force the selector-order by splitting accordingly.
A: Here is how to icrease performance of your jQuery selectors:
*
*Select by #id whenever possible (performance test results ~250 faster)
*Specify scope of your selections ($('.select', this))
A: There is no doubt that filtering by tag name first is much faster than filtering by classname.
This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.
A: I'll add a note that in 99% of web apps, even ajax heavy apps, the connection speed and response of the web server is going to drive the performance of your app rather than the javascript. I'm not saying the you should write intentionally slow code or that generally being aware of what things are likely to be faster than others isn't good.
But I am wondering if you're trying to solve a problem that doesn't really exist yet, or even if you're optimizing for something that might change in the near future (say, if more people start using a browser that supports getElementsByClassName() function referred to earlier), making your optimized code actually run slower.
A: Another place to look for performance information is Hugo Vidal Teixeira's Performance analysis of selectors page.
http://www.componenthouse.com/article-19
This gives a good run down of speeds for selector by id, selector by class, and selector prefixing tag name.
The fastest selectors by id was: $("#id")
The fastest selector by class was: $('tag.class')
So prefixing by tag only helped when selecting by class!
A: In some cases, you can speed up a query by limiting its context. If you have an element reference, you can pass it as the second argument to limit the scope of the query:
$(".myclass", a_DOM_element);
should be faster than
$(".myclass");
if you already have a_DOM_element and it's significantly smaller than the whole document.
A: I've been on some of the jQuery mailing lists and from what I've read there, they most likely filter by tag name then class name (or vice versa if it was faster). They are obsessive about speed and would use anything to gain a smidgen of performance.
I really wouldn't worry about it too much anyway unless you are running that selector thousands of times/sec.
If you are really concerned, try doing some benchmarking and see which is faster.
A: Consider using Oliver Steele's Sequentially library to call methods over time instead of all at once.
http://osteele.com/sources/javascript/sequentially/
The "eventually" method helps you call a method after a certain period of time from its initial call. The "sequentially" method lets you queue several tasks over a period of time.
Very helpful!
A: A great tip from a question I asked: Use standard CSS selectors wherever possible. This allows jQuery to use the Selectors API. According to tests performed by John Resig, this results in near-native performance for selectors. Functions such as :has() and :contains() should be avoided.
From my research support for the Selectors API was introduced with jQuery 1.2.7, Firefox 3.1, IE 8, Opera 10, Safari 3.1.
A: If I am not mistaken, jQuery also is a bottom up engine. That means $('#foo bar div') is a lot slower than $('bar div #foo'). For example, $('#foo a') will go through all of the a elements on the page and see if they have an ancestor of #foo, which makes this selector immensely inefficient.
Resig may have already optimized for this scenario (it wouldn't surprise me if he did - I believe he did in his Sizzle engine, but I am not 100% certain.)
A: I believe that selecting by ID first is always faster:
$("#myform th").css("color","red");
should be faster than
$("th").css("color","red");
However, I wonder how much chaining helps when starting with the ID? Is this
$("#myform").find("th").css("color","red")
.end().find("td").css("color","blue");
any faster than this?
$("#myform th").css("color","red");
$("#myform td").css("color","blue");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
} |
Q: How to determine if user selected a file for file upload? If I have a
<input id="uploadFile" type="file" />
tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.
In FF, I just do:
var selected = document.getElementById("uploadBox").files.length > 0;
But that doesn't work in IE.
A: var nme = document.getElementById("uploadFile");
if(nme.value.length < 4) {
alert('Must Select any of your photo for upload!');
nme.focus();
return false;
}
A: function validateAndUpload(input){
var URL = window.URL || window.webkitURL;
var file = input.files[0];
if (file) {
var image = new Image();
image.onload = function() {
if (this.width) {
console.log('Image has width, I think it is real image');
//TODO: upload to backend
}
};
image.src = URL.createObjectURL(file);
}
};
<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
Call this function on change .
A: You can use:
var files = uploadFile.files;
if (files.length == 0) { console.log(true) } else { console.log(false) }
if (files[0] == undefined) { console.log(true) } else { console.log(false) }
if (files[0] == null) { console.log(true) } else { console.log(false) }
All three give the same result.
A: This works in IE (and FF, I believe):
if(document.getElementById("uploadBox").value != "") {
// you have a file
}
A: The accepted answer is correct to check with "ID"
But, those who are here to check file with class-name,
here is the code:
var elements = document.getElementsByClassName('uploadFile_ClassName');
for (var i = 0; i < elements.length; ++i) {
if(elements[i].value != "") {
// file is selected here;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
} |
Q: iPhone app crashing with NSUnknownKeyException setValue:forUndefinedKey: I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging.
Essentially my app displays an image and when touched plays a short sound.
When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes.
I get the following error:
Application Specific Information:
iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)
*** Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value
coding-compliant for the key kramerImage.'
kramerImage here is the image I'm using for the background.
I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key.
A: Here's one where you'll get this error - and how to fix it. I was getting it when loading a nib that just had a custom TableViewCell. I used IB to build a xib that just had the File's Owner, First Responder, and the TableViewCell. The TableViewCell just had 4 UILabels which matched up to a class with 4 IBOutlet UILabels called rootCell. I changed the class of the TableViewCell to be rootCell. It worked fine until a made a couple of changes and suddenly I was getting the setValue:forUndefinedKey: when I was just instantiating the class after loading it from a nib:
NSArray * nib = [[NSBundle mainBundle] loadNibNamed:@"rootCell-iPad" owner:self options:nil];
cell = [nib objectAtIndex:0];
It failed at the first line, when the nib was trying to load. After a while, I noticed that it was trying to match the IBOutlet Labels to the root controller, NOT the rootCell class! That was my tipoff. What I did wrong was to inadvertently change the File's Owner to rootCell class. When I changed it back to NSObject, then it didn't try to match up to the delegate (rootController) when loading. So, if you're doing the above, make File's Owner an NSObject, but make the UITableCell your desired class.
A: (This isn't really iPhone specific - the same thing will happen in regular Cocoa).
NSUnknownKeyException is a common error when using Key-Value Coding to access a key that the object doesn't have.
The properties of most Cocoa objects can be accessing directly:
[@"hello world" length] // Objective-C 1.0
@"hello world".length // Objective-C 2.0
Or via Key-Value Coding:
[@"hello world" valueForKey:@"length"]
I would get an NSUnknownKeyException if I used the following line:
[@"hello world" valueForKey:@"purpleMonkeyDishwasher"]
because NSString does not have a property (key) called 'purpleMonkeyDishwasher'.
Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib.
Find where 'kramerImage' is being used, and try to track it down from there.
A: I had this same problem today. I didn't have the right class specified for the View Controller in my Navigation Controller. This will happen often if you fail to specify the correct class for your views in Interface Builder.
You'll also get invalid selector issues as well. Always check your Interface Builder classes and connections!
A: I had this situation and it turns out even after finding all instances of the variable and deleting them my app still crashed. Heres what happened... I created another instance of a variable from a textfield from my XIB into my viewController.h but I realized I didnt need it anymore and deleted it. It turns out my program saw that and kept trying to use it in the program so in the future if this happens to anywhere else just go into you XIB right-click on the button or textfield etc and delete any extra unused variables.
A: This is how i solved mine, in Interface builder right-click the View Controller, there should be an exclamation mark on the missing outlet or action method. Find and remove all the references and that solved it.
This happened because i deleted the action method in the .m file.
A: Also when you rename a view, don't forget to delete the reference on File's Owner. It may also raise this error.
A: It seems you are doing
@interface MyFirstIphoneAppViewController : UIViewController<> {
UIImageView *InitialkramerImage;
}
@property(nonatomic,retain) IBOutlet UIImageView *InitialkramerImage;
Then after synthesizing that imageview, When you open "MyFirstIphoneAppViewController.xib" in Interface Builder, you are taking an Image View from Tool(menu)/Library den linking that outlet to the 'InitialkramerImage' from the Files Owner of "MyFirstIphoneAppViewController.xib". Then you saved the project. But after that you might change the name of the outlet variable "InitialkramerImage" to "kramerImage". So, after doing this
@interface MyFirstIphoneAppViewController : UIViewController<> {
UIImageView *kramerImage;
}
@property(nonatomic,retain) IBOutlet UIImageView *kramerImage;
and saving the project when you run it, There is no existance of the outlet of "InitialkramerImage" in the "MyFirstIphoneAppViewController.xib". So, when you run the project there will be no outlet referencing from Imageview to the 'kramerImage' and
"For displaying the view,
UIViewController will try to find the
outlet to "InitialkramerImage" which
is not existing."
So, It will throw the "NSUnknownKeyException".
You can check the missing outlet by
opening the nib(.xib) file then right
clicking on the 'Files Owner' of that.
A: If you have done this code somewhere else and had a zip/compressed file, try to extract it again. It may work I dont know why but I feel like it is an extraction issue.
or you can try to change the IBOutlet to kramerImage and bind it again in NIB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to generate a verification code/number? I'm working on an application where users have to make a call and type a verification number with the keypad of their phone.
I would like to be able to detect if the number they type is correct or not. The phone system does not have access to a list of valid numbers, but instead, it will validate the number against an algorithm (like a credit card number).
Here are some of the requirements :
*
*It must be difficult to type a valid random code
*It must be difficult to have a valid code if I make a typo (transposition of digits, wrong digit)
*I must have a reasonable number of possible combinations (let's say 1M)
*The code must be as short as possible, to avoid errors from the user
Given these requirements, how would you generate such a number?
EDIT :
@Haaked: The code has to be numerical because the user types it with its phone.
@matt b: On the first step, the code is displayed on a Web page, the second step is to call and type in the code. I don't know the user's phone number.
Followup : I've found several algorithms to check the validity of numbers (See this interesting Google Code project : checkDigits).
A: For 1M combinations you'll need 6 digits. To make sure that there aren't any accidentally valid codes, I suggest 9 digits with a 1/1000 chance that a random code works. I'd also suggest using another digit (10 total) to perform an integrity check. As far as distribution patterns, random will suffice and the check digit will ensure that a single error will not result in a correct code.
Edit: Apparently I didn't fully read your request. Using a credit card number, you could perform a hash on it (MD5 or SHA1 or something similar). You then truncate at an appropriate spot (for example 9 characters) and convert to base 10. Then you add the check digit(s) and this should more or less work for your purposes.
A: After some research, I think I'll go with the ISO 7064 Mod 97,10 formula. It seems pretty solid as it is used to validate IBAN (International Bank Account Number).
The formula is very simple:
*
*Take a number : 123456
*Apply the following formula to obtain the 2 digits checksum : mod(98 - mod(number * 100, 97), 97) => 76
*Concat number and checksum to obtain the code => 12345676
*To validate a code, verify that mod(code, 97) == 1
Test :
*
*mod(12345676, 97) = 1 => GOOD
*mod(21345676, 97) = 50 => BAD !
*mod(12345678, 97) = 10 => BAD !
Apparently, this algorithm catches most of the errors.
Another interesting option was the Verhoeff algorithm. It has only one verification digit and is more difficult to implement (compared to the simple formula above).
A: You want to segment your code. Part of it should be a 16-bit CRC of the rest of the code.
If all you want is a verification number then just use a sequence number (assuming you have a single point of generation). That way you know you are not getting duplicates.
Then you prefix the sequence with a CRC-16 of that sequence number AND some private key. You can use anything for the private key, as long as you keep it private. Make it something big, at least a GUID, but it could be the text to War and Peace from project Gutenberg. Just needs to be secret and constant. Having a private key prevents people from being able to forge a key, but using a 16 bit CR makes it easier to break.
To validate you just split the number into its two parts, and then take a CRC-16 of the sequence number and the private key.
If you want to obscure the sequential portion more, then split the CRC in two parts. Put 3 digits at the front and 2 at the back of the sequence (zero pad so the length of the CRC is consistent).
This method allows you to start with smaller keys too. The first 10 keys will be 6 digits.
A: Does it have to be only numbers? You could create a random number between 1 and 1M (I'd suggest even higher though) and then Base32 encode it. The next thing you need to do is Hash that value (using a secret salt value) and base32 encode the hash. Then append the two strings together, perhaps separated by the dash.
That way, you can verify the incoming code algorithmically. You just take the left side of the code, hash it using your secret salt, and compare that value to the right side of the code.
A:
*
*I must have a reasonnable number of possible combinations (let's say 1M)
*The code must be as short as possible, to avoid errors from the user
Well, if you want it to have at least one million combinations, then you need at least six digits. Is that short enough?
A: When you are creating the verification code, do you have access to the caller's phone number?
If so I would use the caller's phone number and run it through some sort of hashing function so that you can guarantee that the verification code you gave to the caller in step 1 is the same one that they are entering in step 2 (to make sure they aren't using a friend's validation code or they simply made a very lucky guess).
About the hashing, I'm not sure if it's possible to take a 10 digit number and come out with a hash result that would be < 10 digits (I guess you'd have to live with a certain amount of collision) but I think this would help ensure the user is who they say they are.
Of course this won't work if the phone number used in step 1 is different than the one they are calling from in step 2.
A: Assuming you already know how to detect which key the user hit, this should be doable reasonably easily. In the security world, there is the notion of a "one time" password. This is sometimes referred to as a "disposable password." Normally these are restricted to the (easily typable) ASCII values. So, [a-zA-z0-9] and a bunch of easily typable symbols. like comma, period, semi colon, and parenthesis. In your case, though, you'd probably want to limit the range to [0-9] and possibly include * and #.
I am unable to explain all the technical details of how these one-time codes are generated (or work) adequately. There is some intermediate math behind it, which I'd butcher without first reviewing it myself. Suffice it to say that you use an algorithm to generate a stream of one time passwords. No matter how mnay previous codes you know, the subsequent one should be impossibel to guess! In your case, you'll simply use each password on the list as the user's random code.
Rather than fail at explaining the details of the implementation myself, I'll direct you to a 9 page article where you can read up on it youself: https://www.grc.com/ppp.htm
A: It sounds like you have the unspoken requirement that it must be quickly determined, via algorithm, that the code is valid. This would rule out you simply handing out a list of one time pad numbers.
There are several ways people have done this in the past.
*
*Make a public key and private key. Encode the numbers 0-999,999 using the private key, and hand out the results. You'll need to throw in some random numbers to make the result come out to the longer version, and you'll have to convert the result from base 64 to base 10. When you get a number entered, convert it back to base64, apply the private key, and see if the intereting numbers are under 1,000,000 (discard the random numbers).
*Use a reversible hash function
*Use the first million numbers from a PRN seeded at a specific value. The "checking" function can get the seed, and know that the next million values are good. It can either generate them each time and check one by one when a code is received, or on program startup store them all in a table, sorted, and then use binary search (maximum of compares) since one million integers is not a whole lot of space.
There are a bunch of other options, but these are common and easy to implement.
-Adam
A: You linked to the check digits project, and using the "encode" function seems like a good solution. It says:
encode may throw an exception if 'bad' data (e.g. non-numeric) is passed to it, while verify only returns true or false. The idea here is that encode normally gets it's data from 'trusted' internal sources (a database key for instance), so it should be pretty usual, in fact, exceptional that bad data is being passed in.
So it sounds like you could pass the encode function a database key (5 digits, for instance) and you could get a number out that would meet your requirements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: Is there a way I can have a VM gain access to my computer? I would like to have a VM to look at how applications appear and to develop OS-specific applications, however, I want to keep all my code on my Windows machine so if I decide to nuke a VM or anything like that, it's all still there.
If it matters, I'm using VirtualBox.
A: This is usually handled with network shares. Share your code folder from your host machine and access it from the VMs.
A: Aside from network shares, another tool to use for this is a version-control system.
A: You should always be able make a normal network connection between the VM and the hosting OS, as though it were another computer on the same network. Which, in some sense, it is.
A: I do this all the time.
I have a directory in a Windows drive that I mount in my host ubuntu 12.04.
I run virtualbox ubuntu 13.04 as a guest.
I want the guest to mount the Windows directory with full non-root permissions.
I do almost all my work from a bash shell, so this method is natural for me.
When searching for methods to automatically mount virtualbox shared folders,
reliable and correct methods are hard to distinguish from those that fail.
Failures include getting and setting permissions, as well as other problems.
Methods that fail include:
*
*modifying /etc/fstab
*modifying /etc/rc.local
I am fairly certain that rc.local can be used,
but no methods I have tried worked.
I welcome improvements on these guidelines.
On virtualbox 4.2.14 running nautilus (bash terminal) on an ubuntu 13.04 guest,
Below is a working method to mount Common (sharename)
on /home/$USER/Desktop/Common (mountpoint) with full permissions.
(Note the ‘\’ command continuation character in the find command.)
First time only: create your mountpoint, modify your .bashrc file, and run it.
Respond with password when requested.
These are the four command-lines needed:
mkdir $HOME/Desktop/Common
sudo echo “$USER ALL=(ALL) NOPASSWD:ALL” >> /etc/sudoers
find $HOME/Desktop/Common -maxdepth 0 -type d -empty -exec sudo \
mount -t vboxsf -o \
uid=`id -u $USER`,gid=`id -g $USER` Common $HOME/Desktop/Common \;
source ~/.bashrc # Needed if you want to mount Common in this bash.
All other times: simply launch a bash shell.
The find command mounts the shared directory if the mountpoint directory is empty.
If the mountpoint directory is not empty, it does not run the mount command.
I hope this is error-free and sufficiently general.
Please let me know of corrections and improvements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Test Driven Development in PHP I am a web-developer working in PHP. I have some limited experience with using Test Driven Development in C# desktop applications. In that case we used nUnit for the unit testing framework.
I would like to start using TDD in new projects but I'm really not sure where to begin.
What recommendations do you have for a PHP-based unit testing framework and what are some good resources for someone who is pretty new to the TDD concept?
A: PHPUnit is a standard, but it's sometimes also overwhelming, so if you find it too complex, check out phpt to get you started. It's very, very easy to write tests in it. A no brainer for any programmer.
And to answer your TDD question - I am not sure if TDD is widley used in the PHP space. I can see that rapid application development and TDD somewhat clash (strictly IMHO). TDD requires you to have the complete picture of what you build and you write your tests up front and then implement the code to make the test pass.
So for example what we do instead, is to write a lot of tests when we are done. This is not always the best approach because you sometimes end up with bogus tests that pass, but are not really useful but at least it's something you can expand on. Internally we continue on tests and basically write a test for each bug we find. This is how it becomes more solid.
A: I've used both PHPUnit & SimpleTest and I found SimpleTest to be easier to use.
As far as TDD goes, I haven't had much luck with it in the purest sense. I think that's mainly a time/discipline issue on my part though.
Adding tests after the fact has been somewhat useful but my favorite things to do is use write SimpleTest tests that test for specific bugs that I have to fix. That makes it very easy to verify that things are actually fixed and stay fixed.
A: I personally prefer SimpleTest. There is a command line test runner and web-based test runner, and there is even an Eclipse plugin to let you run unit tests from the IDE itself. I found the Zend to PHPUnit connection much harder to get working, especially with the debugger.
The way we use SimpleTest in-house is with a continuous integration script that we wrote ourselves. Every time we check in a feature to SVN we include the unit tests. Every hour or so, the CI script runs and calls a command line PHP script that runs all of our unit tests. If any break, I get an email. It's been a great way to reduce bugs in our systems.
However, you can just as easily use something like Phing to run your tests automatically, either on a cron job or with an SVN check-in hook.
In fact, if you want to contact me directly for further help, you can get to me through my profile info on SO. I'd love to help you out.
A: SimpleTest is a great system. I started out with it about 5 months ago, having never heard of TDD, and SimpleTest is easy to learn but still powerful. As for resources, I'm currently reading TDD By Example by Kent Beck, and it's good.
A: I highly recommend Test-Driven Development by Kent Beck (ISBN-10: 0321146530). It wasn't written specifically for PHP, but the concepts are there and should be easily translatable to PHP.
A: You should look into PHPUnit, it looks pretty much like nUnit.
A: Another modern tool you should look it is Codeception. It is much simplier then PHPUnit and incorporates scenario-driven approach, which is quite useful for generating documentation from tests.
A: Test driven development is an approach where tests are always written before code.
You should learn to PHPUNIT first in order to start TDD Development. Then while making your function you should always think how function can fail and write test case in phpunit and in the end you should write code in order to pass your test. Its will be a new approach so it will be little difficult in the beginning but once you get use to it, you will find it very useful specially for after development bugs and coding style. You can go through this Step By Step guide for understanding this concept.
Always Remember if test are written after development they are useless. So TDD is must if you are thinking to write unit tesst
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Passing large files to WCF service We have an encryption service that we've exposed over net. tcp. Most of the time, the service is used to encrypt/decrypt strings. However, every now and then, we the need to encrypt large documents (pdf, JPG, bmp, etc.).
What are the best endpoint settings for a scenario like this? Should I accept/return a stream? I've read a lot about this, but no one gives guidance on what to do when the large file doesn't occur frequently.
A: MSDN describes how to enable streaming over WCF rather well.
Note, if the link between client and server needs to be encrypted, then you'll need to "roll your own" encryption mechanism. The default net.tcp encryption requires X.509 certificates, which won't work with streams as this kind of encryption needs to work on an entire message in one go rather than a stream of bytes.
This, in turn, means that you won't be able to authenticate the client using the default WCF security mechanisms as authentication requires encryption. The only work-around for this that I know of is to implement your own custom behaviour extensions on client and server to handle authentication.
A really good reference on how to add custom behaviour extensions is here: this documents how to provide custom configuration, too (something that I don't think is discussed anywhere in the MSDN documents at this time).
A: One pattern you could follow is to have an asynchronous service that works on files on a shared file system location:
*
*Place the file to be encrypted on a shared location
*Call the service and tell it to encrypt the file, passing both the location and name of the file, and the addres of a callback service on the client
*The service would encrypt the file and place the encrypted copy in a shared location (the same as where the unencrypted was placed or different, doesn't matter)
*The service would call back to the client, giving the name and location of the encrypted file
*The client can retrieve the encrypted file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: web site structure/architecture What web site structure(s)/architecture(s) would the community swear by, with a narrowing down in the direction towards more of a small facebook style project?
I understand the question to be rather broad/subjective; but being relatively new to the area of web development, I find just looking at and learning from examples of working projects most times extremely helpful, and that at other times just blows my mind and changes how I construct future assignments.
With the latter paragraph in mind, does the community have any suggestions on places to look/articles to read?
A: I guess it depends on the technology you select. For web projects in general I've always employed (Web-)MVC for the past two years or so. The advantage being a clear seperation of frontend and backend in order to create a managable code base.
But that's as vague as a recommendation could be. :)
Aside from using a framework to build your site from scratch, you might also want to look into using what's already out there (in terms of open source). I'd recommend any kind of "community software" that's semi-established, well documented, not too often in the news because of security issues and offers API to extend its base. That could indeed jump start you on your facebook-esque site. ;)
A: Possibly a bit heavy for your immediate needs, but have you seen the Polar bear*? Well worth a browse in the library to see if it's what you require.
*Information Architecture for the World Wide Web, Second Edition
A: Thanks, IainMH, Till. I'm without a formal computer science qualification and find large blanks in my knowledge. Over the past couple of years I've gone surprisingly far, though knowing the underlining foundation of projects I've created pollute their efficiency and success.
Being a bit of a perfectionist doesn't help (what programmer isn't?) the headaches I get from looking at badly formed projects, that only to my knowing are badly formed only after stepping back and looking at how they're structured. I guess it's a chicken and egg thing, but also a planning thing.
Anyhow, what has helped is studying existing projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do DVCSs (DRCSs) work? I have been hearing a lot of good things about DVCS systems, in particular about bazaar. Apart from the concept of distributed repository, I see two main advantages being touted: the merge is better automated, and the rename is handled right.
Could someone please point me at some text explaining how exactly the improvements work? How does bazaar know that I renamed a file? What if I rename two files as part of the same commit? What happens when I refactor by putting half of the file's contents into a new file, re-indenting everything and losing some whitespace in nearly every line?
In other words, I'd like to hear from people using bazaar (or another DVCS) in real life, or from people who know how it (they) works. Is the merge really that much better? And how is it achieved?
Related question, with a useful answer:
Why is branching and merging easier in Mercurial than in Subversion?
A: DVCS achieve better merges by tracking the parent revisions of merges. In Subversion, when you merge one branch into another, you lose information about where the merge originated from. In a DVCS like Bazaar or Git, the "merged" revision ends up with two parent revisions.
Renaming is handled differently between DVCS's. Git, for example, does not track renaming at all because it wasn't important to Linus. Mercurial records them as "copy old file to new, delete old". According to Mark Shuttleworth, founder of Canonical, Darcs and Bazaar are the only DVCS's that handle file renaming correctly.
How does bazaar know that I renamed a file?
Renames are specified by the user, just like adding or removing files. Use the "bzr rename <old> <new>" command to mark files or directories for renaming. If you've already renamed a file in the tree, you can use the "--after" option.
What if I rename two files as part of the same commit?
Then you type "bzr rename <old> <new>" once for each file. Bazaar doesn't try to guess which files have been renamed.
What happens when I refactor by putting half of the file's contents into a new file, re-indenting everything and losing some whitespace in nearly every line?
Then you type "bzr add" on the new file, since you're not really renaming it.
A: Merge is not intrinsically better in DVCS, it is just that they would be practically very difficult to use if the branch/merge did not work correctly (svn arguably does not implement branching/merging correctly), because instead of making a checkout, you are making a new branch everytime you start working on a project from an existing code. I think some proprietary, centralized SCS do handle merge/branch correctly.
The way it works for all of them is to record every commit in a Directly Acyclic Graph (DAG), and from this, you have different merge strategies available. Here you can find more information:
http://revctrl.org/CategoryMergeAlgorithm
At least hg, bzr and git can use external merge utilities.
A: The following is a discussion of how darcs (http://darcs.net) deals with patches - http://darcs.net/manual/node9.html.
A: Neat article to read
http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/
A: I'm not familiar with bazaar, but git doesn't track file renames. To git, this looks like a delete and an add. However, git is smart enough to see that the contents of the file already exist in its repository and will track their position in the system. If you split files up or merge them it's smart enough to keep track of segments of code (blobs) and store that information too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create an XmlNode from a call to XmlSerializer.Serialize? I am using a class library which represents some of its configuration in .xml. The configuration is read in using the XmlSerializer. Fortunately, the classes which represent the .xml use the XmlAnyElement attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library.
<?xml version="1.0" encoding="utf-8"?>
<Config>
<data>This is some data</data>
<MyConfig>
<data>This is my data</data>
</MyConfig>
</Config>
This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own XmlSerializer instances with a XmlNodeReader against the internal XmlNode.
public class Config
{
[XmlElement]
public string data;
[XmlAnyElement]
public XmlNode element;
}
public class MyConfig
{
[XmlElement]
public string data;
}
class Program
{
static void Main(string[] args)
{
using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open))
{
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
Config config = (Config)xser1.Deserialize(fs);
if (config.element != null)
{
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element));
}
}
}
I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml?
I realize that I have to initially call XmlSerializer.Serialize on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an XmlNode after calling Serialize. What is the best way to serialize an object into an XmlNode using the XmlSerializer?
Thanks,
-kevin
btw-- It looks like an XmlNodeWriter class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class?
A: It took a bit of work, but the XPathNavigator route does work... just remember to call .Close on the XmlWriter, .Flush() doesn't do anything:
//DataContractSerializer serializer = new DataContractSerializer(typeof(foo));
XmlSerializer serializer = new XmlSerializer(typeof(foo));
XmlDocument doc = new XmlDocument();
XPathNavigator nav = doc.CreateNavigator();
XmlWriter writer = nav.AppendChild();
writer.WriteStartDocument();
//serializer.WriteObject(writer, new foo { bar = 42 });
serializer.Serialize(writer, new foo { bar = 42 });
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Console.WriteLine(doc.OuterXml);
A: So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right?
Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags?
XmlSerializer xs = new XmlSerializer(typeof(MyConfig));
StringWriter xout = new StringWriter();
xs.Serialize(xout, myConfig);
XmlDocument x = new XmlDocument();
x.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>");
Now x is an XmlDocument containing one element, "<myconfig>", which has your serialized custom configuration in it.
Is that at all what you're looking for?
A: One solution is to serialize the inner object to a string and then load the string into a XmlDocument where you can find the XmlNode representing your data and attach it to the outer object.
XmlSerializer xser1 = new XmlSerializer(typeof(Config));
XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig));
MyConfig myConfig = new MyConfig();
myConfig.data = "My special data";
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlWriter xw = new XmlTextWriter(sw);
xser2.Serialize(xw, myConfig);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sb.ToString());
Config config = new Config();
config.data = "some new info";
config.element = doc.LastChild;
xser1.Serialize(fs, config);
However, this solution is cumbersome and I would hope there is a better way, but it resolves my problem for now.
Now if I could just find the mythical XmlNodeWriter referred to on several blogs!
A: At least one resource points to this as an alternative to XmlNodeWriter: http://msdn.microsoft.com/en-us/library/5x8bxy86.aspx. Otherwise, you could write MS using that form they have on the new MSDN Code Library replacement for GotDotNet looking for XmlNodeWriter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Can a service have multiple endpoints? We have a service that has some settings that are supported only over net.tcp. What's the best way to add another endpoint? Do I need to create an entire new host?
A: You can have multiple endpoints defined either on the server, or the client.
To do it on the client, you just need to edit your app.config file with a new endpoint with a different name, then define when you create your new client.
For example if you have an endpoint in your client app like:
<endpoint address="https://yourdomain.com/WCF/YourService.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IYourService"
contract="MessagingService.IYourService"
name="BasicHttpBinding_IYourService" />
Which you call by:
YourServiceClient client = new YourServiceClient();
You can add a new endpoint with a new name:
<endpoint address="https://yourotherdomain.com/WCF/YourService.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IYourService"
contract="MessagingService.IYourService"
name="BasicHttpBinding_IYourService_ENDPOINT2" />
Which you can call with:
YourServiceClient client = new YourServiceClient("BasicHttpBinding_IYourService_ENDPOINT2");
I just changed the domain above, but if you made a new binding configuration section, you could just change the "bindingConfiguration" value.
A: A service may have multiple endpoints within a single host, but every endpoint must have a unique combination of address, binding and contract. For an IIS-hosted service (that is, an .SVC file), just set the address of the endpoint to a relative URI and make sure that your Visual Studio or wsdl.exe generated client specifies the endpoint's name in its constructor.
See also the MSDN article Multiple Endpoints.
A: You will need to create an entire new host if you are currently using IIS as your host - IIS only supports HTTP and not TCP bindings. If however you are using WAS or a windows service, then you'll be able to get away with simply creating a new net.tcp endpoint.
A: We can use multiple endpoints for the same service. We can configure the web config in the following way also
<service name="MessagePatternDemo.Service1">
<endpoint name="ep1" address="/ep1" binding="basicHttpBinding"
contract="MessagePatternDemo.IService1"/>
<endpoint name="ep2" address="/ep2" binding="wsHttpBinding"
contract="MessagePatternDemo.IService1" />
<endpoint name="mex" contract="IMetadataExchange" address="mex"
binding="mexHttpBinding" />
</service>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Which tool do I use if I want to map a programming framework visually and see the relationship between all entities? I find myself to be a visual person and sometimes it's easier to learn something if I can draw diagram/pictures out of it. My question is which tool do I use if I want to map a programming framework (for example .net) visually and see the relationship between all entities (such as classes and members).
A: You might try NDepend. The great Scott Hanselman discusses it more here. Tons of visual dependency formats too. It sounds like its only for .NET though.
A: I find doxygen is useful for generating all kinds of dependency information when faced with a new project. It apparently handles "C++, C, Java, Objective-C, Python, IDL (Corba and Microsoft flavors), Fortran, VHDL, PHP, C#, and to some extent D". It uses Graphviz to generate graphical dependency charts. You can include full source code, with hyperlinks from everything that was recognised. If you are lucky there will be some documentation that doxygen understands in there already. You can then navigate around the code quickly, learning what all the relationships are.
A: The tool NDepend proposes both an interactive Dependency Graph and an interactive Dependency Matrix. Also, the tool is integrated in VisualStudio 2012, 2010 and 2008. Disclaimer: I am one of the developers of the tool
Whether you need to exhibit Call Graph, Coupling Graph, Inheritance Graph, Dependency Graph, very large Graph, pinpoints Dependency Cycles and more, NDepend will generate some visual diagrams. Here are some screenshots:
A: A decent first-cut might be to write a simple PERL script to parse out dependencies and then pipe that data to Graphviz for visualization.
A: I'm not sure if you are asking only about .NET or other frameworks, my experience is mostly with Java but I'm sure similar tools exist for .NET.
On the level of classes you can get an auto-generated visualization using UML tools that can typically reverse engineer source code into a diagram. Netbeans is free and has Java source to UML reverse engineering features.
Class diagrams however are very low level, they tell you little (directly) about the larger architectural themes. At that point tools like Structure101 can be valuable in discovering architectural properties that you didn't realize were there. They have a trial version and can also deal with C and C++.
A: I second the Doxygen comment by Nick. I am using Doxygen for C#.NET and it generates class diagrams, inheritance diagrams, etc. Here is an informative blog post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Plug In Design for .NET App I’m looking at rewriting a portion of our application in C# (currently legacy VB6 code). The module I am starting with is responsible for importing data from a variety of systems into our database. About 5-6 times a year, a new client asks us to write a new import for the system that they use. Presently, this requires us to release a new version of our software for each new import option we add to the application.
One of the goals of the rewrite is to make the application support plug-ins. Every new import can become a separate assembly which the host application will recognize and allow the end user to interact with. This will hopefully simplify life to some degree as we can simply drop a new assembly into the directory and have it be recognized and used by the main (host) application.
One of the items I am struggling with relates to the differences between the import options we currently support. In some cases we actually let the user point to a directory and read all of the files within the directory into our system. In other cases we allow them to point to a single file and import its contents. Additionally, some imports have a date range restriction that the user applies while others do not.
My question is, how can I design the application in a manner that allows for some flexibility among the imports we build and support while at the same time implementing a common interface that will allow the host application to easily recognize the plug-ins and the options that each one exposes to the user?
A: I would recommend you take a look at the Managed Add-In Framework that shipped with .NET 3.5. The Add-In team has posted some samples and tools at CodePlex site as well..
A: .Net 3.5 has the system.Addin namespace.
This thread also has some good information for older versions of the framework:
http://forums.devshed.com/net-development-87/system-plugin-532149.html
A: for the theory take a look at the plugin pattern in martin fowlers Patterns of Enterprise Application Architecture
for an interesting example take a look at this tutorial: Plugin Architecture using C#
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Setting Nameservers - how? I understand how I can change the dns settings for my domains by editing my bind configs, when I run my own name-servers. I know that I can define the name-servers with my registrar via their online control panels. But I have no idea how that part works...
How does my registrar store the data about the name-servers? Is it something clever, like them having the authority to store NS records in the root name-servers?
I'm confused by this part, can anyone explain?
A: The registrar is responsible for setting the Root DNS entry that says, "When someone asks for stackoverflow.com, tell them that the authoritative DNS is xxx.xxx.xxx.xxx". They have an interface that allows them to make changes to the records they own.
Then the requester must go to the authoritative DNS (Which is the one you specified to your registrar was your DNS) to find the IP for stackoverflow.com, any subdomain of it, email server, and other DNS records pertaining to that domain.
-Adam
A: I've just been shown this:
# dig +trace ns stackoverflow.com
; <<>> DiG 9.2.4 <<>> +trace ns stackoverflow.com
;; global options: printcmd
. 269431 IN NS B.ROOT-SERVERS.NET.
. 269431 IN NS C.ROOT-SERVERS.NET.
. 269431 IN NS D.ROOT-SERVERS.NET.
. 269431 IN NS E.ROOT-SERVERS.NET.
. 269431 IN NS F.ROOT-SERVERS.NET.
. 269431 IN NS G.ROOT-SERVERS.NET.
. 269431 IN NS H.ROOT-SERVERS.NET.
. 269431 IN NS I.ROOT-SERVERS.NET.
. 269431 IN NS J.ROOT-SERVERS.NET.
. 269431 IN NS K.ROOT-SERVERS.NET.
. 269431 IN NS L.ROOT-SERVERS.NET.
. 269431 IN NS M.ROOT-SERVERS.NET.
. 269431 IN NS A.ROOT-SERVERS.NET.
;; Received 504 bytes from 83.138.151.80#53(83.138.151.80) in 3 ms
com. 172800 IN NS A.GTLD-SERVERS.NET.
com. 172800 IN NS B.GTLD-SERVERS.NET.
com. 172800 IN NS C.GTLD-SERVERS.NET.
com. 172800 IN NS D.GTLD-SERVERS.NET.
com. 172800 IN NS E.GTLD-SERVERS.NET.
com. 172800 IN NS F.GTLD-SERVERS.NET.
com. 172800 IN NS G.GTLD-SERVERS.NET.
com. 172800 IN NS H.GTLD-SERVERS.NET.
com. 172800 IN NS I.GTLD-SERVERS.NET.
com. 172800 IN NS J.GTLD-SERVERS.NET.
com. 172800 IN NS K.GTLD-SERVERS.NET.
com. 172800 IN NS L.GTLD-SERVERS.NET.
com. 172800 IN NS M.GTLD-SERVERS.NET.
;; Received 495 bytes from 192.228.79.201#53(B.ROOT-SERVERS.NET) in 145 ms
stackoverflow.com. 172800 IN NS ns51.domaincontrol.com.
stackoverflow.com. 172800 IN NS ns52.domaincontrol.com.
;; Received 119 bytes from 192.5.6.30#53(A.GTLD-SERVERS.NET) in 156 ms
Does this tell me that the stackoverflow.com nameservers have been stored in the .com name servers?
Or is it just that they happen to be there now?
A: It may be helpful to understand the difference between a "registrar" and a "registry" to begin with. A registrar is a company that sells domain names (ie. godaddy) to buyers. Anyone can be a registrar. You can become a registrar.
A registry is an entity (chosen by ICANN) that maintains the master database of domain names. There are several registries out there. The Internet Society (ISOC) is the registry for all .org names, Verisign is the registry for all .com and .net domain names. There are others and each country has one for their domain. All the registrars access and update the registry databases.
A registry is responsible for maintaining the top level domain (TLD) which is the ultimate DNS server. A request to resolve a domain name, if it can't be resolved by any other DNS server will filter up to the TLD. Think of it as a hierarchy like a tree where the TLD is the trunk. At that point it will be resolved into an IP address or an error will be returned.
A: Sorry I can't help toooooo much, but go to http://twit.tv, and find the Security Now podcast - they did one a couple of weeks ago on DNS - get the first one. It has a good explanation of how it works etc (which may help).
The second one on that site is about how it's been "hacked" - the first one is the how it works.
To kinda answer it:
The "root servers" (for .com for eg) hold a record for stackoverflow.com. But they can't hold all the details, so they have an NS record (name server record) saying "if you want more info, go look over there". So your machine asks that target machine (ns1.stackoverflow.com) for www.stackoverflow.com, and gets back the A record (IP address), or MX (mail etc)
So, your domain register will store it in a database or whatever they chose, and when you do an update, they SOMEHOW (I dont know, but I guess it's published by NIC, but they DO have to pay to be a registrar, and be checked out etc) push that change to the (cluster of) root name servers. They would then push the changes for your domain (eg where www goes, where your mail goes etc) to their local server, which actually serves the domain info.
Hope that makes SOME sense :)
Does this tell me that the
stackoverflow.com nameservers have
been stored in the .com name servers?
Yes and no.
Its like you going calling directory assistance for everything ending in .com. You ask for stackoverflow - they tell you "if you want SO, call this number, and they can tell you how to get Jeff (www), Joel (mail), etc.".
The root server is the first directory assistance. Your register's name server is the one on the end of the second call (assuming you called it :) )
A: There are some mistakes in the answers so far (and I have not yet sufficient reputation to comment on them).
*
*The ".com" name servers are in no way related with the root name servers. When you change the name servers of stackoverflow.com, through your registrar, the change is made in the ".com" name servers. Root name servers are unaffected.
*It is not true that the registries are all chosen by ICANN. The ccTLD registries (country-code TLD like ".jp" or ".ca"), for instance, are chosen locally, by a process which depends on the country.
*Not all TLD use a registry/registrar system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Possible to perform cross-database queries with PostgreSQL? I'm going to guess that the answer is "no" based on the below error message (and this Google result), but is there anyway to perform a cross-database query using PostgreSQL?
databaseA=# select * from databaseB.public.someTableName;
ERROR: cross-database references are not implemented:
"databaseB.public.someTableName"
I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the users table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie...
A: Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.
I have used DB-Link and TDS-link before with great success.
A: dblink() -- executes a query in a remote database
dblink executes a query (usually a SELECT, but it can be any SQL
statement that returns rows) in a remote database.
When two text arguments are given, the first one is first looked up as
a persistent connection's name; if found, the command is executed on
that connection. If not found, the first argument is treated as a
connection info string as for dblink_connect, and the indicated
connection is made just for the duration of this command.
one of the good example:
SELECT *
FROM table1 tb1
LEFT JOIN (
SELECT *
FROM dblink('dbname=db2','SELECT id, code FROM table2')
AS tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;
Note: I am giving this information for future reference. Reference
A: I have checked and tried to create a foreign key relationships between 2 tables in 2 different databases using both dblink and postgres_fdw but with no result.
Having read the other peoples feedback on this, for example here and here and in some other sources it looks like there is no way to do that currently:
The dblink and postgres_fdw indeed enable one to connect to and query tables in other databases, which is not possible with the standard Postgres, but they do not allow to establish foreign key relationships between tables in different databases.
A: If performance is important and most queries are read-only, I would suggest to replicate data over to another database. While this seems like unneeded duplication of data, it might help if indexes are required.
This can be done with simple on insert triggers which in turn call dblink to update another copy. There are also full-blown replication options (like Slony) but that's off-topic.
A: I have run into this before an came to the same conclusion about cross database queries as you. What I ended up doing was using schemas to divide the table space that way I could keep the tables grouped but still query them all.
A: see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]
These days you also have the option to use https://prestodb.io/
You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.
It does not support:
DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS
So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)
Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API
This is an open source tool governed by the Linux Foundation and Presto Foundation.
The founding members of the Presto Foundation are: Facebook, Uber,
Twitter, and Alibaba.
The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio,
Ahana, Upsolver, and Intel.
A: Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them.
postgres_fdw
Use postgres_fdw (foreign data wrapper) to connect to tables in any Postgres database - local or remote.
Note that there are foreign data wrappers for other popular data sources. At this time, only postgres_fdw and file_fdw are part of the official Postgres distribution.
For Postgres versions before 9.3
Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called dblink.
I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib.
A: Just to add a bit more information.
There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.
contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.
PostgreSQL FAQ
A: In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the databasechangeloglock table on every database that has it:
CREATE EXTENSION IF NOT EXISTS dblink;
DO
$$
DECLARE database_name TEXT;
DECLARE conn_template TEXT;
DECLARE conn_string TEXT;
DECLARE table_exists Boolean;
BEGIN
conn_template = 'user=myuser password=mypass dbname=';
FOR database_name IN
SELECT datname FROM pg_database
WHERE datistemplate = false
LOOP
conn_string = conn_template || database_name;
table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));
IF table_exists THEN
perform dblink_exec(conn_string, 'delete from databasechangeloglock');
END IF;
END LOOP;
END
$$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "190"
} |
Q: How to organize a complex Flash project Let's compile a list of tips.
(Understandably there will be some subjectivity involved, but some pointers would be useful to someone overwhelmed by tackling a large project within the Flash framework.)
A: These are just scattered thoughts on organization for projects being worked on mostly with the Flash IDE.
First, I highly recommend using source control, like Subversion, CVS, or Git.
Organization of filesystem folder structure is subjective, but I generally have a "src" folder for all my source FLAs and AS class files, and a "deploy" or "bin" folder for compiled files. The src folder would contain class package files, with class packages organized in reverse domain style (e.g. - com.codehinting.projectname.context ). Modify the publish path of your FLA to publish to the deploy folder by tracing back up using the "../" path segment, for as many levels as needed to trace back from the nesting in the src folder.
Also, I typically place third-party libraries (that are pretty well "baked") in a separate location and then modify the global classpath in the Flash IDE to point to this location.
Two extremely handy plugins for the Flash IDE are Create Basic Layers and Library Generator, which quickly create your skeleton layer and library folder structure - saves time versus manually creating layers and folders.
A: I adopted the Project Naming guidelines from Blitz:
Blitz Project Naming Conventions & Organizational Guidelines
My DEV_Source is divided in database/flash/flex directories.
The Flex directory is standard to the Adobe conventions, but the flash has a custom setup.
bin -- Output of SWF, contains JS and index.html
classes -- AS3 code
doc -- AS Doc output of code
libs -- 3rd party libraries and components
src -- FLA files (set the Publish settings to compile in bin)
test -- AS Unit test cases of classes
A: A complex project will have many dependencies. In my Flash projects, I put all my libraries in a version controlled location as they are. Third party libraries are usually a mishmash of assets, code, demos and docs.
I keep a small yaml file that keeps track of the location of each type of resource associated with each library on my system. When I add a new library, its location goes into this file first, then I run my Ruby script to move the files over to a single location. This way there is no jockeying around with third party library paths, and making sure include paths in my projects match in my fla files and Flex builder projects.
A single source to bind them all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can you access a model from inside another model in CodeIgniter? I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter?
A: It seems you can load models inside models, although you probably should solve this another way. See CodeIgniter forums for a discussion.
class SomeModel extends Model
{
function doSomething($foo)
{
$CI =& get_instance();
$CI->load->model('SomeOtherModel','NiceName',true);
// use $CI instead of $this to query the other models
$CI->NiceName->doSomethingElse();
}
}
Also, I don't understand what Till is saying about that you shouldn't create objects inside objects. Of course you should! Sending objects as arguments looks much less clear to me.
A: In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model.
<?php
// in your controller
$model1 = new Model1();
$model2 = new Model2();
$model2->setWhatever($model1);
?>
A: Don't handle authentication in your model. Only use models to interface with your database, or ldap or whatever.
I created an Auth library that I use to manage authentication and authorization. You can access a library like this from your controllers.
A: Loading a model within a model is now possible with the new CodeIgniter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How to Dynamically Generate String Validation? Does anyone know of a library (preferably php) or algorithm for auto-generating regex's from some common descriptions?
For example, have a form with the possible options of:
- Length (=x, between x & y, etc)
- Starts with
- Ends with
- Character(s) x(yz) at index i
- Specify one or more alternative behavior based on the above
- And so on..
The idea is that for certain data entities in a system, you'll be able to go to a form and set this criteria for a data field. Afterward, any time that data field for that type of data entity is entered, it will be validated against the regex.
This seems like it could grow into a complex problem though, so I'm not expecting anyone to solve it as a whole. Any suggestions are much appreciated.
A: Would simple globs be enough? For globs it's just a matter of replacing * with .* and adding ^ and $. Or may be Excel-style patterns? It should not be too hard to write a regexp generator for simple rules like this...
My point is, adjust your requirements to simplify the code, and then may be add more features as needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: .NET Console Application Tab Completion Any ideas on how to implement tab completion for a .NET (C#) Console Application?
And I mean within an application that is run and then loops for user input (like if you run ftp.exe without any arguments), like this:
string line = string.Empty;
while (line != "exit")
{
//do something here
Console.ReadLine();
}
I know I probably couldn't actually use readline, but I would like to be able to do tab completion at that same point where you retrieve input from the user.
A: Do a Console.ReadKey().
If you get a Tab, look at what you have in the command buffer, and loop through your available commands. If someCommand.Name.BeginsWith(currentinput), you have a winner, and you can write to screen a list of possible commands.
If there is only one(TM) you can substitute it with what the user had typed :)
A: I created a small lib to add this functionality to an app i made:
https://github.com/fjunqueira/hinter
It might not suit your needs, but you can feel free to edit it.
A: Take a look at this code from the Mono project
http://tirania.org/blog/archive/2008/Aug-26.html
I played with it some the other day.
It does a lot of command line editingy, but I don't think it does line completion.
A: Console.ReadKey
A: https://github.com/tonerdo/readline is what you need.
great lib available as a nuget from the talented dev tonerdo.
pasted from the site:
...
ReadLine is a GNU Readline like library built in pure C#
It can serve as a drop in replacement for the inbuilt Console.ReadLine() and brings along with it some of the terminal goodness you get from unix shells, like command history navigation and tab auto completion.
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: IIS7: HTTP->HTTPS Cleanly Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?
A: A clean way changes only the URL scheme from http -> https and leaves everything else equivalent. It should be server-side so that there are no browser issues.
JPPinto.com has Step-By-Step instructions on how this is done, except that they use javascript (HttpRedirect.htm) instead of a server-side redirect. For some reason, I couldn't get IE run the javascript if you have ‘Show friendly HTTP error messages’ enabled, which is on by default. Another thing with the script is that redirection to path didn't work even in FF or Chrome. The script always redirects to root. (Maybe I have missed something, because it should redirect to path.)
For these reasons I have used an ASP page for the redirect. The downside is of course that this requires classic ASP to be enabled on the server.
OpsanBlog has an ASP script and instructions that work well with IIS6.
I've had a few issues using this method with IIS7. User interface issues mostly, since IIS7 makes it really easy to miss something.
*
*First, you need to install ASP as a
web server role feature.
*Second, using a virtual directory didn't not
work as expected in IIS7 and I didn't
try to debug this. Instead, I put the file in the root folder of the site and used
the url '/SSLRedirect.asp' in the
403.4 error page to reference it.
*Last, the most tricky part, you must NOT enforce SSL for SSLRedirect.asp. Otherwise you'll get an 403.4 error. To do this you pick the file in IIS7 'Content View', and switch to 'Features View' so that you can edit the SSL settings for the single file and disable 'Require SSL' checkbox.
IIS manager should show the file name in the header.
A: I think the cleanest way is as described here on IIS-aid.com. It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works.
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
A: The most easy and clean solution I found was to
*
*In SSL Settings -> require SSL
*In Error Pages -> On 403.4 error -> Redirect to the HTTPS site
*In Error Pages -> Edit Features Settings... -> Set Detailed errors for local requests and custom error pages for remote request
The benefit is that it requires no extra lines of code.
Downside is that it redirects you to an absolute url.
A: Global.asax
protected void Application_BeginRequest()
{
if (!Context.Request.Url.AbsoluteUri.Contains("localhost") && !Context.Request.IsSecureConnection)
Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
}
A: I use classic asp (intranet) and on pages that requires login the logon include file does the redirect:
if Request.ServerVariables("SERVER_PORT_SECURE") <> "1" or Request.ServerVariables("HTTPS") <> "on" then
Response.Redirect "https://" & Request.ServerVariables("SERVER_NAME") & Request.ServerVariables("URL")
end if
This of course does not include GET or POST data. So in effect it's a clean redirect to your secured page.
A: I think by 'cleanly' you mean like with a 300 redirect. Config for a lot of servers & languages here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "148"
} |
Q: Center a block of content when you don't know its width in advance After lots of attempts and search I have never found a satisfactory way to do it with CSS2.
A simple way to accomplish it is to wrap it into a handy <table> as shown in the sample below. Do you know how to do it avoiding table layouts and also avoiding quirky tricks?
table {
margin: 0 auto;
}
<table>
<tr>
<td>test<br/>test</td>
</tr>
</table>
What I want to know is how to do it without a fixed width and also being a block.
A: @Jason, yep, <center> works. Good times. I'll propose the following, though:
body {
text-align: center;
}
.my-centered-content {
margin: 0 auto; /* Centering */
display: inline;
}
<div class="my-centered-content">
<p>test</p>
<p>test</p>
</div>
EDIT @Santi, a block-level element will fill the width of the parent container, so it will effectively be width:100% and the text will flow on the left, leaving you with useless markup and an uncentered element. You might want to try display: inline-block;. Firefox might complain, but it's right. Also, try adding a border: solid red 1px; to the CSS of the .my-centered-content DIV to see what's happening as you try these things out.
A: This is going to be the lamest answer, but it works:
Use the deprecated <center> tag.
:P
I told you it would be lame. But, like I said, it works!
*shudder*
A: I think that your example would work just as well if you used a <div> instead of a <table>. The only difference is that the text in the <table> is also centered. If you want that too, just add the text-align: center; rule.
Another thing to keep in mind is that the <div> will by default fill up all the available horizontal space. Put a border on it if you aren't sure where it starts and ends.
A: The following works well enough. note the position, and the use of auto
<div style="border: 1px solid black;
width: 300px;
height: 300px;">
<div style="width: 150px;
height: 150px;
background-color: blue;
position: relative;
left: auto;
right: auto;
margin-right: auto;
margin-left: auto;">
</div>
</div>
NOTE: not sure if it works in IE.
A:
#wrapper {
width: 100%;
border: 1px solid #333;
}
#content {
width: 200px;
background: #0f0;
}
<div id="wrapper" align="center">
<div id="content" align="left"> Content Here </div>
</div>
A: In FF3, you can:
<div style="display: table; margin: 0px auto 0 auto;">test<br>test</div>
This has the advantage of using whatever element makes most semantic sense (replace the div with something better, if appropriate), but the disadvantage that it fails in IE (grr...)
Other than that, without setting the width, your best bet is to use javascript to precisely position the left-hand edge. I'm not sure if you'd class that as a 'quirky trick', though.
It really depends on what you want to do, of course. Given your simple test case, a div with text-align: center would have exactly the same effect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: "Invalid column name" error on SQL statement from OpenQuery results I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine:
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
But if I try to add:
WHERE "Value" > 0
I get an error
Invalid column name 'Value'
Any ideas what I might be doing wrong?
So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source:
http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx
The order of evaluation in MSSQL is:
*
*FROM
*ON
*JOIN
*WHERE
*GROUP BY
*HAVING
*SELECT
*ORDER BY
So the alias wasn't processed until after the WHERE and HAVING clauses.
A: You're using "Value" as a column alias, and I don't think the alias can appear in the where clause. It's simply used to name the returned column value. Your where clause should refer to the original column name:
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
WHERE "Ugly OLAP name" > 0
A: This should work:
SELECT A.Value
FROM (
SELECT "Ugly OLAP name" as "Value"
FROM OpenQuery( OLAP, 'OLAP Query')
) AS a
WHERE a.Value > 0
It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can then be used in a where clause.
A: Oh, bummer. I just saw, you select AS FOO. Don't you need a HAVING claus in this case?
SELECT whatever AS value FROM table HAVING value > 1;
I still would not use "value". But to be sure, look it up in your docs!
A: I can vouch for leaving it out of GROUP BY. Good news is, it works just fine being a plain old selected alias.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: SQL Server Full-Text Search: Hung processes with MSSEARCH wait type We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post1, it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?
1 [http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]
“Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”
A: Here's a suggestion. I don't have any corrupted databases but you can try this:
declare @t table (name nvarchar(128))
insert into @t select name from sys.databases --where is_fulltext_enabled
while exists(SELECT * FROM @t)
begin
declare @name nvarchar(128)
select @name = name from @t
declare @SQL nvarchar(4000)
set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit'''
print @sql
exec sp_sqlexec @SQL
delete from @t where name = @name
end
If it doesn't work, remove the filter checking sys.databases.
A: Have you tried running process monitor and when it hangs and see what the underlying error is? Using process moniter you should be able to tell whick file/resource it waiting for/erroring on.
A: I had a similar problem with invalid full text catalog locations.
The server wouldn't bring all databases online at start-up. It would process databases in dbid order and get half way through and stop. Only the older DBs were brought online and the remainder were inaccessible.
Looking at sysprocesses revealed a dozen or more processes with a waittype = 0x00CC , lastwaittype = MSSEARCH. MSSEARCH could not be stopped.
The problem was caused when we relocated the full text catalogs but entered the wrong path for one of them when running the alter database ... modifyfile command.
The solution was to disable MSSEARCH, reboot the server allowing all DBs to come online, find the offending database, take it offline, correct the file path using the alter database command, and bring the DB online. Then start MSSEARCH and set to automatic start-up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Windows packet sniffer that can capture loopback traffic? (This is a followup to my previous question about measuring .NET remoting traffic.)
When I am testing our Windows service / service controller GUI combination, it is often most convenient to run both pieces on my development box. With this setup, the remoting traffic between the two is via loopback, not through the Ethernet card.
Are there any software packet sniffers that can capture loopback traffic on a WinXP machine? Wireshark is a great package, but it can only capture external traffic on a Windows machine, not loopback.
A: There is a page on the Wireshark wiki that addresses the problem. Short answer is, you can't do it on a Windows machine, but there might be some workarounds.
A: I'm not sure if it can or not, but have you looked at Microsoft Network Monitor? It might be an option.
A: What you should do is to run RawCap, which is a sniffer that can capture traffic to/from the loopback interface in Windows. Just start it with "RawCap.exe 127.0.0.1 loopback.pcap".
You can then open up loopback.pcap in Wireshark or NetworkMiner to look at the network traffic.
You can find RawCap here:
http://www.netresec.com/?page=RawCap
Good Luck!
A: Did you try to install the MS Loopback Adapter and try sniffing on that adapter with you favorite sniffing application?
Also if I remember correctluy NAI Sniffer link did use to have loopback sniffing capabilities, but it's been a while I used either solution...
A: If you don't care to pay, try this: CommView
It seems to work, however the Evalution version doesn't display the
complete packets.
A: I second the Microsoft Network Monitor (though this link works better at the time of writing) suggestion from Thomas Owens. Also, this post suggests that to get the loopback address, try doing:
route add <Your Machine's IP> <Your Router's IP>
This takes locally-generated packets for the local interface and sends them off to your router... which sends them back.
NOTE: To get your machine back to normal operation, make sure you delete the route when you're finished using:
route delete <Your Machine's IP>
A: You should definitely try Npcap, it works perfectly with Wireshark to capture loopback traffic in Windows, see here:
https://wiki.wireshark.org/CaptureSetup/Loopback
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: How do I specify multiple constraints on a generic type in C#? What is the syntax for placing constraints on multiple types? The basic example:
class Animal<SpeciesType> where SpeciesType : Species
I would like to place constraints on both types in the following definition such that SpeciesType must inherit from Species and OrderType must inherit from Order:
class Animal<SpeciesType, OrderType>
A: public class Animal<SpeciesType,OrderType>
where SpeciesType : Species
where OrderType : Order
{
}
A: You should be able to go :
class Animal<SpeciesType, OrderType>
where SpeciesType : Species
where OrderType : Order {
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Why doesn't Oracle tell you WHICH table or view does not exist? If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object?
Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I'm a developer working with a complex join through several layers of application code, it's often very difficult to tell.
My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.)
Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table?
Although I've accepted an answer which is relevant to the topic, it doesn't really answer my question: Why isn't the name part of the error message? If anyone can come up with the real answer, I'll be happy to change my vote.
A: I would disagree with the opinion, that SQL+ lets you understand which table name is unacceptable. True, it helps in direct DML, although parsing it is very hard. But when it comes to dynamic, we get no help:
SQL> begin
2 execute immediate 'insert into blabla values(1)';
3 end;
4 /
begin
*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at line 2
A: If you are using a SQL browsing tool like TOAD or TORA it will help you with ORA errors by highlightling or pointing moving the cursor to where you made your error.
Copy and paste your SQL in to one of these tools to help. You may also find the analyse info available useful too.
A: If its not a huge statement, then the easiest way is just to check the data dictionary,
SQL> select * from xx,abc;
select * from xx,abc
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select owner,table_name from all_tables where table_name in ('XX','ABC');
OWNER TABLE_NAME
------------------------------ ------------------------------
MWATSON XX
SQL>
This isn't ideal, but short of going and examining trace files, I'm not sure how else to do it.
A: I've never had a problem with interpreting Oracle error messages. Part of the reason is that every interactive tool I've seen for developing SQL for Oracle helpfully points to the location the query went wrong. That includes SQL*Plus, as others have noted, and the Perl DBI module:
$ exec_sql.pl 'select * from daul'
DBD::Oracle::db prepare failed: ORA-00942: table or view does not exist (DBD ERROR: error possibly near <*> indicator at char 14 in 'select * from <*>daul') [for Statement "select * from daul"] at exec_sql.pl line 68.
Well, that is a bit hard to read since it's all squished on one line. But a GUI tool would be able to point to the token where Oracle started having problems with the query. And given a bit of work on a parser, you could write a tool to pick out the offending table.
To answer the underlying question, Oracle errors don't seem to be designed to work the way you expect. As far as I can tell, none of the the error messages in Oracle support variable text. Instead, Oracle returns two bits of information: an error number and a location where the error occurs. If you have proper tools, it's pretty easy to diagnose an error with those pieces of data. It can be argued that Oracle's system is nicer to tool creators than one which provides variable amounts of diagnostic data depending on the error. Imagine having to write a custom parser for all of Oracle's error messages (including future errors) to highlight the offending location.
Sometimes including the table name would be misleading. Just knowing where things went wrong can be a huge help:
SQL> select * from where dummy = 'X';
select * from where dummy = 'X'
*
ERROR at line 1:
ORA-00903: invalid table name
As for why Oracle chose to do thing this way, I have some speculations:
*
*IBM used this style of error message for System R, which Larry Ellison, Bob Miner and Ed Oates copied to build Oracle V2. (Backward compatibility.)
*Error number and location are the smallest possible representation of diagnostic information. (Parsimony.)
*As I indicated above, to simplify the creation of tools that connect to Oracle. (Interoperability.)
In any case, I don't think you need to be a DBA to figure out which table doesn't exist. You just need to use the proper tools. (And adjust your expectations, I suppose.)
A: Reason 1: Multi-lingual interface
There is a language-specific message configuration file for your database instance. Messages are pulled out of there and translated from the pure numeric version to the numeric+text version.
It was probably considered better to have the hardcoded strings, than to run the risk at runtime of having a mysterious failure due to an improperly formatted "%s" string.
(Not that I particularly agree with this POV, btw.)
Reason 2: Security
Right now you don't particularly expose the internal workings of your application if you print a PHP, etc, dump of an Oracle error message to the browser.
Applications would be a bit more exposed if more detail were printed by default... For example, if citibank printed a more explanatory message.
(see disclaimer above, I would be happy to get more information in the error as well.)
A: You can set an EVENT in your parameter file (plain text or spfile) to force Oracle to dump a detailed trace file in the user_dump_dest, the object name might be in there, if not the SQL should be.
EVENT="942 trace name errorstack level 12"
If you are using a plain text file you need to keep all your EVENT settings on consecutive lines. Not sure how that applied to spfile.
A: SQL*Plus does tell you the table that doesn't exist. For example:
SQL> select
2 *
3 from
4 user_tables a,
5 non_existent_table b
6 where
7 a.table_name = b.table_name;
non_existent_table b
*
ERROR at line 5:
ORA-00942: table or view does not exist
Here it shows that the name of the missing table and the line number in the SQL statement where the error occurs.
Similarly, in a one-line SQL statement you can see the asterisk highlighting the name of the unknown table:
SQL> select * from user_tables a, non_existent_table b where a.table_name = b.table_name;
select * from user_tables a, non_existent_table b where a.table_name = b.table_name
*
ERROR at line 1:
ORA-00942: table or view does not exist
In terms of your question, I guess the reason the error message doesn't include the name of the table is that the error message itself needs to be static text. The line number and location in the line of the error is clearly passed back to SQL*Plus (somehow).
A: @Matthew
Your query's a start, but it might not work when you have multiple schemas. For example, if I log into our instance as myself, I have read access to all our tables. But if I don't qualify the table name with the schema I'll get an ORA-00942 for tables without synonyms:
SQL> select * from tools;
select * from tools
*
ERROR at line 1:
ORA-00942: table or view does not exist
The table still shows up in all_tables though:
SQL> select owner, table_name from all_tables where table_name = 'TOOLS';
OWNER TABLE_NAME
------------------------------ ------------------------------
APPLICATION TOOLS
@erikson
Sorry that doesn't help much. I'm with Mark - I used TOAD.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Delete all but top n from database table in SQL What's the best way to delete all rows from a table in sql but to keep n number of rows on the top?
A: DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
Edit:
Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it.
A: I think using a virtual table would be much better than an IN-clause or temp table.
DELETE
Product
FROM
Product
LEFT OUTER JOIN
(
SELECT TOP 10
Product.id
FROM
Product
) TopProducts ON Product.id = TopProducts.id
WHERE
TopProducts.id IS NULL
A: I would select ID column(s) the set of rows that you want to keep into a temp table or table variable. Then delete all the rows that do not exist in the temp table. The syntax mentioned by another user:
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table)
Has a potential problem. The "SELECT TOP 10" query will be executed for each row in the table, which could be a huge performance hit. You want to avoid making the same query over and over again.
This syntax should work, based what you listed as your original SQL statement:
create table #nuke(NukeID int)
insert into #nuke(Nuke) select top 1000 id from article
delete article where not exists (select 1 from nuke where Nukeid = id)
drop table #nuke
A: This really is going to be language specific, but I would likely use something like the following for SQL server.
declare @n int
SET @n = SELECT Count(*) FROM dTABLE;
DELETE TOP (@n - 10 ) FROM dTable
if you don't care about the exact number of rows, there is always
DELETE TOP 90 PERCENT FROM dTABLE;
A: I don't know about other flavors but MySQL DELETE allows LIMIT.
If you could order things so that the n rows you want to keep are at the bottom, then you could do a DELETE FROM table LIMIT tablecount-n.
Edit
Oooo. I think I like Cory Foy's answer better, assuming it works in your case. My way feels a little clunky by comparison.
A: Future reference for those of use who don't use MS SQL.
In PostgreSQL use ORDER BY and LIMIT instead of TOP.
DELETE FROM table
WHERE id NOT IN (SELECT id FROM table ORDER BY id LIMIT n);
MySQL -- well...
Error -- This version of MySQL does not yet support 'LIMIT &
IN/ALL/ANY/SOME subquery'
Not yet I guess.
A: Here is how I did it. This method is faster and simpler:
Delete all but top n from database table in MS SQL using OFFSET command
WITH CTE AS
(
SELECT ID
FROM dbo.TableName
ORDER BY ID DESC
OFFSET 11 ROWS
)
DELETE CTE;
Replace ID with column by which you want to sort.
Replace number after OFFSET with number of rows which you want to keep.
Choose DESC or ASC - whatever suits your case.
A: I would solve it using the technique below. The example expect an article table with an id on each row.
Delete article where id not in (select top 1000 id from article)
Edit: Too slow to answer my own question ...
A: Refactored?
Delete a From Table a Inner Join (
Select Top (Select Count(tableID) From Table) - 10)
From Table Order By tableID Desc
) b On b.tableID = A.tableID
edit: tried them both in the query analyzer, current answer is fasted (damn order by...)
A: Better way would be to insert the rows you DO want into another table, drop the original table and then rename the new table so it has the same name as the old table
A: I've got a trick to avoid executing the TOP expression for every row. We can combine TOP with MAX to get the MaxId we want to keep. Then we just delete everything greater than MaxId.
-- Declare Variable to hold the highest id we want to keep.
DECLARE @MaxId as int = (
SELECT MAX(temp.ID)
FROM (SELECT TOP 10 ID FROM table ORDER BY ID ASC) temp
)
-- Delete anything greater than MaxId. If MaxId is null, there is nothing to delete.
IF @MaxId IS NOT NULL
DELETE FROM table WHERE ID > @MaxId
Note: It is important to use ORDER BY when declaring MaxId to ensure proper results are queried.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "94"
} |
Q: How to get the correct Content-Length for a POST request I am using a perl script to POST to Google Appengine application. I post a text file containing some XML using the -F option.
http://www.cpan.org/authors/id/E/EL/ELIJAH/bget-1.1
There is a version 1.2, already tested and get the same issue. The post looks something like this.
Host: foo.appspot.com
User-Agent: lwp-request/1.38
Content-Type: text/plain
Content-Length: 202
<XML>
<BLAH>Hello World</BLAH>
</XML>
I have modified the example so the 202 isn't right, don't worry about that. On to the problem. The Content-Length matches the number of bytes on the file, however unless I manually increase the Content-Length it does not send all of the file, a few bytes get truncated. The number of bytes truncated is not the same for files of different sizes. I used the -r option on the script and I can see what it is sending and it is sending all of the file, but Google Appengine self.request.body shows that not everything is received. I think the solution is to get the right number for Content-Length and apparently it isn't as simple as number of bytes on the file or the perl script is mangling it somehow.
Update:
Thanks to Erickson for the right answer. I used printf to append characters to the end of the file and it always truncated exactly the number of lines in the file. I suppose I could figure out what is being added by iterating through every character on the server side but not worth it. This wasn't even answered over on the google groups set up for app engine!
A: Is the number of extra bytes you need equal to the number of lines in the file? I ask because perhaps its possible that somehow carriage-returns are being introduced but not counted.
A: I've run into similar problems before.
I assume you're using the length() function to determine the size of the file? If so, it;s likely the data that you're posting is UTF-8 encoded, instead of ASCII.
To get the correct count you may need to add a "use bytes;" pragma to the top of your script, or wrap the length call in a block:
my $size;
do {use bytes; $size = length($file_data)}
From the perlfunc man page:
"Note the characters: if the EXPR is in Unicode, you will get the number of characters, not the number of bytes."
A: How are you getting the number of bytes? .. By looking at the size of the file on the filesystem?
You can use "-s" to get the size of the file.
Or, if you want to do more, you may use File::Stat
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to export findbugs results from Eclipse findbugs plugin? I have findbugs plugin for eclipse which when run on my project will show results in Bugs explorer clubbed by the type of bug.
I need to be able to do two things:
*
*Export all these to excel sheet
*Find out the bugs reported in a set of files (and be able to do it recursively w/o running for whole project and exporting and finding out the classes to be modified.
Any suggestions?
FYI, I am using MyEclipse v 6.0.1 and FindBugs 1.3.4
A: Findbugs dumps its results into an XML file in your workspace's .metadata folder. Look for the subfolder that's named something like findbugs.
You can also download a standalone version of Findbugs that will save the results wherever you like.
Once you have the results file, you might be able to import from XML to Excel and filter there. Alternatively, you can use XSLT to transform to several CSV files and open them in Excel.
A: I had the same problem with findbugs some versions ago.
I updated the plugin today to version 1.3.8 and found out that you can now export and even import reports as XML directly.
All you have to do is right-click on a project either in the package explorer or in the findbugs "Bug explorer" and select "Findbugs->Save XML" or "Findbugs->Load XML".
Finely a proper export and import functionality for a fantastic tool.
Btw, I use Eclipse 3.3.2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Automatic Timeout Web Client Use One of the problems I have come across having complex tasks on the browser is with automatic timeouts.
Currently our site has a sliding expiration of 30 minutes. Normally, this isn't a problem because we use asp.net and most of the time the users update one or two fields and then submit the form. This obviously keeps the session active. I have struggled with how to handle this with significantly more complex forms/user interaction where there are few if no round trips to the server.
Now users can view reports, type emails etc. on our site, and I am struggling with how to keep their session active while they're actually using browser but they are not actively posting information back. I would dispense with the sliding expiration, but it's a requirement, so I am stuck with it. Most of our users are outside of the organization, so I can't use any form of SSO.
Does anyone have an elegant solution (I'll even go for an ugly one if it works), or am I out of luck?
A: Have the browser ping the server via Ajax periodically to keep the session alive. Most sites do something useful in this ping, like save a draft of the user's submission.
A: We recently went through this in my organization. Although it is not the best solution, and hitting the right session across multiple browser windows is rough, we put a countdown timer on our page, included a button that just went back and hit the server to restart the session, and also provided the user with a JavaScript popup (the user's favorite part of the solution) with a message saying that the session was, say, five minutes from timing out and to hit the "OK" button to restart. Then the button would hit the server to restart the session, restart the timer on the base page, close the popup and the base page didn't need to be refreshed at all.
A: erickson is on the the right track.
On the areas of the site that are prone to session-timeout due to "complex forms/user interaction where there are few if no round trips to the server", you can place a keepalive control to keep pinging the server, thus keeping the session alive.
Here is a sample control that you can use, or use as a basis for coding your own.
A: Ah, the age old problem of not wanting to increase the session time because of higher memory usage.
One answer is to also set a cookie that expires after more like a day that will tell the system to still remember the user. That's what eBay does, among others.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing untampered data from Flash app to server? I'm looking for secure ways to pass data between a client running Flash and a server. The data in question will be generated BY the Flash app, which in this case is your score after finishing a game. I want to verify the data is untampered on the server. What are some good methods of getting this done?
One simple way is to perform some operations on the data such as a hash, and pass the hash back to the server along with the data. This is easily broken by someone with access to the client source code, however.
Edit: I realize that nothing will be unhackable, but I want to make it as difficult as possible. @jcnnghm's solution of encryping data with a public key and optionally doing sanity-checks and/or recalculation with the game logs is the best option I think. SSL encryption is also a good idea as this makes it more difficult to decipher what's actually being sent back to the server.
A: Encrypt the data with a public key stored in the binary. This will raise the barrier of entry for an attack. In addition to that, sanity check the data as it arrives on the server. This could be as simple as calculating the maximum number of points that could realistically be earned per time unit of play, or transmitting game logs back to the server to make sure the scoring is correct.
Nothing is going to be totally hack proof, no matter what you do, but this will stop all but the most determined.
Update: @mark: Flash supports SSL natively.
A: Can code running on top of an un-trustworthy platform retain its integrity? No, decades of broken copy-protection schemes lead me to postulate that this is impossible. The inverse, malicious code running in a trusted sandbox is feasible, but the best you can do with your problem is make it inconvenient for people to cheat.
A: Check out the AS3Crypto package at http://code.google.com/p/as3crypto/. I haven't tried it, but this package claims to (partially) support the TLS 1.0 protocol.
TLS will provide a secure tunnel between your Flash application and the server.
http://en.wikipedia.org/wiki/Secure_Sockets_Layer
@jcnnghm
You normally don't want to use public key encryption (RSA, DSA) for the bulk data encryption due to its' large computational time. Public key encryption should be used in the handshaking and key agreement phases in a security protocol, but the bulk data encryption should be handled by a symmetric cipher such as AES and TDES. The TLS and SSL protocols work this way.
A: As long as people can get at the executable - which, unless you want to run the game on a locked kiosk, is always the case - there's no perfectly secure way of doing this.
The music and movie industries spent tens of millions on DRM that got cracked by home hobbyists in days/weeks. If they can't protect their stuff...
A: I agree about the answers given about nothing is hacker proof. Because once you can read it, you can manipulate/copy it and therefor decompile it.
Another approach I have been planing is to generate unique keys pr. player session (including some kinda of time/date as salt values).
Then through out the application, perhaps periodically submitting/transmitting status score and gaining a new valid key. If this synkronisation fails, then break the whole session.
The downside on this could be too many simulitanious players bringing the reply speed of the server down and therefore making "fake timeouts" + leaving the gameserver open for DoS-attacks.
But something with renewing the "session key" while the user has the session, will requier at bit of extra session management, but if it will make the cheaters work a bit hardere I will sure try it :o)
On the other hand, NOTHING is hacker proof, so don't trust it 100% - no matter how clever a solution you think up.
A last note would also be to divide your application into modules/levels etc. so that you don't get access to every piece of the code, just by starting it.
Currently my plan is to build a large multilevel world and the client/player will ONLY get the files attached to the part the player resides in.
Hope this is of any use to your thoughts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Lisp list iteration I have a function that gets x(a value) and xs(a list) and removes all values that are bigger than x from the list. Well it doesn't work, can you tell me why?
(defun biggerElems(x xs)
(let ((xst))
(dolist (elem xs)
(if (> x elem)
(setf xst (remove elem xs))))
xst))
A: I think it's this line that's not right:
(setf xst (remove elem xs))))
The first argument to setf is the place, followed by the value. It looks like you have it backwards (and xst is either nil or uninitialized).
You might find it easier to do this:
(defun biggerElems (x xs)
(remove-if (lambda (item) (> item x)) xs))
A: Most concise AFAIK:
(defun bigger-elements (x xs) (remove x xs :test #'<))
returning a fresh list, it removes all elements y from xs for which
(< y x)
or using the famous LOOP:
(defun bigger-elements-2 (x xs)
(loop for e in xs
unless (< e x)
collect e))
A: It worked like that:
(defun filterBig (x xs)
(remove-if (lambda (item) (> item x)) xs))
What was the '#' for? It didn't compile with it.
A: If you want to do this the Lisp Way, you could use recursion to return the new list:
(defun biggerElems (x xs)
(cond ((null xs) NIL)
((< x (car xs))
(biggerElems x (cdr xs)))
(t
(cons (car xs) (biggerElems x (cdr xs))))))
@Luís Oliveira
This solution is to contrast with the one posted in the question. Had we needed to do something slightly more complicated it's important to be grounded in the recursive approach to manipulating lists.
A: @Ben: It isn't the setf call that is wrong--the problem is that he is not updating xs.
ie: xst is being set to xs with the element removed, but xs is not being updated. If a second element is to be removed, xst will have the first back in it.
you would need to bind xst to xs, and replace the xs in the remove call with xst. This would then remove all elements x is bigger than. ie:
(defun biggerElems(x xs)
(let ((xst xs))
(dolist (elem xs)
(when (> x elem)
(setf xst (remove elem xst))))
xst))
It might be slightly faster to set xst to (copy-list xs) and then use delete instead of remove (delete is destructive... depending on your implementation, it may be faster than remove. Since you are calling this multiple times, you may get better performance copying the list once and destructively deleting from it).
Alternatively:
(defun bigger-elems (x xs) ; I prefer hyphen separated to camelCase... to each his own
(loop for elem in xs when (<= x elem) collect elem))
Looking back over your original post, it is a little confusing... you say you remove all elements bigger than x, but your code looks like it is attempting to remove all elements x is bigger than. The solutions I wrote return all elements bigger than x (ie: remove all elements x is bigger than).
A:
What was the '#' for? It didn't
compile with it.
Typo. Normally you refer to functions with #' (like (remove-if #'oddp list)), but when I was editing, I forgot to remove the '#'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL Server unused, but allocated table space I have ms sql databases that grow very large. Upon examination I find that there is a bunch of unused space in certain tables. I don't do many physical deletes, so I don't think that its just deleted records. DBCC SHRINK doesn't make the file smaller. But, if I dump the table to a new, empty database, the size goes down about 80%. Instead of the 7gb I have in this table in the current database, I end up with about 1.5gb in the fresh database. Its as if sql server is allocating too much memory. Anyone encountered this before? I'd like to be able to shrink the table by removing unused allocated space without having to create a whole new database.
Additional information:
Full recovery model used. I'll try rebuilding the indexes, i think its been a while. ldf's are shrunk daily using some wacky stored proc that truncates them.
A: I have found that if you do not take care to backup your transistion log file (the LDF) you will get something like this behavior. I can not stress enough the importance of having good backup "hygiene". Not only will it save your bacon if something goes wrong but I will also help maintain a nice tight database.
A:
I don't do many physical deletes
what about updates of the table, what is the fragmentation level. run DBCC SHOWCONTIG, then rebuild the index if it is highly fragmented. After that do a BACKUP LOG WITH TRUNCATE_ONLY followed by a SHRINK command
A: In the options, you can specify how much you want to grow by. By default i believe it's 10%, so given a 200MB database, when you fill your last page, it will allocate another 20MB of page space. At 7GB it would allocate 700MB.
I don't know exactly where you can modify it after you create a db, but i know it has it when you create the db. a little google work will most likely reveal the answer to you.
NOTE: my answer is not how to fix it, but maybe how to prevent / explain why you might see all this unallocated space.
A: This has worked for me in the past
USE [DBNAME]
GO
DBCC SHRINKFILE (N'FILENAME' , 0, TRUNCATEONLY)
GO
A: I had a similar problem once and I believe that I found that reindex/shrinking didn't reclaim all of the unused space if there was no clustered index on a given table.
A: It is possible that the table was built with padding turned on for the index. The reason that people build a padded index is to prevent page splits.
Right click on the table in SQL Manager and select SCRIPT TABLE. Then look to see if PAD_INDEX=OFF. If PAD_INDEX is in use, that's probably where the table is taking up space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: WebBrowserControl Scroll to Bottom I am working on a simple chat application using a System.Windows.Forms.WebBrowser Control to display the messages between the user and the recipient. How do I get the control to automatically scroll to the bottom every time I update the DocumentText of the control?
A: Thanks guys -- I voted you both up but neither would work out for my situation. What I ended up doing was
webCtrl.Document.Window.ScrollTo(0, int.MaxValue);
A: I would use the AutoScrollOffset property and set it the the bottom left of the WebBrowser control, so something like:
webCtrl.AutoScrollOffset = new Point(0, webCtrl.Height);
A: This is probably overkill, but you could also invoke script on the WebBrowser control and then use the scroll properties of the body tag. Or the scrollTo method of the window.
To invoke script, the WebBrowser control has a Document property that represents the document object from the DOM. It has a method called InvokeScript that you can pass a string of JavaScript to be executed.
But... if the AutoScrollOffset property works... yeah, I'd just use that instead of getting into JavaScript :)
A: You can keep scroll position on top, and insert new message on top.
that don't need scroll to bottom, its look like twitter :)
user2:
new message ← a new message is insert on top
user1:
old message
A: public virtual void ScrollMessageIntoView()
{
System.Windows.Forms.Application.DoEvents();
if (browser == null || browser.IsDisposed)
return;
if (browser.Document == null)
{
browser.Document.Window.ScrollTo(0,
browser.Document.Body.ScrollRectangle.Height);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Read Access File into a DataSet Is there an easy way to read an entire Access file (.mdb) into a DataSet in .NET (specifically C# or VB)?
Or at least to get a list of tables from an access file so that I can loop through it and add them one at a time into a DataSet?
A: Thanks for the suggestions. I was able to use those samples to put together this code, which seems to achieve what I'm looking for.
Using cn = New OleDbConnection(connectionstring)
cn.Open()
Dim ds As DataSet = new DataSet()
Dim Schema As DataTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
For i As Integer = 0 To Schema.Rows.Count - 1
Dim dt As DataTable = New DataTable(Schema.Rows(i)!TABLE_NAME.ToString())
Using adapter = New OleDbDataAdapter("SELECT * FROM " + Schema.Rows(i)!TABLE_NAME.ToString(), cn)
adapter.Fill(dt)
End Using
ds.Tables.Add(dt)
Next i
End Using
A: You should be able to access it using an OleDbConnection.
Heres a tut on DB access using it for MS Access files.
In terms of getting the table names, back in my VB6 days I always used ADOX, not sure how they do this in .NET now.. Although I know there is a system table in the access file - wanna say "mso...". I google!
EDIT
Ah ha! msysobjects !! xD
A: MSDN has an article on how to use ADO.NET to connect and edit records in an Access database. Once your OleDB connection is made, you can easily create your DataReader/DataAdapter and process as needed.
EDIT: Gah! Curse you Rob and your god-like typing abilities!!! 8^D
A: There is a discussion on this point in Less Than Dot. Here is one example of code from the discussion.
public DataTable GetColumns(string tableName)
{
string[] restrictions = new string[4];
restrictions[2] = tableName;
_connDb.Open();
DataTable mDT = _connDb.GetSchema("Columns", restrictions);
_connDb.Close();
return mDT;
}
A: Your original question as worded is nonsense:
Is there an easy way to read an entire Access file (.mdb) into...
You certainly don't want the entire contents of the MDB file. What you want is the contents of your data tables that are stored in the MDB. Keep in mind that you don't want the contents of the system tables, either.
The key point:
You're asking about JET, not about ACCESS.
Jet is the database engine that ships as the default data store of Access (and in which Access's own objects are stored). But "Access" means something much more than just the data tables.
Whenever you ask a question and confuse Access and Jet, you will likely get at least some unuseful answers.
And you'll get scolded by the likes of me, because developers really should know better than to obfuscate crucial distinctions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: htmlentities() vs. htmlspecialchars() What are the differences between htmlspecialchars() and htmlentities(). When should I use one or the other?
A: htmlentities — Convert all applicable characters to HTML entities.
htmlspecialchars — Convert special characters to HTML entities.
The translations performed translation characters on the below:
*
*'&' (ampersand) becomes '&'
*'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
*"'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
*'<' (less than) becomes '<'
*'>' (greater than) becomes '>'
You can check the following code for more information about what's htmlentities and htmlspecialchars:
https://gist.github.com/joko-wandiro/f5c935708d9c37d8940b
A: You probably want to use some Unicode character encoding, for example UTF-8, and htmlspecialchars. Because there isn't any need to generate "HTML entities" for "all [the] applicable characters" (that is what htmlentities does according to the documentation) if it's already in your character set.
A: The differences between htmlspecialchars() and htmlentities() is very small. Lets see some examples:
htmlspecialchars
htmlspecialchars(string $string) takes multiple arguments where as the first argument is a string and all other arguments (certain flags, certain encodings etc. ) are optional. htmlspecialchars converts special characters in the string to HTML entities. For example if you have < br > in your string, htmlspecialchars will convert it into < b >. Whereas characters like µ † etc. have no special significance in HTML. So they will be not converted to HTML entities by htmlspecialchars function as shown in the below example.
echo htmlspecialchars('An example <br>'); // This will print - An example < br >
echo htmlspecialchars('µ †'); // This will print - µ †
htmlentities
htmlentities ( string $string) is very similar to htmlspecialchars and takes multiple arguments where as the first argument is a string and all other arguments are optional (certain flags, certain encodings etc.). Unlike htmlspecialchars, htmlentities converts not only special characters in the string to HTML entities but all applicable characters to HTML entities.
echo htmlentities('An example <br>'); // This will print - An example < br >
echo htmlentities('µ †'); // This will print - µ †
A: htmlspecialchars may be used:
*
*When there is no need to encode all characters which have their HTML equivalents.
If you know that the page encoding match the text special symbols, why would you use htmlentities? htmlspecialchars is much straightforward, and produce less code to send to the client.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
The second one is shorter, and does not cause any problems if ISO-8859-1 charset is set.
*When the data will be processed not only through a browser (to avoid decoding HTML entities),
*If the output is XML (see the answer by Artefacto).
A: From the PHP documentation for htmlentities:
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
From the PHP documentation for htmlspecialchars:
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead.
The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars).
I prefer to use htmlspecialchars whenever possible.
For example:
echo htmlentities('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^^^^^^^^ ^^^^^^^
echo htmlspecialchars('<Il était une fois un être>.');
// Output: <Il était une fois un être>.
// ^ ^
A: One small example, I needed to have 2 client names indexed in a function:
[1] => Altisoxxce Soluxxons S.à r.l.
[5] => Joxxson & Joxxson
I originally $term = get_term_by('name', htmlentities($name), 'client'); which resulted in term names that only included the ampersand array item (&) but not the accented item. But when I changed the variable setting to htmlspecialchars both were able to run through the function. Hope this helps!
A: You should use htmlspecialchars($strText, ENT_QUOTES) when you just want your string to be XML and HTML safe:
For example, encode
*
*& to &
*" to "
*< to <
*> to >
*' to '
However, if you also have additional characters that are Unicode or uncommon symbols in your text then you should use htmlentities() to ensure they show up properly in your HTML page.
Notes:
*
*' will only be encoded by htmlspecialchars() to ' if the ENT_QUOTES option is passed in. ' is safer to use then ' since older versions of Internet Explorer do not support the ' entity.
*Technically, > does not need to be encoded as per the XML specification, but it is usually encoded too for consistency with the requirement of < being encoded.
A: htmlspecialchars () does the minimum amount of encoding to ensure that your string is not parsed as HTML. This leaves your string more human-readable than it would be if you used htmlentities () to encode absolutely everything that has an encoding.
A: I just found out about the get_html_translation_table function. You pass it HTML_ENTITIES or HTML_SPECIALCHARS and it returns an array with the characters that will be encoded and how they will be encoded.
A: This is being encoded with htmlentities.
implode( "\t", array_values( get_html_translation_table( HTML_ENTITIES ) ) ):
" & < >
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë
Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ
œ Š š Ÿ ƒ ˆ ˜ Α Β Γ Δ Ε Ζ Η Θ Ι Κ Λ Μ Ν Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ ς σ τ
υ φ χ ψ ω ϑ ϒ ϖ – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ′ ″ ‹ › ‾ ⁄ € ℑ ℘ ℜ ™ ℵ ← ↑ → ↓ ↔ ↵ ⇐ ⇑ ⇒ ⇓ ⇔
∀ ∂ ∃ ∅ ∇ ∈ ∉ ∋ ∏ ∑ − ∗ √ ∝ ∞ ∠ ∧ ∨ ∩ ∪ ∫ ∴ ∼ ≅ ≈ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊄ ⊆ ⊇ ⊕ ⊗ ⊥ ⋅ ⌈ ⌉ ⌊ ⌋ ⟨
⟩ ◊ ♠ ♣ ♥ ♦
This is being encoded with htmlspecialchars.
implode( "\t", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) ):
" & < >
A: Because:
*
*Sometimes you're writing XML data, and you can't use HTML entities in a XML file.
*Because htmlentities substitutes more characters than htmlspecialchars. This is unnecessary, makes the PHP script less efficient and the resulting HTML code less readable.
htmlentities is only necessary if your pages use encodings such as ASCII or LATIN-1 instead of UTF-8 and you're handling data with an encoding different from the page's.
A: **HTML Character Entity Reference Chart at W3.org**
https://dev.w3.org/html5/html-author/charref
	


!
!
"
" "
#
#
$
$
%
%
&
& &
'
'
(
(
)
)
*
* *
+
+
,
,
.
.
/
/
:
:
;
;
<
< <
=
=
>
> >
?
?
@
@
[
[ [
\
\
]
] ]
^
^
_
_
`
` `
{
{ {
|
| | |
}
} }
 
¡
¡
¢
¢
£
£
¤
¤
¥
¥
¦
¦
§
§
¨
¨ ¨ ¨ ¨
©
© ©
ª
ª
«
«
¬
¬
­
®
® ® ®
¯
¯ ‾ ¯
°
°
±
± ± ±
²
²
³
³
´
´ ´
µ
µ
¶
¶
·
· · ·
¸
¸ ¸
¹
¹
º
º
»
»
¼
¼
½
½ ½
¾
¾
¿
¿
À
À
Á
Á
Â
Â
Ã
Ã
Ä
Ä
Å
Å
Æ
Æ
Ç
Ç
È
È
É
É
Ê
Ê
Ë
Ë
Ì
Ì
Í
Í
Î
Î
Ï
Ï
Ð
Ð
Ñ
Ñ
Ò
Ò
Ó
Ó
Ô
Ô
Õ
Õ
Ö
Ö
×
×
Ø
Ø
Ù
Ù
Ú
Ú
Û
Û
Ü
Ü
Ý
Ý
Þ
Þ
ß
ß
à
à
á
á
â
â
ã
ã
ä
ä
å
å
æ
æ
ç
ç
è
è
é
é
ê
ê
ë
ë
ì
ì
í
í
î
î
ï
ï
ð
ð
ñ
ñ
ò
ò
ó
ó
ô
ô
õ
õ
ö
ö
÷
÷ ÷
ø
ø
ù
ù
ú
ú
û
û
ü
ü
ý
ý
þ
þ
ÿ
ÿ
Ā
Ā
ā
ā
Ă
Ă
ă
ă
Ą
Ą
ą
ą
Ć
Ć
ć
ć
Ĉ
Ĉ
ĉ
ĉ
Ċ
Ċ
ċ
ċ
Č
Č
č
č
Ď
Ď
ď
ď
Đ
Đ
đ
đ
Ē
Ē
ē
ē
Ė
Ė
ė
ė
Ę
Ę
ę
ę
Ě
Ě
ě
ě
Ĝ
Ĝ
ĝ
ĝ
Ğ
Ğ
ğ
ğ
Ġ
Ġ
ġ
ġ
Ģ
Ģ
Ĥ
Ĥ
ĥ
ĥ
Ħ
Ħ
ħ
ħ
Ĩ
Ĩ
ĩ
ĩ
Ī
Ī
ī
ī
Į
Į
į
į
İ
İ
ı
ı ı
IJ
IJ
ij
ij
Ĵ
Ĵ
ĵ
ĵ
Ķ
Ķ
ķ
ķ
ĸ
ĸ
Ĺ
Ĺ
ĺ
ĺ
Ļ
Ļ
ļ
ļ
Ľ
Ľ
ľ
ľ
Ŀ
Ŀ
ŀ
ŀ
Ł
Ł
ł
ł
Ń
Ń
ń
ń
Ņ
Ņ
ņ
ņ
Ň
Ň
ň
ň
ʼn
ʼn
Ŋ
Ŋ
ŋ
ŋ
Ō
Ō
ō
ō
Ő
Ő
ő
ő
Œ
Œ
œ
œ
Ŕ
Ŕ
ŕ
ŕ
Ŗ
Ŗ
ŗ
ŗ
Ř
Ř
ř
ř
Ś
Ś
ś
ś
Ŝ
Ŝ
ŝ
ŝ
Ş
Ş
ş
ş
Š
Š
š
š
Ţ
Ţ
ţ
ţ
Ť
Ť
ť
ť
Ŧ
Ŧ
ŧ
ŧ
Ũ
Ũ
ũ
ũ
Ū
Ū
ū
ū
Ŭ
Ŭ
ŭ
ŭ
Ů
Ů
ů
ů
Ű
Ű
ű
ű
Ų
Ų
ų
ų
Ŵ
Ŵ
ŵ
ŵ
Ŷ
Ŷ
ŷ
ŷ
Ÿ
Ÿ
Ź
Ź
ź
ź
Ż
Ż
ż
ż
Ž
Ž
ž
ž
ƒ
ƒ
Ƶ
Ƶ
ǵ
ǵ
ȷ
ȷ
ˆ
ˆ
ˇ
ˇ ˇ
˘
˘ ˘
˙
˙ ˙
˚
˚
˛
˛
˜
˜ ˜
˝
˝ ˝
̑
̑
̲
_
Α
Α
Β
Β
Γ
Γ
Δ
Δ
Ε
Ε
Ζ
Ζ
Η
Η
Θ
Θ
Ι
Ι
Κ
Κ
Λ
Λ
Μ
Μ
Ν
Ν
Ξ
Ξ
Ο
Ο
Π
Π
Ρ
Ρ
Σ
Σ
Τ
Τ
Υ
Υ
Φ
Φ
Χ
Χ
Ψ
Ψ
Ω
Ω
α
α
β
β
γ
γ
δ
δ
ε
ϵ ϵ ε
ζ
ζ
η
η
θ
θ
ι
ι
κ
κ
λ
λ
μ
μ
ν
ν
ξ
ξ
ο
ο
π
π
ρ
ρ
ς
ς ς ς
σ
σ
τ
τ
υ
υ υ
φ
φ ϕ ϕ
χ
χ
ψ
ψ
ω
ω
ϑ
ϑ ϑ ϑ
ϒ
ϒ ϒ
ϕ
ϕ
ϖ
ϖ ϖ
Ϝ
Ϝ
ϝ
ϝ ϝ
ϰ
ϰ ϰ
ϱ
ϱ ϱ
ϵ
ε ϵ
϶
϶ ϶
Ё
Ё
Ђ
Ђ
Ѓ
Ѓ
Є
Є
Ѕ
Ѕ
І
І
Ї
Ї
Ј
Ј
Љ
Љ
Њ
Њ
Ћ
Ћ
Ќ
Ќ
Ў
Ў
Џ
Џ
А
А
Б
Б
В
В
Г
Г
Д
Д
Е
Е
Ж
Ж
З
З
И
И
Й
Й
К
К
Л
Л
М
М
Н
Н
О
О
П
П
Р
Р
С
С
Т
Т
У
У
Ф
Ф
Х
Х
Ц
Ц
Ч
Ч
Ш
Ш
Щ
Щ
Ъ
Ъ
Ы
Ы
Ь
Ь
Э
Э
Ю
Ю
Я
Я
а
а
б
б
в
в
г
г
д
д
е
е
ж
ж
з
з
и
и
й
й
к
к
л
л
м
м
н
н
о
о
п
п
р
р
с
с
т
т
у
у
ф
ф
х
х
ц
ц
ч
ч
ш
ш
щ
щ
ъ
ъ
ы
ы
ь
ь
э
э
ю
ю
я
я
ё
ё
ђ
ђ
ѓ
ѓ
є
є
ѕ
ѕ
і
і
ї
ї
ј
ј
љ
љ
њ
њ
ћ
ћ
ќ
ќ
ў
ў
џ
џ
 
 
 
 
 
 
   
   
​ ​ ​ ​ ​
‌
‍
‎
‏
‐
‐ ‐
–
–
—
—
―
―
‖
‖ ‖
‘
‘ ‘
’
’ ’ ’
‚
‚ ‚
“
“ “
”
” ” ”
„
„ „
†
†
‡
‡ ‡
•
• •
‥
‥
…
… …
‰
‰
‱
‱
′
′
″
″
‴
‴
‵
‵ ‵
‹
‹
›
›
‾
‾
⁁
⁁
⁃
⁃
⁄
⁄
⁏
⁏
⁗
⁗
 
⁠
⁡ ⁡
⁢ ⁢
⁣ ⁣
€
€
⃛
⃛ ⃛
⃜
⃜
ℂ
ℂ ℂ
℅
℅
ℊ
ℊ
ℋ
ℋ ℋ ℋ
ℌ
ℌ ℌ
ℍ
ℍ ℍ
ℎ
ℎ
ℏ
ℏ ℏ ℏ ℏ
ℐ
ℐ ℐ
ℑ
ℑ ℑ ℑ ℑ
ℒ
ℒ ℒ ℒ
ℓ
ℓ
ℕ
ℕ ℕ
№
№
℗
℗
℘
℘ ℘
ℙ
ℙ ℙ
ℚ
ℚ ℚ
ℛ
ℛ ℛ
ℜ
ℜ ℜ ℜ ℜ
ℝ
ℝ ℝ
℞
℞
™
™ ™
ℤ
ℤ ℤ
Ω
Ω
℧
℧
ℨ
ℨ ℨ
℩
℩
Å
Å
ℬ
ℬ ℬ ℬ
ℭ
ℭ ℭ
ℯ
ℯ
ℰ
ℰ ℰ
ℱ
ℱ ℱ
ℳ
ℳ ℳ ℳ
ℴ
ℴ ℴ ℴ
ℵ
ℵ ℵ
ℶ
ℶ
ℷ
ℷ
ℸ
ℸ
ⅅ
ⅅ ⅅ
ⅆ
ⅆ ⅆ
ⅇ
ⅇ ⅇ ⅇ
ⅈ
ⅈ ⅈ
⅓
⅓
⅔
⅔
⅕
⅕
⅖
⅖
⅗
⅗
⅘
⅘
⅙
⅙
⅚
⅚
⅛
⅛
⅜
⅜
⅝
⅝
⅞
⅞
←
← ← ← ← ←
↑
↑ ↑ ↑ ↑
→
→ → → → →
↓
↓ ↓ ↓ ↓
↔
↔ ↔ ↔
↕
↕ ↕ ↕
↖
↖ ↖ ↖
↗
↗ ↗ ↗
↘
↘ ↘ ↘
↙
↙ ↙ ↙
↚
↚ ↚
↛
↛ ↛
↝
↝ ↝
↞
↞ ↞
↟
↟
↠
↠ ↠
↡
↡
↢
↢ ↢
↣
↣ ↣
↤
↤ ↤
↥
↥ ↥
↦
↦ ↦ ↦
↧
↧ ↧
↩
↩ ↩
↪
↪ ↪
↫
↫ ↫
↬
↬ ↬
↭
↭ ↭
↮
↮ ↮
↰
↰ ↰
↱
↱ ↱
↲
↲
↳
↳
↵
↵
↶
↶ ↶
↷
↷ ↷
↺
↺ ↺
↻
↻ ↻
↼
↼ ↼ ↼
↽
↽ ↽ ↽
↾
↾ ↾ ↾
↿
↿ ↿ ↿
⇀
⇀ ⇀ ⇀
⇁
⇁ ⇁ ⇁
⇂
⇂ ⇂ ⇂
⇃
⇃ ⇃ ⇃
⇄
⇄ ⇄ ⇄
⇅
⇅ ⇅
⇆
⇆ ⇆ ⇆
⇇
⇇ ⇇
⇈
⇈ ⇈
⇉
⇉ ⇉
⇊
⇊ ⇊
⇋
⇋ ⇋ ⇋
⇌
⇌ ⇌ ⇌
⇍
⇍ ⇍
⇎
⇎ ⇎
⇏
⇏ ⇏
⇐
⇐ ⇐ ⇐
⇑
⇑ ⇑ ⇑
⇒
⇒ ⇒ ⇒ ⇒
⇓
⇓ ⇓ ⇓
⇔
⇔ ⇔ ⇔ ⇔
⇕
⇕ ⇕ ⇕
⇖
⇖
⇗
⇗
⇘
⇘
⇙
⇙
⇚
⇚ ⇚
⇛
⇛ ⇛
⇝
⇝
⇤
⇤ ⇤
⇥
⇥ ⇥
⇵
⇵ ⇵
⇽
⇽
⇾
⇾
⇿
⇿
∀
∀ ∀
∁
∁ ∁
∂
∂ ∂
∃
∃ ∃
∄
∄ ∄ ∄
∅
∅ ∅ ∅ ∅
∇
∇ ∇
∈
∈ ∈ ∈ ∈
∉
∉ ∉ ∉
∋
∋ ∋ ∋ ∋
∌
∌ ∌ ∌
∏
∏ ∏
∐
∐ ∐
∑
∑ ∑
−
−
∓
∓ ∓ ∓
∔
∔ ∔
∖
∖ ∖ ∖ ∖ ∖
∗
∗
∘
∘ ∘
√
√ √
∝
∝ ∝ ∝ ∝ ∝
∞
∞
∟
∟
∠
∠ ∠
∡
∡ ∡
∢
∢
∣
∣ ∣ ∣ ∣
∤
∤ ∤ ∤ ∤
∥
∥ ∥ ∥ ∥ ∥
∦
∦ ∦ ∦ ∦ ∦
∧
∧ ∧
∨
∨ ∨
∩
∩
∪
∪
∫
∫ ∫
∬
∬
∭
∭ ∭
∮
∮ ∮ ∮
∯
∯ ∯
∰
∰
∱
∱
∲
∲ ∲
∳
∳ ∳
∴
∴ ∴ ∴
∵
∵ ∵ ∵
∶
∶
∷
∷ ∷
∸
∸ ∸
∺
∺
∻
∻
∼
∼ ∼ ∼ ∼
∽
∽ ∽
∾
∾ ∾
∿
∿
≀
≀ ≀ ≀
≁
≁ ≁
≂
≂ ≂ ≂
≃
≃ ≃ ≃
≄
≄ ≄ ≄
≅
≅ ≅
≆
≆
≇
≇ ≇
≈
≈ ≈ ≈ ≈ ≈ ≈
≉
≉ ≉ ≉
≊
≊ ≊
≋
≋
≌
≌ ≌
≍
≍ ≍
≎
≎ ≎ ≎
≏
≏ ≏ ≏
≐
≐ ≐ ≐
≑
≑ ≑
≒
≒ ≒
≓
≓ ≓
≔
≔ ≔ ≔
≕
≕ ≕
≖
≖ ≖
≗
≗ ≗
≙
≙
≚
≚
≜
≜ ≜
≟
≟ ≟
≠
≠ ≠
≡
≡ ≡
≢
≢ ≢
≤
≤ ≤
≥
≥ ≥ ≥
≦
≦ ≦ ≦
≧
≧ ≧ ≧
≨
≨ ≨
≩
≩ ≩
≪
≪ ≪ ≪
≫
≫ ≫ ≫
≬
≬ ≬
≭
≭
≮
≮ ≮ ≮
≯
≯ ≯ ≯
≰
≰ ≰ ≰
≱
≱ ≱ ≱
≲
≲ ≲ ≲
≳
≳ ≳ ≳
≴
≴ ≴
≵
≵ ≵
≶
≶ ≶ ≶
≷
≷ ≷ ≷
≸
≸ ≸
≹
≹ ≹
≺
≺ ≺ ≺
≻
≻ ≻ ≻
≼
≼ ≼ ≼
≽
≽ ≽ ≽
≾
≾ ≾ ≾
≿
≿ ≿ ≿
⊀
⊀ ⊀ ⊀
⊁
⊁ ⊁ ⊁
⊂
⊂ ⊂
⊃
⊃ ⊃ ⊃
⊄
⊄
⊅
⊅
⊆
⊆ ⊆ ⊆
⊇
⊇ ⊇ ⊇
⊈
⊈ ⊈ ⊈
⊉
⊉ ⊉ ⊉
⊊
⊊ ⊊
⊋
⊋ ⊋
⊍
⊍
⊎
⊎ ⊎
⊏
⊏ ⊏ ⊏
⊐
⊐ ⊐ ⊐
⊑
⊑ ⊑ ⊑
⊒
⊒ ⊒ ⊒
⊓
⊓ ⊓
⊔
⊔ ⊔
⊕
⊕ ⊕
⊖
⊖ ⊖
⊗
⊗ ⊗
⊘
⊘
⊙
⊙ ⊙
⊚
⊚ ⊚
⊛
⊛ ⊛
⊝
⊝ ⊝
⊞
⊞ ⊞
⊟
⊟ ⊟
⊠
⊠ ⊠
⊡
⊡ ⊡
⊢
⊢ ⊢
⊣
⊣ ⊣
⊤
⊤ ⊤
⊥
⊥ ⊥ ⊥ ⊥
⊧
⊧
⊨
⊨ ⊨
⊩
⊩
⊪
⊪
⊫
⊫
⊬
⊬
⊭
⊭
⊮
⊮
⊯
⊯
⊰
⊰
⊲
⊲ ⊲ ⊲
⊳
⊳ ⊳ ⊳
⊴
⊴ ⊴ ⊴
⊵
⊵ ⊵ ⊵
⊶
⊶
⊷
⊷
⊸
⊸ ⊸
⊹
⊹
⊺
⊺ ⊺
⊻
⊻
⊽
⊽
⊾
⊾
⊿
⊿
⋀
⋀ ⋀ ⋀
⋁
⋁ ⋁ ⋁
⋂
⋂ ⋂ ⋂
⋃
⋃ ⋃ ⋃
⋄
⋄ ⋄ ⋄
⋅
⋅
⋆
⋆ ⋆
⋇
⋇ ⋇
⋈
⋈
⋉
⋉
⋊
⋊
⋋
⋋ ⋋
⋌
⋌ ⋌
⋍
⋍ ⋍
⋎
⋎ ⋎
⋏
⋏ ⋏
⋐
⋐ ⋐
⋑
⋑ ⋑
⋒
⋒
⋓
⋓
⋔
⋔ ⋔
⋕
⋕
⋖
⋖ ⋖
⋗
⋗ ⋗
⋘
⋘
⋙
⋙ ⋙
⋚
⋚ ⋚ ⋚
⋛
⋛ ⋛ ⋛
⋞
⋞ ⋞
⋟
⋟ ⋟
⋠
⋠ ⋠
⋡
⋡ ⋡
⋢
⋢ ⋢
⋣
⋣ ⋣
⋦
⋦
⋧
⋧
⋨
⋨ ⋨
⋩
⋩ ⋩
⋪
⋪ ⋪ ⋪
⋫
⋫ ⋫ ⋫
⋬
⋬ ⋬ ⋬
⋭
⋭ ⋭ ⋭
⋮
⋮
⋯
⋯
⋰
⋰
⋱
⋱
⋲
⋲
⋳
⋳
⋴
⋴
⋵
⋵
⋶
⋶
⋷
⋷
⋹
⋹
⋺
⋺
⋻
⋻
⋼
⋼
⋽
⋽
⋾
⋾
⌅
⌅ ⌅
⌆
⌆ ⌆
⌈
⌈ ⌈
⌉
⌉ ⌉
⌊
⌊ ⌊
⌋
⌋ ⌋
⌌
⌌
⌍
⌍
⌎
⌎
⌏
⌏
⌐
⌐
⌒
⌒
⌓
⌓
⌕
⌕
⌖
⌖
⌜
⌜ ⌜
⌝
⌝ ⌝
⌞
⌞ ⌞
⌟
⌟ ⌟
⌢
⌢ ⌢
⌣
⌣ ⌣
⌭
⌭
⌮
⌮
⌶
⌶
⌽
⌽
⌿
⌿
⍼
⍼
⎰
⎰ ⎰
⎱
⎱ ⎱
⎴
⎴ ⎴
⎵
⎵ ⎵
⎶
⎶
⏜
⏜
⏝
⏝
⏞
⏞
⏟
⏟
⏢
⏢
⏧
⏧
␣
␣
Ⓢ
Ⓢ Ⓢ
─
─ ─
│
│
┌
┌
┐
┐
└
└
┘
┘
├
├
┤
┤
┬
┬
┴
┴
┼
┼
═
═
║
║
╒
╒
╓
╓
╔
╔
╕
╕
╖
╖
╗
╗
╘
╘
╙
╙
╚
╚
╛
╛
╜
╜
╝
╝
╞
╞
╟
╟
╠
╠
╡
╡
╢
╢
╣
╣
╤
╤
╥
╥
╦
╦
╧
╧
╨
╨
╩
╩
╪
╪
╫
╫
╬
╬
▀
▀
▄
▄
█
█
░
░
▒
▒
▓
▓
□
□ □ □
▪
▪ ▪ ▪ ▪
▫
▫
▭
▭
▮
▮
▱
▱
△
△ △
▴
▴ ▴
▵
▵ ▵
▸
▸ ▸
▹
▹ ▹
▽
▽ ▽
▾
▾ ▾
▿
▿ ▿
◂
◂ ◂
◃
◃ ◃
◊
◊ ◊
○
○
◬
◬
◯
◯ ◯
◸
◸
◹
◹
◺
◺
◻
◻
◼
◼
★
★ ★
☆
☆
☎
☎
♀
♀
♂
♂
♠
♠ ♠
♣
♣ ♣
♥
♥ ♥
♦
♦ ♦
♪
♪
♭
♭
♮
♮ ♮
♯
♯
✓
✓ ✓
✗
✗
✠
✠ ✠
✶
✶
❘
❘
❲
❲
❳
❳
⟦
⟦ ⟦
⟧
⟧ ⟧
⟨
⟨ ⟨ ⟨
⟩
⟩ ⟩ ⟩
⟪
⟪
⟫
⟫
⟬
⟬
⟭
⟭
⟵
⟵ ⟵ ⟵
⟶
⟶ ⟶ ⟶
⟷
⟷ ⟷ ⟷
⟸
⟸ ⟸ ⟸
⟹
⟹ ⟹ ⟹
⟺
⟺ ⟺ ⟺
⟼
⟼ ⟼
⟿
⟿
⤂
⤂
⤃
⤃
⤄
⤄
⤅
⤅
⤌
⤌
⤍
⤍ ⤍
⤎
⤎
⤏
⤏ ⤏
⤐
⤐ ⤐
⤑
⤑
⤒
⤒
⤓
⤓
⤖
⤖
⤙
⤙
⤚
⤚
⤛
⤛
⤜
⤜
⤝
⤝
⤞
⤞
⤟
⤟
⤠
⤠
⤣
⤣
⤤
⤤
⤥
⤥ ⤥
⤦
⤦ ⤦
⤧
⤧
⤨
⤨ ⤨
⤩
⤩ ⤩
⤪
⤪
⤳
⤳
⤵
⤵
⤶
⤶
⤷
⤷
⤸
⤸
⤹
⤹
⤼
⤼
⤽
⤽
⥅
⥅
⥈
⥈
⥉
⥉
⥊
⥊
⥋
⥋
⥎
⥎
⥏
⥏
⥐
⥐
⥑
⥑
⥒
⥒
⥓
⥓
⥔
⥔
⥕
⥕
⥖
⥖
⥗
⥗
⥘
⥘
⥙
⥙
⥚
⥚
⥛
⥛
⥜
⥜
⥝
⥝
⥞
⥞
⥟
⥟
⥠
⥠
⥡
⥡
⥢
⥢
⥣
⥣
⥤
⥤
⥥
⥥
⥦
⥦
⥧
⥧
⥨
⥨
⥩
⥩
⥪
⥪
⥫
⥫
⥬
⥬
⥭
⥭
⥮
⥮ ⥮
⥯
⥯ ⥯
⥰
⥰
⥱
⥱
⥲
⥲
⥳
⥳
⥴
⥴
⥵
⥵
⥶
⥶
⥸
⥸
⥹
⥹
⥻
⥻
⥼
⥼
⥽
⥽
⥾
⥾
⥿
⥿
⦅
⦅
⦆
⦆
⦋
⦋
⦌
⦌
⦍
⦍
⦎
⦎
⦏
⦏
⦐
⦐
⦑
⦑
⦒
Not fully, pls track the link for fully document.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "593"
} |
Q: How to encrypt email addresses using JQuery Is there a way to use JQuery to cloak or encrypt email addresses on an HTML page without changing the syntax in the href?
A: Using JQuery may not be the route you want to take since this would be on the client side... Is there a reason you're not encrypting on server side?
A: Well, just as a comment, you probably want the source to have a cloaked email address and then use jQuery to fix or construct the link to have the correct address... because bots will be looking at the source, not the results of running your javascript ;-)
A: Semantic nazis would say "encoding", not "encrypting". Encrypting implies a secret is required to decode. Converting to HTML entity syntax would be a decent encoding process to keep out prying humans, but bots could easily decode it.
A: To kind of piggy-back on what Mike Stone was suggesting, what I would do is encrypt it on the server-side and have something on the server-side that will decrypt it and return it back as JSON (jsonresult in mvc framework, web service, http handler, whatever). That way you could use jQuery to de-obfuscate the e-mail addresses when you wanted but it would still confuse any bot that doesn't support java script. Again this is not a bullet proof solution but it may do what you're looking for.
A: What I've done is obfuscate it when it's rendered and hide it, then use javascript to fix the obfuscation and show the link.
For example, you can render this from the server:
<a href="mailto:some_address^^some_domain$$com" style='display:none'>Email me</a>
then using Javascript you can use regex to swap ^^ for @ and $$ for .
Whatever scheme you can come up with will probably be fine. Of course if the bot understands javascript then it doesn't matter anyway.
You'll block 95% of the bots that come your way and the rest of your users will see the address just fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Referencing Embedded resources from other resources in c# In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using ClientScriptManager.GetWebResourceUrl(). However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.
this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
Could become something like:
this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
A: I'd suggest that you emit the web resources as a dynamic javascript associative array.
Server side code:
StringBuilder script = new StringBuilder();
script.Append("var imgResources = {};");
script.AppendFormat("imgResources['{0}'] = '{1}';",
"drophint",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.dragdrophint.gif"));
script.AppendFormat("imgResources['{0}'] = '{1}';",
"anotherimg",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.anotherimg.gif"));
Page.ClientScript.RegisterClientScriptBlock(
Page.GetType(),
"imgResources",
script.ToString(),
true);
Then your client side code looks like this:
this.drophint = document.createElement('img');
this.drophint.src = imgResources['drophint'];
this.anotherimg = document.createElement('img');
this.anotherimg.src = imgResources['anotherimg'];
Hope this helps.
A: I don't particularly care for the exact implementation @Jon suggests, but the idea behind it is sound and I would concur that emitting these would be a good thing to do.
A slightly better implementation, though this is all subjective to some degree, would be to create a server-side model (read: C# class(es)) that represents this dictionary (or simply use an instance of Dictionary<string, string>) and serialize that to JavaScript literal object notation. That way you are not dealing with the string hacking you see in Jon's example (if that bothers you).
A: I concur with Jason's assessment of the initial solution I proposed, it can definitely be improved. My solution represents an older school javascript mentality (read, pre the emergence of ajax and JSON). There are always better ways to solve a problem, which one of the reasons why StackOverflow is so cool. Collectively we are better at the craft of programming than anyone of us on our own.
Based on Jason's ideas I'd revise my initial code, and revise some of what Jason suggested. Implement a C# class with two properties, the img resource id and a property that contains the WebResourceUrl. Then, where I differ some from Jason is that rather than using a Dictionary<string, string> I'd propose using a List<MyImageResourceClass>, which you can then in turn serialize to JSON (using DataContractJsonSerializer), and emit the JSON as the dynamic script, rather than manually generating the javascript using a string builder.
Why a List? I think you may find that dictionaries when serialized to JSON, at least using the DataContractJsonSerializer (fyi available with the 3.5 framework only, with the 2.0 or 3.0 framework you'd need to bolt on aspnet ajax and use is JSON serializer), are a little more cumbersome to work with than how a list would serialize. Although that is subjective.
There are implications too with your client side code. Now on the client side you'll have an array of the JSON serialized MyImageResourceClass instances. You'd need to iterate through this array creating your img tags as you go.
Hopefully, these ideas and suggestions can help get you going! And no doubt there are other solutions. I'm interested to see what comes of this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQL Server 2005 error Why can't you do this and is there are work around?
You get this error.
Msg 2714, Level 16, State 1, Line 13
There is already an object named '#temptable' in the database.
declare @x int
set @x = 1
if (@x = 0)
begin
select 1 as Value into #temptable
end
else
begin
select 2 as Value into #temptable
end
select * from #temptable
drop table #temptable
A: You can't do that because of deferred name resolution, you can do it with a real table, just take out the pound signs
You could also create the temp table first on top and then do a regular insert into table
A: First step... check if the table already exists... if it does, delete it. Next, explicitly create the table rather than using SELECT INTO...
You'll find it much more reliable that way.
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
BEGIN
DROP TABLE #temptable
END
CREATE TABLE #temptable (Value INT)
declare @x int
set @x = 1
if (@x = 0)
begin
INSERT INTO #temptable (Value) select 1
end
else
begin
INSERT INTO #temptable (Value) select 2
end
select * from #temptable
drop table #temptable
Also, hopefully the table and field names are simplified for your example and aren't what you really call them ;)
-- Kevin Fairchild
A: Deferred name resolution is also the reason you cannot be sure that sp_depends gives back correct results, check out this post I wrote a while back Do you depend on sp_depends (no pun intended)
A: This is a two-part question and while Kev Fairchild provides a good answer to the second question he totally ignores the first - why is the error produced?
The answer lies in the way the preprocessor works. This
SELECT field-list INTO #symbol ...
is resolved into a parse-tree that is directly equivalent to
DECLARE #symbol_sessionid TABLE(field-list)
INSERT INTO #symbol_sessionid SELECT field-list ...
and this puts #symbol into the local scope's name table. The business with _sessionid is to provide each user session with a private namespace; if you specify two hashes (##symbol) this behaviour is suppressed. Munging and unmunging of the sessionid extension is (ovbiously) transparent.
The upshot of all this is that multiple INTO #symbol clauses produce multiple declarations in the same scope, leading to Msg 2714.
A: I am going to guess that the issue is that you haven't created the #temptable.
Sorry I can't be more detailed but since you haven't even tried to explain what you are seeing you get a less than stellar answer.
A: From the look of the code is seems like you might have been prototyping this in SQL Studio or similiar, right? Can I guess that you've run this a few times and had it get to the point where it's created #temptable but then failed before it got to the end and dropped the table again? Restart the SQL editing tool you're using and try again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I avoid using Java Label Statements? Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?
A: I'm curious to hear what your alternative to labels is. I think this is pretty much going to boil down to the argument of "return as early as possible" vs. "use a variable to hold the return value, and only return at the end."
Labels are pretty standard when you have nested loops. The only way they really decrease readability is when another developer has never seen them before and doesn't understand what they mean.
A: I have use a Java labeled loop for an implementation of a Sieve method to find prime numbers (done for one of the project Euler math problems) which made it 10x faster compared to nested loops. Eg if(certain condition) go back to outer loop.
private static void testByFactoring() {
primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {
int toTest = m_toFactor[ctr];
for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {
// max (int) Math.sqrt(m_numberToTest) + 1 iterations
if (toTest != m_divisors[ctr2]
&& toTest % m_divisors[ctr2] == 0) {
continue primes;
}
} // end of the divisor loop
} // end of primes loop
} // method
I asked a C++ programmer how bad labeled loops are, he said he would use them sparingly, but they can occasionally come in handy. For example, if you have 3 nested loops and for certain conditions you want to go back to the outermost loop.
So they have their uses, it depends on the problem you were trying to solve.
A: I've never seen labels used "in the wild" in Java code. If you really want to break across nested loops, see if you can refactor your method so that an early return statement does what you want.
Technically, I guess there's not much difference between an early return and a label. Practically, though, almost every Java developer has seen an early return and knows what it does. I'd guess many developers would at least be surprised by a label, and probably be confused.
I was taught the single entry / single exit orthodoxy in school, but I've since come to appreciate early return statements and breaking out of loops as a way to simplify code and make it clearer.
A: I think with the new for-each loop, the label can be really clear.
For example:
sentence: for(Sentence sentence: paragraph) {
for(String word: sentence) {
// do something
if(isDone()) {
continue sentence;
}
}
}
I think that looks really clear by having your label the same as your variable in the new for-each. In fact, maybe Java should be evil and add implicit labels for-each variables heh
A: I'd argue in favour of them in some locations, I found them particularly useful in this example:
nextItem: for(CartItem item : user.getCart()) {
nextCondition : for(PurchaseCondition cond : item.getConditions()) {
if(!cond.check())
continue nextItem;
else
continue nextCondition;
}
purchasedItems.add(item);
}
A: Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.
Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.
What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.
Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.
A: Labels are like goto's: Use them sparingly, and only when they make your code faster and more importantly, more understandable,
e.g., If you are in big loops six levels deep and you encounter a condition that makes the rest of the loop pointless to complete, there's no sense in having 6 extra trap doors in your condition statements to exit out the loop early.
Labels (and goto's) aren't evil, it's just that sometimes people use them in bad ways. Most of the time we are actually trying to write our code so it is understandable for you and the next programmer who comes along. Making it uber-fast is a secondary concern (be wary of premature optimization).
When Labels (and goto's) are misused they make the code less readable, which causes grief for you and the next developer. The compiler doesn't care.
A: I never use labels in my code. I prefer to create a guard and initialize it to null or other unusual value. This guard is often a result object. I haven't seen any of my coworkers using labels, nor found any in our repository. It really depends on your style of coding. In my opinion using labels would decrease the readability as it's not a common construct and usually it's not used in Java.
A: There are few occasions when you need labels and they can be confusing because they are rarely used. However if you need to use one then use one.
BTW: this compiles and runs.
class MyFirstJavaProg {
public static void main(String args[]) {
http://www.javacoffeebreak.com/java101/java101.html
System.out.println("Hello World!");
}
}
A: Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent). In such a case I would advise adding sufficient comments or other documentation to explain the reasoning behind it so that someone doesn't come along later and mangle it out of some notion of "improving the code" or "getting rid of code smell" or some other potentially BS excuse.
I would equate this sort of question with deciding when one should or shouldn't use the ternary if. The chief rationale being that it can impede readability and unless the programmer is very careful to name things in a reasonable way then use of conventions such as labels might make things a lot worse. Suppose the example using 'nextCondition' and 'nextItem' had used 'loop1' and 'loop2' for his label names.
Personally labels are one of those features that don't make a lot of sense to me, outside of Assembly or BASIC and other similarly limited languages. Java has plenty of more conventional/regular loop and control constructs.
A: I found labels to be sometimes useful in tests, to separate the usual setup, excercise and verify phases and group related statements. For example, using the BDD terminology:
@Test
public void should_Clear_Cached_Element() throws Exception {
given: {
elementStream = defaultStream();
elementStream.readElement();
Assume.assumeNotNull(elementStream.lastRead());
}
when:
elementStream.clearLast();
then:
assertThat(elementStream.lastRead()).isEmpty();
}
Your formatting choices may vary but the core idea is that labels, in this case, provide a noticeable distinction between the logical sections comprising your test, better than comments can. I think the Spock library just builds on this very feature to declare its test phases.
A: Personally whenever I need to use nested loops with the innermost one having to break out of all the parent loops, I just write everything in a method with a return statement when my condition is met, it's far more readable and logical.
Example Using method:
private static boolean exists(int[][] array, int searchFor) {
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
return true;
}
}
}
return false;
}
Example Using label (less readable imo):
boolean exists = false;
existenceLoop:
for (int[] nums : array) {
for (int num : nums) {
if (num == searchFor) {
exists = true;
break existenceLoop;
}
}
}
return exists;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "69"
} |
Q: Automated Unit Testing Gen Tools for .NET Looking to get your take on an automated testing tool (voting should bring good ones to the top)
Ideal tool would:
*
*Eliminate the need to present a set
of values to a method.
*employ techniques such as Interactive
Exploratory Testing where the code
is examined to determine what values
are required to exercise all code
paths. i.e. the unit tests for a method is determined by the complexity of the code
For example, if a method checks that an integer argument is 123, at least 2 unit tests are generated: one where that argument is 123 and one where it is not.
For Java my understanding is these are some options but not .NET
*
*TestGen4J
*AgitarOne
Have heard of Pex - For .NET from Microsoft Research but this has a non-commercial license
Thanks
A: Pex enables parameterized unit testing and uses dynamic symbolic execution (some kind of automated exploratory testing) to generate inputs. Pex can understand the semantics of MSIL, i.e. of any managed method call. In the '123' example, Pex would find both tests.
It lets developers write parameterized unit tests - so it totally fits in a test-first development style.
For commercial software, Pex requires an MSDN license. More info at http://research.microsoft.com/pex
a pex developer :)
A: I've tried some of these tools in other languages and IMHO they are almost a complete waste of time. Reason? They can't guess at the semantics of a method call in any meaningful way. There's a very good article about this here -- well worth a read.
A: Another good tool that automatically generates unit tests is Randoop.
Randoop is available for Java (http://mernst.github.io/randoop/) and for .NET (https://github.com/abb-iss/Randoop.NET).
Randoop has found previously unknown errors in widely-used libraries including Sun and IBM's JDKs and in core Microsoft .NET components.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can Visual Studio put timestamps in the build log? In the build log I'd like to the start and end time of each project's compilation. Is there any way to get VS to do this?
A: Other option is to increase level of MSBuild verbosity.
Tools -> Options -> Projects and Solutions -> Build and Run ->
Set MSBuild project build output verbosity to Normal. That will give you output like this:
------ Build started: MyProject, Configuration: Debug x86 ------
Build started 24/03/2014 08:46:18.
...
Build succeeded.
Time Elapsed 00:00:05.18
A: For VC++ builds you can enable build timing. Go to Tools->Options->Projects and Solutions->VC++ Project settings and choose the option for 'Build Timing'
A: A new way I found is to call the Time command in the post event Pre and Post-build event command line:
TIME /T
A: Not without modifying the actual project file (using a text editor) to add calls in to the MSBuild script targets.
A: Alternate solution with script file...
Also includes Elapsed Time for the build for a project.
Create VBS file somewhere in your projects shared space "GetTime.vbs"
VBS Code ...
dim out : Set out = WScript.StdOut
Set objShell = WScript.CreateObject("WScript.Shell")
dim regDir: regDir="HKEY_CURRENT_USER\Software\VB and VBA Program Settings\GetTime.vbs\"
dim msg: msg=""
dim s: s=""
dim e: e=""
dim st:st=""
' param s is start flag keyed to the application being built.
if wscript.arguments.named.exists("s") then
s = wscript.arguments.named("s")
objShell.RegWrite regdir & s,now
end if
if wscript.arguments.named.exists("e") then
e = wscript.arguments.named("e")
st = cdate(objShell.RegRead(regDir & e))
end if
if e<>"" and isdate(st) then
out.writeline e & " ENDED " & now & " ELAPSED " & datediff("s",cdate(st),now) & " seconds"
elseif e<>"" then
out.writeline e & " ENDED " & now
elseif s<>"" then
out.writeline s & " STARTED " & now
else
out.writeline now
end if
Alter you Build Events to include this script with some parameters as such...
(You will need to alter the direcotry path relative to your output directory to find the file from multiple projects)
Prebuild Event Command Line ...
cscript "../../../../Scorecards/gettime.vbs" //B /s:"$(ProjectName)"
Post Build Event Command Line
cscript "../../../../Scorecards/gettime.vbs" //B /e:"$(ProjectName)"
Example output from multiple projects ...
2> OPResources STARTED 7/9/2020 12:59:04 PM
2> ...
2> OPResources ENDED 7/9/2020 12:59:05 PM ELAPSED 1 seconds
1> OPLib_WF STARTED 7/9/2020 12:59:04 PM
1> ...
1> OPLib_WF ENDED 7/9/2020 12:59:05 PM ELAPSED 1 seconds
4>------ Rebuild All started: Project: OPLib, Configuration: Debug Any CPU ------
4> OPLib STARTED 7/9/2020 12:59:06 PM
4> ...
4> OPLib ENDED 7/9/2020 12:59:10 PM ELAPSED 4 seconds
5>------ Rebuild All started: Project: PerfUpdater, Configuration: Debug Any CPU ------
6>------ Rebuild All started: Project: Scorecards2, Configuration: Debug Any CPU ------
7>------ Rebuild All started: Project: SingleSignOn, Configuration: Debug Any CPU ------
7> SingleSignOn STARTED 7/9/2020 12:59:10 PM
7> ...
7> SingleSignOn ENDED 7/9/2020 12:59:12 PM ELAPSED 2 seconds
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Can i get an image output for a Developer Express WebChartControl? I have a WebChartControl on my web page. When the chart was generated, an image is being produced and it was shown on the page.
Is there a way to get and save this chart as an image output on runtime?
A: Sure. Ultimately the image comes from a URL of some sort. Do a view-source on the web page and see what that URL looks like. With a certain amount of reverse-engineering, usage of System.Web.UI.HtmlTextWriter, perhaps an HttpHandler, etc. you should be able to get what you want.
A: The best solution for exporting an image from a Developer Express chart control (web) is:
((IChartContainer)[Your web chart control]).Chart.ExportToImage([Your file name], ImageFormat.Png);
A: Use the ExportToImage method of the ChartControl object .. This is WinForm code, but the same concept should hold true for WebChartControl:
Dim chart As ChartControl = ChartControl1.Clone()
chart.Size = New Size(800, 600)
chart.ExportToImage("file.png", System.Drawing.Imaging.ImageFormat.Png)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Do namespaces propagate to children in XElement objects? If I have an XElement that has child elements, and if I remove a child element from the parent, removing all references between the two, will the child XElement have the same namespaces as the parent?
In other words, if I have the following XML:
<parent xmlns:foo="abc">
<foo:child />
</parent>
and I remove the child element, will the child element's xml look like
<child xmlns="abc" />
or like
<child />
A: The answer is yes, namespaces do propagate to children.
You do NOT have to specify the namespace within child elements. The scoping of a namespace includes all elements until the closing tag of the element it was defined in.
See section #6.1 here http://www.w3.org/TR/REC-xml-names/#scoping
hope that helps
A: If you include mentioned element in the new xml tree it will be in the same namespace.
var xml1 = XElement.Parse("<a xmlns:foo=\"abc\"><foo:b></foo:b></a>");
var xml2 = XElement.Parse("<a xmlns:boo=\"efg\"></a>");
XNamespace ns = "abc";
var elem = xml1.Element(ns + "b");
elem.Remove();
xml2.Add(elem);
Console.WriteLine(xml1.ToString());
Console.WriteLine(xml2.ToString());
Result:
<a xmlns:foo="abc" />
<a xmlns:boo="efg">
<b xmlns="abc"></b>
</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When should you use the singleton pattern instead of a static class? Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :)
A: *
*Singletons can implement interfaces and inherit from other classes.
*Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections.
*Singletons offer an actual object.
*Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code.
A: I'd argue the only difference is syntax: MySingleton.Current.Whatever() vs MySingleton.Whatever(). The state, as David mentioned, is ultimately "static" in either case.
EDIT: The bury brigade came over from digg ... anyhow, I thought of a case that would require a singleton. Static classes cannot inherit from a base class nor implement an interface (at least in .Net they cannot). So if you require this functionality then you must use a singleton.
A: One of my favorite discussions about this issue is here (original site down, now linked to Internet Archive Wayback Machine.)
To summarize the flexibility advantages of a Singleton:
*
*a Singleton can be easily converted
into a factory
*a Singleton can be easily
modified to return different
subclasses
*this can result in a more maintainable application
A: A static class with a load of static variables is a bit of a hack.
/**
* Grotty static semaphore
**/
public static class Ugly {
private static int count;
public synchronized static void increment(){
count++;
}
public synchronized static void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized static boolean isClear(){
return count==0;
}
}
A singleton with an actual instance is better.
/**
* Grotty static semaphore
**/
public static class LessUgly {
private static LessUgly instance;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( instance==null){
instance = new LessUgly();
}
return instance;
}
public synchronized void increment(){
count++;
}
public synchronized void decrement(){
count--;
if( count<0 ) {
count=0;
}
}
public synchronized boolean isClear(){
return count==0;
}
}
The state is in ONLY in the instance.
So the singleton can be modified later to do pooling, thread-local instances etc.
And none of the already written code needs to change to get the benefit.
public static class LessUgly {
private static Hashtable<String,LessUgly> session;
private static FIFO<LessUgly> freePool = new FIFO<LessUgly>();
private static final POOL_SIZE=5;
private int count;
private LessUgly(){
}
public static synchronized getInstance(){
if( session==null){
session = new Hashtable<String,LessUgly>(POOL_SIZE);
for( int i=0; i < POOL_SIZE; i++){
LessUgly instance = new LessUgly();
freePool.add( instance)
}
}
LessUgly instance = session.get( Session.getSessionID());
if( instance == null){
instance = freePool.read();
}
if( instance==null){
// TODO search sessions for expired ones. Return spares to the freePool.
//FIXME took too long to write example in blog editor.
}
return instance;
}
It's possible to do something similar with a static class but there will be per-call overhead in the indirect dispatch.
You can get the instance and pass it to a function as an argument. This lets code be directed to the "right" singleton. We know you'll only need one of it... until you don't.
The big benefit is that stateful singletons can be made thread safe, whereas a static class cannot, unless you modify it to be a secret singleton.
A: Think of a singleton like a service. It's an object which provides a specific set of functionality. E.g.
ObjectFactory.getInstance().makeObject();
The object factory is an object which performs a specific service.
By contrast, a class full of static methods is a collection of actions that you might want to perform, organised in a related group (The class). E.g.
StringUtils.reverseString("Hello");
StringUtils.concat("Hello", "World");
The StringUtils example here is a collection of functionality that can be applied anywhere. The singleton factory object is a specific type of object with a clear responsibility that can be created and passed around where required.
A: Static classes are instantiated at runtime. This could be time consuming. Singletons can be instantiated only when needed.
A: Singletons should not be used in the same way as static classes. In essense,
MyStaticClass.GetInstance().DoSomething();
is essentially the same as
MyStaticClass.DoSomething();
What you should actually be doing is treating the singleton as just another object. If a service requires an instance of the singleton type, then pass that instance in the constructor:
var svc = new MyComplexServce(MyStaticClass.GetInstance());
The service should not be aware that the object is a singleton, and should treat the object as just an object.
The object can certainly be implemented, as an implementation detail and as an aspect of overall configuration, as a singleton if that makes things easier. But the things that use the object should not have to know whether the object is a singleton or not.
A: If by "static class" you mean a class that has only static variables, then they actually can maintain state. My understanding is the that the only difference would be how you access this thing. For example:
MySingleton().getInstance().doSomething();
versus
MySingleton.doSomething();
The internals of MySingleton will obviously be different between them but, thread-safety issues aside, they will both perform the same with regards to the client code.
A: Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. One example can be state codes.
A: How about "avoid both"? Singletons and static classes:
*
*May introduce global state
*Get tightly coupled to multiple other classes
*Hide dependencies
*Can make unit testing classes in isolation difficult
Instead, look into Dependency Injection and Inversion of Control Container libraries. Several of the IoC libraries will handle lifetime management for you.
(As always, there are exceptions, such as static math classes and C# extension methods.)
A: Singletons should never be used (unless you consider a class with no mutable state a singleton). "static classes" should have no mutable state, other than perhaps thread-safe caches and the like.
Pretty much any example of a singleton shows how not to do it.
A: If a singleton is something you can dispose of, to clean up after it, you can consider it when it's a limited resource (ie. only 1 of it) that you don't need all the time, and have some kind of memory or resource cost when it is allocated.
The cleanup code looks more natural when you have a singleton, as opposed to a static class containing static state fields.
The code, however, will look kind of the same either way so if you have more specific reasons for asking, perhaps you should elaborate.
A: The two can be quite similar, but remember that the true Singleton must itself be instantiated (granted, once) and then served. A PHP database class that returns an instance of mysqli is not really a Singleton (as some people call it), because it is returning an instance of another class, not an instance of the class that has the instance as a static member.
So, if you're writing a new class that you plan to allow only one instance of in your code, you might as well write it as a Singleton. Think of it as writing a plain-jane class and adding to it to facilitate the single-instantiation requirement. If you're using someone else's class that you can't modify (like mysqli), you should be using a static class (even if you fail to prefix its definition with the keyword).
A: Singletons are more flexible, which can be useful in cases where you want the Instance method to return different concrete subclasses of the Singleton's type based on some context.
A: Static classes can't be passed around as arguments; instances of a singleton can be. As mentioned in other answers, watch for threading issues with static classes.
rp
A: A singleton may have a constructor and destructor. Depending on your language, the constructor may be called automatically the first time your singleton is used, or never if your singleton is not used at all. A static class would have no such automatic initialization.
Once a reference to a singleton object is obtained, it can be used just like any other object. The client code may not even need to know its using a singleton if a reference to the singleton is stored earlier on:
Foo foo = Foo.getInstance();
doSomeWork(foo); // doSomeWork wont even know Foo is a singleton
This obviously makes things easier when you choose to ditch the Singleton pattern in favor of a real pattern, like IoC.
A: Use the singleton pattern when you need to compute something at runtime that you would compute at compile time if you could, like lookup tables.
A: I think a place where Singleton will make more sense than the static class is when you have to construct a pool of costly resources (like database connections). You would not be interested in creating the pool if noone ever uses them (static class will means that you do the costly work when class is loaded).
A: A singleton is also a good idea if you want to force efficient caching of data. for example, I have a class that looks up definitions in an xml document. Since parsing the document can take a while, I set up a cache of definitions (I use SoftReferences to avoid outOfmemeoryErrors). If the desired definition is not in the cache I do the expensive xml parsing. Otherwise I return a copy from the cache. Since having multiple caches would mean I still might have to load the same definition multiple times, I need to have a static cache. I choose to implement this class as a singleton so that I could write the class using only normal (non-static) data members. This allows me to still create an istantiation of the class should I need it for some reason (serialization, unit testing, etc.)
A: Singleton is like a service, as already mentioned. Pro is its flexibility.
Static, well, you need some static parts in order to implement Singleton.
Singleton has code to take care of instantiation of th actual object, which can be a great help if you run into racing problems. In a static solution you may need to deal with racing problems at multiple code locations.
However, same as Singleton can be constructed with some static variables, you may be able to compare it with 'goto'. It can bevery useful for building other structures, but you really need to know how to use it and should not 'overuse' it. Therefore general recommendation is to stick to Singleton, and use static if you have to.
also check the other post: Why choose a static class over a singleton implementation?
A: refer this
summary:
a. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.
b. use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, lot of n/w calls(connection pool) ..etc. To make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening
A: When the single class needs state. Singletons maintain a global state, static classes do not.
For instance, making a helper around a registry class: If you have changable hive (HKey Current User vs. HKEY Local Machine) you could go:
RegistryEditor editor = RegistryEditor.GetInstance();
editor.Hive = LocalMachine
Now any further calls to that singleton will operate on the Local Machine hive. Otherwise, using a static class, you would have to specify that Local Machine hive everytiem, or have a method like ReadSubkeyFromLocalMachine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "86"
} |
Q: How do I do backups in MySQL? How do I do backups in MySQL?
I'm hoping there'll be something better than just running mysqldump every "x" hours.
Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup?
Something like the DB log, where as long as the log doesn't die, you can restore up to the exact point where the DB died?
Also, how do these things affect locking?
I'd expect the online transactions to be locked for a while if I do a mysqldump.
A: now i am beginning to sound like a marketeer for this product. i answered a question with it here, then i answered another with it again here.
in a nutshell, try sqlyog (enterprise in your case) from webyog for all your mysql requirements. it not only schedules backups, but also schedules synchronization so you can actually replicate your database to a remote server.
it has a free community edition as well as an enterprise edition. i recommend the later to you though i also reccomend you start with the comm edition and first see how you like it.
A: I use mysqlhotcopy, a fast on-line hot-backup utility for local MySQL databases and tables. I'm pretty happy with it.
A: the Percona guys made a open source altenative to innobackup ...
Xtrabackup
https://launchpad.net/percona-xtrabackup/
Read this article about XtraDB
http://www.linux-mag.com/cache/7356/1.html
A: You might want to supplement your current offline backup scheme with MySQL replication.
Then if you have a hardware failure you can just swap machines. If you catch the failure quickly you're users won't even notice any downtime or data loss.
A: I use a simple script that dumps the mysql database into a tar.gz file, encrypts it using gpg and sends it to a mail account (Google Mail, but that's irrelevant really)
The script is a Python script, which basically runs the following command, and emails the output file.
mysqldump -u theuser -p mypassword thedatabase | gzip -9 - | gpg -e -r 12345 -r 23456 > 2008_01_02.tar.gz.gpg
This is the entire backup. It also has the web-backup part, which just tar/gzips/encrypts the files. It's a fairly small site, so the web backups are much less than 20MB, so can be sent to the GMail account without problem (the MySQL dumps are tiny, about 300KB compressed). It's extremely basic, and won't scale very well. I run it once a week using cron.
I'm not quite sure how we're supposed to put longish scripts in answers, so I'll just shove it as a code-block..
#!/usr/bin/env python
#encoding:utf-8
#
# Creates a GPG encrypted web and database backups, and emails it
import os, sys, time, commands
################################################
### Config
DATE = time.strftime("%Y-%m-%d_%H-%M")
# MySQL login
SQL_USER = "mysqluser"
SQL_PASS = "mysqlpassword"
SQL_DB = "databasename"
# Email addresses
BACKUP_EMAIL=["[email protected]", "[email protected]"] # Array of email(s)
FROM_EMAIL = "[email protected]" # Only one email
# Temp backup locations
DB_BACKUP="/home/backupuser/db_backup/mysite_db-%(date)s.sql.gz.gpg" % {'date':DATE}
WEB_BACKUP="/home/backupuser/web_backup/mysite_web-%(date)s.tar.gz.gpg" % {'date':DATE}
# Email subjects
DB_EMAIL_SUBJECT="%(date)s/db/mysite" % {'date':DATE}
WEB_EMAIL_SUBJECT="%(date)s/web/mysite" % {'date':DATE}
GPG_RECP = ["MrAdmin","MrOtherAdmin"]
### end Config
################################################
################################################
### Process config
GPG_RECP = " ".join(["-r %s" % (x) for x in GPG_RECP]) # Format GPG_RECP as arg
sql_backup_command = "mysqldump -u %(SQL_USER)s -p%(SQL_PASS)s %(SQL_DB)s | gzip -9 - | gpg -e %(GPG_RECP)s > %(DB_BACKUP)s" % {
'GPG_RECP':GPG_RECP,
'DB_BACKUP':DB_BACKUP,
'SQL_USER':SQL_USER,
'SQL_PASS':SQL_PASS,
'SQL_DB':SQL_DB
}
web_backup_command = "cd /var/www/; tar -c mysite.org/ | gzip -9 | gpg -e %(GPG_RECP)s > %(WEB_BACKUP)s" % {
'GPG_RECP':GPG_RECP,
'WEB_BACKUP':WEB_BACKUP,
}
# end Process config
################################################
################################################
### Main application
def main():
"""Main backup function"""
print "Backing commencing at %s" % (DATE)
# Run commands
print "Creating db backup..."
sql_status,sql_cmd_out = commands.getstatusoutput(sql_backup_command)
if sql_status == 0:
db_file_size = round(float( os.stat(DB_BACKUP)[6] ) /1024/1024, 2) # Get file-size in MB
print "..successful (%.2fMB)" % (db_file_size)
try:
send_mail(
send_from = FROM_EMAIL,
send_to = BACKUP_EMAIL,
subject = DB_EMAIL_SUBJECT,
text = "Database backup",
files = [DB_BACKUP],
server = "localhost"
)
print "Sending db backup successful"
except Exception,errormsg:
print "Sending db backup FAILED. Error was:",errormsg
#end try
# Remove backup file
print "Removing db backup..."
try:
os.remove(DB_BACKUP)
print "...successful"
except Exception, errormsg:
print "...FAILED. Error was: %s" % (errormsg)
#end try
else:
print "Creating db backup FAILED. Output was:", sql_cmd_out
#end if sql_status
print "Creating web backup..."
web_status,web_cmd_out = commands.getstatusoutput(web_backup_command)
if web_status == 0:
web_file_size = round(float( os.stat(WEB_BACKUP)[6] ) /1024/1024, 2) # File size in MB
print "..successful (%.2fMB)" % (web_file_size)
try:
send_mail(
send_from = FROM_EMAIL,
send_to = BACKUP_EMAIL,
subject = WEB_EMAIL_SUBJECT,
text = "Website backup",
files = [WEB_BACKUP],
server = "localhost"
)
print "Sending web backup successful"
except Exception,errormsg:
print "Sending web backup FAIELD. Error was: %s" % (errormsg)
#end try
# Remove backup file
print "Removing web backup..."
try:
os.remove(WEB_BACKUP)
print "...successful"
except Exception, errormsg:
print "...FAILED. Error was: %s" % (errormsg)
#end try
else:
print "Creating web backup FAILED. Output was:", web_cmd_out
#end if web_status
#end main
################################################
################################################
# Send email function
# needed email libs..
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
assert type(send_to)==list
assert type(files)==list
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
try:
part.set_payload( open(f,"rb").read() )
except Exception, errormsg:
raise IOError("File not found: %s"%(errormsg))
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
#end for f
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
#end send_mail
################################################
if __name__ == '__main__':
main()
A: You can make full dumps of InnoDB databases/tables without locking (downtime) via mysqldump with "--single-transaction --skip-lock-tables" options. Works well for making weekly snapshots + daily/hourly binary log increments (#Using the Binary Log to Enable Incremental Backups).
A: You might want to look at incremental backups.
A: mysqldump is a reasonable approach, but bear in mind that for some engines, this will lock your tables for the duration of the dump - and this has availability concerns for large production datasets.
An obvious alternative to this is mk-parallel-dump from Maatkit (http://www.maatkit.org/) which you should really check out if you're a mysql administrator. This dumps multiple tables or databases in parallel using mysqldump, thereby decreasing the amount of total time your dump takes.
If you're running in a replicated setup (and if you're using MySQL for important data in production, you have no excuses not to be doing so), taking dumps from a replication slave dedicated to the purpose will prevent any lock issues from causing trouble.
The next obvious alternative - on Linux, at least - is to use LVM snapshots. You can lock your tables, snapshot the filesystem, and unlock the tables again; then start an additional MySQL using a mount of that snapshot, dumping from there. This approach is described here: http://www.mysqlperformanceblog.com/2006/08/21/using-lvm-for-mysql-backup-and-replication-setup/
A: @Jake,
Thanks for the info.
Now, it looks like only the commercial version has backup features.
Isn't there ANYTHING built into MySQL to do decent backups?
The official MySQL page even recommends things like "well, you can copy the files, AS LONG AS THEY'RE NOT BEING UPDATED"...
A: The problem with a straight backup of the mysql database folder is that the backup will not necessarily be consistent, unless you do a write-lock during the backup.
I run a script that iterates through all of the databases, doing a mysqldump and gzip on each to a backup folder, and then backup that folder to tape.
This, however, means that there is no such thing as incremental backups, since the nightly dump is a complete dump. But I would argue that this could be a good thing, since a restore from a full backup will be a significantly quicker process than restoring from incrementals - and if you are backing up to tape, it will likely mean gathering a number of tapes before you can do a full restore.
In any case, whichever backup plan you go with, make sure to do a trial restore to ensure that it works, and get an idea of how long it might take, and exactly what the steps are that you need to go through.
A: the correct way to run incremental or continuous backups of a mysql server is with binary logs.
to start with, lock all of the tables or bring the server down. use mysql dump to make a backup, or just copy the data directory. you only have to do this once, or any time you want a FULL backup.
before you bring the server back up, make sure binary logging is enabled.
to take an incremental backup, log in to the server and issue a FLUSH LOGS command. then backup the most recently closed binary log file.
if you have all innodb tables, it's simpler to just use inno hot backup (not free) or mysqldump with the --single-transaction option (you'd better have a lot of memory to handle the transactions).
A: Binary logs are probably the correct way to do incremental backups, but if you don't trust binary file formats for permanent storage here is an ASCII way to do incremental backups.
mysqldump is not a bad format, the main problem is that it outputs stuff a table as one big line. The following trivial sed will split its output along record borders:
mysqldump --opt -p | sed -e "s/,(/,\n(/g" > database.dump
The resulting file is pretty diff-friendly, and I've been keeping them in a standard SVN repository fairly successfully. That also allows you to keep a history of backups, if you find that the last version got borked and you need last week's version.
A: This is a pretty solid solution for Linux shell. I have been using it for years:
http://sourceforge.net/projects/automysqlbackup/
*
*Does rolling backups: daily, monthly, yearly
*Lots of options
A: @Daniel,
in case you are still interested, there is a newish (new to me) solution shared by Paul Galbraith, a tool that allows for online backup of innodb tables called ibbackup from oracle which to quote Paul,
when used in conjunction with
innobackup, has worked great in
creating a nightly backup, with no
downtime during the backup
more detail can be found on Paul's blog
A: Sound like you are talking about transaction roll back.
So in terms of what you need, if you have the logs containing all historical queries, isn't that the backup already? Why do you need an incremental backup which is basically a redundant copy of all the information in DB logs?
If so, why don't you just use mysqldump and do the backup every once a while?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: ViewState and changing control order This has been a fun week (if you look back at my questions you'll see a common theme).
I have a repeater that is bound to a collection. Each repeater item dynamic control that corresponds to the collection item, it also renders out a header over each control that contains a Delete link.
When the delete link is clicked, the appropriate item is removed from the collection, and the repeater is rebound.
The problem I am encountering is that once I alter the repeater items, the state on some of the usercontrols is lost. Its always the same controls, regardless of where they are in the collection.
I'm wondering if changing the bound collection is a no-no, and it may confuse viewstate from properly restoring the values.
Can anyone clarify? How else can I do this?
A: Ok, answered my own question.
The answer is, don't...its a nightmare.
Instead, I added a softDelete flag, and instead of removing the item from the collection, I just set this flag. Then, the repeater does not render items are marked for deletion.
When the collection is saved, it discards the items marked for deletion, and saves...
Everything is fixed, if not in an odd way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can you programmatically restart a j2ee application? Does anyone know if it is possible to restart a J2EE application (from the application)? If so, how?
I would like to be able to do it in an app-server-agnostic way, if it is possible.
The application will be run on many different app servers-- basically whatever the client prefers.
If it isn't possible to do this in an app-server-agnostic manner, then it probably isn't really worth doing for my purposes. I can always just display a message informing the user that they will need to restart the app manually.
A: I would suggest that you're unlikely to find an appserver agnostic way. And while I don't pretend to know your requirements, I might question a design that requires the application to restart itself, other than an installer that is deploying a new version. Finally, I would suggest that for any nontrivial purpose "any" appserver will not work. You should have a list of supported app servers and versions, documented in your release notes, so you can test on all of those and dont have to worry about supporting clients on a non-conforming server/version. From experience, there are always subtle differences between, for example, Apache Tomcat and BEA WebLogic, and these differences are often undocument and hard to determine until you run into them.
A: Most application servers provide a JMX interface, so you could invoke that.
A: I'd suggest using servicewrapper to manage the application server, and then use its api methods for requesting a restart of the service. There would be some configuration involved and its hard to know if this would work in your particuar environment, but thats the only solution that I know of which is even reasonably cross-server compatible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: cfqueryparam with like operator in ColdFusion I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <cfqueryparam> tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator?
If my query looks like this:
select * from Foo where name like '%Bob%'
what should my <cfqueryparam> tag look like?
A: @Joel, I have to disagree.
select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" />
*
*Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!)
*The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently.
*When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are.
A: select a,b,c
from Foo
where name like <cfqueryparam cfsqltype="cf_sql_varchar" value="%Bob%" />;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: What is the ASP.NET process for IIS 7.0? Looking at what's running and nothing jumps out.
Thanks!
A: It should be w3wp.exe
EDIT: In line with Darren's comment, you should also check the "Show processes from all users" in Task Manager if that is where you are looking for the process.
A: Just to add something here, process explorer comes in handy when trying to track down a process:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
Beats task manager hands down and can be substituted.
A: make sure you have show all processes checked (in vs)
A: Furthermore if you need to look at the .NET/unmanaged stack just donwload Process Explorer and look at your w3wp.exe processes to examine memory and other stats without having to do a remote/local debugging (just look at the .NET Tab on the properties of the process). It will show all the .NET performance counters for that particular process.
Awesome tool!
A: Using TaskManager should show you the process W3WP.exe is the IIS worker process, if you have multiple instances adding the Column "Command Line" will show you which Application Pool is being hosted on each of them in the -ap switch.
Also, in the IIS Manager UI there is a "Worker Processes" feature that if you double click that you will see the list of processes, Memory and CPU they are consuming, and double clicking the instance will show you the list of executing requests on it, really useful when trying to figure out a "misbehaving" request.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Response.Redirect with POST instead of Get? We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET.
I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit();
Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic.
Anyway, thanks for any and all responses.
A: Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.
A: This should make life much easier.
You can simply use Response.RedirectWithData(...) method in your web application easily.
Imports System.Web
Imports System.Runtime.CompilerServices
Module WebExtensions
<Extension()> _
Public Sub RedirectWithData(ByRef aThis As HttpResponse, ByVal aDestination As String, _
ByVal aData As NameValueCollection)
aThis.Clear()
Dim sb As StringBuilder = New StringBuilder()
sb.Append("<html>")
sb.AppendFormat("<body onload='document.forms[""form""].submit()'>")
sb.AppendFormat("<form name='form' action='{0}' method='post'>", aDestination)
For Each key As String In aData
sb.AppendFormat("<input type='hidden' name='{0}' value='{1}' />", key, aData(key))
Next
sb.Append("</form>")
sb.Append("</body>")
sb.Append("</html>")
aThis.Write(sb.ToString())
aThis.End()
End Sub
End Module
A: Thought it might interesting to share that heroku does this with it's SSO to Add-on providers
An example of how it works can be seen in the source to the "kensa" tool:
https://github.com/heroku/kensa/blob/d4a56d50dcbebc2d26a4950081acda988937ee10/lib/heroku/kensa/post_proxy.rb
And can be seen in practice if you turn of javascript. Example page source:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Heroku Add-ons SSO</title>
</head>
<body>
<form method="POST" action="https://XXXXXXXX/sso/login">
<input type="hidden" name="email" value="XXXXXXXX" />
<input type="hidden" name="app" value="XXXXXXXXXX" />
<input type="hidden" name="id" value="XXXXXXXX" />
<input type="hidden" name="timestamp" value="1382728968" />
<input type="hidden" name="token" value="XXXXXXX" />
<input type="hidden" name="nav-data" value="XXXXXXXXX" />
</form>
<script type="text/javascript">
document.forms[0].submit();
</script>
</body>
</html>
A: HttpWebRequest is used for this.
On postback, create a HttpWebRequest to your third party and post the form data, then once that is done, you can Response.Redirect wherever you want.
You get the added advantage that you don't have to name all of your server controls to make the 3rd parties form, you can do this translation when building the POST string.
string url = "3rd Party Url";
StringBuilder postData = new StringBuilder();
postData.Append("first_name=" + HttpUtility.UrlEncode(txtFirstName.Text) + "&");
postData.Append("last_name=" + HttpUtility.UrlEncode(txtLastName.Text));
//ETC for all Form Elements
// Now to Send Data.
StreamWriter writer = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.ToString().Length;
try
{
writer = new StreamWriter(request.GetRequestStream());
writer.Write(postData.ToString());
}
finally
{
if (writer != null)
writer.Close();
}
Response.Redirect("NewPage");
However, if you need the user to see the response page from this form, your only option is to utilize Server.Transfer, and that may or may not work.
A: PostbackUrl can be set on your asp button to post to a different page.
if you need to do it in codebehind, try Server.Transfer.
A: @Matt,
You can still use the HttpWebRequest, then direct the response you receive to the actual outputstream response, this would serve the response back to the user. The only issue is that any relative urls would be broken.
Still, that may work.
A: Doing this requires understanding how HTTP redirects work. When you use Response.Redirect(), you send a response (to the browser that made the request) with HTTP Status Code 302, which tells the browser where to go next. By definition, the browser will make that via a GET request, even if the original request was a POST.
Another option is to use HTTP Status Code 307, which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning. To do that, you would write something like this:
public void PageLoad(object sender, EventArgs e)
{
// Process the post on your side
Response.Status = "307 Temporary Redirect";
Response.AddHeader("Location", "http://example.com/page/to/post.to");
}
Unfortunately, this won't always work. Different browsers implement this differently, since it is not a common status code.
Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, effectively changing 307 redirect into the more common 302.
So, as far as I know, the only way to implement something like this would be to use Javascript. There are two options I can think of off the top of my head:
*
*Create the form and have its action attribute point to the third-party server. Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server.
*Create the form to post to your server. When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs. Just show a message like "Redirecting...". Then, add a javascript event to the page that submits the form to the third-party server.
Of the two, I would choose the second, for two reasons. First, it is more reliable than the first because Javascript is not required for it to work; for those who don't have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds. Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want. Same for the 307 solution, assuming it worked for all of your users.
A: I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.
A: Here's what I'd do :
Put the data in a standard form (with no runat="server" attribute) and set the action of the form to post to the target off-site page.
Before submitting I would submit the data to my server using an XmlHttpRequest and analyze the response. If the response means you should go ahead with the offsite POSTing then I (the JavaScript) would proceed with the post otherwise I would redirect to a page on my site
A:
In PHP, you can send POST data with cURL. Is there something comparable for .NET?
Yes, HttpWebRequest, see my post below.
A: The GET (and HEAD) method should never be used to do anything that has side-effects. A side-effect might be updating the state of a web application, or it might be charging your credit card. If an action has side-effects another method (POST) should be used instead.
So, a user (or their browser) shouldn't be held accountable for something done by a GET. If some harmful or expensive side-effect occurred as the result of a GET, that would be the fault of the web application, not the user. According to the spec, a user agent must not automatically follow a redirect unless it is a response to a GET or HEAD request.
Of course, a lot of GET requests do have some side-effects, even if it's just appending to a log file. The important thing is that the application, not the user, should be held responsible for those effects.
The relevant sections of the HTTP spec are 9.1.1 and 9.1.2, and 10.3.
A: You can use this aproach:
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>",postbackUrl);
sb.AppendFormat("<input type='hidden' name='id' value='{0}'>", id);
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
As result right after client will get all html from server the event onload take place that triggers form submit and post all data to defined postbackUrl.
A: Typically, all you'll ever need is to carry some state between these two requests. There's actually a really funky way to do this which doesn't rely on JavaScript (think <noscript/>).
Set-Cookie: name=value; Max-Age=120; Path=/redirect.html
With that cookie there, you can in the following request to /redirect.html retrieve the name=value info, you can store any kind of information in this name/value pair string, up to say 4K of data (typical cookie limit). Of course you should avoid this and store status codes and flag bits instead.
Upon receiving this request you in return respond with a delete request for that status code.
Set-Cookie: name=value; Max-Age=0; Path=/redirect.html
My HTTP is a bit rusty I've been going trough RFC2109 and RFC2965 to figure how reliable this really is, preferably I would want the cookie to round trip exactly once but that doesn't seem to be possible, also, third-party cookies might be a problem for you if you are relocating to another domain. This is still possible but not as painless as when you're doing stuff within your own domain.
The problem here is concurrency, if a power user is using multiple tabs and manages to interleave a couple of requests belonging to the same session (this is very unlikely, but not impossible) this may lead to inconsistencies in your application.
It's the <noscript/> way of doing HTTP round trips without meaningless URLs and JavaScript
I provide this code as a prof of concept: If this code is run in a context that you are not familiar with I think you can work out what part is what.
The idea is that you call Relocate with some state when you redirect, and the URL which you relocated calls GetState to get the data (if any).
const string StateCookieName = "state";
static int StateCookieID;
protected void Relocate(string url, object state)
{
var key = "__" + StateCookieName + Interlocked
.Add(ref StateCookieID, 1).ToInvariantString();
var absoluteExpiration = DateTime.Now
.Add(new TimeSpan(120 * TimeSpan.TicksPerSecond));
Context.Cache.Insert(key, state, null, absoluteExpiration,
Cache.NoSlidingExpiration);
var path = Context.Response.ApplyAppPathModifier(url);
Context.Response.Cookies
.Add(new HttpCookie(StateCookieName, key)
{
Path = path,
Expires = absoluteExpiration
});
Context.Response.Redirect(path, false);
}
protected TData GetState<TData>()
where TData : class
{
var cookie = Context.Request.Cookies[StateCookieName];
if (cookie != null)
{
var key = cookie.Value;
if (key.IsNonEmpty())
{
var obj = Context.Cache.Remove(key);
Context.Response.Cookies
.Add(new HttpCookie(StateCookieName)
{
Path = cookie.Path,
Expires = new DateTime(1970, 1, 1)
});
return obj as TData;
}
}
return null;
}
A: Copy-pasteable code based on Pavlo Neyman's method
RedirectPost(string url, T bodyPayload) and GetPostData() are for those who just want to dump some strongly typed data in the source page and fetch it back in the target one.
The data must be serializeable by NewtonSoft Json.NET and you need to reference the library of course.
Just copy-paste into your page(s) or better yet base class for your pages and use it anywhere in you application.
My heart goes out to all of you who still have to use Web Forms in 2019 for whatever reason.
protected void RedirectPost(string url, IEnumerable<KeyValuePair<string,string>> fields)
{
Response.Clear();
const string template =
@"<html>
<body onload='document.forms[""form""].submit()'>
<form name='form' action='{0}' method='post'>
{1}
</form>
</body>
</html>";
var fieldsSection = string.Join(
Environment.NewLine,
fields.Select(x => $"<input type='hidden' name='{HttpUtility.UrlEncode(x.Key)}' value='{HttpUtility.UrlEncode(x.Value)}'>")
);
var html = string.Format(template, HttpUtility.UrlEncode(url), fieldsSection);
Response.Write(html);
Response.End();
}
private const string JsonDataFieldName = "_jsonData";
protected void RedirectPost<T>(string url, T bodyPayload)
{
var json = JsonConvert.SerializeObject(bodyPayload, Formatting.Indented);
//explicit type declaration to prevent recursion
IEnumerable<KeyValuePair<string, string>> postFields = new List<KeyValuePair<string, string>>()
{new KeyValuePair<string, string>(JsonDataFieldName, json)};
RedirectPost(url, postFields);
}
protected T GetPostData<T>() where T: class
{
var urlEncodedFieldData = Request.Params[JsonDataFieldName];
if (string.IsNullOrEmpty(urlEncodedFieldData))
{
return null;// default(T);
}
var fieldData = HttpUtility.UrlDecode(urlEncodedFieldData);
var result = JsonConvert.DeserializeObject<T>(fieldData);
return result;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "274"
} |
Q: When should one use a project reference opposed to a binary reference? My company has a common code library which consists of many class libary projects along with supporting test projects. Each class library project outputs a single binary, e.g. Company.Common.Serialization.dll. Since we own the compiled, tested binaries as well as the source code, there's debate as to whether our consuming applications should use binary or project references.
Some arguments in favor of project references:
*
*Project references would allow users to debug and view all solution code without the overhead of loading additional projects/solutions.
*Project references would assist in keeping up with common component changes committed to the source control system as changes would be easily identifiable without the active solution.
Some arguments in favor of binary references:
*
*Binary references would simplify solutions and make for faster solution loading times.
*Binary references would allow developers to focus on new code rather than potentially being distracted by code which is already baked and proven stable.
*Binary references would force us to appropriately dogfood our stuff as we would be using the common library just as those outside of our organization would be required to do.
*Since a binary reference can't be debugged (stepped into), one would be forced to replicate and fix issues by extending the existing test projects rather than testing and fixing within the context of the consuming application alone.
*Binary references will ensure that concurrent development on the class library project will have no impact on the consuming application as a stable version of the binary will be referenced rather than an influx version. It would be the decision of the project lead whether or not to incorporate a newer release of the component if necessary.
What is your policy/preference when it comes to using project or binary references?
A: It sounds to me as though you've covered all the major points. We've had a similar discussion at work recently and we're not quite decided yet.
However, one thing we've looked into is to reference the binary files, to gain all the advantages you note, but have the binaries built by a common build system where the source code is in a common location, accessible from all developer machines (at least if they're sitting on the network at work), so that any debugging can in fact dive into library code, if necessary.
However, on the same note, we've also tagged a lot of the base classes with appropriate attributes in order to make the debugger skip them completely, because any debugging you do in your own classes (at the level you're developing) would only be vastly outsized by code from the base libraries. This way when you hit the Step Into debugging shortcut key on a library class, you resurface into the next piece of code at your current level, instead of having to wade through tons of library code.
Basically, I definitely vote up (in SO terms) your comments about keeping proven library code out of sight for the normal developer.
Also, if I load the global solution file, that contains all the projects and basically, just everything, ReSharper 4 seems to have some kind of coronary problem, as Visual Studio practically comes to a stand-still.
A: In my opinion the greatest problem with using project references is that it does not provide consumers with a common baseline for their development. I am assuming that the libraries are changing. If that's the case, building them and ensuring that they are versioned will give you an easily reproducible environment.
Not doing this will mean that your code will mysteriously break when the referenced project changes. But only on some machines.
A: I tend to treat common libraries like this as 3rd-party resources. This allows the library to have it's own build processes, QA testing, etc. When QA (or whomever) "blesses" a release of the library, it's copied to a central location available to all developers. It's then up to each project to decide which version of the library to consume by copying the binaries to a project folder and using binary references in the projects.
One thing that is important is to create debug symbol (pdb) files with each build of the library and make those available as well. The other option is to actually create a local symbol store on your network and have each developer add that symbol store to their VS configuration. This would allow you to debug through the code and still have the benefits of usinng binary references.
As for the benefits you mention for project references, I don't agree with your second point. To me, it's important that the consuming projects explicitly know which version of the common library they are consuming and for them to take a deliberate step to upgrade that version. This is the best way to guarantee that you don't accidentally pick up changes to the library that haven't been completed or tested.
A: when you don't want it in your solution, or have potential to split your solution, send all library output to a common, bin directory and reference there.
I have done this in order to allow developers to open a tight solution that only has the Domain, tests and Web projects. Our win services, and silverlight stuff, and web control libraries are in seperate solutions that include the projects you need when looking at those, but nant can build it all.
A: I believe your question is actually about when projects go together in the same solution; the reason being that projects in the same solution should have project references to each other, and projects in different solutions should have binary references to each other.
I tend to think solutions should contain projects that are developed closely together. Such as your API assemblies and your implementations of those APIs.
Closeness is relative, however. A designer for an application, by definition, is closely related to the app, however you wouldn't want to have the designer and the application within the same solution (if they are at all complex, that is). You'd probably want to develop the designer against a branch of the program that is merged at intervals further spaced apart than the normal daily integration.
A: I think that if the project is not part of the solution, you shouldn't include it there... but that's just my opinion
I separate it by concept in short
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: When do you use POST and when do you use GET? From what I can gather, there are three categories:
*
*Never use GET and use POST
*Never use POST and use GET
*It doesn't matter which one you use.
Am I correct in assuming those three cases? If so, what are some examples from each case?
A: Use GET if you don't mind the request being repeated (That is it doesn't change state).
Use POST if the operation does change the system's state.
A: My general rule of thumb is to use Get when you are making requests to the server that aren't going to alter state. Posts are reserved for requests to the server that alter state.
A: One practical difference is that browsers and webservers have a limit on the number of characters that can exist in a URL. It's different from application to application, but it's certainly possible to hit it if you've got textareas in your forms.
Another gotcha with GETs - they get indexed by search engines and other automatic systems. Google once had a product that would pre-fetch links on the page you were viewing, so they'd be faster to load if you clicked those links. It caused major havoc on sites that had links like delete.php?id=1 - people lost their entire sites.
A: Use GET when you want the URL to reflect the state of the page. This is useful for viewing dynamically generated pages, such as those seen here. A POST should be used in a form to submit data, like when I click the "Post Your Answer" button. It also produces a cleaner URL since it doesn't generate a parameter string after the path.
A: Short Version
GET: Usually used for submitted search requests, or any request where you want the user to be able to pull up the exact page again.
Advantages of GET:
*
*URLs can be bookmarked safely.
*Pages can be reloaded safely.
Disadvantages of GET:
*
*Variables are passed through url as name-value pairs. (Security risk)
*Limited number of variables that can be passed. (Based upon browser. For example, Internet Explorer is limited to 2,048 characters.)
POST: Used for higher security requests where data may be used to alter a database, or a page that you don't want someone to bookmark.
Advantages of POST:
*
*Name-value pairs are not displayed in url. (Security += 1)
*Unlimited number of name-value pairs can be passed via POST. Reference.
Disadvantages of POST:
*
*Page that used POST data cannot be bookmark. (If you so desired.)
Longer Version
Directly from the Hypertext Transfer Protocol -- HTTP/1.1:
9.3 GET
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.
The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.
The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client.
The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.
See section 15.1.3 for security considerations when used for forms.
9.5 POST
The POST method is used to request that the origin server accept the
entity enclosed in the request as a new subordinate of the resource
identified by the Request-URI in the Request-Line. POST is designed
to allow a uniform method to cover the following functions:
*
*Annotation of existing resources;
*Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
*Providing a block of data, such as the result of submitting a
form, to a data-handling process;
*Extending a database through an append operation.
The actual function performed by the POST method is determined by the
server and is usually dependent on the Request-URI. The posted entity
is subordinate to that URI in the same way that a file is subordinate
to a directory containing it, a news article is subordinate to a
newsgroup to which it is posted, or a record is subordinate to a
database.
The action performed by the POST method might not result in a
resource that can be identified by a URI. In this case, either 200
(OK) or 204 (No Content) is the appropriate response status,
depending on whether or not the response includes an entity that
describes the result.
A: Because GETs are purely URLs, they can be cached by the web browser and may be better used for things like consistently generated images. (Set an Expiry time)
One example from the gravatar page: http://www.gravatar.com/avatar/4c3be63a4c2f539b013787725dfce802?d=monsterid
GET may yeild marginally better performance, some webservers write POST contents to a temporary file before invoking the handler.
Another thing to consider is the size limit. GETs are capped by the size of the URL, 1024 bytes by the standard, though browsers may support more.
Transferring more data than that should use a POST to get better browser compatibility.
Even less than that limit is a problem, as another poster wrote, anything in the URL could end up in other parts of the brower's UI, like history.
A: 1.3 Quick Checklist for Choosing HTTP GET or POST
Use GET if:
The interaction is more like a question (i.e., it is a safe operation such as a query, read operation, or lookup).
Use POST if:
The interaction is more like an order, or
The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
The user be held accountable for the results of the interaction.
Source.
A: Use POST for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action. So a URL like:
http://myblog.org/admin/posts/delete/357
Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way.
POST is also more secure than GET, because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea.
One final note: POST can transmit a larger amount of information than GET. 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters.
A: This traverses into the concept of REST and how the web was kinda intended on being used. There is an excellent podcast on Software Engineering radio that gives an in depth talk about the use of Get and Post.
Get is used to pull data from the server, where an update action shouldn't be needed. The idea being is that you should be able to use the same GET request over and over and have the same information returned. The URL has the get information in the query string, because it was meant to be able to be easily sent to other systems and people like a address on where to find something.
Post is supposed to be used (at least by the REST architecture which the web is kinda based on) for pushing information to the server/telling the server to perform an action. Examples like: Update this data, Create this record.
A: There is nothing you can't do per-se. The point is that you're not supposed to modify the server state on an HTTP GET. HTTP proxies assume that since HTTP GET does not modify the state then whether a user invokes HTTP GET one time or 1000 times makes no difference. Using this information they assume it is safe to return a cached version of the first HTTP GET. If you break the HTTP specification you risk breaking HTTP client and proxies in the wild. Don't do it :)
A: The first important thing is the meaning of GET versus POST :
*
*GET should be used to... get... some information from the server,
*while POST should be used to send some information to the server.
After that, a couple of things that can be noted :
*
*Using GET, your users can use the "back" button in their browser, and they can bookmark pages
*There is a limit in the size of the parameters you can pass as GET (2KB for some versions of Internet Explorer, if I'm not mistaken) ; the limit is much more for POST, and generally depends on the server's configuration.
Anyway, I don't think we could "live" without GET : think of how many URLs you are using with parameters in the query string, every day -- without GET, all those wouldn't work ;-)
A:
i dont see a problem using get though, i use it for simple things where it makes sense to keep things on the query string.
Using it to update state - like a GET of delete.php?id=5 to delete a page - is very risky. People found that out when Google's web accelerator started prefetching URLs on pages - it hit all the 'delete' links and wiped out peoples' data. Same thing can happen with search engine spiders.
A: POST can move large data while GET cannot.
But generally it's not about a shortcomming of GET, rather a convention if you want your website/webapp to be behaving nicely.
Have a look at http://www.w3.org/2001/tag/doc/whenToUseGet.html
A: From RFC 2616:
9.3 GET
The GET method means retrieve whatever information (in the form of
an entity) is identified by the
Request-URI. If the Request-URI refers
to a data-producing process, it is the
produced data which shall be returned
as the entity in the response and not
the source text of the process, unless
that text happens to be the output of
the process.
9.5 POST The POST method is used to request that the origin server
accept the entity enclosed in the
request as a new subordinate of the
resource identified by the Request-URI
in the Request-Line. POST is designed
to allow a uniform method to cover the
following functions:
*
*Annotation of existing resources;
*Posting a message to a bulletin board, newsgroup, mailing list, or
similar group of articles;
*Providing a block of data, such as the result of submitting a form, to a
data-handling process;
*Extending a database through an append operation.
The actual function performed by the
POST method is determined by the
server and is usually dependent on the
Request-URI. The posted entity is
subordinate to that URI in the same
way that a file is subordinate to a
directory containing it, a news
article is subordinate to a newsgroup
to which it is posted, or a record is
subordinate to a database.
The action performed by the POST
method might not result in a resource
that can be identified by a URI. In
this case, either 200 (OK) or 204 (No
Content) is the appropriate response
status, depending on whether or not
the response includes an entity that
describes the result.
A: In brief
*
*Use GET for safe andidempotent requests
*Use POST for neither safe nor idempotent requests
In details
There is a proper place for each. Even if you don't follow RESTful principles, a lot can be gained from learning about REST and how a resource oriented approach works.
A RESTful application will use GETs for operations which are both safe and idempotent.
A safe operation is an operation which does not change the data requested.
An idempotent operation is one in which the result will be the same no matter how many times you request it.
It stands to reason that, as GETs are used for safe operations they are automatically also idempotent. Typically a GET is used for retrieving a resource (a question and its associated answers on stack overflow for example) or collection of resources.
A RESTful app will use PUTs for operations which are not safe but idempotent.
I know the question was about GET and POST, but I'll return to POST in a second.
Typically a PUT is used for editing a resource (editing a question or an answer on stack overflow for example).
A POST would be used for any operation which is neither safe or idempotent.
Typically a POST would be used to create a new resource for example creating a NEW SO question (though in some designs a PUT would be used for this also).
If you run the POST twice you would end up creating TWO new questions.
There's also a DELETE operation, but I'm guessing I can leave that there :)
Discussion
In practical terms modern web browsers typically only support GET and POST reliably (you can perform all of these operations via javascript calls, but in terms of entering data in forms and pressing submit you've generally got the two options). In a RESTful application the POST will often be overriden to provide the PUT and DELETE calls also.
But, even if you are not following RESTful principles, it can be useful to think in terms of using GET for retrieving / viewing information and POST for creating / editing information.
You should never use GET for an operation which alters data. If a search engine crawls a link to your evil op, or the client bookmarks it could spell big trouble.
A: I use POST when I don't want people to see the QueryString or when the QueryString gets large. Also, POST is needed for file uploads.
I don't see a problem using GET though, I use it for simple things where it makes sense to keep things on the QueryString.
Using GET will allow linking to a particular page possible too where POST would not work.
A: Apart from the length constraints difference in many web browsers, there is also a semantic difference. GETs are supposed to be "safe" in that they are read-only operations that don't change the server state. POSTs will typically change state and will give warnings on resubmission. Search engines' web crawlers may make GETs but should never make POSTs.
Use GET if you want to read data without changing state, and use POST if you want to update state on the server.
A: The original intent was that GET was used for getting data back and POST was to be anything. The rule of thumb that I use is that if I'm sending anything back to the server, I use POST. If I'm just calling an URL to get back data, I use GET.
A: Read the article about HTTP in the Wikipedia. It will explain what the protocol is and what it does:
GET
Requests a representation of the specified resource. Note that GET should not be used for operations that cause side-effects, such as using it for taking actions in web applications. One reason for this is that GET may be used arbitrarily by robots or crawlers, which should not need to consider the side effects that a request should cause.
and
POST
Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. This may result in the creation of a new resource or the updates of existing resources or both.
The W3C has a document named URIs, Addressability, and the use of HTTP GET and POST that explains when to use what. Citing
1.3 Quick Checklist for Choosing HTTP GET or POST
*
*Use GET if:
*
*The interaction is more like a question (i.e., it is a
safe operation such as a query, read operation, or lookup).
and
*
*Use POST if:
*
*The interaction is more like an order, or
*The interaction changes the state of the resource in a way that the user would perceive (e.g., a subscription to a service), or
o The user be held accountable for the results of the interaction.
However, before the final decision to use HTTP GET or POST, please also consider considerations for sensitive data and practical considerations.
A practial example would be whenever you submit an HTML form. You specify either post or get for the form action. PHP will populate $_GET and $_POST accordingly.
A: In PHP, POST data limit is usually set by your php.ini. GET is limited by server/browser settings I believe - usually around 255 bytes.
A: From w3schools.com:
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable
communications between clients and servers.
HTTP works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that
hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to the server;
then the server returns a response to the client. The response
contains status information about the request and may also contain the
requested content.
Two HTTP Request Methods: GET and POST
Two commonly used methods for a request-response between a client and
server are: GET and POST.
GET – Requests data from a specified resource POST – Submits data to
be processed to a specified resource
Here we distinguish the major differences:
A: Another difference is that POST generally requires two HTTP operations, whereas GET only requires one.
Edit: I should clarify--for common programming patterns. Generally responding to a POST with a straight up HTML web page is a questionable design for a variety of reasons, one of which is the annoying "you must resubmit this form, do you wish to do so?" on pressing the back button.
A: Well one major thing is anything you submit over GET is going to be exposed via the URL. Secondly as Ceejayoz says, there is a limit on characters for a URL.
A: As answered by others, there's a limit on url size with get, and files can be submitted with post only.
I'd like to add that one can add things to a database with a get and perform actions with a post. When a script receives a post or a get, it can do whatever the author wants it to do. I believe the lack of understanding comes from the wording the book chose or how you read it.
A script author should use posts to change the database and use get only for retrieval of information.
Scripting languages provided many means with which to access the request. For example, PHP allows the use of $_REQUEST to retrieve either a post or a get. One should avoid this in favor of the more specific $_GET or $_POST.
In web programming, there's a lot more room for interpretation. There's what one should and what one can do, but which one is better is often up for debate. Luckily, in this case, there is no ambiguity. You should use posts to change data, and you should use get to retrieve information.
A: Gorgapor, mod_rewrite still often utilizes GET. It just allows to translate a friendlier URL into a URL with a GET query string.
A: HTTP Post data doesn't have a specified limit on the amount of data, where as different browsers have different limits for GET's. The RFC 2068 states:
Servers should be cautious about
depending on URI lengths above 255
bytes, because some older client or
proxy implementations may not properly
support these lengths
Specifically you should the right HTTP constructs for what they're used for. HTTP GET's shouldn't have side-effects and can be safely refreshed and stored by HTTP Proxies, etc.
HTTP POST's are used when you want to submit data against a url resource.
A typical example for using HTTP GET is on a Search, i.e. Search?Query=my+query
A typical example for using a HTTP POST is submitting feedback to an online form.
A: Simple version of POST GET PUT DELETE
*
*use GET - when you want to get any resource like List of data based on any Id or Name
*use POST - when you want to send any data to server. keep in mind POST is heavy weight operation because for updation we should use PUT instead of POST
internally POST will create new resource
*use PUT - when you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "403"
} |
Q: GOTO still considered harmful? Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here .html transcript and here .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in modern programming languages. Even the advanced continuation control structure in Scheme can be described as a sophisticated goto.
What circumstances warrant the use of goto? When is it best to avoid?
As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous?
Dijkstra himself regretted that title, for which he was not responsible. At the end of EWD1308 (also here .pdf) he wrote:
Finally a short story for the record.
In 1968, the Communications of the ACM
published a text of mine under the
title "The goto statement considered
harmful", which in later years would
be most frequently referenced,
regrettably, however, often by authors
who had seen no more of it than its
title, which became a cornerstone of
my fame by becoming a template: we
would see all sorts of articles under
the title "X considered harmful" for
almost any X, including one titled
"Dijkstra considered harmful". But
what had happened? I had submitted a
paper under the title "A case against
the goto statement", which, in order
to speed up its publication, the
editor had changed into a "letter to
the Editor", and in the process he had
given it a new title of his own
invention! The editor was Niklaus
Wirth.
A well thought out classic paper about this topic, to be matched to that of Dijkstra, is Structured Programming with go to Statements, by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong:
Donald E. Knuth: I believe that by presenting such a
view I am not in fact disagreeing
sharply with Dijkstra's ideas, since
he recently wrote the following:
"Please don't fall into the trap of
believing that I am terribly
dogmatical about [the go to
statement]. I have the uncomfortable
feeling that others are making a
religion out of it, as if the
conceptual problems of programming
could be solved by a single trick, by
a simple form of coding discipline!"
A: Goto is extremely low on my list of things to include in a program just for the sake of it. That doesn't mean it's unacceptable.
Goto can be nice for state machines. A switch statement in a loop is (in order of typical importance): (a) not actually representative of the control flow, (b) ugly, (c) potentially inefficient depending on language and compiler. So you end up writing one function per state, and doing things like "return NEXT_STATE;" which even look like goto.
Granted, it is difficult to code state machines in a way which make them easy to understand. However, none of that difficulty is to do with using goto, and none of it can be reduced by using alternative control structures. Unless your language has a 'state machine' construct. Mine doesn't.
On those rare occasions when your algorithm really is most comprehensible in terms of a path through a sequence of nodes (states) connected by a limited set of permissible transitions (gotos), rather than by any more specific control flow (loops, conditionals, whatnot), then that should be explicit in the code. And you ought to draw a pretty diagram.
setjmp/longjmp can be nice for implementing exceptions or exception-like behaviour. While not universally praised, exceptions are generally considered a "valid" control structure.
setjmp/longjmp are 'more dangerous' than goto in the sense that they're harder to use correctly, never mind comprehensibly.
There never has been, nor will there
ever be, any language in which it is
the least bit difficult to write bad
code. -- Donald Knuth.
Taking goto out of C would not make it any easier to write good code in C. In fact, it would rather miss the point that C is supposed to be capable of acting as a glorified assembler language.
Next it'll be "pointers considered harmful", then "duck typing considered harmful". Then who will be left to defend you when they come to take away your unsafe programming construct? Eh?
A: We already had this discussion and I stand by my point.
Furthermore, I'm fed up with people describing higher-level language structures as “goto in disguise” because they clearly haven't got the point at all. For example:
Even the advanced continuation control structure in Scheme can be described as a sophisticated goto.
That is complete nonsense. Every control structure can be implemented in terms of goto but this observation is utterly trivial and useless. goto isn't considered harmful because of its positive effects but because of its negative consequences and these have been eliminated by structured programming.
Similarly, saying “GOTO is a tool, and as all tools, it can be used and abused” is completely off the mark. No modern construction worker would use a rock and claim it “is a tool.” Rocks have been replaced by hammers. goto has been replaced by control structures. If the construction worker were stranded in the wild without a hammer, of course he would use a rock instead. If a programmer has to use an inferior programming language that doesn't have feature X, well, of course she may have to use goto instead. But if she uses it anywhere else instead of the appropriate language feature she clearly hasn't understood the language properly and uses it wrongly. It's really as simple as that.
A: "In this link http://kerneltrap.org/node/553/2131"
Ironically, eliminating the goto introduced a bug: the spinlock call was omitted.
A: In Linux: Using goto In Kernel Code on Kernel Trap, there's a discussion with Linus Torvalds and a "new guy" about the use of GOTOs in Linux code. There are some very good points there and Linus dressed in that usual arrogance :)
Some passages:
Linus: "No, you've been brainwashed by
CS people who thought that Niklaus
Wirth actually knew what he was
talking about. He didn't. He doesn't
have a frigging clue."
-
Linus: "I think goto's are fine, and
they are often more readable than
large amounts of indentation."
-
Linus: "Of course, in stupid languages
like Pascal, where labels cannot be
descriptive, goto's can be bad."
A: The original paper should be thought of as "Unconditional GOTO Considered Harmful". It was in particular advocating a form of programming based on conditional (if) and iterative (while) constructs, rather than the test-and-jump common to early code. goto is still useful in some languages or circumstances, where no appropriate control structure exists.
A: About the only place I agree Goto could be used is when you need to deal with errors, and each particular point an error occurs requires special handling.
For instance, if you're grabbing resources and using semaphores or mutexes, you have to grab them in order and you should always release them in the opposite manner.
Some code requires a very odd pattern of grabbing these resources, and you can't just write an easily maintained and understood control structure to correctly handle both the grabbing and releasing of these resources to avoid deadlock.
It's always possible to do it right without goto, but in this case and a few others Goto is actually the better solution primarily for readability and maintainability.
-Adam
A: In C, goto only works within the scope of the current function, which tends to localise any potential bugs. setjmp and longjmp are far more dangerous, being non-local, complicated and implementation-dependent. In practice however, they're too obscure and uncommon to cause many problems.
I believe that the danger of goto in C is greatly exaggerated. Remember that the original goto arguments took place back in the days of languages like old-fashioned BASIC, where beginners would write spaghetti code like this:
3420 IF A > 2 THEN GOTO 1430
Here Linus describes an appropriate use of goto: http://www.kernel.org/doc/Documentation/CodingStyle (chapter 7).
A: Today, it's hard to see the big deal about the GOTO statement because the "structured programming" people mostly won the debate and today's languages have sufficient control flow structures to avoid GOTO.
Count the number of gotos in a modern C program. Now add the number of break, continue, and return statements. Furthermore, add the number of times you use if, else, while, switch or case. That's about how many GOTOs your program would have had if you were writing in FORTRAN or BASIC in 1968 when Dijkstra wrote his letter.
Programming languages at the time were lacking in control flow. For example, in the original Dartmouth BASIC:
*
*IF statements had no ELSE. If you wanted one, you had to write:
100 IF NOT condition THEN GOTO 200
...stuff to do if condition is true...
190 GOTO 300
200 REM else
...stuff to do if condition is false...
300 REM end if
*Even if your IF statement didn't need an ELSE, it was still limited to a single line, which usually consisted of a GOTO.
*There was no DO...LOOP statement. For non-FOR loops, you had to end the loop with an explicit GOTO or IF...GOTO back to the beginning.
*There was no SELECT CASE. You had to use ON...GOTO.
So, you ended up with a lot of GOTOs in your program. And you couldn't depend on the restriction of GOTOs to within a single subroutine (because GOSUB...RETURN was such a weak concept of subroutines), so these GOTOs could go anywhere. Obviously, this made control flow hard to follow.
This is where the anti-GOTO movement came from.
A: One modern GOTO usage is by the C# compiler to create state machines for enumerators defined by yield return.
GOTO is something that should be used by compilers and not programmers.
A: Until C and C++ (amongst other culprits) have labelled breaks and continues, goto will continue to have a role.
A: If GOTO itself were evil, compilers would be evil, because they generate JMPs. If jumping into a block of code, especially following a pointer, were inherently evil, the RETurn instruction would be evil. Rather, the evil is in the potential for abuse.
At times I have had to write apps that had to keep track of a number of objects where each object had to follow an intricate sequence of states in response to events, but the whole thing was definitely single-thread. A typical sequence of states, if represented in pseudo-code would be:
request something
wait for it to be done
while some condition
request something
wait for it
if one response
while another condition
request something
wait for it
do something
endwhile
request one more thing
wait for it
else if some other response
... some other similar sequence ...
... etc, etc.
endwhile
I'm sure this is not new, but the way I handled it in C(++) was to define some macros:
#define WAIT(n) do{state=(n); enque(this); return; L##n:;}while(0)
#define DONE state = -1
#define DISPATCH0 if state < 0) return;
#define DISPATCH1 if(state==1) goto L1; DISPATCH0
#define DISPATCH2 if(state==2) goto L2; DISPATCH1
#define DISPATCH3 if(state==3) goto L3; DISPATCH2
#define DISPATCH4 if(state==4) goto L4; DISPATCH3
... as needed ...
Then (assuming state is initially 0) the structured state machine above turns into the structured code:
{
DISPATCH4; // or as high a number as needed
request something;
WAIT(1); // each WAIT has a different number
while (some condition){
request something;
WAIT(2);
if (one response){
while (another condition){
request something;
WAIT(3);
do something;
}
request one more thing;
WAIT(4);
}
else if (some other response){
... some other similar sequence ...
}
... etc, etc.
}
DONE;
}
With a variation on this, there can be CALL and RETURN, so some state machines can act like subroutines of other state machines.
Is it unusual? Yes. Does it take some learning on the part of the maintainer? Yes. Does that learning pay off? I think so. Could it be done without GOTOs that jump into blocks? Nope.
A: I actually found myself forced to use a goto, because I literally couldn't think of a better (faster) way to write this code:
I had a complex object, and I needed to do some operation on it. If the object was in one state, then I could do a quick version of the operation, otherwise I had to do a slow version of the operation. The thing was that in some cases, in the middle of the slow operation, it was possible to realise that this could have been done with the fast operation.
SomeObject someObject;
if (someObject.IsComplex()) // this test is trivial
{
// begin slow calculations here
if (result of calculations)
{
// just discovered that I could use the fast calculation !
goto Fast_Calculations;
}
// do the rest of the slow calculations here
return;
}
if (someObject.IsmediumComplex()) // this test is slightly less trivial
{
Fast_Calculations:
// Do fast calculations
return;
}
// object is simple, no calculations needed.
This was in a speed critical piece of realtime UI code, so I honestly think that a GOTO was justified here.
Hugo
A: One thing I've not seen from any of the answers here is that a 'goto' solution is often more efficient than one of the structured programming solutions often mentioned.
Consider the many-nested-loops case, where using 'goto' instead of a bunch of if(breakVariable) sections is obviously more efficient. The solution "Put your loops in a function and use return" is often totally unreasonable. In the likely case that the loops are using local variables, you now have to pass them all through function parameters, potentially handling loads of extra headaches that arise from that.
Now consider the cleanup case, which I've used myself quite often, and is so common as to have presumably been responsible for the try{} catch {} structure not available in many languages. The number of checks and extra variables that are required to accomplish the same thing are far worse than the one or two instructions to make the jump, and again, the additional function solution is not a solution at all. You can't tell me that's more manageable or more readable.
Now code space, stack usage, and execution time may not matter enough in many situations to many programmers, but when you're in an embedded environment with only 2KB of code space to work with, 50 bytes of extra instructions to avoid one clearly defined 'goto' is just laughable, and this is not as rare a situation as many high-level programmers believe.
The statement that 'goto is harmful' was very helpful in moving towards structured programming, even if it was always an over-generalization. At this point, we've all heard it enough to be wary of using it (as we should). When it's obviously the right tool for the job, we don't need to be scared of it.
A: I avoid it since a coworker/manager will undoubtedly question its use either in a code review or when they stumble across it. While I think it has uses (the error handling case for example) - you'll run afoul of some other developer who will have some type of problem with it.
It’s not worth it.
A: Almost all situations where a goto can be used, you can do the same using other constructs. Goto is used by the compiler anyway.
I personally never use it explicitly, don't ever need to.
A: Go To can provide a sort of stand-in for "real" exception handling in certain cases. Consider:
ptr = malloc(size);
if (!ptr) goto label_fail;
bytes_in = read(f_in,ptr,size);
if (bytes_in=<0) goto label_fail;
bytes_out = write(f_out,ptr,bytes_in);
if (bytes_out != bytes_in) goto label_fail;
Obviously this code was simplified to take up less space, so don't get too hung up on the details. But consider an alternative I've seen all too many times in production code by coders going to absurd lengths to avoid using goto:
success=false;
do {
ptr = malloc(size);
if (!ptr) break;
bytes_in = read(f_in,ptr,size);
if (count=<0) break;
bytes_out = write(f_out,ptr,bytes_in);
if (bytes_out != bytes_in) break;
success = true;
} while (false);
Now functionally this code does the exact same thing. In fact, the code generated by the compiler is nearly identical. However, in the programmer's zeal to appease Nogoto (the dreaded god of academic rebuke), this programmer has completely broken the underlying idiom that the while loop represents, and did a real number on the readability of the code. This is not better.
So, the moral of the story is, if you find yourself resorting to something really stupid in order to avoid using goto, then don't.
A: Donald E. Knuth answered this question in the book "Literate Programming", 1992 CSLI. On p. 17 there is an essay "Structured Programming with goto Statements" (PDF). I think the article might have been published in other books as well.
The article describes Dijkstra's suggestion and describes the circumstances where this is valid. But he also gives a number of counter examples (problems and algorithms) which cannot be easily reproduced using structured loops only.
The article contains a complete description of the problem, the history, examples and counter examples.
A: You can use it for breaking from a deeply nested loop, but most of the time your code can be refactored to be cleaner without deeply nested loops.
A: GOTO is like a table saw, extremely useful when appropriate safety measures are taken.
I consider it harmful, because most beginners lose fingers with both table saws, and GOTOs.
There are some situations where its the only way to control flow, but those situations can be avoided.
A: Yes, GOTO is still considered harmful. By the time you find yourself in the rare situation where the use of a GOTO might be valid, you should be confident enough in your own programming skill not to need the validation of others. Any GOTO-like functions that allow you to jump even farther away in scope than allowed by GOTO should be considered more dangerous than GOTO.
A: C++ contains constructors and destructors. This allows for a pattern know as RAII (resource allocation is initialization). Basically, you create a local stack variable, and the act of creating the stack variable opens a file, allocates memory, locks a mutex, or otherwise acquires a resource that must later be released.
When the variable goes out of scope, the destructor runs and frees the resource.
C doesn't have this feature. But you still often need to acquire resources at the beginning of a function, and release them at the end.
Your function probably has one or more error conditions that cause it to return early. You don't want to duplicate the resource release code. The solution is to use goto.
Example:
int
foo(const char *arg)
{
char *argcopy = strdup(arg);
if (!isvalid(argcopy))
goto out1;
FILE *myfile = fopen(argcopy, "r");
if (myfile == NULL)
goto out1;
char bytes[10];
if (fread(bytes, sizeof(bytes), 1, myfile) != sizeof(mybytes))
goto out2;
/* do some actual work */
/* .... */
/* end of actual work */
out2:
fclose(myfile);
out1:
free(argcopy);
return 0;
}
A: Goto considered helpful.
I started programming in 1975. To 1970s-era programmers, the words "goto considered harmful" said more or less that new programming languages with modern control structures were worth trying. We did try the new languages. We quickly converted. We never went back.
We never went back, but, if you are younger, then you have never been there in the first place.
Now, a background in ancient programming languages may not be very useful except as an indicator of the programmer's age. Notwithstanding, younger programmers lack this background, so they no longer understand the message the slogan "goto considered harmful" conveyed to its intended audience at the time it was introduced.
Slogans one does not understand are not very illuminating. It is probably best to forget such slogans. Such slogans do not help.
This particular slogan however, "Goto considered harmful," has taken on an undead life of its own.
Can goto not be abused? Answer: sure, but so what? Practically every programming element can be abused. The humble bool for example is abused more often than some of us would like to believe.
By contrast, I cannot remember meeting a single, actual instance of goto abuse since 1990.
The biggest problem with goto is probably not technical but social. Programmers who do not know very much sometimes seem to feel that deprecating goto makes them sound smart. You might have to satisfy such programmers from time to time. Such is life.
The worst thing about goto today is that it is not used enough.
A: Attracted by Jay Ballou adding an answer, I'll add my £0.02. If Bruno Ranschaert had not already done so, I'd have mentioned Knuth's "Structured Programming with GOTO Statements" article.
One thing that I've not seen discussed is the sort of code that, while not exactly common, was taught in Fortran text books. Things like the extended range of a DO loop and open-coded subroutines (remember, this would be Fortran II, or Fortran IV, or Fortran 66 - not Fortran 77 or 90). There's at least a chance that the syntactic details are inexact, but the concepts should be accurate enough. The snippets in each case are inside a single function.
Note that the excellent but dated (and out of print) book 'The Elements of Programming Style, 2nd Edn' by Kernighan & Plauger includes some real-life examples of abuse of GOTO from programming text books of its era (late-70s). The material below is not from that book, however.
Extended range for a DO loop
do 10 i = 1,30
...blah...
...blah...
if (k.gt.4) goto 37
91 ...blah...
...blah...
10 continue
...blah...
return
37 ...some computation...
goto 91
One reason for such nonsense was the good old-fashioned punch-card. You might notice that the labels (nicely out of sequence because that was canonical style!) are in column 1 (actually, they had to be in columns 1-5) and the code is in columns 7-72 (column 6 was the continuation marker column). Columns 73-80 would be given a sequence number, and there were machines that would sort punch card decks into sequence number order. If you had your program on sequenced cards and needed to add a few cards (lines) into the middle of a loop, you'd have to repunch everything after those extra lines. However, if you replaced one card with the GOTO stuff, you could avoid resequencing all the cards - you just tucked the new cards at the end of the routine with new sequence numbers. Consider it to be the first attempt at 'green computing' - a saving of punch cards (or, more specifically, a saving of retyping labour - and a saving of consequential rekeying errors).
Oh, you might also note that I'm cheating and not shouting - Fortran IV was written in all upper-case normally.
Open-coded subroutine
...blah...
i = 1
goto 76
123 ...blah...
...blah...
i = 2
goto 76
79 ...blah...
...blah...
goto 54
...blah...
12 continue
return
76 ...calculate something...
...blah...
goto (123, 79) i
54 ...more calculation...
goto 12
The GOTO between labels 76 and 54 is a version of computed goto. If the variable i has the value 1, goto the first label in the list (123); if it has the value 2, goto the second, and so on. The fragment from 76 to the computed goto is the open-coded subroutine. It was a piece of code executed rather like a subroutine, but written out in the body of a function. (Fortran also had statement functions - which were embedded functions that fitted on a single line.)
There were worse constructs than the computed goto - you could assign labels to variables and then use an assigned goto. Googling assigned goto tells me it was deleted from Fortran 95. Chalk one up for the structured programming revolution which could fairly be said to have started in public with Dijkstra's "GOTO Considered Harmful" letter or article.
Without some knowledge of the sorts of things that were done in Fortran (and in other languages, most of which have rightly fallen by the wayside), it is hard for us newcomers to understand the scope of the problem which Dijkstra was dealing with. Heck, I didn't start programming until ten years after that letter was published (but I did have the misfortune to program in Fortran IV for a while).
A:
A coworker of mine said the only reason to use a GOTO is if you programmed yourself so far into a corner that it is the only way out. In other words, proper design ahead of time and you won't need to use a GOTO later.
I thought this comic illustrates that beautifully "I could restructure the program's flow, or use one little 'GOTO' instead." A GOTO is a weak way out when you have weak design. Velociraptors prey on the weak.
A: On every platform I have seen, high level control structures are implemented as low level gotos (jumps). For example, the Java Virtual Machine has a Jump byte code, but nothing for if, else, while, for, etc.
And some of these compilers create spaghetti code for a simple conditional block.
To answer your question, goto is still considered harmful by people who believe it to be harmful. Goto makes it easy to lose the advantages of structured programming.
In the end, it's your program; and therefore your decision. I suggest not using goto until you are able to answer your question yourself, but in the context of a specific problem.
A: While I think it's best to avoid goto on almost any situation, there are exceptions.
For example, one place I've seen where goto statements are the elegant solution compared to others much more convoluted ways is implementing tail call elimintation for an interpreter.
A: The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks.
*
*Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes.
*The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.)
*Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns.
*Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)?
Footnotes to the above:
Regarding point 2, consider the following code:
a = b + 1
/* do something with a */
At the "do something" point in the code, we can state with high confidence that a is greater than b. (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.)
On the other hand, if the code had read this way:
...
goto 10
...
a = b + 1
10: /* do something with a */
...
goto 10
...
The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between a and b at that point. (In fact, in the general case it's undecideable!)
Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where
if (some condition) {
action-1
} else {
action-2
}
was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor.
A: There is no such things as GOTO considered harmful.
GOTO is a tool, and as all tools, it can be used and abused.
There are, however, many tools in the programming world that have a tendency to be abused more than being used, and GOTO is one of them. the WITH statement of Delphi is another.
Personally I don't use either in typical code, but I've had the odd usage of both GOTO and WITH that were warranted, and an alternative solution would've contained more code.
The best solution would be for the compiler to just warn you that the keyword was tainted, and you'd have to stuff a couple of pragma directives around the statement to get rid of the warnings.
It's like telling your kids to not run with scissors. Scissors are not bad, but some usage of them are perhaps not the best way to keep your health.
A: Since I began doing a few things in the linux kernel, gotos don't bother me so much as they once did. At first I was sort of horrified to see they (kernel guys) added gotos into my code. I've since become accustomed to the use of gotos, in some limited contexts, and will now occasionally use them myself. Typically, it's a goto that jumps to the end of a function to do some kind of cleanup and bail out, rather than duplicating that same cleanup and bailout in several places in the function. And typically, it's not something large enough to hand off to another function -- e.g. freeing some locally (k)malloc'ed variables is a typical case.
I've written code that used setjmp/longjmp only once. It was in a MIDI drum sequencer program. Playback happened in a separate process from all user interaction, and the playback process used shared memory with the UI process to get the limited info it needed to do the playback. When the user wanted to stop playback, the playback process just did a longjmp "back to the beginning" to start over, rather than some complicated unwinding of wherever it happened to be executing when the user wanted it to stop. It worked great, was simple, and I never had any problems or bugs related to it in that instance.
setjmp/longjmp have their place -- but that place is one you'll not likely visit but once in a very long while.
Edit: I just looked at the code. It was actually siglongjmp() that I used, not longjmp (not that it's a big deal, but I had forgotten that siglongjmp even existed.)
A: It never was, as long as you were able to think for yourself.
A: Because goto can be used for confusing metaprogramming
Goto is both a high-level and a low-level control expression, and as a result it just doesn't have a appropriate design pattern suitable for most problems.
It's low-level in the sense that a goto is a primitive operation that implements something higher like while or foreach or something.
It's high-level in the sense that when used in certain ways it takes code that executes in a clear sequence, in an uninterrupted fashion, except for structured loops, and it changes it into pieces of logic that are, with enough gotos, a grab-bag of logic being dynamically reassembled.
So, there is a prosaic and an evil side to goto.
The prosaic side is that an upward pointing goto can implement a perfectly reasonable loop and a downward-pointing goto can do a perfectly reasonable break or return. Of course, an actual while, break, or return would be a lot more readable, as the poor human wouldn't have to simulate the effect of the goto in order to get the big picture. So, a bad idea in general.
The evil side involves a routine not using goto for while, break, or return, but using it for what's called spaghetti logic. In this case the goto-happy developer is constructing pieces of code out of a maze of goto's, and the only way to understand it is to simulate it mentally as a whole, a terribly tiring task when there are many goto's. I mean, imagine the trouble of evaluating code where the else is not precisely an inverse of the if, where nested ifs might allow in some things that were rejected by the outer if, etc, etc.
Finally, to really cover the subject, we should note that essentially all early languages except Algol initially made only single statements subject to their versions of if-then-else. So, the only way to do a conditional block was to goto around it using an inverse conditional. Insane, I know, but I've read some old specs. Remember that the first computers were programmed in binary machine code so I suppose any kind of an HLL was a lifesaver; I guess they weren't too picky about exactly what HLL features they got.
Having said all that I used to stick one goto into every program I wrote "just to annoy the purists".
A: If you're writing a VM in C, it turns out that using (gcc's) computed gotos like this:
char run(char *pc) {
void *opcodes[3] = {&&op_inc, &&op_lda_direct, &&op_hlt};
#define NEXT_INSTR(stride) goto *(opcodes[*(pc += stride)])
NEXT_INSTR(0);
op_inc:
++acc;
NEXT_INSTR(1);
op_lda_direct:
acc = ram[++pc];
NEXT_INSTR(1);
op_hlt:
return acc;
}
works much faster than the conventional switch inside a loop.
A: Sometimes it is valid to use GOTO as an alternative to exception handling within a single function:
if (f() == false) goto err_cleanup;
if (g() == false) goto err_cleanup;
if (h() == false) goto err_cleanup;
return;
err_cleanup:
...
COM code seems to fall into this pattern fairly often.
A: I can only recall using a goto once. I had a series of five nested counted loops and I needed to be able to break out of the entire structure from the inside early based on certain conditions:
for{
for{
for{
for{
for{
if(stuff){
GOTO ENDOFLOOPS;
}
}
}
}
}
}
ENDOFLOOPS:
I could just have easily declared a boolean break variable and used it as part of the conditional for each loop, but in this instance I decided a GOTO was just as practical and just as readable.
No velociraptors attacked me.
A: Denying the use of the GOTO statement to programmers is like telling a carpenter not to use a hammer as it Might damage the wall while he is hammering in a nail. A real programmer Knows How and When to use a GOTO. I’ve followed behind some of these so-called ‘Structured Programs’ I’ve see such Horrid code just to avoid using a GOTO, that I could shoot the programmer. Ok, In defense of the other side, I’ve seen some real spaghetti code too and again, those programmers should be shot too.
Here is just one small example of code I’ve found.
YORN = ''
LOOP
UNTIL YORN = 'Y' OR YORN = 'N' DO
CRT 'Is this correct? (Y/N) : ':
INPUT YORN
REPEAT
IF YORN = 'N' THEN
CRT 'Aborted!'
STOP
END
-----------------------OR----------------------
10: CRT 'Is this Correct (Y)es/(N)o ':
INPUT YORN
IF YORN='N' THEN
CRT 'Aborted!'
STOP
ENDIF
IF YORN<>'Y' THEN GOTO 10
A: I only have the need for it in Basic (ie. VB, VBScript, etc.) and batch files. I then only use it for error handling. In Basic I tend only use the "on error goto". In batch files I have to use it because there isn't an else command. I then only use them as forward jumps to meaningful labels.
A: Using a goto makes it far too easy to write "spaghetti code" which is not particularly maintainable. The most important rule to follow is to write readable code, but of course it depends on what the goals of the project are. As a "best practice" avoiding a goto is a good idea. It's something extreme programming types would refer to as "code smell" because it indicates that you may be doing something wrong. Using a break while looping is remarkably similar to a goto, except it isn't a goto, but again is an indication that the code may not be optimal. This is why, I believe, it is also important to not find more modern programming loopholes which are essentially a goto by a different name.
A: Once, early in my programming life, I produced a program that consisted of a series of functions in a chain, where each function called its successor given successful conditions and completions.
It was a hideous cludge that had multiple serious problems, the most serious being that no function could terminate until all the functions under it had terminated.
But it was quickly developed, worked well for the limited set of problems it was designed to solve, and was showed the logic and flow of the program explicitly, which worked well when I refactored and extended it for inclusion in another project.
My vote's on use it when it makes sense, and refactor it out as soon as its convenient.
A: Many modern programming languages use their compiler to enforce restrictions on the usage of GOTO - this cuts down on the potential risks. For example, C# will not allow you to use GOTO to jump into the body of a loop from outside of it. Restrictions are mentioned in the documentation.
This is one example of how GOTO is sometimes safer than it used to be.
In some cases the use of GOTO is the same as returning early from a function (i.e. to break out of a loop early). However good form can be argued.
A: In my opinion, 'goto being harmful' is more about encapsulation and consistency of state than anything else.
Much code, even 'oo' code, has as bad messy state encapsultation as any spaghetti code ever did.
The problem with 'goto considered harmful' is that it leaves the programmer who only looks at the mechanistic rule without the understanding the impression that the only flow control that should be available is the return method, and that very easily leads to passing much state around by reference - and that leads right back to a lack of state encapsulation, the very thing that 'goto considered harmful' was trying to get rid of.
Follow the flow of control in a typical 'OO' codebase, and tell me that we don't still have spaghetti code.... (btw, I don't mean the 'ravioli' code that usuall gets so much hate - the path of execution of ravioli code is usually pretty straightforward, even if the object relationships aren't immediately obvious).
Or, to put it a different way, avoiding gotos in favor of everything being a subroutine is only useful if each subroutine only modifies local state, that cannot be modified except via that subroutine (or at least that object).
A: There are a few issues with goto. One is that it is difficult to see how the code flows. It is easier to see an if-block because of the curly braces, but a goto hides that from you. Also, while and if are also essentially gotos, but they help explain why you are jumping back and forth in your code. With a regular goto that you have to piece together yourself.
As an excercise try writing some code for calculating the fibonacci sequence and see how hard it is to read when you are done.
If you are going to be working on that code then I would recommend writing some unittests and rewriting it. Otherwise, just let it be.
All that said, sometimes, for performance reasons, it 'may' be appropriate to use a goto.
A: It's not that goto in of itself is bad; it's that using goto when the same logic can be more clearly expressed in another way is bad. It can make the code very hard to follow and makes maintenance hard. Just go and look at some programs in Basic from the Bad Old Days as an example.
In my opinion, in a modern language like C# we should never have a need for goto in normal circumstances. If I find myself using it, it's usually a sign that I need to rethink my logic --- there's almost certainly a clearer way of expressing the same code using normal code flow statements.
That said, there are special purposes for which goto can be extremely useful (and I find myself getting annoyed at languages that don't have it). I mostly use it in C for breaking out of multiple levels of loops, or for error handling; I believe that C# has language features that mean you don't have to do this. (It's also really useful when producing autogenerated code, but that's not something most people encounter in real life.)
There's also another problem with goto, which is purely political: a lot of people hate it, and using it in code, even if justified, may cause issues. If this is assignment code, then yes, rewrite it, or you're likely to get marked down. Otherwise I'd be inclined to leave it in until the next time you need to do maintenance on that section.
A: goto can be useful, here is an example of very strong open-source chess engine stockfish written in c++. The goto just skips some conditions checking (efficiency gain) that the program would have to do if not for the goto statement. If the goto statement label is after the goto declaration, then they are pretty harmless and readable.
A: The basic idea is that goto gives you too much freedom to do something you didn't intend to. It can cause errors in places that don't appear to be related to the goto statement, so it makes code maintenance more difficult. If you think you need a goto statement, you're wrong :) and you should instead rethink your code construction. This is why modern programming languages have put alot of effort into giving you readable, maintainable flow control constructs, and exception handling mechanisms.
I'm also going to disagree with lassevk. Since goto is abused more than correctly used, I believe it has no place in a well designed language. Even for goto's "ideal" uses, the other ways of doing it which require more code should be preferred.
So in summary, yes it is still considered harmful.
A: Look this, it's a good usse of GoTo, but in a language with garbage collector I think the only reason to use GoTo is to obfuscate your code (obfuscators tools use GoTo to hide their code)
A: Computed gotos for dispatch, often is easyer to understand than a very large switch statement.
For errors and co-threads I think setcontex or setjmp (where available) are 'better'.
A: Using a GOTO can be nice when you are generating C state machines. I would never use a GOTO in hand-written code - "modern" language constructs make it utterly unnecessary.
The setjmp/longjmp construct can be useful in certain circumstances (when "true" exceptions are missing, or when you are implementing something like Chicken scheme), but it has no place in "ordinary" programming.
A: In a perfect world we would never need a GOTO. However, we live in an imperfect world. We don't have compilers with every control structure we can dream of. On occasion I feel it's better to use a GOTO than kludge a control structure that doesn't really exist.
The most common (not that it's common) is the loop and a half construct. You always execute the first part, maybe you execute the rest of it and then go back and do the first part again. Sure, you can implement it with a boolean flag inside a while loop but I don't like this answer because it's less clear in my opinion. When you see something like:
loop:
GetSomeData;
if GotData then
Begin
ProcessTheData;
StoreTheResult;
Goto Loop;
End;
to me it's clearer than
Repeat
GetSomeData;
Flag := GotData;
if Flag then
Begin
ProcessTheData;
StoreTheResult;
End;
Until Not Flag;
and there are times where
Function GotTheData;
Begin
GetSomeData;
Result := GotData;
End;
While GotTheData do
Begin
ProcessTheData;
StoreTheResult;
End;
isn't a workable answer, and I'm a firm believer that code should be clear. If I have to make a comment explaining what the code is doing I consider whether I could make the code clearer and get rid of the comment.
A: Example of jump in Java String class source code:
int firstUpper;
/* Now check if there are any characters that need to be changed. */
scan: {
for (firstUpper = 0 ; firstUpper < count; ) {
char c = value[offset+firstUpper];
if ((c >= Character.MIN_HIGH_SURROGATE) &&
(c <= Character.MAX_HIGH_SURROGATE)) {
int supplChar = codePointAt(firstUpper);
if (supplChar != Character.toLowerCase(supplChar)) {
break scan;
}
firstUpper += Character.charCount(supplChar);
} else {
if (c != Character.toLowerCase(c)) {
break scan;
}
firstUpper++;
}
}
return this;
}
[... subsequent use of firstUpper ...]
this could be rewritten with very little overhead for instance as:
int firstUpper = indexOfFirstUpper();
if (firstUpper < 0) return this;
Even in modern languages, and even if I don't actually like the use of gotos but I consider those acceptable in many cases, in a low-level case like this one looks better to me (and it does a little more than just exiting the loop).
No intention to reanimate a religion war.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "310"
} |
Q: DotNetNuke using PNG images with Transparency I have a DotNetNuke site where my main logo is a PNG file using transparency. I tried GIF but the quality wasn't good enough.
Anyways it worked great on IE7 but I just saw my site in IE6 and noticed that the transparency isn't working with my logo.
Does anyone know of a quick way to fix this in a DotNetNuke portal?
A: I don't know that it's a DotNetNuke issue as much as it is IE6. Anyways, here's a site that shows you how to work around IE6's png issues. Hope it helps.
http://24ways.org/2007/supersleight-transparent-png-in-ie6
A: For a DotNetNuke-specific way to fix the issue, you can install the DotNetNuke Widget Suite, and use the IE PNG Fix widget on your site (probably include it in your skin).
That said, if you're going to need to integrate something into your skin anyway, the widget doesn't give you a whole lot of advantage. If you're able to evaluate and integrate the techniques in the accepted answer, that's probably a better route to take.
A: IE6 doesn't support transparent PNGs. It isn't a DotNetNuke issue. You could try looking into some JavaScript solutions that help with IE6.
A: Googling "pngfix" should find a lot of different techniques for enabling alpha transparency in IE6.
One common one is a HTC behaviour file.
A: It has nothing to do with DotNetNuke, it's an IE6 thing. IE6 doesn't do very well with certain transparent PNG.
A: You can't. IE6 only supports a specific, and visually ugly, version of PNG transparency. I believe its PNG-8.
You can use a conditional comment to handle IE6 differently:
<!--[if IE 6]>
background-image:crappy.gif
<![endif]-->
A: There are some discussions regarding this on dotnetnuke.com forums, but I had the wrong date criteria in my search so the reason I didn't see any responses previously and thought I would ask here.
I think I found what I am looking for from a dotnetnuke perspective its a module that you install on your page which fixes this problem automatically. But unfortunately you have to pay for it. (I won't post the link since I don't want people thinking I was am asking just to advertise for them.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Copying from network share using BAT What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter?
A: Can you just use the full UNC path to the file?
copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles
A: You can specify the drive letter for net use. Put this in the command prompt for more info:
net use /?
A: You can also use xcopy and robocopy:
xcopy "\\server\share\path" "destination"
robocopy "\\server\share\path" "destination"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Does anyone here have a favorite memory profiling/memory leak tool they like to use for their java webapps? I'm looking for a good tool to profile a java webapp. I'd like to get performance information and memory usage if possible.
Any suggestions?
A: JProfiler is a really good one. It integrates with all the major IDEs and application servers.
A: The Eclipse Memory Analyzer is the best tool for analysing the memory usage of java applications
A: I use Netbeans Profiler:
alt text http://www.netbeans.org/images/v6/1/features/profiler-java-cut.png
Its free, has task based profiling, a heap walker, allows the insertion of profiling points, tracks memory usage and threading, but best of all it allows you to profile remote JVM's. You can even attach to ones which are already running.
Oh, and it works really well if you've a maven build for your project too.
A: SmartInspect is a profiler and logger. Not specific to memory, but you might want to take a look. It works with a variety of languages too, including Delphi, Java and .NET. Includes other more advanced features.
A: I've used YourKit Java Profiler 7.5 and was reasonably happy with it. Java has some pretty good tools included with recent releases that are worth looking into. (e.g., jmap -histo <pid>)
A: I like to use SAP Memory Analyzer, which is based in Eclipse. It works very well, also for large heap dumps!
A: For initial investigation, you can start jconsole and attach it to a running process. This will allow you to see memory usage over time even in production, including garbage collections without the full impact of a profiler setup.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Any way to handle Put and Delete verbs in ASP.Net MVC? just wondering if anyone knows of a truly restful Put/delete implementation asp.net mvc preview 5 preferably.
A: Check out the mvccontrib project at http://www.mvccontrib.org.
In the source code a restful implementation has been added and it is current up to Preview 5. Check out the source code here - http://mvccontrib.googlecode.com/svn/trunk/src/MVCContrib/SimplyRestful
A: Rails uses a "method" parameter in the form and then fakes it, but calls the appropriate method if you designate it.
I understand most clients won't support restful stack, but can asp.net mvc, auto-negotiate these verbs and place them in the appropriately deemed actions?
A: I've been covering this in my blog http://shouldersofgiants.co.uk/blog/ where I'm looking at an entire RESTful web service based on ASP.Net and MVC
A: I don't know of one off the top of my head, but you might look into the way that Rails handles it if you don't find anything else, and try porting it over. Rails utilizes POST, GET, PUT, and DELETE, but it apparently has to do some fakery for PUT. Could be worth looking into if you come up dry here.
A: I think that the new AcceptVerbsAttribute in preview 5 should be capable of directing any type of request to a designated action. Marking a method like below in theory allows handling of all verbs but I haven't explicitly tested put or delete.
[AcceptVerbs("delete")]
public object DoDeleteAction()
A: With MVC Beta, u can now use an HttpVerbs enumeration.
here's an example...
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{ ... }
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Update()
{ ... }
[AcceptVerbs(HttpVerbs.Delete)]
public ActionResult Delete()
{ ... }
you get the idea.
hth :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I send an email by Java application using GMail, Yahoo, or Hotmail? Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.
A: My complete code as below is working well:
package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail
{
public static void main(String [] args)
{
// Sender's email ID needs to be mentioned
String from = "[email protected]";
String pass ="test123";
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
String host = "smtp.gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.user", from);
properties.put("mail.smtp.password", pass);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
A: //set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class Mail
{
String d_email = "[email protected]",
d_password = "****",
d_host = "smtp.gmail.com",
d_port = "465",
m_to = "[email protected]",
m_subject = "Testing",
m_text = "Hey, this is the testing email using smtp.gmail.com.";
public static void main(String[] args)
{
String[] to={"[email protected]"};
String[] cc={"[email protected]"};
String[] bcc={"[email protected]"};
//This is for google
Mail.sendMail("[email protected]", "password", "smtp.gmail.com",
"465", "true", "true",
true, "javax.net.ssl.SSLSocketFactory", "false",
to, cc, bcc,
"hi baba don't send virus mails..",
"This is my style...of reply..If u send virus mails..");
}
public synchronized static boolean sendMail(
String userName, String passWord, String host,
String port, String starttls, String auth,
boolean debug, String socketFactoryClass, String fallback,
String[] to, String[] cc, String[] bcc,
String subject, String text)
{
Properties props = new Properties();
//Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if(!"".equals(port))
props.put("mail.smtp.port", port);
if(!"".equals(starttls))
props.put("mail.smtp.starttls.enable",starttls);
props.put("mail.smtp.auth", auth);
if(debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if(!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if(!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class",socketFactoryClass);
if(!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);
try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("[email protected]"));
for(int i=0;i<to.length;i++) {
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to[i]));
}
for(int i=0;i<cc.length;i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
for(int i=0;i<bcc.length;i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
}
catch (Exception mex)
{
mex.printStackTrace();
return false;
}
}
}
A: The minimum required:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MessageSender {
public static void sendHardCoded() throws AddressException, MessagingException {
String to = "[email protected]";
final String from = "[email protected]";
Properties properties = new Properties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "BeNice");
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Hello");
message.setText("What's up?");
Transport.send(message);
}
}
A: Other people have good answers above, but I wanted to add a note on my experience here. I've found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access. The emails I was sending were not spam, but were website "welcome" emails when users registered with my system. So, YMMV, and I wouldn't rely on Gmail for a production webapp. If you're sending email on a user's behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.
Also, if you're using Spring, here's a working config to use Gmail for outbound SMTP:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="UTF-8"/>
<property name="host" value="smtp.gmail.com"/>
<property name="port" value="465"/>
<property name="username" value="${mail.username}"/>
<property name="password" value="${mail.password}"/>
<property name="javaMailProperties">
<value>
mail.debug=true
mail.smtp.auth=true
mail.smtp.socketFactory.class=java.net.SocketFactory
mail.smtp.socketFactory.fallback=false
</value>
</property>
</bean>
A: First download the JavaMail API and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "[email protected]";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
A: The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.
The JavaMail FAQ recommends using
Session.getInstance(properties);
instead of
Session.getDefaultInstance(properties);
because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.
See http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance
A: Value added:
*
*encoding pitfalls in subject, message and display name
*only one magic property is needed for modern java mail library versions
*Session.getInstance() recommended over Session.getDefaultInstance()
*attachment in the same example
*still works after Google turns off less secure apps: Enable 2-factor authentication in your organization -> turn on 2FA -> generate app password.
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
public class Gmailer {
private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());
public static void main(String[] args) {
send();
}
public static void send() {
Transport transport = null;
try {
String accountEmail = "[email protected]";
String accountAppPassword = "";
String displayName = "Display-Name 東";
String replyTo = "[email protected]";
String to = "[email protected]";
String cc = "[email protected]";
String bcc = "[email protected]";
String subject = "Subject 東";
String message = "<span style='color: red;'>東</span>";
String type = "html"; // or "plain"
String mimeTypeWithEncoding = "text/" + type + "; charset=" + StandardCharsets.UTF_8.name();
File attachmentFile = new File("Attachment.pdf");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
String attachmentMimeType = "application/pdf";
byte[] bytes = ...; // read file to byte array
Properties properties = System.getProperties();
properties.put("mail.debug", "true");
// i found that this is the only property necessary for a modern java mail version
properties.put("mail.smtp.starttls.enable", "true");
// https://javaee.github.io/javamail/FAQ#getdefaultinstance
Session session = Session.getInstance(properties);
MimeMessage mimeMessage = new MimeMessage(session);
// probably best to use the account email address, to avoid landing in spam or blacklists
// not even sure if the server would accept a differing from address
InternetAddress from = new InternetAddress(accountEmail);
from.setPersonal(displayName, StandardCharsets.UTF_8.name());
mimeMessage.setFrom(from);
mimeMessage.setReplyTo(InternetAddress.parse(replyTo));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setContent(mimeMessage, mimeTypeWithEncoding);
multipart.addBodyPart(messagePart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));
attachmentPart.setFileName(attachmentFile.getName());
multipart.addBodyPart(attachmentPart);
mimeMessage.setContent(multipart);
transport = session.getTransport();
transport.connect("smtp.gmail.com", 587, accountEmail, accountAppPassword);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
catch(Exception e) {
// I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.
// I also prefer not to force the exception in the signature.
throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);
}
finally {
if(transport != null) {
try {
transport.close();
}
catch(Exception e) {
LOGGER.log(Level.WARNING, "failed to close java mail transport: " + e);
}
}
}
}
}
A: Even though this question is closed, I'd like to post a counter solution, but now using Simple Java Mail (Open Source JavaMail smtp wrapper):
final Email email = new Email();
String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"[email protected]"};
email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");
new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);
A: Something like this (sounds like you just need to change your SMTP server):
String host = "smtp.gmail.com";
String from = "user name";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "asdfgh");
props.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] to_address = new InternetAddress[to.length];
int i = 0;
// To get the array of addresses
while (to[i] != null) {
to_address[i] = new InternetAddress(to[i]);
i++;
}
System.out.println(Message.RecipientType.TO);
i = 0;
while (to_address[i] != null) {
message.addRecipient(Message.RecipientType.TO, to_address[i]);
i++;
}
message.setSubject("sending in a group");
message.setText("Welcome to JavaMail");
// alternately, to send HTML mail:
// message.setContent("<p>Welcome to JavaMail</p>", "text/html");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
A: This is what I do when i want to send email with attachment, work fine. :)
public class NewClass {
public static void main(String[] args) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); // smtp port
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username-gmail", "password-gmail");
}
};
Session session = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setSubject("Try attachment gmail");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
//add atleast simple body
MimeBodyPart body = new MimeBodyPart();
body.setText("Try attachment");
//do attachment
MimeBodyPart attachMent = new MimeBodyPart();
FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
attachMent.setDataHandler(new DataHandler(dataSource));
attachMent.setFileName("file-sent.txt");
attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachMent);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
A: An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.
Then you'd just send through smtp.gmail.com (on port 587)
A: Hi try this code....
package my.test.service;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Sample {
public static void main(String args[]) {
final String SMTP_HOST = "smtp.gmail.com";
final String SMTP_PORT = "587";
final String GMAIL_USERNAME = "[email protected]";
final String GMAIL_PASSWORD = "xxxxxxxxxx";
System.out.println("Process Started");
Properties prop = System.getProperties();
prop.setProperty("mail.smtp.starttls.enable", "true");
prop.setProperty("mail.smtp.host", SMTP_HOST);
prop.setProperty("mail.smtp.user", GMAIL_USERNAME);
prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);
prop.setProperty("mail.smtp.port", SMTP_PORT);
prop.setProperty("mail.smtp.auth", "true");
System.out.println("Props : " + prop);
Session session = Session.getInstance(prop, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(GMAIL_USERNAME,
GMAIL_PASSWORD);
}
});
System.out.println("Got Session : " + session);
MimeMessage message = new MimeMessage(session);
try {
System.out.println("before sending");
message.setFrom(new InternetAddress(GMAIL_USERNAME));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
message.setSubject("My First Email Attempt from Java");
message.setText("Hi, This mail came from Java Application.");
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(GMAIL_USERNAME));
Transport transport = session.getTransport("smtp");
System.out.println("Got Transport" + transport);
transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
System.out.println("message Object : " + message);
System.out.println("Email Sent Successfully");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A: Here's an easy-to-use class for sending emails with Gmail. You need to have the JavaMail library added to your build path or just use Maven.
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GmailSender
{
private static String protocol = "smtp";
private String username;
private String password;
private Session session;
private Message message;
private Multipart multipart;
public GmailSender()
{
this.multipart = new MimeMultipart();
}
public void setSender(String username, String password)
{
this.username = username;
this.password = password;
this.session = getSession();
this.message = new MimeMessage(session);
}
public void addRecipient(String recipient) throws AddressException, MessagingException
{
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
public void setSubject(String subject) throws MessagingException
{
message.setSubject(subject);
}
public void setBody(String body) throws MessagingException
{
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(body);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
public void send() throws MessagingException
{
Transport transport = session.getTransport(protocol);
transport.connect(username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
public void addAttachment(String filePath) throws MessagingException
{
BodyPart messageBodyPart = getFileBodyPart(filePath);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
private BodyPart getFileBodyPart(String filePath) throws MessagingException
{
BodyPart messageBodyPart = new MimeBodyPart();
DataSource dataSource = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setFileName(filePath);
return messageBodyPart;
}
private Session getSession()
{
Properties properties = getMailServerProperties();
Session session = Session.getDefaultInstance(properties);
return session;
}
private Properties getMailServerProperties()
{
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", protocol + ".gmail.com");
properties.put("mail.smtp.user", username);
properties.put("mail.smtp.password", password);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
return properties;
}
}
Example usage:
GmailSender sender = new GmailSender();
sender.setSender("[email protected]", "mypassword");
sender.addRecipient("[email protected]");
sender.setSubject("The subject");
sender.setBody("The body");
sender.addAttachment("TestFile.txt");
sender.send();
A: If you want to use outlook with Javamail API then use
smtp-mail.outlook.com
as a host for more and complete working code Check out this answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "218"
} |
Q: IBM DB2 Type 4 driver? Where can I find the redistributable version of the IBM DB2 Type 4 driver?
I suppose this is the driver I would use to connect from a Java app (on windows) to DB2 on the mainframe?
A: You will not be able to connect to the mainframe with any redistributable JDBC driver. The driver pack consists of the actual type 4 driver (db2jcc.jar) and any number of license files of the form:
db2jcc_license_cisuz.jar
where the cisuz bit is variable, indicating the platforms that you're allowed to run on (iSeries, pSeries, System z, LUW and so on).
You're only likely to get cu with any freely distributable pack. You need the z to access DB2 on the mainframe and that's jealously guarded so you'll need to purchase a specific edition of DB2 Connect to get it. I think both PE and EE, the personal and enterprise editions, have this licence file.
Without that license file, the type 4 driver won't even try to talk to the server, you'll get an exception.
A: IBM's Fix pack site has the "IBM Data Server Driver for JDBC and SQLJ" which is nothing but the JDBC type 4 driver. Though the page I pointed to above happens to be the windows page, it's the same type 4 driver for all platforms, as should be expected.
I don't think any user/password is required.
A: There is no need to download the JDBC driver separately it is already shipped with your DB2 product.
You can easily find it at this location : C:\Program Files\IBM\SQLLIB\java\db2jcc.jar
db2jcc.jar is the driver name
A: You can get the drivers from the IBM site. You will need to have IBM ID and password to login (which you can obtain here). Zip file is about 7 MBs, in contains DB2 9.5 JDBC (type 2/4) and SQLJ drivers. Type 4 drivers are in db2jcc4.jar.
However, you won't be able to connect to mainframes with this driver if mainframe is running DB2 for z/OS. To do so, you need at least to purchase DB2 Connect product, which will cost you about $500 minimum.
A: If you're running on an AS/400 (or iSeries, or whatever the heck IBM is calling it these days), you'll probably want to get it from JTOpen.
Their toolbox replaces the old Java Toolbox and includes the JDBC drivers.
A: If I need any IBM JARs for DB2 or MQ, I usually just add it to the instructions that DB2 or MQ needs to be installed as a prerequisite along with a URL to download it.
The same goes for Java and many other not easily redistributable products as well.
This eliminates the need to worry about licensing issues as it would be on the onus of the user rather than the vendor to obtain the proper licenses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Employee Web Usage From Proxy Logs I need to find/create an application that will create employee web usage reports from HTTP proxy logs. Does anyone know of a good product that will do this?
@Joe Liversedge - Good point. I don't have to worry about this, however, as I am the only person in my company with the know-how to pull off an SSH tunnel.
A: Here's a scenario: What's to stop two employees, let's call them 'Eric' and 'Tim', from running their own little SSH tunnel back home to prevent 'the Man', in this case you, from narc'ing out their use of the Internet. Now you have a useless report.
If you're serious about getting real data, you'll want something close to the pipes.
But agreed, Splunk would work pretty well, as would an over-long and unmaintainable Perl script or a series of awks, sorts, uniq -c's, etc.
A: I don't use it, but I hear Splunk is a really good log aggregation and reporting tool. It comes recommended by my sysadmin buddys, I just haven't had a need for it, since we use, IndexTools for our usage stats.
A: or Sensage... which has a more formalized model {more like a normal relational database} of data - at the expense of requiring a little more thought and setup cost to start consuming logs.
I don't think that they offer a free low-volume version like splunk do though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Information Management Policy in SharePoint An obscure puzzle, but it's driving me absolutely nuts:
I'm creating a custom Information Management Policy in MOSS. I've implemented IPolicyFeature, and my policy feature happily registers itself by configuring a new SPItemEventReceiver. All new items in my library fire the events as they should, and it all works fine.
IPolicyFeature also has a method ProcessListItem, which is supposed to retroactively apply the policy to items that were already in the library (at least, it's supposed to do that for as long as it keeps returning true). Except it doesn't. It only applies the policy to the first item in the library, and I have absolutely no idea why.
It doesn't seem to be throwing an exception, and it really does return true from processing that first item, and I can't think what else to look at. Anyone?
Edit: Cory's answer, below, set me on the right track. Something else was indeed failing -- I didn't find out what, since my windbg-fu isn't what it should be, but I suspect it was something like "modifying a collection while it's being iterated over". My code was modifying the SPListItem that's passed into ProcessListItem, and then calling SystemUpdate on it; as soon as I changed the code so that it created its own variable (pointing at the exact same SPListItem) and used that, the problem went away...
A: There's only a couple of things I can think of to try. First, are you developing on the box where you might be able to use Visual Studio to debug? So just stepping through it.
Assuming that's not the case - what I'd do is fire up WinDBG and attach it to the process just before I registered the policy. Turn on first chance exceptions so that it breaks whenever they occur. you can do that by issuing the command "sxe clr" once it is broken in. Here's a little more info about WinDBG:
http://blogs.msdn.com/tess/archive/2008/06/05/setting-net-breakpoints-in-windbg-for-applications-that-crash-on-startup.aspx
What I'd do is then watch for First Chance exceptions to be thrown, and do a !PrintException to see what is going on. My guess is that there is an exception being thrown somewhere that is causing the app to stop processing the other items.
What does the logic look like for your ProcessListItem? Have you tried just doing a return true to make sure it works?
A: Some nice ideas there, thanks. The Visual Studio debugger wasn't showing an exception (and I've wrapped everything in try/catch blocks just in case), but I hadn't thought of trying Windbg...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .Net 3.5, most secure way to pass string between processes I'd like to be able to pass a SecureString (a cached passphrase) to a child process in C# (.Net 3.5), but I don't know what the most secure way is to do it. If I were to convert the SecureString back to a regular string and pass it as a command-line argument, for example, then I think the value may be prone to disk paging--which would make the plaintext touch the filesystem and ruin the point of using SecureString.
Can the IntPtr for the SecureString be passed instead? Could I use a named pipe without increasing the risk?
A: In general you should define your threat model before worrying about more exotic attacks. In this case: are you worried that somebody shuts down the computer and does a forensic analysis of the harddrive? Application memory can also be swapped out, so the simple fact that one process has it in memory, makes it potentially possible for it to end in the swap file. What about hibernation? During hibernation the entire content of the memory is written to the harddisk (including the SecureString - and presumably the encryption key!). What if the attacker has access to the system while it's running and can search through the memory of applications?
In general client side security is very tricky and unless you have dedicated hardware (like a TPM chip) it is almost impossible to get right. Two solutions would be:
*
*If you only need to test for equality between two strings (ie: is this string the same as the one I had earlier), store only a (salted) hash value of it.
*Make the user re-enter the information when it is needed a second time (not very convenient, but security and convenience are opposed to each other)
A: Unless your child process also understands how to work with SecureString I don't think there is a way to pass it directly. For example, the Process.Start() method has two overloads that take a SecureString so the risk of the actual string value being sniffed is minimized (it's still possible since somewhere along the the way the actual value has to be retrieved/unmarshalled).
I think a lot of how to do this will depend on what the child process is and how it is being started.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Monitoring GDI calls Is there a tool that allows one to monitor GDI calls?
A: Tools like AutomatedQA AQTime can help you diagnose GDI usage. A much simpler, but free tool one can be found here.
A: Good advice, Lars. I've had a similar problem. Now use deleaker and do not worry;) GDI do not lose!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using jQuery, what is the best way to set onClick event listeners for radio buttons? For the following HTML:
<form name="myForm">
<label>One<input name="area" type="radio" value="S" /></label>
<label>Two<input name="area" type="radio" value="R" /></label>
<label>Three<input name="area" type="radio" value="O" /></label>
<label>Four<input name="area" type="radio" value="U" /></label>
</form>
Changing from the following JavaScript code:
$(function() {
var myForm = document.myForm;
var radios = myForm.area;
// Loop through radio buttons
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "S") {
radios[i].checked = true; // Selected when form displays
radioClicks(); // Execute the function, initial setup
}
radios[i].onclick = radioClicks; // Assign to run when clicked
}
});
Thanks
EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons
A: $(function() {
$("form#myForm input[type='radio']").click( fn );
});
function fn()
{
//do stuff here
}
A: $(document).ready(function(){
$("input[name='area']").bind("click", radioClicks);
});
functionradioClicks() {
alert($(this).val());
}
I like to use bind() instead of directly wiring the event handler because you can pass additional data to the event hander (not shown here but the data is a third bind() argument) and because you can easily unbind it (and you can bind and unbind by group--see the jQuery docs).
http://docs.jquery.com/Events/bind#typedatafn
A: $( function() {
$("input:radio")
.click(radioClicks)
.filter("[value='S']")
.attr("checked", "checked");
});
A: $(function() {
$('input[@type="radio"]').click(radioClicks);
});
A: I think something like this should work (but it's untested):
$("input[@type='radio']").each(function(i) {
if (this.val() == 'E') {
radioClicks();
this.get().checked = true;
}
}
$("input[@type='radio']").click(radioClicks);
A: $(function() {
$('#myForm :radio').each(function() {
if ($(this).value == 'S') {
$(this).attr("checked", true);
radioClicks();
}
$(this).click(radioClicks);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Which ORM framework can best handle an MVCC database design? When designing a database to use MVCC (Multi-Version Concurrency Control), you create tables with either a boolean field like "IsLatest" or an integer "VersionId", and you never do any updates, you only insert new records when things change.
MVCC gives you automatic auditing for applications that require a detailed history, and it also relieves pressure on the database with regards to update locks. The cons are that it makes your data size much bigger and slows down selects, due to the extra clause necessary to get the latest version. It also makes foreign keys more complicated.
(Note that I'm not talking about the native MVCC support in RDBMSs like SQL Server's snapshot isolation level)
This has been discussed in other posts here on Stack Overflow. [todo - links]
I am wondering, which of the prevalent entity/ORM frameworks (Linq to Sql, ADO.NET EF, Hibernate, etc) can cleanly support this type of design? This is a major change to the typical ActiveRecord design pattern, so I'm not sure if the majority of tools that are out there could help someone who decides to go this route with their data model. I'm particularly interested in how foreign keys would be handled, because I'm not even sure of the best way to data model them to support MVCC.
A: I might consider implementing the MVCC tier purely in the DB, using stored procs and views to handle my data operations. Then you could present a reasonable API to any ORM that was capable of mapping to and from stored procs, and you could let the DB deal with the data integrity issues (since it's pretty much build for that). If you went this way, you might want to look at a more pure Mapping solution like IBatis or IBatis.net.
A: I designed a database similarly (only INSERTs — no UPDATEs, no DELETEs).
Almost all of my SELECT queries were against views of only the current rows for each table (highest revision number).
The views looked like this…
SELECT
dbo.tblBook.BookId,
dbo.tblBook.RevisionId,
dbo.tblBook.Title,
dbo.tblBook.AuthorId,
dbo.tblBook.Price,
dbo.tblBook.Deleted
FROM
dbo.tblBook INNER JOIN
(
SELECT
BookId,
MAX(RevisionId) AS RevisionId
FROM
dbo.tblBook
GROUP BY
BookId
) AS CurrentBookRevision ON
dbo.tblBook.BookId = CurrentBookRevision.BookId AND
dbo.tblBook.RevisionId = CurrentBookRevision.RevisionId
WHERE
dbo.tblBook.Deleted = 0
And my inserts (and updates and deletes) were all handled by stored procedures (one per table).
The stored procedures looked like this…
ALTER procedure [dbo].[sp_Book_CreateUpdateDelete]
@BookId uniqueidentifier,
@RevisionId bigint,
@Title varchar(256),
@AuthorId uniqueidentifier,
@Price smallmoney,
@Deleted bit
as
insert into tblBook
(
BookId,
RevisionId,
Title,
AuthorId,
Price,
Deleted
)
values
(
@BookId,
@RevisionId,
@Title,
@AuthorId,
@Price,
@Deleted
)
Revision numbers were handled per-transaction in the Visual Basic code…
Shared Sub Save(ByVal UserId As Guid, ByVal Explanation As String, ByVal Commands As Collections.Generic.Queue(Of SqlCommand))
Dim Connection As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Connection").ConnectionString)
Connection.Open()
Dim Transaction As SqlTransaction = Connection.BeginTransaction
Try
Dim RevisionId As Integer = Nothing
Dim RevisionCommand As SqlCommand = New SqlCommand("sp_Revision_Create", Connection)
RevisionCommand.CommandType = CommandType.StoredProcedure
RevisionCommand.Parameters.AddWithValue("@RevisionId", 0)
RevisionCommand.Parameters(0).SqlDbType = SqlDbType.BigInt
RevisionCommand.Parameters(0).Direction = ParameterDirection.Output
RevisionCommand.Parameters.AddWithValue("@UserId", UserId)
RevisionCommand.Parameters.AddWithValue("@Explanation", Explanation)
RevisionCommand.Transaction = Transaction
LogDatabaseActivity(RevisionCommand)
If RevisionCommand.ExecuteNonQuery() = 1 Then 'rows inserted
RevisionId = CInt(RevisionCommand.Parameters(0).Value) 'generated key
Else
Throw New Exception("Zero rows affected.")
End If
For Each Command As SqlCommand In Commands
Command.Connection = Connection
Command.Transaction = Transaction
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.AddWithValue("@RevisionId", RevisionId)
LogDatabaseActivity(Command)
If Command.ExecuteNonQuery() < 1 Then 'rows inserted
Throw New Exception("Zero rows affected.")
End If
Next
Transaction.Commit()
Catch ex As Exception
Transaction.Rollback()
Throw New Exception("Rolled back transaction", ex)
Finally
Connection.Close()
End Try
End Sub
I created an object for each table, each with constructors, instance properties and methods, create-update-delete commands, a bunch of finder functions, and IComparable sorting functions. It was a huge amount of code.
One-to-one DB table to VB object...
Public Class Book
Implements iComparable
#Region " Constructors "
Private _BookId As Guid
Private _RevisionId As Integer
Private _Title As String
Private _AuthorId As Guid
Private _Price As Decimal
Private _Deleted As Boolean
...
Sub New(ByVal BookRow As DataRow)
Try
_BookId = New Guid(BookRow("BookId").ToString)
_RevisionId = CInt(BookRow("RevisionId"))
_Title = CStr(BookRow("Title"))
_AuthorId = New Guid(BookRow("AuthorId").ToString)
_Price = CDec(BookRow("Price"))
Catch ex As Exception
'TO DO: log exception
Throw New Exception("DataRow does not contain valid Book data.", ex)
End Try
End Sub
#End Region
...
#Region " Create, Update & Delete "
Function Save() As SqlCommand
If _BookId = Guid.Empty Then
_BookId = Guid.NewGuid()
End If
Dim Command As SqlCommand = New SqlCommand("sp_Book_CreateUpdateDelete")
Command.Parameters.AddWithValue("@BookId", _BookId)
Command.Parameters.AddWithValue("@Title", _Title)
Command.Parameters.AddWithValue("@AuthorId", _AuthorId)
Command.Parameters.AddWithValue("@Price", _Price)
Command.Parameters.AddWithValue("@Deleted", _Deleted)
Return Command
End Function
Shared Function Delete(ByVal BookId As Guid) As SqlCommand
Dim Doomed As Book = FindByBookId(BookId)
Doomed.Deleted = True
Return Doomed.Save()
End Function
...
#End Region
...
#Region " Finders "
Shared Function FindByBookId(ByVal BookId As Guid, Optional ByVal TryDeleted As Boolean = False) As Book
Dim Command As SqlCommand
If TryDeleted Then
Command = New SqlCommand("sp_Book_FindByBookIdTryDeleted")
Else
Command = New SqlCommand("sp_Book_FindByBookId")
End If
Command.Parameters.AddWithValue("@BookId", BookId)
If Database.Find(Command).Rows.Count > 0 Then
Return New Book(Database.Find(Command).Rows(0))
Else
Return Nothing
End If
End Function
Such a system preserves all past versions of each row, but can be a real pain to manage.
PROS:
*
*Total history preserved
*Fewer stored procedures
CONS:
*
*relies on non-database application for data integrity
*huge amount of code to be written
*No foreign keys managed within database (goodbye automatic Linq-to-SQL-style object generation)
*I still haven't come up with a good user interface to retrieve all that preserved past versioning.
CONCLUSION:
*
*I wouldn't go to such trouble on a new project without some easy-to-use out-of-the-box ORM solution.
I'm curious if the Microsoft Entity Framework can handle such database designs well.
Jeff and the rest of that Stack Overflow team must have had to deal with similar issues while developing Stack Overflow: Past revisions of edited questions and answers are saved and retrievable.
I believe Jeff has stated that his team used Linq to SQL and MS SQL Server.
I wonder how they handled these issues.
A: To the best of my knowledge, ORM frameworks are going to want to generate the CRUD code for you, so they would have to be explicitly designed to implement a MVCC option; I don't know of any that do so out of the box.
From an Entity framework standpoint, CSLA doesn't implement persistence for you at all -- it just defines a "Data Adapter" interface that you use to implement whatever persistence you need. So you could set up code generation (CodeSmith, etc.) templates to auto-generate CRUD logic for your CSLA entities that go along with a MVCC database architecture.
This approach would work with any entity framework, most likely, not just CSLA, but it would be a very "clean" implementation in CSLA.
A: Check out the Envers project - works nice with JPA/Hibernate applications and basically does that for you - keeps track of different versions of each Entity in another table and gives you SVN-like possibilities ("Gimme the version of Person being used 2008-11-05...")
http://www.jboss.org/envers/
/Jens
A: I always figured you'd use a db trigger on update and delete to push those rows out into a TableName_Audit table.
That'd work with ORMs, give you your history and wouldn't decimate select performance on that table. Is that a good idea or am I missing something?
A: What we do, is just use a normal ORM ( hibernate ) and handle the MVCC with views + instead of triggers.
So, there is a v_emp view, which just looks like a normal table, you can insert and update into it fine, when you do this though, the triggers handle actually inserting the correct data into the base table.
Not.. I hate this method :) I'd go with a stored procedure API as suggested by Tim.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Why is ARG_MAX not defined via limits.h? On Fedora Core 7, I'm writing some code that relies on ARG_MAX. However, even if I #include <limits.h>, the constant is still not defined. My investigations show that it's present in <sys/linux/limits.h>, but this is supposed to be portable across Win32/Mac/Linux, so directly including it isn't an option. What's going on here?
A: The reason it's not in limits.h is that it's not a quantity giving the limits of the value range of an integral type based on bit width on the current architecture. That's the role assigned to limits.h by the ISO standard.
The value in which you're interested is not hardware-bound in practice and can vary from platform to platform and perhaps system build to system build.
The correct thing to do is to call sysconf and ask it for "ARG_MAX" or "_POSIX_ARG_MAX". I think that's the POSIX-compliant solution anyway.
Acc. to my documentation, you include one or both of unistd.h or limits.h based on what values you're requesting.
One other point: many implementations of the exec family of functions return E2BIG or a similar value if you try to call them with an oversized environment. This is one of the defined conditions under which exec can actually return.
A: For the edification of future people like myself who find themselves here after a web search for "arg_max posix", here is a demonstration of the POSIXly-correct method for discerning ARG_MAX on your system that Thomas Kammeyer refers to in his answer:
cc -x c <(echo '
#include <unistd.h>
#include <stdio.h>
int main() { printf("%li\n", sysconf(_SC_ARG_MAX)); }
')
This uses the process substitution feature of Bash; put the same lines in a file and run cc thefile.c if you are using some other shell.
Here's the output for macOS 10.14:
$ ./a.out
262144
Here's the output for a RHEL 7.x system configured for use in an HPC environment:
$ ./a.out
4611686018427387903
$ ./a.out | numfmt --to=iec-i # 'numfmt' from GNU coreutils
4.0Ei
For contrast, here is the method prescribed by https://porkmail.org/era/unix/arg-max.html, which uses the C preprocessor:
cpp <<HERE | tail -1
#include <limits.h>
ARG_MAX
HERE
This does not work on Linux for reasons still not entirely clear to me—I am not a systems programmer and not conversant in the POSIX or ISO specs—but probably explained above.
A: ARG_MAX is defined in /usr/include/linux/limits.h. My linux kernel version is 3.2.0-38.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Best way to make a printer-friendly ASP.NET page? I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables?
Is there one elegant solution that works for the majority of the cases?
A: Our gracious host wrote a good blog post on this topic:
Coding Horror: Stylesheets for Print and Handheld
A: You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a media="print" so that it only applies to print media (when it is printed)
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
A: I am a php user, but the point must be that the result no matter what is HTML and HTML is styled with CSS and there is an option for your style sheets for just using the style for printing. This should be the way to do it, imho. About big tables, there isnt really a magic "fix" for that. Page will break where it breaks, dont really understand the problem here either.
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
<link rel="stylesheet" type="text/css" media="screen" href="screen.css" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Want to Encode text during Regex.Replace call I have a regex call that I need help with.
I haven't posted my regex, because it is not relevant here.
What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.
Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.
RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase;
text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions);
A: There is an incredibly easy way of doing this (in .net). Its called a MatchEvaluator and it lets you do all sorts of cool find and replace. Essentially you just feed the Regex.Replace method the method name of a method that returns a string and takes in a Match object as its only parameter. Do whatever makes sense for your particular match (html encode) and the string you return will replace the entire text of the match in the input string.
Example: Lets say you wanted to find all the places where there are two numbers being added (in text) and you want to replace the expression with the actual number. You can't do that with a strict regex approach, but you can when you throw in a MatchEvaluator it becomes easy.
public void Stuff()
{
string pattern = @"(?<firstNumber>\d+)\s*(?<operator>[*+-/])\s*(?<secondNumber>\d+)";
string input = "something something 123 + 456 blah blah 100 - 55";
string output = Regex.Replace(input, pattern, MatchMath);
//output will be "something something 579 blah blah 45"
}
private static string MatchMath(Match match)
{
try
{
double first = double.Parse(match.Groups["firstNumber"].Value);
double second = double.Parse(match.Groups["secondNumber"].Value);
switch (match.Groups["operator"].Value)
{
case "*":
return (first * second).ToString();
case "+":
return (first + second).ToString();
case "-":
return (first - second).ToString();
case "/":
return (first / second).ToString();
}
}
catch { }
return "NaN";
}
Find out more at http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx
A: Don't use Regex.Replace in this case... use..
foreach(Match in Regex.Matches(...))
{
//do your stuff here
}
A: Heres an implementation of this I've used to pick out special replace strings from content and localize them.
protected string FindAndTranslateIn(string content)
{
return Regex.Replace(content, @"\{\^(.+?);(.+?)?}", new MatchEvaluator(TranslateHandler), RegexOptions.IgnoreCase);
}
public string TranslateHandler(Match m)
{
if (m.Success)
{
string key = m.Groups[1].Value;
key = FindAndTranslateIn(key);
string def = string.Empty;
if (m.Groups.Count > 2)
{
def = m.Groups[2].Value;
if(def.Length > 1)
{
def = FindAndTranslateIn(def);
}
}
if (group == null)
{
return Translate(key, def);
}
else
{
return Translate(key, group, def);
}
}
return string.Empty;
}
From the match evaluator delegate you return everything you want replaced, so where I have returns you would have bold tags and an encode call, mine also supports recursion, so a little over complicated for your needs, but you can just pare down the example for your needs.
This is equivalent to doing an iteration over the collection of matches and doing parts of the replace methods job. It just saves you some code, and you get to use a fancy shmancy delegate.
A: If you do a Regex.Match, the resulting match objects group at the 0th index, is the subset of the intput that matched the regex.
you can use this to stitch in the bold tags and encode it there.
A: Can you fill in the code inside {} to add the bold tag, and encode the text?
I'm confused as to how to apply the changes to the entire text block AND replace the section in the text variable at the end.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Tools for converting non-Java into Java source Are there any good tools out there for automatically converting non-Java source code into Java source?
I'm not expecting something perfect, just to get the worst of the grunt work out of the way.
I guess there is a sliding scale of difficulty. C# should be relatively easy (so long as you ignore all the libraries). (well written) C++ not so bad. C requires making a little OO. (Statically type) functional languages may be easy to grok. Dynamic OO languages may require non-local analysis.
A: One thing you can try is find a Java bytecode compiler for the language you're talking about (there are JVM compilers for all kinds of languages) and then decompile the bytecode back into Java using a decompiler like Jad.
This is fraught with peril. The regenerated code will suck and will probably be unreadable.
A: Source-to-source migrations fall under the umbrella of Program Transformation. Program-Transformation.org tracks a bunch of tools that are useful for language recognition, analysis, and transformation. Here are few that are capable of source-to-source migrations:
*
*ASF+SDF Meta-Environment - As noted, there is no new development on this tool. Instead, the developers are focusing on Rascal.
*Rascal Meta Programming Language
*Stratego /XT
*TXL
*DMS® Software Reengineering Toolkit (commercial)
If you spend any time with one of the open source tools, you'll notice that even though they include source-to-source migration as a feature, it's hard to find working examples. I imagine this is because there's no such thing as a one-size-fits-all migration. Each project/team makes unique use of a language and can vary by libraries used, type complexity, idioms, style, etc. It makes sense to define some transformations per migration. This means a project must reach some critical mass before automatic migration is worth the effort.
A few related documents:
*
*An introduction to Rascal - includes a migration between the toy language Pico and Assembly starting at page 94.
*Cracking the 500 Language Problem
*An Experiment in Automatic Conversion of Legacy Java Programs to C# (gated) - uses TXL
A: Google: ANTLR
A: The language conversion is fairly simple, but you will find the libraries are different.
This is likely to be most of your work.
A: If you just want to use some legacy C/Pascal code, you could also use JNI to call it from Java.
If you want to run it in a Java applet or similar constrained environment, and it does not have to be very efficient, you can use NestedVM (which is a MIPS to Java bytecode converter) in conjunction with a gcc cross-compiler that compiles to MIPS). But don't expect to get readably Java code from that.
A: Any of those tools might help only if your non java code is not huge enough.
If its huge non java code and if you want to seriously translate it to java, then few things need to be thought of, its not just hundreds of lines of code, there is a design beneath it, there are few decisions taken by people beneath the code due to which certain problems might have been solved and few things have been working there. and investing time on any good translator won't be worth as it won't exist, it's not just syntax translation from one language to another.
If its not so huge code, its better to re write in java, as it has so many APIs packages out of box, it might not be big deal, hiring few interns for this also might help.
A: ADA to Java can be done with a find-and-replace!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to control a web application through email? Or how to run php script by sending an email? I want to run a web application on php and mysql, using the CakePHP framework. And to keep the threshold of using the site at a very low place, I want to not use the standard login with username/password. (And I don't want to hassle my users with something like OpenID either. Goes to user type.)
So I'm thinking that the users shall be able to log in by sending an email to [email protected] with no subject or content required. And they will get, in reply, an email with a link that will log them in (it will contain a hash). Also I will let the users do some actions without even visiting the site at all, just send an email with [email protected] and the command will be carried out. I will assume that the users and their email providers takes care of their email account security and as such there is no need for it on my site.
Now, how do I go from an email is sent to an account that is not read by humans to there being fired off some script (basically a "dummy browser client" calls an url( and the cakephp will take care of the rest)?
I have never used a cron job before, but I do think I understand their purpose or how they generally work. I can not have the script be called by random people visiting the site, as that solution won't work for several reasons. I think I would like to hear more about the possibility of having the script be run as response to an email coming in, if anyone has any input at all on that. If it's run as a cron job it would only check every X minutes and users would get a lag in their response (if i understand it correctly).
Since there will be different email addresses for different commands, like [email protected] and I know what to do and how to do it to based on the sender email, i dont even need the content, subject or any other headers from the email.
There is a lot of worry about security of this application, I understand the issues, but without giving away my concept, I dont think it is a big issue for what I am doing. Also about the usability issue, there really isnt any. It's just gonna be login to provide changes on a users profile if/when they need that and one other command. And this is the main email and is very easy to remember and the outset of this whole concept.
A: I have used the pop3 php class with great success (there is also a Pear POP3 module).
Using the pop3 class looks something like this:
require ('pop3.php');
$pop3 = new pop3_class();
$pop3->hostname = MAILHOST;
$pop3->Open();
$pop3->Login('[email protected]', 'mypassword');
foreach($pop3->ListMessages("","") as $msgidx => $msgsize)
{
$headers = "";
$body = "";
$pop3->RetrieveMessage($msgidx, $headers, $body, -1);
}
I use it to monitor a POP3 mailbox which feeds into a database.
It gets called by a cronjob which uses wget to call the url to my php script.
*/5 * * * * "wget -q --http-user=me --http-passwd=pass 'http://mydomain.com/mail.php'" >> /dev/null 2>&1
Edit
I've been thinking about your need to have users send certain site commands by email.
Wouldn't it be easier to have a single address that multiple commands can be sent to rather than having multiple addresses?
I think the security concerns are pretty valid too. Unless the commands are non-destructive or aren't doing anything user-specific, the system will be wide open to anyone who knows how to spoof an email address (which would be everyone :) ).
A: You'll need some sort of CronJob/Timer Service that checks the Mailbox regularly and then acts on it. Alternatively, you should check the mailserver if it can run a script when a mail arrives (i.e. see if it's possible to put a spamfilter-script in and "abuse" that functionality to call your script instead).
With pure PHP, you're mostly out of luck as something needs to trigger the script. On a Pagewith a LOT of traffic, you could have your index.php or whatever do the check, but when no one visits your site for quite some time, then the mail will not be sent, and you have to be careful of "race conditions" when multiple people are accessing the script at the same time.
Edit: Just keep one usability flaw in mind: People with Multiple PCs and without an e-Mail Client on every one. For example, I use 4 PCs, but only 1 (my main one) has a Mail Client installed, and I use Webmail to check the other ones. Now, logging in and sending a mail through Webmail is not the greatest usability - in order to use YOUR site, I first have to log in to ANOTHER site, compose a mail through the crappy interface most Webmail tools have and wait for answer. Could as well use OpenID there :-)
A: If your server allows it you can use a .forward file or Procmail to start a process (php or anything) when a mail arrives to a certain address.
A: You don't want to hassle users with OpenID, but you want them to deal with this email scheme. Firstly, email can take a long time to go through. There isn't any guaranteed time that an email will be delivered in. It's not even guaranteed that the email will get there at all. I know things usually are quick, but it's not uncommon to take up to 10 minutes for a round trip to be completed. Also, unless you're encrypting the email, the link you are sending back is sent in the open. That means anybody can use that link to log in. Depending one how secure you want to be, this may or may not be an issue, but it's definitely something to think about. Using a non-standard login method like this is going to be a lot more work than it is probably worth, and I can't really see any advantages to the whole process.
A: I was also thinking using procmail to start some script. There is also formail, which might come in handy to change or extract headers. If you have admin access to the mail server, you could also use /etc/aliases and just pipe to your script.
Besides usability issues, you should really think about security - it's actually quite simple to send email with a fake sender address, so I would not rely on it for anything critical.
A: I agree with all the security concerns. Your assumption that "the users and their email providers takes care of their email account security" is not correct when it comes to the sender's e-mail address.
But since you specifically asked "how do I go from an email is sent to an account that is not read by humans to there being fired off some script", I recommend using procmail to deliver the incoming e-mail to a script you write.
I would not call a URL. I would have the script perform the work by reading the message sent in on stdin. That way, the script is not acessible to anyone on the web site.
To set this up, the e-mail address you provide to your users will have to be associated with a real user
on the system. In that user's home directory, create a file called ".procmailrc"
In that file, add these two lines:
:0 hb:
| /path/to/program
Where /path/to/program is the full path to the script or program for handling
the incoming message. Then create the script with code something like this:
#!/usr/bin/php
<?php
$fp=fopen('php://stdin','r');
while($line = fgets($fp)) {
[do something with each $line of input here]
}
?>
The e-mail message will not remain in the mailbox, so if you want to save or log it, have the script do it.
--
Bruce
A: I would seriously reconsider this approach. E-mail hasn't got very high reliability. There's all kinds of spamfilters that might intercept e-mails with links thereby rendering the "command" half-finished, not to mention the security risks.
It's very easy to spoof the sender-address on an e-mail. You are basically opening up your system to anyone.
Also instead of a username/password combination you're suddenly requiring the users to remember a list of commands to put in front of an email-address. It would be better to provide them with a username/password and then giving access to a help page.
In other words the usability and security of this scheme scores very low.
I can't really find any advantages to this approach that even comes close to outweighing the massive disadvantages.
A: One solution to prevent spam, make sure the first line, last line or a specific line contains a certain string, almost like a password, but a full sentence is better.
Only you have the word or words, pretty secure, just remember to delete the mails after use and those that do not have the secret line.
A: Apart from the security and usability email delivery can be another problem. Depending on the user's email provider, email delivery can be delayed from a few minutes to few hours.
A: There is a realy nice educational story on thedailywtf.com on designing software. The posed question should be solved by a proper design, not by techo-woopla.
Alexander, please read the linked story and think gloves, not email-driven webpage browsing.
PHP is not a hammer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to bind a MemoryStream to asp:image control? Is there a way to bind a MemoryStream to asp:image control?
A: A handler can accept a url parameter like any other request. So instead of linking your <asp:image/> to image.ashx you'd set it to image.ashx?ImageID=[Your image ID here].
A: Best bet is to create an HttpHandler that would return the image. Then bind the ImageUrl property on the asp:Image to the url of the HttpHandler.
Here is some code.
First create the HttpHandler:
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.Clear();
if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
{
int id = Int32.Parse(context.Request.QueryString["id"]);
// Now you have the id, do what you want with it, to get the right image
// More than likely, just pass it to the method, that builds the image
Image image = GetImage(id);
// Of course set this to whatever your format is of the image
context.Response.ContentType = "image/jpeg";
// Save the image to the OutputStream
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Need a valid id</p>");
}
}
public bool IsReusable
{
get
{
return false;
}
}
private Image GetImage(int id)
{
// Not sure how you are building your MemoryStream
// Once you have it, you just use the Image class to
// create the image from the stream.
MemoryStream stream = new MemoryStream();
return Image.FromStream(stream);
}
}
Next, just call it inside your aspx page where you are using the asp:Image.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="myImage" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" />
</div>
</form>
</body>
</html>
And that is it.
A: I am assuming you need to generate dynamic images from asp.net
You might be in luck
http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449
Hanselman blogged about it recently
http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx
A: @Will and Ben Griswald: instead of "image.aspx" use "image.ashx".
It's more light-weight than a full ASP.Net Page, and it's specifically designed to handle content-types other than text/html.
A: While Databinding a MemoryStream to a Image is not possible, it could be possible to use a Label/GenericControl, some Code and the data URI scheme to embed Images in Pages, but there are severe issues with that approach:
Disadvantages
*
*Embedded content must be extracted and decoded before changes may be made, then re-encoded and re-embedded afterwards.
*Cookies are not supported.
*Information that is embedded more than once is redownloaded as part of the containing file, and thus does not benefit from the browser's cache.
*Browsers may limit URI lengths, creating an effective maximum data size. For example, URIs in previous versions of Opera had limits of 4kB, and 32kB for IE8 Beta 1[citation needed]
*Data is included as a simple stream, and many processing environments (such as web browsers) may not support using containers (such as multipart/alternative or message/rfc822) to provide greater complexity such as metadata, data compression, or content negotiation.
*Microsoft's Internet Explorer, through version 7 (some 70% of the market as of 2008 Q2), lacks support.
The better Approach is to use a separate "Image.aspx" Page which takes and outputs your MemoryStream, kinda like I did in my Photo Album software that i've created when I started learning ASP.net:
(Don't laugh, that was my first attempt at ASP.net :-)
Edit: Agreed on ASHX, the code above is just to show one sample implementation. When I come around to update the Photo Album, it will use ASHX for that.
A: You can use Telerik's BinaryImage control for ASP.net.
More info in here:
http://www.telerik.com/products/aspnet-ajax/binaryimage.aspx
A: Nope.
But you can create a special page to stream that image out. First, you set the URL of the image to the page that performs the streaming, including some url parameters that let you know where to get the image:
<img src="GetImage.aspx?filename=foo" ... />
in GetImage.aspx, you get the filename (or whatever) from the URL, load the image in your MemoryStream, and then write the content of that memory stream directly to the HttpResponse:
response.Expires = 0;
response.Buffer = false;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "image/jpeg";
response.BinaryWrite(stream);
response.Flush();
response.Close();
A: For me it was necessary to add "buffer="false" to the @Page. Otherwise I would keep getting the same picture all the time...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Custom cursor in WPF? I want to use an image or icon as a custom cursor in WPF app. How can I do that?
A: I wanted to load a custom cursor file from the project resources and ran into similar problems. I searched the internet for a solution and didn't find what I needed: to set the this.Cursor to a custom cursor stored in my resources folder in my project at runtime.
I've tried Ben's xaml solution, but didn't find it elegant enough.
PeterAllen stated:
Lamely, a relative path or Pack URI will not work. If you need to load the cursor from a relative path or from a resource packed with your assembly, you will need to get a stream from the file and pass it in to the Cursor(Stream cursorStream) constructor. Annoying but true.
I stumbled on a nice way to do this and resolves my problem:
System.Windows.Resources.StreamResourceInfo info =
Application.GetResourceStream(new
Uri("/MainApp;component/Resources/HandDown.cur", UriKind.Relative));
this.Cursor = new System.Windows.Input.Cursor(info.Stream);
MainApp should be replaced with the name of your application. Resources should be replaced with the relative folder path to your *.cur files inside your project.
A: A very easy way is to create the cursor within Visual Studio as a .cur file, and then add that to the projects Resources.
Then just add the following code when you want to assign the cursor:
myCanvas.Cursor = new Cursor(new System.IO.MemoryStream(myNamespace.Properties.Resources.Cursor1));
A: One more solution somewhat similar to Ray's but instead of slow and cumbersome pixel copying, this uses some Windows internals:
private struct IconInfo {
public bool fIcon;
public int xHotspot;
public int yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
[DllImport("user32.dll")]
private static extern IntPtr CreateIconIndirect(ref IconInfo icon);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
public Cursor ConvertToCursor(FrameworkElement cursor, Point HotSpot) {
cursor.Arrange(new Rect(new Size(cursor.Width, cursor.Height)));
var bitmap = new RenderTargetBitmap((int)cursor.Width, (int)cursor.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(cursor);
var info = new IconInfo();
GetIconInfo(bitmap.ToBitmap().GetHicon(), ref info);
info.fIcon = false;
info.xHotspot = (byte)(HotSpot.X * cursor.Width);
info.yHotspot = (byte)(HotSpot.Y * cursor.Height);
return CursorInteropHelper.Create(new SafeFileHandle(CreateIconIndirect(ref info), true));
}
There is an extension method in the middle that I prefer to have in an extension class for such cases:
using DW = System.Drawing;
public static DW.Bitmap ToBitmap(this BitmapSource bitmapSource) {
var bitmap = new DW.Bitmap(bitmapSource.PixelWidth, bitmapSource.PixelHeight, DW.Imaging.PixelFormat.Format32bppPArgb);
var data = bitmap.LockBits(new DW.Rectangle(DW.Point.Empty, bitmap.Size), DW.Imaging.ImageLockMode.WriteOnly, DW.Imaging.PixelFormat.Format32bppPArgb);
bitmapSource.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride);
bitmap.UnlockBits(data);
return bitmap;
}
With all this, it's rather simple and straightforward.
And, if you happen not to need to specify your own hotspot, you can even cut this shorter (you don't need the struct or the P/Invokes, either):
public Cursor ConvertToCursor(FrameworkElement cursor, Point HotSpot) {
cursor.Arrange(new Rect(new Size(cursor.Width, cursor.Height)));
var bitmap = new RenderTargetBitmap((int)cursor.Width, (int)cursor.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(cursor);
var icon = System.Drawing.Icon.FromHandle(bitmap.ToBitmap().GetHicon());
return CursorInteropHelper.Create(new SafeFileHandle(icon.Handle, true));
}
A: You have two basic options:
*
*When the mouse cursor is over your control, hide the system cursor by setting this.Cursor = Cursors.None; and draw your own cursor using whatever technique you like. Then, update the position and appearance of your cursor by responding to mouse events. Here are two examples:
*
*http://www.xamlog.com/2006/07/17/creating-a-custom-cursor/
*http://www.hanselman.com/blog/DeveloperDesigner.aspx
Additional examples can be found here:
*WPF Tutorial - How To Use Custom Cursors
*Setting the Cursor to Render Some Text While Dragging
*Getting fancy and using the Visual we are dragging for feedback [instead of a cursor]
*How can I drag and drop items between data bound ItemsControls?
*Create a new Cursor object by loading an image from a .cur or .ani file. You can create and edit these kinds of files in Visual Studio. There are also some free utilites floating around for dealing with them. Basically they're images (or animated images) which specify a "hot spot" indicating what point in the image the cursor is positioned at.
If you choose to load from a file, note that you need an absolute file-system path to use the Cursor(string fileName) constructor. Lamely, a relative path or Pack URI will not work. If you need to load the cursor from a relative path or from a resource packed with your assembly, you will need to get a stream from the file and pass it in to the Cursor(Stream cursorStream) constructor. Annoying but true.
On the other hand, specifying a cursor as a relative path when loading it using a XAML attribute does work, a fact you could use to get your cursor loaded onto a hidden control and then copy the reference to use on another control. I haven't tried it, but it should work.
A: Like Peter mentioned, if you already have a .cur file, you can use it as an embedded resource by creating a dummy element in the resource section, and then referencing the dummy's cursor when you need it.
For example, say you wanted to display non-standard cursors depending on the selected tool.
Add to resources:
<Window.Resources>
<ResourceDictionary>
<TextBlock x:Key="CursorGrab" Cursor="Resources/Cursors/grab.cur"/>
<TextBlock x:Key="CursorMagnify" Cursor="Resources/Cursors/magnify.cur"/>
</ResourceDictionary>
</Window.Resources>
Example of embedded cursor referenced in code:
if (selectedTool == "Hand")
myCanvas.Cursor = ((TextBlock)this.Resources["CursorGrab"]).Cursor;
else if (selectedTool == "Magnify")
myCanvas.Cursor = ((TextBlock)this.Resources["CursorMagnify"]).Cursor;
else
myCanvas.Cursor = Cursor.Arrow;
A: You could try this
<Window Cursor=""C:\WINDOWS\Cursors\dinosaur.ani"" />
A: you can do this by Code like
this.Cursor = new Cursor(@"<your address of icon>");
A: There is an easier way than managing the cursor display yourself or using Visual Studio to construct lots of custom cursors.
If you have a FrameworkElement you can construct a Cursor from it using the following code:
public Cursor ConvertToCursor(FrameworkElement visual, Point hotSpot)
{
int width = (int)visual.Width;
int height = (int)visual.Height;
// Render to a bitmap
var bitmapSource = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
bitmapSource.Render(visual);
// Convert to System.Drawing.Bitmap
var pixels = new int[width*height];
bitmapSource.CopyPixels(pixels, width, 0);
var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
for(int y=0; y<height; y++)
for(int x=0; x<width; x++)
bitmap.SetPixel(x, y, Color.FromArgb(pixels[y*width+x]));
// Save to .ico format
var stream = new MemoryStream();
System.Drawing.Icon.FromHandle(resultBitmap.GetHicon()).Save(stream);
// Convert saved file into .cur format
stream.Seek(2, SeekOrigin.Begin);
stream.WriteByte(2);
stream.Seek(10, SeekOrigin.Begin);
stream.WriteByte((byte)(int)(hotSpot.X * width));
stream.WriteByte((byte)(int)(hotSpot.Y * height));
stream.Seek(0, SeekOrigin.Begin);
// Construct Cursor
return new Cursor(stream);
}
Note that your FrameworkElement 's size must be a standard cursor size (eg 16x16 or 32x32), for example:
<Grid x:Name="customCursor" Width="32" Height="32">
...
</Grid>
It would be used like this:
someControl.Cursor = ConvertToCursor(customCursor, new Point(0.5, 0.5));
Obviously your FrameworkElement could be an <Image> control if you have an existing image, or you can draw anything you like using WPF's built-in drawing tools.
Note that details on the .cur file format can be found at ICO (file format).
A: To use a custom cursor in XAML I altered the code Ben McIntosh provided slightly:
<Window.Resources>
<Cursor x:Key="OpenHandCursor">Resources/openhand.cur</Cursor>
</Window.Resources>
To use the cursor just reference to the resource:
<StackPanel Cursor="{StaticResource OpenHandCursor}" />
A: In case anyone is looking for a UIElement itself as a cursor, I combined the solutions of Ray and Arcturus:
public Cursor ConvertToCursor(UIElement control, Point hotSpot)
{
// convert FrameworkElement to PNG stream
var pngStream = new MemoryStream();
control.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Rect rect = new Rect(0, 0, control.DesiredSize.Width, control.DesiredSize.Height);
RenderTargetBitmap rtb = new RenderTargetBitmap((int)control.DesiredSize.Width, (int)control.DesiredSize.Height, 96, 96, PixelFormats.Pbgra32);
control.Arrange(rect);
rtb.Render(control);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(rtb));
png.Save(pngStream);
// write cursor header info
var cursorStream = new MemoryStream();
cursorStream.Write(new byte[2] { 0x00, 0x00 }, 0, 2); // ICONDIR: Reserved. Must always be 0.
cursorStream.Write(new byte[2] { 0x02, 0x00 }, 0, 2); // ICONDIR: Specifies image type: 1 for icon (.ICO) image, 2 for cursor (.CUR) image. Other values are invalid
cursorStream.Write(new byte[2] { 0x01, 0x00 }, 0, 2); // ICONDIR: Specifies number of images in the file.
cursorStream.Write(new byte[1] { (byte)control.DesiredSize.Width }, 0, 1); // ICONDIRENTRY: Specifies image width in pixels. Can be any number between 0 and 255. Value 0 means image width is 256 pixels.
cursorStream.Write(new byte[1] { (byte)control.DesiredSize.Height }, 0, 1); // ICONDIRENTRY: Specifies image height in pixels. Can be any number between 0 and 255. Value 0 means image height is 256 pixels.
cursorStream.Write(new byte[1] { 0x00 }, 0, 1); // ICONDIRENTRY: Specifies number of colors in the color palette. Should be 0 if the image does not use a color palette.
cursorStream.Write(new byte[1] { 0x00 }, 0, 1); // ICONDIRENTRY: Reserved. Should be 0.
cursorStream.Write(new byte[2] { (byte)hotSpot.X, 0x00 }, 0, 2); // ICONDIRENTRY: Specifies the horizontal coordinates of the hotspot in number of pixels from the left.
cursorStream.Write(new byte[2] { (byte)hotSpot.Y, 0x00 }, 0, 2); // ICONDIRENTRY: Specifies the vertical coordinates of the hotspot in number of pixels from the top.
cursorStream.Write(new byte[4] { // ICONDIRENTRY: Specifies the size of the image's data in bytes
(byte)((pngStream.Length & 0x000000FF)),
(byte)((pngStream.Length & 0x0000FF00) >> 0x08),
(byte)((pngStream.Length & 0x00FF0000) >> 0x10),
(byte)((pngStream.Length & 0xFF000000) >> 0x18)
}, 0, 4);
cursorStream.Write(new byte[4] { // ICONDIRENTRY: Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file
(byte)0x16,
(byte)0x00,
(byte)0x00,
(byte)0x00,
}, 0, 4);
// copy PNG stream to cursor stream
pngStream.Seek(0, SeekOrigin.Begin);
pngStream.CopyTo(cursorStream);
// return cursor stream
cursorStream.Seek(0, SeekOrigin.Begin);
return new Cursor(cursorStream);
}
A: Also check out Scott Hanselman's BabySmash (www.codeplex.com/babysmash). He used a more "brute force" method of hiding the windows cursor and showing his new cursor on a canvas and then moving the cursor to were the "real" cursor would have been
Read more here:
http://www.hanselman.com/blog/DeveloperDesigner.aspx
A: Make sure, that any GDI resource (for example bmp.GetHIcon) gets disposed. Otherwise you end up with a memory leak. The following code (extension method for icon) works perfectly for WPF. It creates the arrow cursor with a small icon on it's lower right.
Remark: This code uses an icon to create the cursor. It does not use a current UI control.
public static Cursor CreateCursor(this Icon icon, bool includeCrossHair, System.Drawing.Color crossHairColor)
{
if (icon == null)
return Cursors.Arrow;
// create an empty image
int width = icon.Width;
int height = icon.Height;
using (var cursor = new Bitmap(width * 2, height * 2))
{
// create a graphics context, so that we can draw our own cursor
using (var gr = System.Drawing.Graphics.FromImage(cursor))
{
// a cursor is usually 32x32 pixel so we need our icon in the lower right part of it
gr.DrawIcon(icon, new Rectangle(width, height, width, height));
if (includeCrossHair)
{
using (var pen = new System.Drawing.Pen(crossHairColor))
{
// draw the cross-hair
gr.DrawLine(pen, width - 3, height, width + 3, height);
gr.DrawLine(pen, width, height - 3, width, height + 3);
}
}
}
try
{
using (var stream = new MemoryStream())
{
// Save to .ico format
var ptr = cursor.GetHicon();
var tempIcon = Icon.FromHandle(ptr);
tempIcon.Save(stream);
int x = cursor.Width/2;
int y = cursor.Height/2;
#region Convert saved stream into .cur format
// set as .cur file format
stream.Seek(2, SeekOrigin.Begin);
stream.WriteByte(2);
// write the hotspot information
stream.Seek(10, SeekOrigin.Begin);
stream.WriteByte((byte)(width));
stream.Seek(12, SeekOrigin.Begin);
stream.WriteByte((byte)(height));
// reset to initial position
stream.Seek(0, SeekOrigin.Begin);
#endregion
DestroyIcon(tempIcon.Handle); // destroy GDI resource
return new Cursor(stream);
}
}
catch (Exception)
{
return Cursors.Arrow;
}
}
}
/// <summary>
/// Destroys the icon.
/// </summary>
/// <param name="handle">The handle.</param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static Boolean DestroyIcon(IntPtr handle);
A: If you are using visual studio, you can
*
*New a cursor file
*Copy/Paste the image
*Save it to .cur file.
A: It may have changed with Visual Studio 2017 but I was able to reference a .cur file as an embedded resource:
<Setter
Property="Cursor"
Value="/assembly-name;component/location-name/curser-name.cur" />
A: This will convert any image stored in your project to a cursor using an attached property. The image must be compiled as a resource!
Example
<Button MyLibrary:FrameworkElementExtensions.Cursor=""{MyLibrary:Uri MyAssembly, MyImageFolder/MyImage.png}""/>
FrameworkElementExtensions
using System;
using System.Windows;
using System.Windows.Media;
public static class FrameworkElementExtensions
{
#region Cursor
public static readonly DependencyProperty CursorProperty = DependencyProperty.RegisterAttached("Cursor", typeof(Uri), typeof(FrameworkElementExtensions), new UIPropertyMetadata(default(Uri), OnCursorChanged));
public static Uri GetCursor(FrameworkElement i) => (Uri)i.GetValue(CursorProperty);
public static void SetCursor(FrameworkElement i, Uri input) => i.SetValue(CursorProperty, input);
static void OnCursorChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (sender is FrameworkElement frameworkElement)
{
if (GetCursor(frameworkElement) != null)
frameworkElement.Cursor = new ImageSourceConverter().ConvertFromString(((Uri)e.NewValue).OriginalString).As<ImageSource>().Bitmap().Cursor(0, 0).Convert();
}
}
#endregion
}
ImageSourceExtensions
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;
public static class ImageSourceExtensions
{
public static Bitmap Bitmap(this ImageSource input) => input.As<BitmapSource>().Bitmap();
}
BitmapSourceExtensions
using System.IO;
using System.Windows.Media.Imaging;
public static class BitmapSourceExtensions
{
public static System.Drawing.Bitmap Bitmap(this BitmapSource input)
{
if (input == null)
return null;
System.Drawing.Bitmap result;
using (var outStream = new MemoryStream())
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(input));
encoder.Save(outStream);
result = new System.Drawing.Bitmap(outStream);
}
return result;
}
}
BitmapExtensions
using System;
using System.Drawing;
using System.Runtime.InteropServices;
public static class BitmapExtensions
{
[StructLayout(LayoutKind.Sequential)]
public struct ICONINFO
{
/// <summary>
/// Specifies whether this structure defines an icon or a cursor. A value of TRUE specifies an icon; FALSE specifies a cursor.
/// </summary>
public bool fIcon;
/// <summary>
/// Specifies the x-coordinate of a cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
/// </summary>
public Int32 xHotspot;
/// <summary>
/// Specifies the y-coordinate of the cursor's hot spot. If this structure defines an icon, the hot spot is always in the center of the icon, and this member is ignored.
/// </summary>
public Int32 yHotspot;
/// <summary>
/// (HBITMAP) Specifies the icon bitmask bitmap. If this structure defines a black and white icon, this bitmask is formatted so that the upper half is the icon AND bitmask and the lower half is the icon XOR bitmask. Under this condition, the height should be an even multiple of two. If this structure defines a color icon, this mask only defines the AND bitmask of the icon.
/// </summary>
public IntPtr hbmMask;
/// <summary>
/// (HBITMAP) Handle to the icon color bitmap. This member can be optional if this structure defines a black and white icon. The AND bitmask of hbmMask is applied with the SRCAND flag to the destination; subsequently, the color bitmap is applied (using XOR) to the destination by using the SRCINVERT flag.
/// </summary>
public IntPtr hbmColor;
}
[DllImport("user32.dll")]
static extern IntPtr CreateIconIndirect([In] ref ICONINFO piconinfo);
[DllImport("user32.dll")]
static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO piconinfo);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyIcon(IntPtr hIcon);
public static System.Windows.Forms.Cursor Cursor(this Bitmap input, int hotX, int hotY)
{
ICONINFO Info = new ICONINFO();
IntPtr Handle = input.GetHicon();
GetIconInfo(Handle, out Info);
Info.xHotspot = hotX;
Info.yHotspot = hotY;
Info.fIcon = false;
IntPtr h = CreateIconIndirect(ref Info);
return new System.Windows.Forms.Cursor(h);
}
}
CursorExtensions
using Microsoft.Win32.SafeHandles;
public static class CursorExtensions
{
public static System.Windows.Input.Cursor Convert(this System.Windows.Forms.Cursor Cursor)
{
SafeFileHandle h = new SafeFileHandle(Cursor.Handle, false);
return System.Windows.Interop.CursorInteropHelper.Create(h);
}
}
As
public static Type As<Type>(this object input) => input is Type ? (Type)input : default;
Uri
using System;
using System.Windows.Markup;
public class Uri : MarkupExtension
{
public string Assembly { get; set; } = null;
public string RelativePath { get; set; }
public Uri(string relativePath) : base()
{
RelativePath = relativePath;
}
public Uri(string assembly, string relativePath) : this(relativePath)
{
Assembly = assembly;
}
static Uri Get(string assemblyName, string relativePath) => new Uri($"pack://application:,,,/{assemblyName};component/{relativePath}", UriKind.Absolute);
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (Assembly == null)
return new System.Uri(RelativePath, UriKind.Relative);
return Get(Assembly, RelativePath);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "53"
} |
Q: Terminating intermittently Has anyone had and solved a problem where programs would terminate without any indication of why? I encounter this problem about every 6 months and I can get it to stop by having me (the administrator) log-in then out of the machine. After this things are back to normal for the next 6 months. I've seen this on Windows XP and Windows 2000 machines.
I've looked in the Event Viewer and monitored API calls and I cannot see anything out of the ordinary.
UPDATE: On the Windows 2000 machine, Visual Basic 6 would terminate when loading a project. On the Windows XP machine, IIS stopped working until I logged in then out.
UPDATE: Restarting the machine doesn't work.
A: Perhaps it's not solved by you logging in, but by the user logging out. It could be a memory leak and logging out closes the process, causing windows to reclaim the memory. I assume programs indicated multiple applications, so it could be a shared dll that's causing the problem. Is there any kind of similarities in the programs? .Net, VB6, Office, and so on, or is it everything on the computer? You may be able to narrow it down to shared libraries.
During the 6 month "no error" time frame, is the system always on and logged in? If that's the case, you may suggest the user periodically reboot, perhaps once a week, in order to reclaim leaked memory, or memory claimed by hanging programs that didn't close properly.
A: You need to take this issue to the software developer.
A: The more details you provide the more likely it will be that you will get an answer: explain what exact program was 'terminating'. A termination is usually caused by an internal unhandled error, and not all programs check for them, and log them before quitting. However I think you can install Dr Watson, and it will give you at least a stack trace when a crash happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database? Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas?
A: Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:
ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
If you are doing CE development, i would recomend this FAQ:
EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.
A: You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:
ALTER TABLE tblAlpha
ADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES
tblGamma(GammaID)
ON UPDATE CASCADE
To verify that your foreign key was created, execute the following SQL:
SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
Credit to E Jensen (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1)
A: Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.
A: Alan is correct when he says there's designer support. Rhywun is incorrect when he implies you cannot choose the foreign key table. What he means is that in the UI the foreign key table drop down is greyed out - all that means is he has not right clicked on the correct table to add the foreign key to.
In summary, right click on the foriegn key table and then via the 'Table Properties' > 'Add Relations' option you select the related primary key table.
I've done it numerous times and it works.
A: create table employee
(
empid int,
empname varchar(40),
designation varchar(30),
hiredate datetime,
Bsalary int,
depno constraint emp_m foreign key references department(depno)
)
We should have an primary key to create foreign key or relationship between two or more table .
A: I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,
Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.
A: Walkthrough: Creating a SQL Server Compact 3.5 Database
To create a relationship between the tables created in the previous procedure
*
*In Server Explorer/Database Explorer, expand Tables.
*Right-click the Orders table and then click Table Properties.
*Click Add Relations.
*Type FK_Orders_Customers in the Relation Name box.
*Select CustomerID in the Foreign Key Table Column list.
*Click Add Columns.
*Click Add Relation.
*Click OK to complete the process and create the relationship in the
database.
*Click OK again to close the Table Properties dialog box.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: Why do I get this error "[DBNETLIB][ConnectionRead (recv()).]General network error" with ASP pages Occasionally, on a ASP (classic) site users will get this error:
[DBNETLIB][ConnectionRead (recv()).]General network error.
Seems to be random and not connected to any particular page. The SQL server is separated from the web server and my guess is that every once and a while the "link" goes down between the two. Router/switch issue... or has someone else ran into this problem before?
A: Using the same setup as yours (ie separate web and database server), I've seen it from time to time and it has always been a connection problem between the servers - typically when the database server is being rebooted but sometimes when there's a comms problem somewhere in the system. I've not seen it triggered by any problems with the ASP code itself, which is why you're seeing it apparently at random and not connected to a particular page.
A: I'd seen this error many times. It could be caused by many things including network errors too :).
But one of the reason could be built-in feature of MS-SQL.
The feature detects DoS attacks -- in this case too many request from web server :).
But I have no idea how we fixed it :(.
A: SQL server configuration Manager
Disable TCP/IP , Enable Shared Memory & Named Pipes
Good Luck !
A: Not a solution exactly and not the same environment. However I get this error in a VBA/Excel program, and the problem is I have a hanging transaction which has not been submitted in SQL Server Management Studio (SSMS). After closing SSMS, everything works. So the lesson is a hanging transaction can block sprocs from proceeding (obvious fact, I know!). Hope this help someone here.
A: open command prompt - Run as administrator and type following command on the client side
netsh advfirewall set allprofiles state off
A: FWIW, I had this error from Excel, which would hang on an EXEC which worked fine within SSMS. I've seen queries with problems before, which were also OK within SSMS, due to 'parameter sniffing' and unsuitable cached query plans. Making a minor edit to the SP cured the problem, and it worked OK afterwards in its orginal form. I'd be interested to hear if anyone has encountered this scenario too. Try the good old OPTION (OPTIMIZE FOR UNKNOWN) :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SQL Server Duplicate Checking What is the best way to determine duplicate records in a SQL Server table?
For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).
Sample data:
1 01/01/2008 [email protected]
2 02/01/2008 [email protected]
3 01/12/2008 [email protected]
A: something like this
select email ,max(receiveddate) as MaxDate
from YourTable
group by email
having count(email) > 1
A: Try something like:
SELECT * FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ReceivedDate, Email ORDER BY ReceivedDate, Email DESC) AS RowNumber
FROM EmailTable
) a
WHERE RowNumber = 1
See http://www.technicaloverload.com/working-with-duplicates-in-sql-server/
A: Couldn't you join the list on the e-mail field and then see what nulls you get in your result?
Or better yet, count the instances of each e-mail address? And only return the ones with count > 1
Or even take the email and id fields. And return the entries where the e-mail is the same, and the IDs are different. (To avoid duplicates don't use != but rather either < or >.)
A: Try this
select * from table a, table b
where a.email = b.email
A: SELECT [id], [receivedate], [email]
FROM [mytable]
WHERE [email] IN ( SELECT [email]
FROM [myTable]
GROUP BY [email]
HAVING COUNT([email]) > 1 )
A: Do you want a list of the last items? If so you could use:
SELECT [info] FROM [table] t WHERE NOT EXISTS (SELECT * FROM [table] tCheck WHERE t.date > tCheck.date)
If you want a list of all duplicate email address use GROUP BY to collect similar data, then a HAVING clause to make sure the quantity is more than 1:
SELECT [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 DESC
If you want the last duplicate e-mail (a single result) you simply add a "TOP 1" and "ORDER BY":
SELECT TOP 1 [info] FROM [table] GROUP BY [email] HAVING Count(*) > 1 ORDER BY Date DESC
A: If you have surrogate key, it is relatively easy to use the group by syntax mentioned in SQLMenance's post. Essentially, group by all the fields that make two or more rows 'the same'.
Example pseudo-code to delete duplicate records.
Create table people (ID(PK), Name, Address, DOB)
Delete from people where id not in (
Select min(ID) from people group by name, address, dob
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C# Game Network Library I am developing an online strategy game using .Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data.
{EDIT} I forgot to mention that I am leaning away from WCF and .NET 3+ for a couple of reasons. First, because I want to keep my download small and most of my customers already have .NET 2.0. Second, because I would like to have the option of porting to Mac and Linux and am unsure of WCF availability in Mono. {/EDIT}
I am looking for network library recommendations. I have found a few options, such as GarageGames' Torque Network Library (C++), RakNet (C++), and the lidgren network library (C#):
http://www.opentnl.org/
http://www.jenkinssoftware.com/
http://code.google.com/p/lidgren-network/
Does anyone have real-world experience with these or other libraries?
I just stumbled on RakNetDotNet:
http://code.google.com/p/raknetdotnet/
This might be what I'm looking for...
A: Microsoft's own .NET based XNA allows you to create networked games on Windows and XBox 360.
A: http://code.google.com/p/lidgren-network-gen3/
Lidgren.Network is a networking library for .net framework which uses
a single udp socket to deliver a simple API for connecting a client to
a server, reading and sending messages.
A: I'd also like to note that "Games for Windows", which XNA uses on windows with its Live! networking APIs is now free ... which means that if you write an XNA game that uses the networking features, your users do not have to have a gold membership :-)
http://www.engadget.com/2008/07/22/games-for-windows-live-now-free/
A: Why limit yourself to .NET 2.0. .NET 3.0 (or 3.5) contains WCF and is a solid, performant communications subsystem with good security. .NET 3.0 is just .NET 2.0 with additional libraries (WCF, WF, WPF).
A: You could take a look at Entanglar ( http://entanglar.dunnchurchill.com ) if you are looking for something higher level. Entanglar provides full entity lifecycle and sync.
A: Although this question is rather old, a somewhat higher level system developed specifically for games is APlay - among the supported platforms is also C#. There are evaluation versions and it is free for personal use.
You define your game objects in an UML alike fashion and an online code generator creates assemblies containing your game objects. Sending state updates is then as simple as calling setter methods.
Not the right thing, if you want to cope with sockets by yourself. Please also note that I am a developer of APlay so this is a biased answer.
A: An ancient question, but I'll put this out there for anyone else who stumbles across this. We're using OpenTNL for our game, Bitfighter, and I am consistently surprised at how well it works. And it's free if you can live with GPL.
A: If you're new to game development, I'd recommend XNA- it's easy to program with. The advantage of Torque, however, is it has asset creation tools, which can also be invaluable. For a higher end game or FPS, the Source engine is great.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Where do attached properties fit in a class diagram? What is the most appropriate way to represent attached properties in a UML diagram or an almost-uml diagram like the VS2008 class diagram?
A: In UML it'll be quoted tag before the member. Something conventional, like this:
"attached" Align: ElementAlign
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Showing a hint for a C# winforms edit control I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field the text should disappear. How can I achieve this?
A: You will need to use some P/Inovke interop code to do this. Look for the Win32 API SendMessage function and the EM_SETCUEBANNER message.
A: Its better to post the code instead of link. I am posting this from here
//Copyright (c) 2008 Jason Kemp
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;
public static class Win32Utility
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg,
int wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
[DllImport("user32.dll")]
private static extern bool SendMessage(IntPtr hwnd, int msg, int wParam, StringBuilder lParam);
[DllImport("user32.dll")]
private static extern bool GetComboBoxInfo(IntPtr hwnd, ref COMBOBOXINFO pcbi);
[StructLayout(LayoutKind.Sequential)]
private struct COMBOBOXINFO
{
public int cbSize;
public RECT rcItem;
public RECT rcButton;
public IntPtr stateButton;
public IntPtr hwndCombo;
public IntPtr hwndItem;
public IntPtr hwndList;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
private const int EM_SETCUEBANNER = 0x1501;
private const int EM_GETCUEBANNER = 0x1502;
public static void SetCueText(Control control, string text)
{
if (control is ComboBox)
{
COMBOBOXINFO info = GetComboBoxInfo(control);
SendMessage(info.hwndItem, EM_SETCUEBANNER, 0, text);
}
else
{
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);
}
}
private static COMBOBOXINFO GetComboBoxInfo(Control control)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of three controls, a button, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
return info;
}
public static string GetCueText(Control control)
{
StringBuilder builder = new StringBuilder();
if (control is ComboBox)
{
COMBOBOXINFO info = new COMBOBOXINFO();
//a combobox is made up of two controls, a list and textbox;
//we want the textbox
info.cbSize = Marshal.SizeOf(info);
GetComboBoxInfo(control.Handle, ref info);
SendMessage(info.hwndItem, EM_GETCUEBANNER, 0, builder);
}
else
{
SendMessage(control.Handle, EM_GETCUEBANNER, 0, builder);
}
return builder.ToString();
}
}
A: I think the way this is generally done is to set the color of the text to gray and prefill it with your hint text.
Then, write handlers for the text field's focus events, modifying the fields contents and color based when focus is gained and lost. Here's some pseudocode (sorry, it's totally not C# code. I have Actionscript on the brain right now):
TextInput myInput;
boolean showingHint = true;
myInput.text = "Search Terms";
myInput.color = 0xcccccc;
myInput.onFocusGained = function() {
if(showingHint) {
myInput.text = "";
myInput.color = 0x000000;
showingHint = false;
}
}
myInput.onFocusLost = function() {
if(!showingHint && myInput.text.length == 0) {
myInput.text = "Search Terms";
myInput.color = 0xcccccc;
showingHint = true;
}
}
Remember, you only want to change the text on focus lost if the user hasn't manually changed the text. Use a separate boolean to track if you're showing the hint or not so you can differentiate between the user manually typing your "hint" text as actual content. Similarly, you only want to clear the contents of the input box if the hint is being displayed so you don't get rid of user input accidentally.
A: There is built-in functionality in the text box control -- AutoCompleteMode and AutoCompleteSource. They may be worth a try before you go into custom or 3rd party controls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: concatenating unknown-length strings in COBOL How do I concatenate together two strings, of unknown length, in COBOL? So for example:
WORKING-STORAGE.
FIRST-NAME PIC X(15) VALUE SPACES.
LAST-NAME PIC X(15) VALUE SPACES.
FULL-NAME PIC X(31) VALUE SPACES.
If FIRST-NAME = 'JOHN ' and LAST-NAME = 'DOE ', how can I get:
FULL-NAME = 'JOHN DOE '
as opposed to:
FULL-NAME = 'JOHN DOE '
A: I believe the following will give you what you desire.
STRING
FIRST-NAME DELIMITED BY " ",
" ",
LAST-NAME DELIMITED BY SIZE
INTO FULL-NAME.
A: At first glance, the solution is to use reference modification to STRING together the two strings, including the space. The problem is that you must know how many trailing spaces are present in FIRST-NAME, otherwise you'll produce something like 'JOHNbbbbbbbbbbbbDOE', where b is a space.
There's no intrinsic COBOL function to determine the number of trailing spaces in a string, but there is one to determine the number of leading spaces in a string. Therefore, the fastest way, as far as I can tell, is to reverse the first name, find the number of leading spaces, and use reference modification to string together the first and last names.
You'll have to add these fields to working storage:
WORK-FIELD PIC X(15) VALUE SPACES.
TRAILING-SPACES PIC 9(3) VALUE ZERO.
FIELD-LENGTH PIC 9(3) VALUE ZERO.
*
*Reverse the FIRST-NAME
*
*MOVE FUNCTION REVERSE (FIRST-NAME) TO WORK-FIELD.
*WORK-FIELD now contains leading spaces, instead of trailing spaces.
*Find the number of trailing spaces in FIRST-NAME
*
*INSPECT WORK-FIELD TALLYING TRAILING-SPACES FOR LEADING SPACES.
*TRAILING-SPACE now contains the number of trailing spaces in FIRST-NAME.
*Find the length of the FIRST-NAME field
*
*COMPUTE FIELD-LENGTH = FUNCTION LENGTH (FIRST-NAME).
*Concatenate the two strings together.
*
*STRING FIRST-NAME (1:FIELD-LENGTH – TRAILING-SPACES) “ “ LAST-NAME DELIMITED BY SIZE, INTO FULL-NAME.
A: You could try making a loop for to get the real length.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: What's a good method for extracting text from a PDF using C# or classic ASP (VBScript)? Is there a good library for extracting text from a PDF? I'm willing to pay for it if I have to.
Something that works with C# or classic ASP (VBScript) would be ideal and I also need to be able to separate the pages from the PDF.
This question had some interesting stuff, especially pdftotext but I'd like to avoid calling to an external command-line app if I can.
A: You can use the IFilter interface built into Windows to extract text and properties (author, title, etc.) from any supported file type. It's a COM interface so you would have use the .NET interop facilities.
You'd also have to download the free PDF IFilter driver from Adobe.
A: Here is a good list:
Open Source Libs for PDF/C#
Most of these are geared toward creating PDFs, but they should have read capability as well.
There is this one as well: iText
I have only played with iText before. Nothing major.
A: We've used Aspose with good results.
A: Docotic.Pdf library can be used to extract formatted or plain text from PDF documents.
The library can read PDF documents of any version (up to the latest published standard). Extraction of pages is also supported by the library.
Links to sample code:
*
*How to extract text from PDF
*How to extract PDF pages
Disclaimer: I work for the vendor of the library.
A: Addition to the to the approved answer: there are also alternative commercial solutions to replace Adobe IFilter for text indexing (providing the similar API but also offering additional premium functionality):
*
*Foxit PDF IFilter: provides much faster text indexing comparing to Adobe's plugin.
*PDFLib PDF iFilter: includes support for damaged PDF documents plus the additional API to run your own queries.
If you are looking for the single tool that can be used from both managed .NET apps and legacy programming languages like classic ASP or VB6 then this is where the commercial ByteScout PDF Extractor SDK would fit as it provides both .NET and ActiveX/COM API.
Disclaimer: I work for ByteScout
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Developing a online exam application, how do I prevent cheaters? I have the task of developing an online examination software for a small university, I need to implement measures to prevent cheating...
What are your ideas on how to do this?
I would like to possibly disable all IE / firefox tabs, or some how log internet activity so I know if they are googling anwsers...is there any realistic way to do such things from a flex / web application?
A: Simply put, no there is no realistic way to accomplish this if it is an online exam (assuming they are using their own computers to take the exam).
A: Is opening the browser window full screen an option? You could possibly also check for the window losing focus and start a timer that stops the test after some small period of time.
A: @Chuck - a good idea.
If the test was created in Flash/Flex, you could force the user to make the application fullscreen in order to start the test (fullscreen mode has to be user-initiated). Then, you can listen for the Flash events dispatched when flash exits fullscreen mode and take whatever appropriate action you want (end the test, penalize the user, etc.).
Flash/Flex fullscreen event info.
blog.flexexamples.com has an example fo creating a fullscreen-capable app.
A: Random questions and large banks of questions help. Randomizing even the same question (say changing the numbers, and calculating the result) helps too. None of these will prevent cheating though.
In the first case, if the pool is large enough, so that no two students get the same question, all that means is that students will compile a list of questions over the course of several semesters. (It is also a ton of work for the professors to come up with so many questions, I've had to do it as a TA it is not fun.)
In the second case, all you need is one smart student to solve the general case, and all the rest just take that answer and plug in the values.
Online review systems work well with either of these strategies (no benefit in cheating.) Online tests? They won't work.
Finally, as for preventing googling... good luck. Even if your application could completely lock down the machine. The user could always run a VM or a second machine and do whatever they want.
A: My school has always had a download link for the Lockdown browser, but I've never taken a course that required it. You can probably force the student to use it with a user agent check, but it could probably be spoofed with some effort.
Proctored tests are the only way to prevent someone from cheating. All the other methods might make it hard enough to not be worth the effort for most, but don't discount the fact that certain types of people will work twice as hard to cheat than it would have taken them to study honestly.
A: Since you can't block them from using google, you've got to make sure they don't have time to google. Put the questions in images so they can't copy and paste (randomize the image names each time they are displayed).
Make the question longer (100 words or more) and you will find that people would rather answer the question than retype the whole thing in google.
Give them a very short time. like 30-45 seconds. Time to read the question, think for a moment, and click either A, B, C, D, E,
(having just graduated from CSUN I can tell you scantron tests work.)
For essay questions? do a reverse google lookup (meaning put their answer into google as soon as they click submit) and see if you get exact matches. If so, you know what to do.
A: Will they always take the test on test machines, or will they be able to take the test from any machine on the network? If it will be specific machines, just use the hosts file to prevent them from getting out to the web.
If it is any machine, then I would look at having the testing backend change the firewall rules for the machine the test is running on so the machine cannot get out to the interwebs.
A: I'd probably implement a simple winforms (or WPF) app that hosts a browser control in it -- which is locked in to your site. Then you can remove links to browsers and lock down the workstations so that all they can open is your app.
This assumes you have control over the workstations on which the students are taking the tests, of course.
A: As a teacher, I can tell you the single best way would be to have human review of the answers. A person can sense copy/paste or an answer that doesn't make sense given the context of the course, expected knowledge level of the students, content of the textbook, etc, etc, etc.
A computer can do things like check for statistical similarity of answers, but you really need a person for final review (or, alternatively, build a massive statistical-processing, AI stack that will cost 10x the cost of human review and won't be as good ;-))
A: No, browsers are designed to limit the amount of damage a website or application can do to the system. You might be able to accomplish your goals through Java, an activex control, or a custom plugin, but other than that you aren't going to be able to 'watch' what they're doing on their system, much less control it. (Think if you could! I could put a spy on this webpage, and if you have it open I get to see what other websites you have open?)
Even if you could do this, using a browser inside a VM would give them the ability to use one computer to browse during the test, and if you could fix that they could simply use a library computer with their laptop next to it, or read things from a book.
The reality is that such unmonitored tests either have to be considered "open book" or "honor" tests. You must design the test questions in such a manner that references won't help solve the problems, which also means that each student needs to get a slightly different test so there is no way for them to collude and generate a key.
You have to develop an application that runs on their computer, but even then you can't solve the VM problem easily, and cannot solve the side by side computers or book problem at all.
-Adam
A: Randomize questions, ask a random set of questions from a large bank... time the answers...
Unless you mean hacking your site, which is a different question.
A: Short of having the application run completely on the user's machine, I do not believe there is a way to make sure they are not google-ing the answers. Even then it would be difficult to check for all possible loop-holes.
I have taken classes that used web based quiz software and used to work for a small college as well. For basic cheating prevention I would say randomize the questions.
A: Try adding SMS messages into the mix.
A: I agree with Adam, that even with the limitations that I suggested, it would still be trivial to cheat. Those were just "best effort" suggestions.
A: Your only hopes are a strong school honor code and human proctoring of the room where the test is being given.
As many other posters have said, you can't control the student's computer, and you certainly can't keep them from using a second computer or an iPhone along side the one being used for the test -- note that an iPhone (or other cellular device) can bypass any DNS or firewall on the network, since it uses the cellular provider's network, not the college's.
Good luck; you're going to need it.
A: Ban them from using any wireless device or laptop and keylog the machines?
A: You could enforce a small time window during which the test is available. This could reduce the chance that a student who knows the answers will be free to help one who doesn't (since they both need to be taking the test at the same time).
If it's math-related, use different numbers for different students. In general, try to have different questions for different copies of the test.
If you get to design the entire course: try to have some online homeworks as well, so that you can build a profile for each student, such as a statistical analysis of how often they use certain common words and punctuations. Some students use semi-colons often; others never, for example. When they take the test you get a good idea of whether or not it's really them typing.
You could also ask a couple questions you know they don't know. For example, list 10 questions and say they must answer any 6 out of the 10. But make 3 of the questions based on materials not taught in class. If they choose 2 or 3 of these, you have good reason to be suspicious.
Finally, use an algorithm to compare for similar answers. Do a simple hash to get rid of small changes. For example, hash an answer to a list of lower-cased 3-grams (3 words in a row), alphabetize it, and then look for many collisions between different users. This may sound like an obvious technique, but as a teacher I can assure you this will catch a surprising number of cheaters.
Sadly, the real trouble is to actually enforce punishment against cheaters. At the colleges where I have taught, if a student objects to your punishment (such as flunking them on the test in question), the administration will usually give the student something back, such as a positive grade change. I guess this is because the student('s parents) have paid the university a lot of money, but it is still very frustrating as a teacher.
A: The full screen suggestions are quite limited in their effectiveness as the user can always use a second computer or w/ multi monitor a second screen to perform their lookups. In the end it is probably better to just assume the students are going to cheat and then not count online tests for anything important.
If the tests are helpful for the students they will then do better on the final / mid term exams that are proctored in a controlled setting. Otherwise, why have them in the first place...
A: Make the questions and answers jpeg images so that you cannot copy and paste blocks of text into a search engine or IDE (if it is a coding test). This combined with a tight time limit to answer each question, say three minutes, makes it much harder to cheat.
A: I second what Guy said. We also created a Flex based examination system which was hosted in a custom browser built in .NET. The custom browser launched fullscreen, all toolbars were hidden and shortcuts were disabled.
Here is tutorial on how to create a custom browser with C# and VB.NET.
A: This will solve your problem. http://www.neuber.com/usermonitor/index.html
This will allow you to view the student's browser history during and after the test as well as look in on their screen during the test. Any urls visited during test time will be logged, so you can show them the log when you put a big F on their report card. :)
A: No one can stop people from cheating, but everyone can receive different questions altogether.
I prefer you buy available online scripts in market as starting point for it. This will save you time, cost and testing efforts.
Below is one of the fine scripts that I worked with and it worked like charm. Using this as base I developed a online testing portal of over 1000 users using computer adaptive test.
http://codecanyon.net/item/online-skills-assessment/9379895
It is a good starting point for people looking to develop Online Exam System.
I customized the script with the help of their support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How do I efficiently iterate over each entry in a Java Map? If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
Will the ordering of elements depend on the specific map implementation that I have for the interface?
A: There are several ways to iterate over map.
Here is comparison of their performances for a common data set stored in map by storing a million key value pairs in map and will iterate over map.
1) Using entrySet() in for each loop
for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
entry.getKey();
entry.getValue();
}
50 milliseconds
2) Using keySet() in for each loop
for (String key : testMap.keySet()) {
testMap.get(key);
}
76 milliseconds
3) Using entrySet() and iterator
Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
while(itr1.hasNext()) {
Map.Entry<String,Integer> entry = itr1.next();
entry.getKey();
entry.getValue();
}
50 milliseconds
4) Using keySet() and iterator
Iterator itr2 = testMap.keySet().iterator();
while(itr2.hasNext()) {
String key = itr2.next();
testMap.get(key);
}
75 milliseconds
I have referred this link.
A: package com.test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("ram", "ayodhya");
map.put("krishan", "mathura");
map.put("shiv", "kailash");
System.out.println("********* Keys *********");
Set<String> keys = map.keySet();
for (String key : keys) {
System.out.println(key);
}
System.out.println("********* Values *********");
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
System.out.println("***** Keys and Values (Using for each loop) *****");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + "\t Value: "
+ entry.getValue());
}
System.out.println("***** Keys and Values (Using while loop) *****");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
.next();
System.out.println("Key: " + entry.getKey() + "\t Value: "
+ entry.getValue());
}
System.out
.println("** Keys and Values (Using java 8 using lambdas )***");
map.forEach((k, v) -> System.out
.println("Key: " + k + "\t value: " + v));
}
}
A: Map.forEach
What about simply using Map::forEach where both the key and the value are passed to your BiConsumer?
map.forEach((k,v)->{
System.out.println(k+"->"+v);
});
A: Here is a generic type-safe method which can be called to dump any given Map.
import java.util.Iterator;
import java.util.Map;
public class MapUtils {
static interface ItemCallback<K, V> {
void handler(K key, V value, Map<K, V> map);
}
public static <K, V> void forEach(Map<K, V> map, ItemCallback<K, V> callback) {
Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<K, V> entry = it.next();
callback.handler(entry.getKey(), entry.getValue(), map);
}
}
public static <K, V> void printMap(Map<K, V> map) {
forEach(map, new ItemCallback<K, V>() {
@Override
public void handler(K key, V value, Map<K, V> map) {
System.out.println(key + " = " + value);
}
});
}
}
Example
Here is an example of its use. Notice that the type of the Map is inferred by the method.
import java.util.*;
public class MapPrinter {
public static void main(String[] args) {
List<Map<?, ?>> maps = new ArrayList<Map<?, ?>>() {
private static final long serialVersionUID = 1L;
{
add(new LinkedHashMap<String, Integer>() {
private static final long serialVersionUID = 1L;
{
put("One", 0);
put("Two", 1);
put("Three", 3);
}
});
add(new LinkedHashMap<String, Object>() {
private static final long serialVersionUID = 1L;
{
put("Object", new Object());
put("Integer", new Integer(0));
put("Double", new Double(0.0));
}
});
}
};
for (Map<?, ?> map : maps) {
MapUtils.printMap(map);
System.out.println();
}
}
}
Output
One = 0
Two = 1
Three = 3
Object = java.lang.Object@15db9742
Integer = 0
Double = 0.0
A: Since Java 10, you can use local variable inference (a.k.a. "var") to make a lot of the already available answers less bloated. For example:
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
A: FYI, you can also use map.keySet() and map.values() if you're only interested in keys/values of the map and not the other.
A: The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.
for (String key: map.keySet()) {
System.out.println(key + "/" + map.get(key));
}
A: There are several ways to iterate a map. Please refer to the following code.
When you iterate a map using iterator Interface you must go with Entry<K,V> or entrySet().
It looks like this:
import java.util.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IteratMapDemo{
public static void main(String arg[]){
Map<String, String> mapOne = new HashMap<String, String>();
mapOne.put("1", "January");
mapOne.put("2", "February");
mapOne.put("3", "March");
mapOne.put("4", "April");
mapOne.put("5", "May");
mapOne.put("6", "June");
mapOne.put("7", "July");
mapOne.put("8", "August");
mapOne.put("9", "September");
mapOne.put("10", "Octomber");
mapOne.put("11", "November");
mapOne.put("12", "December");
Iterator it = mapOne.entrySet().iterator();
while(it.hasNext())
{
Map.Entry me = (Map.Entry) it.next();
//System.out.println("Get Key through While loop = " + me.getKey());
}
for(Map.Entry<String, String> entry:mapOne.entrySet()){
//System.out.println(entry.getKey() + "=" + entry.getValue());
}
for (Object key : mapOne.keySet()) {
System.out.println("Key: " + key.toString() + " Value: " +
mapOne.get(key));
}
}
}
A: If your reason for iterating trough the Map, is to do an operation on the value and write to a resulting Map. I recommend using the transform-methods in the Google Guava Maps class.
import com.google.common.collect.Maps;
After you have added the Maps to your imports, you can use Maps.transformValues and Maps.transformEntries on your maps, like this:
public void transformMap(){
Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.put("b", 4);
Map<String, Integer> result = Maps.transformValues(map, num -> num * 2);
result.forEach((key, val) -> print(key, Integer.toString(val)));
// key=a,value=4
// key=b,value=8
Map<String, String> result2 = Maps.transformEntries(map, (key, value) -> value + "[" + key + "]");
result2.forEach(this::print);
// key=a,value=2[a]
// key=b,value=4[b]
}
private void print(String key, String val){
System.out.println("key=" + key + ",value=" + val);
}
A: I like to concat a counter, then save the final value of the counter;
int counter = 0;
HashMap<String, String> m = new HashMap<String, String>();
for(int i = 0;i<items.length;i++)
{
m.put("firstname"+i, items.get(i).getFirstName());
counter = i;
}
m.put("recordCount",String.valueOf(counter));
Then when you want to retrieve:
int recordCount = Integer.parseInf(m.get("recordCount"));
for(int i =0 ;i<recordCount;i++)
{
System.out.println("First Name :" + m.get("firstname"+i));
}
A:
Using Java 7
Map<String,String> sampleMap = new HashMap<>();
for (sampleMap.Entry<String,String> entry : sampleMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
/* your Code as per the Business Justification */
}
Using Java 8
Map<String,String> sampleMap = new HashMap<>();
sampleMap.forEach((k, v) -> System.out.println("Key is : " + k + " Value is : " + v));
A: Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
On Java 10+:
for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
A: With Java 8, you can iterate Map using forEach and lambda expression,
map.forEach((k, v) -> System.out.println((k + ":" + v)));
A: With Eclipse Collections, you would use the forEachKeyValue method on the MapIterable interface, which is inherited by the MutableMap and ImmutableMap interfaces and their implementations.
MutableMap<Integer, String> map =
Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
MutableBag<String> result = Bags.mutable.empty();
map.forEachKeyValue((key, value) -> result.add(key + value));
MutableBag<String> expected = Bags.mutable.of("1One", "2Two", "3Three");
Assertions.assertEquals(expected, result);
The reason using forEachKeyValue with Eclipse Collections (EC) Map implementations will be more efficient than using entrySet is because EC Map implementations do not store Map.Entry objects. Using entrySet with EC Map implementations results in Map.Entry objects being generated dynamically. The forEachKeyValue method is able to avoid creating the Map.Entry objects because it can navigate the internal structure of the Map implementations directly. This is a case where there is a benefit of using an internal iterator over an external iterator.
Note: I am a committer for Eclipse Collections.
A: Java 8
We have got forEach method that accepts a lambda expression. We have also got stream APIs. Consider a map:
Map<String,String> sample = new HashMap<>();
sample.put("A","Apple");
sample.put("B", "Ball");
Iterate over keys:
sample.keySet().forEach((k) -> System.out.println(k));
Iterate over values:
sample.values().forEach((v) -> System.out.println(v));
Iterate over entries (Using forEach and Streams):
sample.forEach((k,v) -> System.out.println(k + ":" + v));
sample.entrySet().stream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
System.out.println(currentKey + ":" + currentValue);
});
The advantage with streams is they can be parallelized easily in case we want to. We simply need to use parallelStream() in place of stream() above.
forEachOrdered vs forEach with streams ?
The forEach does not follow encounter order (if defined) and is inherently non-deterministic in nature where as the forEachOrdered does. So forEach does not guarantee that the order would be kept. Also check this for more.
A: In theory, the most efficient way will depend on which implementation of Map. The official way to do this is to call map.entrySet(), which returns a set of Map.Entry, each of which contains a key and a value (entry.getKey() and entry.getValue()).
In an idiosyncratic implementation, it might make some difference whether you use map.keySet(), map.entrySet() or something else. But I can't think of a reason why anyone would write it like that. Most likely it makes no difference to performance what you do.
And yes, the order will depend on the implementation - as well as (possibly) the order of insertion and other hard-to-control factors.
[edit] I wrote valueSet() originally but of course entrySet() is actually the answer.
A: You can search for the key and with the help of the key you can find the associated value of the map as map has unique key, see what happens when key is duplicate here or here.
Demo map :
Map<String, String> map = new HashMap();
map.put("name", "Name");
map.put("age", "23");
map.put("address", "NP");
map.put("faculty", "BE");
map.put("major", "CS");
map.put("head", "MDK");
To get key only, you can use map.keySet(); like this :
for(String key : map.keySet()) {
System.out.println(key);
}
To get value only , you can use map.values(); like this:
for(String value : map.values()) {
System.out.println(value);
}
To get both key and its value you still can use map.keySet(); and get its corresponding value, like this :
//this prints the key value pair
for (String k : map.keySet()) {
System.out.println(k + " " + map.get(k) + " ");
}
map.get(key) gives the value pointed by that key.
A:
Lambda Expression Java 8
In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.
Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
// Just copy and paste above line to your code.
Below is the sample code that I tried using Lambda Expression. This stuff is so cool. Must try.
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
Random rand = new Random(47);
int i = 0;
while(i < 5) {
i++;
int key = rand.nextInt(20);
int value = rand.nextInt(50);
System.out.println("Inserting key: " + key + " Value: " + value);
Integer imap = hm.put(key, value);
if( imap == null) {
System.out.println("Inserted");
} else {
System.out.println("Replaced with " + imap);
}
}
hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
Output:
Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
Also one can use Spliterator for the same.
Spliterator sit = hm.entrySet().spliterator();
UPDATE
Including documentation links to Oracle Docs.
For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.
A: Java 8:
You can use lambda expressions:
myMap.entrySet().stream().forEach((entry) -> {
Object currentKey = entry.getKey();
Object currentValue = entry.getValue();
});
For more information, follow this.
A: In Java 8 you can do it clean and fast using the new lambdas features:
Map<String,String> map = new HashMap<>();
map.put("SomeKey", "SomeValue");
map.forEach( (k,v) -> [do something with key and value] );
// such as
map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));
The type of k and v will be inferred by the compiler and there is no need to use Map.Entry anymore.
Easy-peasy!
A: In Map one can Iteration over keys and/or values and/or both (e.g., entrySet) depends on one's interested in_ Like:
*
*Iterate through the keys -> keySet() of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
//your Business logic...
}
*Iterate through the values -> values() of the map:
for (Object value : map.values()) {
//your Business logic...
}
*Iterate through the both -> entrySet() of the map:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
//your Business logic...
}
Moreover, there are 3 different ways to iterate through a HashMap. They are as below:
//1.
for (Map.Entry entry : hm.entrySet()) {
System.out.print("key,val: ");
System.out.println(entry.getKey() + "," + entry.getValue());
}
//2.
Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
Integer key = (Integer)iter.next();
String val = (String)hm.get(key);
System.out.println("key,val: " + key + "," + val);
}
//3.
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Integer key = (Integer)entry.getKey();
String val = (String)entry.getValue();
System.out.println("key,val: " + key + "," + val);
}
A: Try this with Java 1.4:
for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){
Entry entry = (Entry) entries.next();
System.out.println(entry.getKey() + "/" + entry.getValue());
//...
}
A: It doesn't quite answer the OP's question, but might be useful to others who find this page:
If you only need the values and not the keys, you can do this:
Map<Ktype, Vtype> myMap = [...];
for (Vtype v: myMap.values()) {
System.out.println("value: " + v);
}
Ktype, Vtype are pseudocode.
A: If you want to iterate through the map in the order that the elements were added, use LinkedHashMap as opposed to just Map.
This approach has worked for me in the past:
LinkedHashMap<String,Integer> test=new LinkedHashMap();
test.put("foo",69);
test.put("bar",1337);
for(int i=0;i<test.size();i++){
System.out.println(test.get(test.keySet().toArray()[i]));
}
Output:
69
1337
A: Map<String, String> map =
for (Map.Entry<String, String> entry : map.entrySet()) {
MapKey = entry.getKey()
MapValue = entry.getValue();
}
A: The ordering will always depend on the specific map implementation.
Using Java 8 you can use either of these:
map.forEach((k,v) -> { System.out.println(k + ":" + v); });
Or:
map.entrySet().forEach((e) -> {
System.out.println(e.getKey() + " : " + e.getValue());
});
The result will be the same (same order). The entrySet backed by the map so you are getting the same order. The second one is handy as it allows you to use lambdas, e.g. if you want only to print only Integer objects that are greater than 5:
map.entrySet()
.stream()
.filter(e-> e.getValue() > 5)
.forEach(System.out::println);
The code below shows iteration through LinkedHashMap and normal HashMap (example). You will see difference in the order:
public class HMIteration {
public static void main(String[] args) {
Map<Object, Object> linkedHashMap = new LinkedHashMap<>();
Map<Object, Object> hashMap = new HashMap<>();
for (int i=10; i>=0; i--) {
linkedHashMap.put(i, i);
hashMap.put(i, i);
}
System.out.println("LinkedHashMap (1): ");
linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v + ", "); });
System.out.println("\nLinkedHashMap (2): ");
linkedHashMap.entrySet().forEach((e) -> {
System.out.print(e.getKey() + " : " + e.getValue() + ", ");
});
System.out.println("\n\nHashMap (1): ");
hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() + "):" + v + ", "); });
System.out.println("\nHashMap (2): ");
hashMap.entrySet().forEach((e) -> {
System.out.print(e.getKey() + " : " + e.getValue() + ", ");
});
}
}
Output:
LinkedHashMap (1):
10 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,
LinkedHashMap (2):
10 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,
HashMap (1):
0 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,
HashMap (2):
0 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,
A: Yes, the order depends on the specific Map implementation.
@ScArcher2 has the more elegant Java 1.5 syntax. In 1.4, I would do something like this:
Iterator entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
Entry thisEntry = (Entry) entries.next();
Object key = thisEntry.getKey();
Object value = thisEntry.getValue();
// ...
}
A: Most compact with Java 8:
map.entrySet().forEach(System.out::println);
A:
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
If efficiency of looping the keys is a priority for your app, then choose a Map implementation that maintains the keys in your desired order.
Will the ordering of elements depend on the specific map implementation that I have for the interface?
Yes, absolutely.
*
*Some Map implementations promise a certain iteration order, others do not.
*Different implementations of Map maintain different ordering of the key-value pairs.
See this table I created summarizing the various Map implementations bundled with Java 11. Specifically, notice the iteration order column. Click/tap to zoom.
You can see there are four Map implementations maintaining an order:
*
*TreeMap
*ConcurrentSkipListMap
*LinkedHashMap
*EnumMap
NavigableMap interface
Two of those implement the NavigableMap interface: TreeMap & ConcurrentSkipListMap.
The older SortedMap interface is effectively supplanted by the newer NavigableMap interface. But you may find 3rd-party implementations implementing the older interface only.
Natural order
If you want a Map that keeps its pairs arranged by the “natural order” of the key, use TreeMap or ConcurrentSkipListMap. The term “natural order” means the class of the keys implements Comparable. The value returned by the compareTo method is used for comparison in sorting.
Custom order
If you want to specify a custom sorting routine for your keys to be used in maintaining a sorted order, pass a Comparator implementation appropriate to the class of your keys. Use either TreeMap or ConcurrentSkipListMap, passing your Comparator.
Original insertion order
If you want the pairs of your map to be kept in their original order in which you inserted them into the map, use LinkedHashMap.
Enum-definition order
If you are using an enum such as DayOfWeek or Month as your keys, use the EnumMap class. Not only is this class highly optimized to use very little memory and run very fast, it maintains your pairs in the order defined by the enum. For DayOfWeek, for example, the key of DayOfWeek.MONDAY will be first found when iterated, and the key of DayOfWeek.SUNDAY will be last.
Other considerations
In choosing a Map implementation, also consider:
*
*NULLs. Some implementations forbid/accept a NULL as key and/or value.
*Concurrency. If you are manipulating the map across threads, you must use an implementation that supports concurrency. Or wrap the map with Collections::synchronizedMap (less preferable).
Both of these considerations are covered in the graphic table above.
A: If you have a generic untyped Map you can use:
Map map = new HashMap();
for (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
A: public class abcd{
public static void main(String[] args)
{
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Integer key:testMap.keySet()) {
String value=testMap.get(key);
System.out.println(value);
}
}
}
OR
public class abcd {
public static void main(String[] args)
{
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Entry<Integer, String> entry : testMap.entrySet()) {
Integer key=entry.getKey();
String value=entry.getValue();
}
}
}
A: These are all the possible ways of iterating HashMap.
HashMap<Integer,String> map=new HashMap<Integer,String>();
map.put(1,"David"); //Adding elements in Map
map.put(2,"John");
map.put(4,"Samyuktha");
map.put(3,"jasmin");
System.out.println("Iterating Hashmap...");
//way 1 (java 8 Method)
map.forEach((key, value) -> {
System.out.println(key+" : "+ value);
});
//way 2 (java 7 Method)
for(Map.Entry me : map.entrySet()){
System.out.println(me.getKey()+" "+me.getValue());
}
//way 3 (Legacy way to iterate HashMap)
Iterator iterator = map.entrySet().iterator();//map.keySet().iterator()
while (iterator.hasNext())
{
Map.Entry me =(Map.Entry)iterator.next();
System.out.println(me.getKey()+" : "+ me.getValue());
}
}
A: I copied the data of a map to another with this code:
HashMap product =(HashMap)shopping_truck.get(i);
HashMap tmp = new HashMap();
for (Iterator it = product.entrySet().iterator(); it.hasNext();) {
Map.Entry thisEntry = (Map.Entry) it.next();
tmp.put(thisEntry.getKey(), thisEntry.getValue());
}
A: This is the easiest way of doing it I believe...
/* For example, this could be a map object */
Map<String, Integer> MAP = new Map<>();
// Do something like put keys/value pairs into the map, etc...
MAP.put("Denver", 35);
MAP.put("Patriots", 14);
/* Then, simply use a for each loop like this to iterate */
for (Object o : MAP.entrySet()) {
Map.Entry pair = (Map.Entry) o;
// Do whatever with the pair here (i.e. pair.getKey(), or pair.getValue();
}
A: Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry element = (Map.Entry)it.next();
LOGGER.debug("Key: " + element.getKey());
LOGGER.debug("value: " + element.getValue());
}
A: To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:
*
*Using iterator and Map.Entry
long i = 0;
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> pair = it.next();
i += pair.getKey() + pair.getValue();
}
*Using foreach and Map.Entry
long i = 0;
for (Map.Entry<Integer, Integer> pair : map.entrySet()) {
i += pair.getKey() + pair.getValue();
}
*Using forEach from Java 8
final long[] i = {0};
map.forEach((k, v) -> i[0] += k + v);
*Using keySet and foreach
long i = 0;
for (Integer key : map.keySet()) {
i += key + map.get(key);
}
*Using keySet and iterator
long i = 0;
Iterator<Integer> itr2 = map.keySet().iterator();
while (itr2.hasNext()) {
Integer key = itr2.next();
i += key + map.get(key);
}
*Using for and Map.Entry
long i = 0;
for (Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
Map.Entry<Integer, Integer> entry = entries.next();
i += entry.getKey() + entry.getValue();
}
*Using the Java 8 Stream API
final long[] i = {0};
map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
*Using the Java 8 Stream API parallel
final long[] i = {0};
map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
*Using IterableMap of Apache Collections
long i = 0;
MapIterator<Integer, Integer> it = iterableMap.mapIterator();
while (it.hasNext()) {
i += it.next() + it.getValue();
}
*Using MutableMap of Eclipse (CS) collections
final long[] i = {0};
mutableMap.forEachKeyValue((key, value) -> {
i[0] += key + value;
});
Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)
*
*For a small map (100 elements), score 0.308 is the best
Benchmark Mode Cnt Score Error Units
test3_UsingForEachAndJava8 avgt 10 0.308 ± 0.021 µs/op
test10_UsingEclipseMap avgt 10 0.309 ± 0.009 µs/op
test1_UsingWhileAndMapEntry avgt 10 0.380 ± 0.014 µs/op
test6_UsingForAndIterator avgt 10 0.387 ± 0.016 µs/op
test2_UsingForEachAndMapEntry avgt 10 0.391 ± 0.023 µs/op
test7_UsingJava8StreamApi avgt 10 0.510 ± 0.014 µs/op
test9_UsingApacheIterableMap avgt 10 0.524 ± 0.008 µs/op
test4_UsingKeySetAndForEach avgt 10 0.816 ± 0.026 µs/op
test5_UsingKeySetAndIterator avgt 10 0.863 ± 0.025 µs/op
test8_UsingJava8StreamApiParallel avgt 10 5.552 ± 0.185 µs/op
*For a map with 10000 elements, score 37.606 is the best
Benchmark Mode Cnt Score Error Units
test10_UsingEclipseMap avgt 10 37.606 ± 0.790 µs/op
test3_UsingForEachAndJava8 avgt 10 50.368 ± 0.887 µs/op
test6_UsingForAndIterator avgt 10 50.332 ± 0.507 µs/op
test2_UsingForEachAndMapEntry avgt 10 51.406 ± 1.032 µs/op
test1_UsingWhileAndMapEntry avgt 10 52.538 ± 2.431 µs/op
test7_UsingJava8StreamApi avgt 10 54.464 ± 0.712 µs/op
test4_UsingKeySetAndForEach avgt 10 79.016 ± 25.345 µs/op
test5_UsingKeySetAndIterator avgt 10 91.105 ± 10.220 µs/op
test8_UsingJava8StreamApiParallel avgt 10 112.511 ± 0.365 µs/op
test9_UsingApacheIterableMap avgt 10 125.714 ± 1.935 µs/op
*For a map with 100000 elements, score 1184.767 is the best
Benchmark Mode Cnt Score Error Units
test1_UsingWhileAndMapEntry avgt 10 1184.767 ± 332.968 µs/op
test10_UsingEclipseMap avgt 10 1191.735 ± 304.273 µs/op
test2_UsingForEachAndMapEntry avgt 10 1205.815 ± 366.043 µs/op
test6_UsingForAndIterator avgt 10 1206.873 ± 367.272 µs/op
test8_UsingJava8StreamApiParallel avgt 10 1485.895 ± 233.143 µs/op
test5_UsingKeySetAndIterator avgt 10 1540.281 ± 357.497 µs/op
test4_UsingKeySetAndForEach avgt 10 1593.342 ± 294.417 µs/op
test3_UsingForEachAndJava8 avgt 10 1666.296 ± 126.443 µs/op
test7_UsingJava8StreamApi avgt 10 1706.676 ± 436.867 µs/op
test9_UsingApacheIterableMap avgt 10 3289.866 ± 1445.564 µs/op
Graphs (performance tests depending on map size)
Table (perfomance tests depending on map size)
100 600 1100 1600 2100
test10 0.333 1.631 2.752 5.937 8.024
test3 0.309 1.971 4.147 8.147 10.473
test6 0.372 2.190 4.470 8.322 10.531
test1 0.405 2.237 4.616 8.645 10.707
test2 0.376 2.267 4.809 8.403 10.910
test7 0.473 2.448 5.668 9.790 12.125
test9 0.565 2.830 5.952 13.220 16.965
test4 0.808 5.012 8.813 13.939 17.407
test5 0.810 5.104 8.533 14.064 17.422
test8 5.173 12.499 17.351 24.671 30.403
All tests are on GitHub.
A: Typical code for iterating over a map is:
Map<String,Thing> map = ...;
for (Map.Entry<String,Thing> entry : map.entrySet()) {
String key = entry.getKey();
Thing thing = entry.getValue();
...
}
HashMap is the canonical map implementation and doesn't make guarantees (or though it should not change the order if no mutating operations are performed on it). SortedMap will return entries based on the natural ordering of the keys, or a Comparator, if provided. LinkedHashMap will either return entries in insertion-order or access-order depending upon how it has been constructed. EnumMap returns entries in the natural order of keys.
(Update: I think this is no longer true.) Note, IdentityHashMap entrySet iterator currently has a peculiar implementation which returns the same Map.Entry instance for every item in the entrySet! However, every time a new iterator advances the Map.Entry is updated.
A: An effective iterative solution over a Map is a for loop from Java 5 through Java 7. Here it is:
for (String key : phnMap.keySet()) {
System.out.println("Key: " + key + " Value: " + phnMap.get(key));
}
From Java 8 you can use a lambda expression to iterate over a Map. It is an enhanced forEach
phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));
If you want to write a conditional for lambda you can write it like this:
phnMap.forEach((k,v)->{
System.out.println("Key: " + k + " Value: " + v);
if("abc".equals(k)){
System.out.println("Hello abc");
}
});
A: You can do it using generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
A: Use Java 8:
map.entrySet().forEach(entry -> System.out.println(entry.getValue()));
A: Example of using iterator and generics:
Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
String key = entry.getKey();
String value = entry.getValue();
// ...
}
A: //Functional Oprations
Map<String, String> mapString = new HashMap<>();
mapString.entrySet().stream().map((entry) -> {
String mapKey = entry.getKey();
return entry;
}).forEach((entry) -> {
String mapValue = entry.getValue();
});
//Intrator
Map<String, String> mapString = new HashMap<>();
for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String> entry = it.next();
String mapKey = entry.getKey();
String mapValue = entry.getValue();
}
//Simple for loop
Map<String, String> mapString = new HashMap<>();
for (Map.Entry<String, String> entry : mapString.entrySet()) {
String mapKey = entry.getKey();
String mapValue = entry.getValue();
}
A: Iterating a Map is very easy.
for(Object key: map.keySet()){
Object value= map.get(key);
//Do your stuff
}
For instance, you have a Map<String, int> data;
for(Object key: data.keySet()){
int value= data.get(key);
}
A: There are a lot of ways to do this. Below is a few simple steps:
Suppose you have one Map like:
Map<String, Integer> m = new HashMap<String, Integer>();
Then you can do something like the below to iterate over map elements.
// ********** Using an iterator ****************
Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
while(me.hasNext()){
Entry<String, Integer> pair = me.next();
System.out.println(pair.getKey() + ":" + pair.getValue());
}
// *********** Using foreach ************************
for(Entry<String, Integer> me : m.entrySet()){
System.out.println(me.getKey() + " : " + me.getValue());
}
// *********** Using keySet *****************************
for(String s : m.keySet()){
System.out.println(s + " : " + m.get(s));
}
// *********** Using keySet and iterator *****************
Iterator<String> me = m.keySet().iterator();
while(me.hasNext()){
String key = me.next();
System.out.println(key + " : " + m.get(key));
}
A: This is a two part question:
How to iterate over the entries of a Map - @ScArcher2 has answered that perfectly.
What is the order of iteration - if you are just using Map, then strictly speaking, there are no ordering guarantees. So you shouldn't really rely on the ordering given by any implementation. However, the SortedMap interface extends Map and provides exactly what you are looking for - implementations will aways give a consistent sort order.
NavigableMap is another useful extension - this is a SortedMap with additional methods for finding entries by their ordered position in the key set. So potentially this can remove the need for iterating in the first place - you might be able to find the specific entry you are after using the higherEntry, lowerEntry, ceilingEntry, or floorEntry methods. The descendingMap method even gives you an explicit method of reversing the traversal order.
A: Yes, as many people agreed this is the best way to iterate over a Map.
But there are chances to throw nullpointerexception if the map is null. Don't forget to put null .check in.
|
|
- - - -
|
|
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3891"
} |
Q: Is there anything wrong with this query? INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
I've got an Access table that has five fields: id, ename, position, phone, and email...each one is plain text field with 50 characters, save for position which is 255 and id which is an autoincrement field. I'm using a VB.NET to read data from an Excel table, which gets pushed into a simple class that's used to fill out that query. I do the same thing with two other tables, whose data are pulled from a DB2 table and a MySQL table through. The other two work, but this simple INSERT loop keeps failing, so I don't think it's my "InsertNoExe" function that handles all the OleDb stuff.
So, um, does that query, any of the field titles, etc. look bogus? I can post other bits of code if anyone wants to see it.
EDIT: Fixed. I wasn't sure if the wide image counted as a Stack Overflow bug or not, which is why I left it.
EDIT 2: I'm dense. I use a try...catch to see the bogus query, and don't even check the ex.messsage. Gah.
INSERT INTO tblExcel (ename, position, phone, email) VALUES ('Burton, Andrew', 'Web Developer / Network Assistant', '876-9259', '[email protected]')
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr)
at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at EmployeeList.EmployeeDatabase.ExeNonQuery(String sql) in C:\andy\html\code\vb\EmployeeList\EmployeeDatabase.vb:line 263
Syntax error in INSERT INTO statement.
EDIT 3: Thank you, Chris.
A: I beleive "position" is a reserved word.
Try...
INSERT into tblExcel (ename, [position], phone, email) VALUES (...
Reserved Words
A: The spacing of "Web Developer / Network Assistant" looks a little wonky, maybe there is a hidden character in there (carriage return?)
I'd try taking the slash out, and see if the insert works, if not try taking all punctuation out. Then add it back and maybe you will be able to identify the bug.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this the proper use of a mutex? I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.
Is this the proper way to use a mutex to prevent this from happening?
lock (this.GetType()) {
_log.Info("Doing Sync");
DoSync();
_log.Info("Sync Completed");
}
A: TheSeeker is correct.
Jeff Richter's advice in Clr Via C# (p638-9) on locking is to create a private object specifically for the purpose of being locked.
private Object _lock = new Object();
// usage
lock( _lock )
{
// thread-safe code here..
}
This works because _lock cannot be locked by anything outside the current class.
EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.
A: You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object.
Here is a usage example:
bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
try
{
mtx.WaitOne();
MessageBox.Show("Click OK to release the mutex.");
}
finally
{
mtx.ReleaseMutex();
}
}
The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I detect if a Flex app loses focus As a follow up to this question: Developing a online exam application, how do I prevent cheaters?
Can I detect when Flex application looses its focus? that is if a user has clicked onto another application or opened a browser tab?
I read this: Detecting when a Flex application loses focus but was not very clear...
A: The key part of the code at that link is the
systemManager.stage.addEventListener(Event.DEACTIVATE,deactivate);
The Flash player send outs activate and deactivate events when the focus enters and leaves the player. All you need to do is create a listenr for them and react appropriately.
A more clear example of how to use to the activate and deactivate events can be seen at blog.flexaxamples.com.
Also, it looks like the activate and deactivate events have trouble in some browsers. Colin Moock has more info on that here.
A: You can add a handler for activate in the main application tag. This detects whenever the flex application comes to focus.
Eg:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
activate="activateHandler(event);"
deactivate="deactivateHandler(event);">
A: This will work to detect when the Flex windows loses focus, but to detect when the window regains focus without having to actually click on the flex app requires an update in the HTML wrapper, correct? Something like:
<script language="JavaScript" type="text/javascript">
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = ${version_major};
// Minor version of Flash required
var requiredMinorVersion = ${version_minor};
// Minor version of Flash required
var requiredRevision = ${version_revision};
// -----------------------------------------------------------------------------
// -->
function onAppFocusIn()
{
${application}.onAppFocusIn();
alert("onAppFocusIn");
}
</script>
<body scroll="no" onFocus="onAppFocusIn()">
I am trying to implement this but the onAppFocusIn() function is not executing once I move back to the flex app window. When I view the source, the code is there. Does anyone know why??
Thanks,
Annie
A: In Flex 4.6, this command works systemManager.stage.addEventListener(Event.DEACTIVATE, deactivate)
but make sure the flash app wmode is set to window (default). When the wmode was transparent, the event didn't get caught. You set the wmode in the embedded html where you put your flash app. example:
<object classid="clsid:D27WEE-A16D-21cf-90F2-422253540410" width="100%" height="100%"
id="MyApp" name="MyApp" align="middle">
<param name="movie" value="MyApp.swf?v=1.00.008" />
<param name="wmode" value="transparent"> <----- take out this
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What's the proper way to minimize to tray a C# WinForms app? What is the proper way to minimize a WinForms app to the system tray?
Note: minimize to system tray; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window.
I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon."
Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues.
What's the proper way to do this?
A: this.WindowState = FormWindowState.Minimized
That is the built in way to do it and it looks fine to me most of the time. The only time is has some weirdness to it is if you call it on startup which has some weirdness sometimes which is why most people will also set the ShowInTaskbar = false and hide the form too.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.windowstate.aspx
A: It will helps:
public partial class Form1 : Form
{
public static bool Close = false;
Icon[] images;
int offset = 0;
public Form1()
{
InitializeComponent();
notifyIcon1.BalloonTipText = "My application still working...";
notifyIcon1.BalloonTipTitle = "My Sample Application";
notifyIcon1.BalloonTipIcon = ToolTipIcon.Info;
}
private void Form1_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
{
this.Hide();
notifyIcon1.ShowBalloonTip(500);
//WindowState = FormWindowState.Minimized;
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
notifyIcon1.ShowBalloonTip(1000);
WindowState = FormWindowState.Normal;
}
private void maximizeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Show();
WindowState = FormWindowState.Normal;
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
Close = true;
this.Close();
}
// Handle Closing of the Form.
protected override void OnClosing(CancelEventArgs e)
{
if (Close)
{
e.Cancel = false;
}
else
{
WindowState = FormWindowState.Minimized;
e.Cancel = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Load the basic set of eight icons.
images = new Icon[5];
images[0] = new Icon("C:\\icon1.ico");
images[1] = new Icon("C:\\icon2.ico");
images[2] = new Icon("C:\\icon3.ico");
images[3] = new Icon("C:\\icon4.ico");
images[4] = new Icon("C:\\icon5.ico");
}
private void timer1_Tick(object sender, EventArgs e)
{
// Change the icon.
// This event handler fires once every second (1000 ms).
if (offset < 5)
{
notifyIcon1.Icon = images[offset];
offset++;
}
else
{
offset = 0;
}
}
}
A: This code is tested and supports many options.
More here: http://code.msdn.microsoft.com/TheNotifyIconExample
A: Update: Looks like I posted too soon.
I was also using the below hack for a tool of mine. Waiting for the right solution for this..........
You can use Windows.Forms.NotifyIcon for this. http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx
Add NotifyIcon to the form, set some properties and you are done.
this.ShowIcon = false;//for the main form
this.ShowInTaskbar = false;//for the main form
this.notifyIcon1.Visible = true;//for notify icon
this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));//set an icon for notifyicon
private void Form1_Shown(object sender, EventArgs e)
{
this.Hide();
}
A: There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it:
Some good info here (In the comments not the post):
http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx
And here it is in C++:
http://www.codeproject.com/KB/shell/minimizetotray.aspx
You can use that to figure out what stuff to Pinvoke for your C# version.
A: Similar as above...
I have a resize event handler that is triggered whenever the window gets resized (Maximized, minimized, etc.)...
public form1()
{
Initialize Component();
this.Resize += new EventHanlder(form1_Resize);
}
private void form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized && minimizeToTrayToolStripMenuItem.Checked == true)
{
NotificationIcon1.Visible = true;
NotificationIcon1.BalloonTipText = "Tool Tip Text"
NotificationIcon1.ShowBalloonTip(2); //show balloon tip for 2 seconds
NotificationIcon1.Text = "Balloon Text that shows when minimized to tray for 2 seconds";
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
}
}
This allows the user to select whether or not they want to minimize to tray via a menubar. They can go to Windows -> and click on Minimize to Tray. If this is checked,
and the window is being resized to Minimized, then it will minimize to the tray. Works flawlessly for me.
A: I have programmed a quick solution for you guys, this might not be the most efficient way (I'm not sure), but it definitely works !
The below solution successfully minimizes your Winforms application to the system Tray, and by using the notify Icon you create a small icon in the system tray with the aforementioned menu items. than we use the in-built libraries to fetch the Window (GUI in this case), and using the appropriate methods with Booleans we then minimize the window to the tray.
private void TransformWindow()
{
ContextMenu Menu = new ContextMenu();
Menu.MenuItems.Add(RestoreMenu);
Menu.MenuItems.Add(HideMenu);
Menu.MenuItems.Add(new MenuItem("Exit", new EventHandler(CleanExit)));
notifyIcon = new NotifyIcon()
{
Icon = Properties.Resources.Microsft_Icon,
Text = "Folder Watcher",
Visible = true,
ContextMenu = Menu
};
processHandle = Process.GetCurrentProcess().MainWindowHandle;
ResizeWindow(false);
}
#region Getting Libraries
[DllImport("user32.dll")]
public static extern IntPtr GetShellWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
public const Int32 SwMINIMIZE = 0;
public const Int32 SwMaximize = 9;
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern IntPtr GetConsoleWindow();
[DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);
public static void MinimizeConsoleWindow()
{
IntPtr hWndConsole = processHandle;
ShowWindow(hWndConsole, SwMINIMIZE);
}
public static void MaximizeConsoleWindow()
{
IntPtr hWndConsole = processHandle;
ShowWindow(hWndConsole, SwMaximize);
}
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public static void ResizeWindow(bool show)
{
RestoreMenu.Enabled = !show;
HideMenu.Enabled = show;
SetParent(processHandle, WinDesktop);
if (show)
MaximizeConsoleWindow();
else
MinimizeConsoleWindow();
}
public static void MinimizeClick(object sender, EventArgs e) => ResizeWindow(false);
public static void MaximizeClick(object sender, EventArgs e) => ResizeWindow(true);
public static IntPtr processHandle;
public static IntPtr WinShell;
public static IntPtr WinDesktop;
public static NotifyIcon notifyIcon;
public static MenuItem HideMenu = new MenuItem("Hide", new EventHandler(MinimizeClick));
public static MenuItem RestoreMenu = new MenuItem("Restore", new EventHandler(MaximizeClick));
public void CleanExit(object sender, EventArgs e)
{
notifyIcon.Visible = false;
this.Close();
}
A: In the constructor of the Form:
this.Resize += new EventHandler(MainForm_Minimize);
Then use this Event Handler method:
private void MainForm_Minimize(object sender, EventArgs e)
{
if(this.WindowState == FormWindowState.Minimized)
Hide();
}
A: If you are having problems getting this to work, check that you have
this.Resize += new System.EventHandler(this.Form1_Resize);
in the fom1.designer.cs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: How can a simple tree algorithm be coded in a functional language? Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first given a list of keyword, and must then answer if another given word was in the list.
In an imperative language, I would store the keywords in a tree (one node per character). Then, when receiving a word to test, I would scan my tree to test if the word is a keyword.
I'd like to understand how such an algorithm would be coded in a functional language. How does one get the benefits of 'stateless' programming while keeping the efficiency of 'imperative' algorithms. Isn't it necessary to store the tree somewhere between the lookups if you don't want to rebuild it each time?
A: I think what you mean is a character per node... sort of like a simple hash tree scheme for keyword lookup. Assuming this or even another kind of tree... imagine doing something like this (in pseudo-LISP):
(defun buildtree (wordlist) ...code to build tree recursively returns the tree...)
(define lookup (tree word) ...code to look up word using tree, returns t or nil...)
(defun lookupmany (tree querylist)
(if (eq querylist nil)
nil
(cons (lookup tree (car querylist)) (lookupmany tree (cdr querylist))
)
)
(defun main (wordlist querylist) ; the main entry point
(lookupmany (buildtree wordlist) querylist)
)
if this is what you mean, this is fairly straight-forward functional programming.
Is it really stateless? That's a matter of debate. Some people would say some
forms of functional programming store what we normally call "state" on the stack.
Moreover, Common LISP even since the first edition of the Steele book has had iterative
constructs, and LISP has had setq for a long, long time.
But in the theory of programming languages, what we mean by "stateless" is pretty much satisfied by the idea shown here.
I think the above is something like the arrangement you mean.
A: I imagine you'd want something like a tree with a list of children, as described here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Reference material for LabVIEW I'm supposed to learn how to use LabVIEW for my new job, and I'm wondering if anybody can recommend some good books or reference/tutorial web sites.
I'm a senior developer with lots of Java/C#/C++ experience.
I realize that this question is perhaps more vague than is intended on stack overflow, so how about this? Please answer with one book or web site and a brief description. Then people can vote up their favourites.
A: It will take some training and some time to learn the style needed to develop maintainable code.
Coming from Java/C#/C++, you probably have a good idea of good software architecture. Now you just need to learn the peculiarities of LabView and the common pitfalls.
For the basics, National Instruments offers training courses. See if your new employer can send you to a Basics I/II class to get your feet wet. They offer some online classes as well. Following classes, you can sign up to take tests for certification.
Get an evaluation copy of Labview from National Instruments; they have a well maintained help file that you can dive right into, with example code included. Look at "Getting Started" and "LabVIEW Environment". You should be able to jump right in and become familiar with the dev environment pretty quickly.
LabVIEW, being graphical is nice, but don't throw out your best practices from an application design point of view. It is common to end up with code looking like rainbow sphaghetti, or code that stretches several screens wide. Use subvi's and keep each vi with a specific purpose and function.
The official NI support forums and knowledgebase are probably the best resources out there at the moment.
Unofficial sites like Tutorials in G have a subset of the information found on the official site and documentation, but still may be useful for cross reference if you get stuck.
Edit: Basics I/II are designed to be accessible to users without prior software development experience. Depending on how you feel after using the evaluation version, you may be able to move directly into Intermediate I/II. NI has the course outlines available on their website as well, so you know what you're going to cover in each.
A: LabVIEW for Everyone is recently revised and quite comprehensive. Other than the free stuff available on the Web, this is probably the best place to start learning the language.
The LabVIEW Style Guide is a great book on how to organize and arrange your code and files for maximum benefit.
Object oriented programming is a recent addition to LabVIEW. The LVOOP white paper explains much about how it works and why the way it is the way it is.
It's a bit out of date, but LabVIEW Advanced Programming Techniques by Bitter, Mohiuddin and Nawrocki is still full of useful stuff.
The National Instruments forums are a great place to go for basic help. The LabVIEW Advanced Virtual Architects (LAVA) is the community forum for advanced topics.
A: Tutorials in G, also check out the webring.
-Adam
A: The official NI support page and support forums are hard to beat.
It really helps having a guru around for LabVIEW.
A: 'Arc the daft' pretty much nailed exactly what one should try to do to learn LabVIEW. However, I would not skip Basic's I and II. The classes do teach basic programming concepts and are geared to non-programmers, however they do cover the IDE extensively. The LabVIEW IDE is strange coming from a text based language and spending the time in the class learning it with an instructor can really accelerate your learning.
I would skip Intermediate 1 if you are a seasoned developer. Intermediate 1 tries to teach software engineering practices in the span of a three day course. If you are studying to get your CLD you need to know the course and the terminology for the exam, otherwise I wouldn't spend my time or capital in the course.
A: Subscribe to the Info-LabVIEW mailing list. It's got a lot quieter in recent times as the NI and LAVA forums have grown in popularity, but it's still read by some very experienced and helpful people, including people at NI, and if you can't find what you need elsewhere then a good question will usually get a good answer.
The NI style guide, as already mentioned, is a good reference - re-read it as you learn about more of the things it covers, it contains some densely packed good advice.
Personal top tips: look at the supplied example code (although it's not necessarily perfect); learn to use queues and notifiers as soon as possible; don't dive in to using event structures and control references until you've figured out what you can and can't do without them; and start small and simple - you should find it easy to reuse this code later on by repackaging it into subVI's as the scope of your ambitions increases. And have fun!
A: For me the best way to learn LabVIEW was by analyzing the in-build examples. The best forums are NI Developer Zone Community and LAVA Forums
LabVIEW is really easy to work with but the tricky bit is to know how to design your application so that it will not becaome a spaghetti. Once you get the basics (e.g. LabVIEW Introduction Course) learn how to use design patterns, events, queues, typedefs and references. Use modular architecture, avoid big structures, try 'writing' your code in small window.
It is also important to know the differences between LabVIEW versions (full/pro, and ver 7.1.1, 8.2, 8.5, 8.6, 2009), how to use version control system with the vi's (binary files), and how to keep your files in project so that you can easily reuse any code and be "DRY" (don't repeat yourself), how to build executable and what LabVIEW RunTime Engine it needs (for customers), what is DAQmx and how to use it, what are VISA drivers and which version is correct for you settings, how to use Measurements & Automation program..
A: When I started with LabVIEW a few years ago I was given a link to the LabVIEW Graphical Programming Course. It covers the basics and having a sound knowledge of other programming languages I think helped me pick things up quickly.
A: I would start with the LabVIEW wiki.
Specifically, LabVIEW Tutorial. There are lots of online references and links to LabVIEW reference books. Welcome to the world of LabVIEW!
A: I would suggest you start with LabVIEW for Everyone. Its a good book which covers the basics of LabVIEW well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Why doesn't inheritance work the way I think it should work? I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following:
abstract class Animal
{
public Leg GetLeg() {...}
}
abstract class Leg { }
class Dog : Animal
{
public override DogLeg Leg() {...}
}
class DogLeg : Leg { }
This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#.
EDIT: I modified this somewhat, since I'm actually using properties instead of functions in my code.
EDIT: I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant.
A: Dog should return a Leg not a DogLeg as the return type. The actual class may be a DogLeg, but the point is to decouple so the user of Dog doesn't have to know about DogLegs, they only need to know about Legs.
Change:
class Dog : Animal
{
public override DogLeg GetLeg() {...}
}
to:
class Dog : Animal
{
public override Leg GetLeg() {...}
}
Don't Do this:
if(a instanceof Dog){
DogLeg dl = (DogLeg)a.GetLeg();
it defeats the purpose of programing to the abstract type.
The reason to hide DogLeg is because the GetLeg function in the abstract class returns an Abstract Leg. If you are overriding the GetLeg you must return a Leg. Thats the point of having a method in an abstract class. To propagate that method to it's childern. If you want the users of the Dog to know about DogLegs make a method called GetDogLeg and return a DogLeg.
If you COULD do as the question asker wants to, then every user of Animal would need to know about ALL animals.
A: It is a perfectly valid desire to have the signature an overriding method have a return type that is a subtype of the return type in the overridden method (phew). After all, they are run-time type compatible.
But C# does not yet support "covariant return types" in overridden methods (unlike C++ [1998] & Java [2004]).
You'll need to work around and make do for the foreseeable future, as Eric Lippert stated in his blog
[June 19, 2008]:
That kind of variance is called "return type covariance".
we have no plans to implement that kind of variance in C#.
A: abstract class Animal
{
public virtual Leg GetLeg ()
}
abstract class Leg { }
class Dog : Animal
{
public override Leg GetLeg () { return new DogLeg(); }
}
class DogLeg : Leg { void Hump(); }
Do it like this, then you can leverage the abstraction in your client:
Leg myleg = myDog.GetLeg();
Then if you need to, you can cast it:
if (myleg is DogLeg) { ((DogLeg)myLeg).Hump()); }
Totally contrived, but the point is so you can do this:
foreach (Animal a in animals)
{
a.GetLeg().SomeMethodThatIsOnAllLegs();
}
While still retaining the ability to have a special Hump method on Doglegs.
A: You can use generics and interfaces to implement that in C#:
abstract class Leg { }
interface IAnimal { Leg GetLeg(); }
abstract class Animal<TLeg> : IAnimal where TLeg : Leg
{ public abstract TLeg GetLeg();
Leg IAnimal.GetLeg() { return this.GetLeg(); }
}
class Dog : Animal<Dog.DogLeg>
{ public class DogLeg : Leg { }
public override DogLeg GetLeg() { return new DogLeg();}
}
A: GetLeg() must return Leg to be an override. Your Dog class however, can still return DogLeg objects since they are a child class of Leg. clients can then cast and operate on them as doglegs.
public class ClientObj{
public void doStuff(){
Animal a=getAnimal();
if(a is Dog){
DogLeg dl = (DogLeg)a.GetLeg();
}
}
}
A: The concept that is causing you problems is described at http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)
A: Not that it is much use, but it is maybe interesting to note the Java does support covariant returns, and so this would work exactly how you hoped. Except obviously that Java doesn't have properties ;)
A: The short answer is that GetLeg is invariant in its return type. The long answer can be found here: Covariance and contravariance
I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers.
A: Clearly, you'll need a cast if you're
operating on a broken DogLeg.
A: Perhaps it's easier to see the problem with an example:
Animal dog = new Dog();
dog.SetLeg(new CatLeg());
Now that should compile if you're Dog compiled, but we probably don't want such a mutant.
A related issue is should Dog[] be an Animal[], or IList<Dog> an IList<Animal>?
A: C# has explicit interface implementations to address just this issue:
abstract class Leg { }
class DogLeg : Leg { }
interface IAnimal
{
Leg GetLeg();
}
class Dog : IAnimal
{
public override DogLeg GetLeg() { /* */ }
Leg IAnimal.GetLeg() { return GetLeg(); }
}
If you have a Dog through a reference of type Dog, then calling GetLeg() will return a DogLeg. If you have the same object, but the reference is of type IAnimal, then it will return a Leg.
A: Right, I understand that I can just cast, but that means the client has to know that Dogs have DogLegs. What I'm wondering is if there are technical reasons why this isn't possible, given that an implicit conversion exists.
A: @Brian Leahy
Obviously if you are only operating on it as a Leg there is no need or reason to cast. But if there is some DogLeg or Dog specific behavior, there are sometimes reasons that the cast is neccessary.
A: @Luke
I think your perhaps misunderstanding inheritance. Dog.GetLeg() will return a DogLeg object.
public class Dog{
public Leg GetLeg(){
DogLeg dl = new DogLeg(super.GetLeg());
//set dogleg specific properties
}
}
Animal a = getDog();
Leg l = a.GetLeg();
l.kick();
the actual method called will be Dog.GetLeg(); and DogLeg.Kick() (I'm assuming a method Leg.kick() exists) there for, the declared return type being DogLeg is unneccessary, because that is what returned, even if the return type for Dog.GetLeg() is Leg.
A: You could also return the interface ILeg that both Leg and/or DogLeg implement.
A: The important thing to remember is that you can use a derived type every place you use the base type (you can pass Dog to any method/property/field/variable that expects Animal)
Let's take this function:
public void AddLeg(Animal a)
{
a.Leg = new Leg();
}
A perfectly valid function, now let's call the function like that:
AddLeg(new Dog());
If the property Dog.Leg isn't of type Leg the AddLeg function suddenly contains an error and cannot be compiled.
A: You can achieve what you want by using a generic with an appropriate constraint, like the following:
abstract class Animal<LegType> where LegType : Leg
{
public abstract LegType GetLeg();
}
abstract class Leg { }
class Dog : Animal<DogLeg>
{
public override DogLeg GetLeg()
{
return new DogLeg();
}
}
class DogLeg : Leg { }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do you convert an aspx or master page file to page and code behind? I have a project where a .master page was created without a code behind page. Now I want to add a code behind page for this .master page and move the "in page" code to the code behind file. What is the best/easiest way to go about doing this? I'm using Visual Studio 2008.
A: Create new class file, name it yourmaster.master.cs (Visual Studio will automaticly group it with the .master) and move the code to it, reference it in your masterpage.
Then rightclick on your project and click "Convert to Web Application" and Visual Studio will create the designer file.
A: One way to do it, is to create a new empty masterpage/aspx-file and then copy-paste the code you allready have into that page. That will take care of all the wire-up and creating of code-files.
A: Or you can adapt the Page or Master directive while creating an appropiate code behind file (.master.cs or .aspx.cs or for VB.NET .master.vb or .aspx.vb).
I don't know of a simple click way to achieve this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Silverlight DataBinding cross thread issue I have an Image control with it's source bound to a property on an object(string url to an image). After making a service call, i update the data object with a new URL. The exception is thrown after it leaves my code, after invoking the PropertyChanged event.
The data structure and the service logic are all done in a core dll that has no knowledge of the UI. How do I sync up with the UI thread when i cant access a Dispatcher?
PS: Accessing Application.Current.RootVisual in order to get at a Dispatcher is not a solution because the root visual is on a different thread(causing the exact exception i need to prevent).
PPS: This only is a problem with the image control, binding to any other ui element, the cross thread issue is handled for you.
A: System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});
Also look here.
A: Have you tried implementing INotifyPropertyChanged?
A: The property getter for RootVisual on the Application class has a thread check which causes that exception. I got around this by storing the root visual's dispatcher in my own property in my App.xaml.cs:
public static Dispatcher RootVisualDispatcher { get; set; }
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Page();
RootVisualDispatcher = RootVisual.Dispatcher;
}
If you then call BeginInvoke on App.RootVisualDispatcher rather than Application.Current.RootVisual.Dispatcher you shouldn't get this exception.
A: I ran into a similar issue to this, but this was in windows forms:
I have a class that has it's own thread, updating statistics about another process, there is a control in my UI that is databound to this object. I was running into cross-thread call issues, here is how I resolved it:
Form m_MainWindow; //Reference to the main window of my application
protected virtual void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
if(m_MainWindow.InvokeRequired)
m_MainWindow.Invoke(
PropertyChanged, this, new PropertyChangedEventArgs(propertyName);
else
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
This seems to work great, if anyone has suggestions, please let me know.
A: When ever we want to update UI related items that action should happen in the UI thread else you will get an invalid cross thread access exception
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
UpdateUI(); // DO the actions in the function Update UI
});
public void UpdateUI()
{
//to do :Update UI elements here
}
A: The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed.
For example, consider a Person object with a property called FirstName. To provide generic property-change notification, the Person type implements the INotifyPropertyChanged interface and raises a PropertyChanged event when FirstName is changed.
For change notification to occur in a binding between a bound client and a data source, your bound type should either:
Implement the INotifyPropertyChanged interface (preferred).
Provide a change event for each property of the bound type.
Do not do both.
Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
// Change the namespace to the project name.
namespace TestNotifyPropertyChangedCS
{
// This form demonstrates using a BindingSource to bind
// a list to a DataGridView control. The list does not
// raise change notifications. However the DemoCustomer type
// in the list does.
public partial class Form1 : Form
{
// This button causes the value of a list element to be changed.
private Button changeItemBtn = new Button();
// This DataGridView control displays the contents of the list.
private DataGridView customersDataGridView = new DataGridView();
// This BindingSource binds the list to the DataGridView control.
private BindingSource customersBindingSource = new BindingSource();
public Form1()
{
InitializeComponent();
// Set up the "Change Item" button.
this.changeItemBtn.Text = "Change Item";
this.changeItemBtn.Dock = DockStyle.Bottom;
this.changeItemBtn.Click +=
new EventHandler(changeItemBtn_Click);
this.Controls.Add(this.changeItemBtn);
// Set up the DataGridView.
customersDataGridView.Dock = DockStyle.Top;
this.Controls.Add(customersDataGridView);
this.Size = new Size(400, 200);
}
private void Form1_Load(object sender, EventArgs e)
{
// Create and populate the list of DemoCustomer objects
// which will supply data to the DataGridView.
BindingList<DemoCustomer> customerList = new BindingList<DemoCustomer>();
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
customerList.Add(DemoCustomer.CreateNewCustomer());
// Bind the list to the BindingSource.
this.customersBindingSource.DataSource = customerList;
// Attach the BindingSource to the DataGridView.
this.customersDataGridView.DataSource =
this.customersBindingSource;
}
// Change the value of the CompanyName property for the first
// item in the list when the "Change Item" button is clicked.
void changeItemBtn_Click(object sender, EventArgs e)
{
// Get a reference to the list from the BindingSource.
BindingList<DemoCustomer> customerList =
this.customersBindingSource.DataSource as BindingList<DemoCustomer>;
// Change the value of the CompanyName property for the
// first item in the list.
customerList[0].CustomerName = "Tailspin Toys";
customerList[0].PhoneNumber = "(708)555-0150";
}
}
// This is a simple customer class that
// implements the IPropertyChange interface.
public class DemoCustomer : INotifyPropertyChanged
{
// These fields hold the values for the public properties.
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// The constructor is private to enforce the factory pattern.
private DemoCustomer()
{
customerNameValue = "Customer";
phoneNumberValue = "(312)555-0100";
}
// This is the public factory method.
public static DemoCustomer CreateNewCustomer()
{
return new DemoCustomer();
}
// This property represents an ID, suitable
// for use as a primary key in a database.
public Guid ID
{
get
{
return this.idValue;
}
}
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged();
}
}
}
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged();
}
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Javascript and CSS parsing performance I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application.
I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts?
Are there any tools that could help me generate metrics for this?
A: I believe YSlow does, but be aware that unless all requests are over a loopback connection you shouldn't worry. The HTTP overhead of split-up files will impact performance far more than parsing, unless your CSS/JS files exceed several megabytes.
A: To add to kamen's great answer, I would say that on some browsers, the parse time for larger js resources grows non-linearly. That is, a 1 meg JS file will take longer to parse than two 500k files. So if a lot of your traffic is people who are likely to have your JS cached (return visitors), and all your JS files are cache-stable, it may make sense to break them up even if you end up loading all of them on every pageview.
A: Context: While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble.
YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they've been updated very recently, they don't separate the amount of time required to fetch JS over HTTP or load from cache versus the amount of time spent parsing the actual JS payload.
Parse speed is slightly difficult to measure, but we've chased this metric a number of times on projects I've worked on and the impact on pageloads were significant even with ~500k of JS. Obviously the older browsers suffer the most...hopefully Chrome, TraceMonkey and the like help resolve this situation.
Suggestion: Depending on the type of traffic you have at your site, it may be well worth your while to split up your JS payload so some large chunks of JS that will never be used on a the most popular pages are never sent down to the client. Of course, this means that when a new client hits a page where this JS is needed, you'll have to send it over the wire.
However, it may well be the case that, say, 50% of your JS is never needed by 80% of your users due to your traffic patterns. If this is so, you should definitely user smaller, packaged JS payloads only on pages where the JS is necessary. Otherwise 80% of your users will suffer unnecessary JS parsing penalties on every single pageload.
Bottom Line: It's difficult to find the proper balance of JS caching and smaller, packaged payloads, but depending on your traffic pattern it's definitely well worth considering a technique other than smashing all of your JS into every single pageload.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Rotate Windows XP Desktop My LCD rotates. The software that comes with my ATI card to rotate the desktop just crashes (I've uninstalled, reinstalled and rolled them back, still crashes). Is there any other way to rotate a Windows XP Desktop by 90 degree increments? I am looking for either software or code (any language is fine.) I know I have seen 3rd party support for this before, but I can't find it now.
I realize this may not be a strictly software development related question, but it is programmer productivity related. If I can get an answer that involves how to write a program to do this, even better!
A: IRotate: http://www.entechtaiwan.net/util/irotate.shtm.
Have not used it but heard good things.
Same people that make Powerstrip http://www.entechtaiwan.net/util/ps.shtm.
Which gets rave reviews from the HTPC crowd.
Was looking at these recently while researching stuff for an HTPC.
Both are try before buy shareware.
A: I hate to give you the answer you probably already know, but yeah this is a video card driver software thing and if the ATI software crashes then it's either corrupted or buggy or your Windows install has gone rotten.
I've done this before on my NVidia-based cards without issue. I've never owned an ATI card.
A: iRotate worked great, and it is free for personal use. Very quick and painless install. Thanks seanb. My only complaint is it binds hot keys to CTRL+ALT+[arrows], so I have to close it after I rotate. It seems to stay rotated, but I guess I will see what happens when I reboot.
A: XP with SP3 has a known issue with ATI video cards where it will not rotate the desktop.
I'm thinking I might go back to SP2 to get that back.
A: Right-click on Desktop
-> Graphics Properties...
-> Display Settings
-> Enable Rotation
-> 90 degrees
Well, it works on my laptop (XP Professional, SP3).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: C# .NET + PostgreSQL I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components.
Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.?
A: I'm working with C# and Postgres using Npgsql2 component, and they work fast, I recommend you.
You can download from https://github.com/npgsql/Npgsql/releases
Note: If you want an application that works with any database you can use the DbProviderFactory class and make your queries using IDbConnection, IDbCommand, IDataReader and/or IDbTransaction interfaces.
A: We have developed several applications using visual studio 2005 with the devart ado.net data provider for PostgreSql (http://www.devart.com/pgsqlnet/).
One of the advantages of this provider is that it provides full Visual Studio support. The latest versions include all the new framework features like linq.
A: Today most languages/platforms (Java, .NET, PHP, Perl etc.) can work with almost any DBMS (SQL Server, Firebird, MySQL, Oracle, PostgresSQL etc.) so I wouldn't worry for one second. Sure there might be glitches and small problems but no showstopper.
As jalcom suggested you should program against a set of interfaces or at least a set of base classes (DbConnection, DbCommand and so on) to have an easily adaptable application.
A: You shouldn't have too many problems. As others have mentioned, there's many .Net PostgreSQL data providers available. One thing you may want to look out for is that features like Linq will probably not be able to be used.
A: Dont let a lack of Linq support stop you. A pattern I use is to always return my data into lists, and then linq away. I started doing this religiously when I found that the same (admittedly obscure) Linq expression in MySQL didnt bring back the same data as it did in Sql Server.
A: Npgsql - .Net Provider for PostGreSQL - is an excellent driver. If you have used the more traditional ADO.NET framework you are really in luck here. I have code that connects to Oracle that looks almost identical to the PostGreSQL connections. Easier to transition off of Oracle and reuse brain cells.
It supports all of the standard things you would want to do with calling SQL, but it also supports calling Functions (stored procedures). This includes the returning of reference cursors. The documentation is well written and provides useful examples without getting philosophical or arcane. Steal the code right out of the documentation and it will work instantly.
Francisco Figueiredo, Jr's and team have done a great job with this.
It is now available on Github.
https://github.com/franciscojunior/Npgsql2
The better site for info is:
http://npgsql.projects.postgresql.org/
Read the documentation!
http://npgsql.projects.postgresql.org/docs/manual/UserManual.html
A: There is a Linq provider for PostgreSQL at https://www.nuget.org/packages/linq2db.PostgreSQL/.
A: Just Go to Tool-->NuGet Package Manager-->Manager Nuget Package Manager
search for NpgSql and then select your project and click Install
sample Code
public void Demo()
{
NpgsqlConnection connection = new NpgsqlConnection();
connection = d_connection; // your connection string
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
try
{
cmd.Connection = connection;
cmd.CommandText = "select * from your table name";
cmd.CommandType = System.Data.CommandType.Text;
using (var dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
string answer= dataReader.IsDBNull(0) ? "" : dataReader.GetString(0);
}
dataReader.Dispose();
}
}
catch (Exception e)
{
}
finally
{
cmd.Dispose();
connection.Dispose();
}
}
Dont use upper case in postgreSql because its case sensitive.
A: Npgsql is excellent driver, but only issue Ive found so far is that Numeric value does not fit in a System.Decimal, so only option is correct each query or DB schema
https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/438#issuecomment-486586272
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: MySQL UTF/Unicode migration tips Does anyone have any tips or gotcha moments to look out for when trying to migrate MySQL tables from the the default case-insenstive swedish or ascii charsets to utf-8? Some of the projects that I'm involved in are striving for better internationalization and the database is going to be a significant part of this change.
Before we look to alter the database, we are going to convert each site to use UTF-8 character encoding (from least critical to most) to help ensure all input/output is using the same character set.
Thanks for any help
A: Some hints:
*
*Your CHAR and VARCHAR columns will use up to 3 times more disk space. (You probably won't get much disk space grow for Swedish words.)
*Use SET NAMES utf8 before reading or writing to the database. If you don't this then you will get partially garbled characters.
A: I am going to be going over the following sites/articles to help find an answer.
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) - Joel on Software
UTF-8 And Unicode FAQ
Hanselminutes episode "Sorting out Internationalization with Michael Kaplan"
And I also just found a very on topic post by Derek Sivers @ O'Reilly ONLamp Blog as I was writing this out. Turning MySQL data in latin1 to utf8 utf-8
A: Beware index length limitations. If a table is structured, say:
a varchar(255)
b varchar(255)
key ('a', 'b')
You're going to go past the 1000 byte limit on key lengths. 255+255 is okay, but 255*3 + 255*3 isn't going to work.
A:
Your CHAR and VARCHAR columns will use up to 3 times more disk space.
Only if they're stuffed full of latin-1 with ordinals > 128. Otherwise, the increased space use of UTF-8 is minimal.
A: The collations are not always favorable. You'll get umlats collating to non umlatted versions which is not always correct. Might want to go w/ utf8_bin, but then everything is case sensitive as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Determining the last changelist synced to in Perforce A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system.
A: I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using:
p4 changes -s submitted -m1
then sync to that change and record it in the revision info. The reason is as follows. Although Perforce recommends the following to determine the changelist to which the workspace is synced:
p4 changes -m1 @clientname
they note a few gotchas:
*
*This only works if you have not submitted anything from the workspace in question.
*It is also possible that a client workspace is not synced to any specific changelist.
and there's an additional gotcha they don't mention:
*
*If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files).
If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed:
p4 sync -n @changelist_number
Note that this method doesn't work if a file is added in a changelist (n-1) and then deleted in the very next changelist (n). p4 changes -m1 @clientname and p4 changes ...#have both return n-3 and p4 sync -n @n-3 will say "file(s) up-to-date."
A: You could also use the cstat command:
p4 help cstat
cstat -- Dump change/sync status for current client
p4 cstat [files...]
Lists changes that are needed, had or partially synced in the current
client. The output is returned in tagged format, similar to the fstat
command.
The fields that cstat displays are:
change changelist number
status 'have', 'need' or 'partial'
A: For a serious build (one that is being prepared for testing), explicitly specify the desired label or changelist number, sync to label, and imbed it in build artifacts.
If a changelist (or label) is not given, use p4 counter change to get the current change number, and record it. But you still need to sync everything using that change number.
I don't think you can achieve exactly what you want, because in general, an entire workspace isn't synced to a particular changelist number. One can explicitly sync some files to older revisions, and then a single changelist number is meaningless. That's why a fresh sync is required to ensure that a single changelist number accurately represents the code version.
Regarding the comments: Yes, my answer is intended for use by configuration managers preparing a build to give to QA. Our developers don't normally sync as part of a build; they do a build prior to submitting—so that they can make sure their changes don't break the build or tests. In that context, we don't bother to embed a repository label.
With your approach, you are making the assumption that your whole workspace was synced to head at the time of your last changelist submission, and that changelist included all of your open files. It's too easy to be mistaken in those assumptions, hard to detect, and horribly expensive in terms of lost time. On the other hand, solving the problem is easy, with no drawbacks. And because a changelist number can be explicitly specified, it doesn't matter what revision you need or how quickly the codebase is changing.
A: Just to answer this myself in keeping with Jeff's suggestion of using Stackoverflow as a place to keep technical snippets....
From the command line use:
p4 changes -m1 @<clientname>
And just replace with the name of your client spec. This will produce output of the form:
Change 12345 on 2008/08/21 by joebloggs@mainline-client '....top line of description...'
Which is easily parsed to extract the changelist number.
A: For the whole depot (not just your workspace/client)
p4 counter change
does the job, just telling the last changelist.
A: The best I've found so far is to do your sync to whatever changelist you want to build and then use changes -m1 //...#have to get the current local changelist (revision).
p4 sync @CHANGELIST_NUM
p4 changes -m1 //...#have | awk '{print $2}'
Gives you the changelist number that you can the use wherever you want. I am currently looking for a simpler way than p4 changes -m1 //...#have.
A: You may try finding the maximum change number in the output of the "p4 files" command. The working directory should not contain post-sync commits, though. This is just a tad better than
p4 changes -m1 "./...#have"
as the latter seems to run on the server and may fail on big source trees due to "MaxResults" limits.
$ p4 changes -m1 "./...#have"
Request too large (over 850000); see 'p4 help maxresults'.
$ p4 -G files "./...#have" | python c:/cygwin/usr/local/bin/p4lastchange.py
Files: 266948
2427657
where p4lastchange.py is based on the code from the Using P4G.py From the Command Line presentation by J.T.Goldstone, Kodak Information Network/Ofoto, April 15, 2005.
#! /usr/bin/env python
import sys, os, marshal
if os.name == "nt":
# Disable newline translation in Windows. Other operating systems do not
# translate file contents.
import msvcrt
msvcrt.setmode( sys.stdin.fileno(), os.O_BINARY )
lastcl = 0
num = 0
try:
while 1:
dict = marshal.load(sys.stdin)
num = num + 1
for key in dict.keys():
# print "%s: %s" % (key,dict[key])
if key == "change":
cl = int(dict[key])
if cl > lastcl:
lastcl = cl
except EOFError:
pass
print "Files: %s" % num
print lastcl
A: p4 changes -m1 @clientname which is the "recommended" way to do it for my client takes about 10 minutes
this is what I use:
p4 cstat ...#have | grep change | awk '$3 > x { x = $3 };END { print x }'
for the same client takes 2.1 seconds
A: If you are using P4V you can do this graphically:
*
*In the Dashboard tab (View->Dashboard) choose a folder and you will see a list of changelists that the folder isn't yet updated with. Note the lowest number (in the highest row).
*Make sure that in the Workspace Tree you have selected the same folder as previously in the Dashboard. Then go to the History tab (View->History) and scroll down to the number noted previously. The number just below that number is the number of your current changelist.
A: I am not sure if you got the answer you needed but I had a similar problem. The goal was to write in our logger the specific version of the project. The problem was that while we are making our own makefile, the overall build system is controlled by our configuration management. This means that all the solutions which say "sync to something then do something" don't really work and I didn't want to manually change the version whenever we commit (a sure source for errors).
The solution (which is actually hinted in some of the answers above) is this:
in our makefile, I do p4 changes -m1 "./...#have"
The result for this is Change change_number on date by user@client 'msg'
I simply create the message into a string which is printed by the logger (the change number is the important element but the other is also useful to quickly decide if a certain version contains changes you know you made yourself without going to perforce to check).
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "122"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.